fwdloop 0.11.0 → 0.13.0

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 (62) hide show
  1. package/bin/fwdloop +248 -27
  2. package/package.json +1 -1
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +103 -13
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +36 -0
  7. package/src/config.js +256 -0
  8. package/src/declaration.js +72 -2
  9. package/src/drafter.js +53 -11
  10. package/src/draftspend.js +70 -0
  11. package/src/flow.js +43 -0
  12. package/src/keysfile.js +180 -0
  13. package/src/liveness.js +1 -1
  14. package/src/model-step.js +43 -8
  15. package/src/monthly.js +276 -0
  16. package/src/panel/author.js +482 -0
  17. package/src/panel/authorcard.js +297 -0
  18. package/src/panel/authorflows.js +312 -0
  19. package/src/panel/authorresume.js +149 -0
  20. package/src/panel/authorstart.js +257 -0
  21. package/src/panel/authorvalues.js +110 -0
  22. package/src/panel/data.js +228 -34
  23. package/src/panel/index.html +2073 -124
  24. package/src/panel/resume.js +14 -11
  25. package/src/panel/server.js +150 -117
  26. package/src/panel/settings.js +270 -0
  27. package/src/panel/spawn.js +77 -0
  28. package/src/provider.js +189 -43
  29. package/src/providershapes.js +19 -0
  30. package/src/runner.js +639 -85
  31. package/src/runvalues.js +178 -0
  32. package/src/send.js +10 -3
  33. package/src/setup.js +120 -0
  34. package/types/authoring.d.ts +24 -2
  35. package/types/books.d.ts +14 -2
  36. package/types/canrun.d.ts +32 -0
  37. package/types/config.d.ts +52 -0
  38. package/types/declaration.d.ts +9 -1
  39. package/types/drafter.d.ts +18 -2
  40. package/types/draftspend.d.ts +21 -0
  41. package/types/flow.d.ts +23 -0
  42. package/types/keysfile.d.ts +90 -0
  43. package/types/liveness.d.ts +2 -2
  44. package/types/model-step.d.ts +6 -2
  45. package/types/monthly.d.ts +130 -0
  46. package/types/panel/author.d.ts +335 -0
  47. package/types/panel/authorcard.d.ts +120 -0
  48. package/types/panel/authorflows.d.ts +175 -0
  49. package/types/panel/authorresume.d.ts +32 -0
  50. package/types/panel/authorstart.d.ts +115 -0
  51. package/types/panel/authorvalues.d.ts +62 -0
  52. package/types/panel/data.d.ts +103 -12
  53. package/types/panel/resume.d.ts +8 -1
  54. package/types/panel/server.d.ts +19 -33
  55. package/types/panel/settings.d.ts +23 -0
  56. package/types/panel/spawn.d.ts +30 -0
  57. package/types/provider.d.ts +123 -70
  58. package/types/providershapes.d.ts +11 -0
  59. package/types/runner.d.ts +120 -5
  60. package/types/runvalues.d.ts +97 -0
  61. package/types/send.d.ts +5 -1
  62. package/types/setup.d.ts +83 -0
@@ -33,6 +33,7 @@
33
33
  --magenta:#bb9af7;
34
34
  --accent:#7aa2f7;
35
35
  --btn-bg:#1f2335; --btn-text:#c0caf5;
36
+ --field-bg:var(--bg); --field-soft-bg:var(--bg); --field-border:var(--text-dim);
36
37
  --primary-bg:#7aa2f7; --primary-text:#1a1b26; --primary-border:#7aa2f7;
37
38
  font: 14px/1.5 "Courier Prime", "Courier New", Courier, ui-monospace, monospace;
38
39
  }
@@ -74,6 +75,7 @@
74
75
  --magenta:#9854f1;
75
76
  --accent:#2668c2;
76
77
  --btn-bg:#e9e9ed; --btn-text:#3760bf;
78
+ --field-bg:#ffffff; --field-soft-bg:#f7f7f9;
77
79
  --primary-bg:#2668c2; --primary-text:#e1e2e7; --primary-border:#2668c2;
78
80
  }
79
81
  }
@@ -88,6 +90,7 @@
88
90
  --magenta:#9854f1;
89
91
  --accent:#2668c2;
90
92
  --btn-bg:#e9e9ed; --btn-text:#3760bf;
93
+ --field-bg:#ffffff; --field-soft-bg:#f7f7f9;
91
94
  --primary-bg:#2668c2; --primary-text:#e1e2e7; --primary-border:#2668c2;
92
95
  }
93
96
  .theme-toggle{padding:4px 9px;min-height:32px;border:1px solid var(--border-strong);background:var(--btn-bg);color:var(--text);}
@@ -157,6 +160,11 @@
157
160
  /* M4c amendment 2: stuck — answer saved, nobody carrying the run on. Its own glyph,
158
161
  amber like the other "needs you" signs; it pulses (server-decided, glyphPulses). */
159
162
  .dot.stuck::before{content:"[II]";color:var(--amber);}
163
+ /* M4e amendment 4: stopped — by you, or at the money cap; Resume goes on. Grey like the other quiet end, never the red [✗]. */
164
+ .dot.stopped::before{content:"[■]";color:var(--grey-dot);}
165
+ /* the Run tab's top action row (Stop, Resume) */
166
+ .run-actions{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin-bottom:8px;}
167
+ .run-actions .answer-msg{margin-top:0;flex:1 1 100%;}
160
168
  /* M4c: only the two "alive" signs pulse — [▶] running and [·] waiting on
161
169
  you — keyed to `.pulse`, which the server decides (glyphPulses), never to
162
170
  a colour class (.grey is also the placeholder dot). A gentle opacity wave on the existing colors;
@@ -186,6 +194,7 @@
186
194
  .badge.cyan{color:var(--cyan);}
187
195
 
188
196
  .hint{font-size:11px;color:var(--text-faint);margin-top:4px;}
197
+ .hint.money-red{color:var(--red);}
189
198
  .btn{padding:8px 14px;min-height:44px;border:1px solid var(--border-strong);background:var(--panel2);color:var(--text);white-space:nowrap;flex:none;position:relative;}
190
199
  .btn::before{content:"[ ";color:var(--text-faint);}
191
200
  .btn::after{content:" ]";color:var(--text-faint);}
@@ -227,11 +236,11 @@
227
236
  the same behavior fix #7 already gave phone width alone. */
228
237
  .wf-meta-line{white-space:normal;overflow:visible;text-overflow:clip;min-width:0;}
229
238
  /* M4c-fix amendment 2 (g), line 2 of a run row: **word** — plain why. Wraps, never clips. */
230
- .wf-sign-line{font-size:12px;color:var(--text-dim);white-space:normal;overflow-wrap:anywhere;min-width:0;}
239
+ .wf-sign-line{font-size:12px;color:var(--text-dim);white-space:normal;overflow-wrap:anywhere;}
231
240
  .wf-sign-line .sign-word,.hdr-verdict .sign-word{color:var(--text);}
232
241
  .hdr-verdict{font-size:12px;color:var(--text-dim);min-width:0;overflow-wrap:anywhere;}
233
242
  .wf-meta{font-size:12px;color:var(--text-dim);}
234
- .wf-meta + .wf-meta::before{content:" · ";color:var(--text-faint);}
243
+ .wf-sep{font-size:12px;color:var(--text-faint);}
235
244
  .wf-row.selected,.hist-row.selected{border:2px solid var(--accent);border-radius:4px;}
236
245
  /* item 2 (2026-09-26 merge): a Workflows-view job row expands inline to
237
246
  list ALL its runs (build spec's own design) — the caret glyph on the
@@ -296,7 +305,7 @@
296
305
  `[✓]`, so it draws no second pair of brackets (`.sign-badge`). */
297
306
  .step-card .step-head{display:flex;align-items:center;justify-content:space-between;gap:8px;flex-wrap:wrap;text-transform:none;font-weight:700;}
298
307
  .step-card h4{margin:0;font-size:13px;text-transform:none;letter-spacing:normal;}
299
- .step-card .sign-badge::before,.step-card .sign-badge::after{content:none;}
308
+ .sign-badge::before,.sign-badge::after{content:none;}
300
309
  /* Every OTHER line on the card (goal, actions, granted, stopped reason) —
301
310
  lower case exactly as the data reads, normal weight; never inherits the
302
311
  header's uppercase/bold (same ruling, the non-header half of it). */
@@ -342,7 +351,8 @@
342
351
  .audit-group h4::before{content:"┤ ";color:var(--text-faint);}
343
352
  .audit-group h4::after{content:" ├";color:var(--text-faint);}
344
353
  /* hamr's 2026-09-27 review: the Audit-group's own state header ("[done] ·
345
- step · ...", built by buildAuditGroupHeaderEl) is NOT bold — a plain h4
354
+ step · ...", built by buildAuditGroupHeaderEl): M4e amendment 10 made its STATUS bold (the `> .badge`,
355
+ weight 700); the rest of the line stays normal — a plain h4
346
356
  is bold by default, so its own class (`.audit-status-header`, NOT the
347
357
  shared `.audit-group h4`, which the Ask tab's `.ask-question-heading`
348
358
  h4 also matches and must stay bold per review #3) overrides it back to
@@ -350,6 +360,7 @@
350
360
  `.audit-group h4` (0,1,1) and `.ask-question-heading` (0,1,0) alone, so
351
361
  this never un-bolds the ask question heading. */
352
362
  .audit-group h4.audit-status-header{font-weight:400;}
363
+ .audit-group h4.audit-status-header > .badge{font-weight:700;}
353
364
  /* M4c-fix amendment 2 (f): a foldable step group. The header sits IN the box (not pinned over its top edge),
354
365
  so a long header wraps inside its own box and never lands on the next group; a closed group is that one
355
366
  header line with a caret and no empty table under it. */
@@ -359,6 +370,7 @@
359
370
  .audit-group.audit-fold h4.audit-status-header > .badge,.audit-group.audit-fold h4.audit-status-header::before{flex:none;white-space:pre;}
360
371
  .audit-fold-name{flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
361
372
  .audit-fold-tail{flex:none;white-space:nowrap;}
373
+ .audit-fold-dot{flex:none;}
362
374
  .audit-group.audit-fold h4.audit-status-header::before{content:"\25B6 ";color:var(--text-faint);}
363
375
  .audit-group.audit-fold h4.audit-status-header[aria-expanded="true"]::before{content:"\25BC ";}
364
376
  .audit-group.audit-fold h4.audit-status-header::after{content:none;}
@@ -369,8 +381,13 @@
369
381
  .audit-group.audit-fold h4.audit-status-header > .badge{padding-left:0;padding-right:0;font-size:10px;}
370
382
  .audit-group.audit-fold h4.audit-status-header::before{content:"\25B6";}
371
383
  .audit-group.audit-fold h4.audit-status-header[aria-expanded="true"]::before{content:"\25BC";}
372
- .audit-fold-sep,.audit-fold-try{display:none;}
373
- .audit-fold-n{margin-left:.4em;}
384
+ .audit-fold-sep{display:none;}
385
+ .audit-fold-try{margin-left:.4em;} /* the cost and the try count never touch: "$0.0010" + "1" must not read $0.00101 */
386
+ /* the tail wraps inside the header (never spills or is cut): it may break at its spaces and shrink */
387
+ .audit-fold-tail{flex:0 1 auto;min-width:0;max-width:100%;white-space:normal;overflow-wrap:anywhere;}
388
+ /* a narrow header WRAPS (amendment 7 walk): the name keeps a readable line of its own and the tail drops under it, never a one-letter name */
389
+ .audit-group.audit-fold h4.audit-status-header{flex-wrap:wrap;row-gap:2px;}
390
+ .audit-fold-name{flex:0 1 auto;max-width:100%;white-space:normal;overflow:visible;text-overflow:clip;overflow-wrap:anywhere;}
374
391
  }
375
392
  .audit-group.audit-fold table{margin-top:8px;}
376
393
  .audit-group.audit-fold table[hidden]{display:none !important;}
@@ -409,11 +426,129 @@
409
426
  line) so it reads as a clear, bold heading without a second border. */
410
427
  .ask-question-heading{margin:6px 0 0;font-size:13px;font-weight:700;color:var(--text);}
411
428
  .ro-value{padding:6px 8px;min-height:32px;box-sizing:border-box;border:1px solid var(--border);background:var(--bg);color:var(--text-dim);}
429
+ .art-head{color:var(--accent);}
430
+ .ro-value.sub{margin-left:20px;min-height:0;padding-top:2px;padding-bottom:2px;border-top-width:0;overflow-wrap:anywhere;}
412
431
  .ro-value.scroll{max-height:160px;overflow-y:auto;white-space:pre-wrap;word-break:break-word;}
413
432
  .field-row{display:flex;flex-wrap:wrap;gap:10px;}
414
433
  .field-row .field{flex:1 1 140px;margin-bottom:10px;}
415
434
 
416
- .chat-thread{padding:20px 8px;color:var(--text-faint);font-size:13px;}
435
+ /* borrowed-from: bareloop src/panel/index.html@ca7195e — the Chat card's CSS (job card, radio row, cap row, the one progress
436
+ list, the ask box, the one wide button, field colours, .locked, the one focus rule). fwdloop's own tokens win where both define
437
+ one; the global `input,select` rule is scoped to #panel-chat so no other panel box is restyled. */
438
+ #panel-chat input,#panel-chat select{font:inherit;padding:6px 8px;border:1px solid var(--border-strong);border-radius:0;background:var(--bg);color:var(--text);}
439
+ #panel-chat input::placeholder,#panel-chat textarea::placeholder{color:var(--text-faint);}
440
+ .job-card .card-clear{position:absolute;top:-13px;right:10px;padding:1px 8px;font-size:11px;line-height:1.4;background:var(--panel2);}
441
+ .job-card .locked{opacity:.55;cursor:not-allowed;}
442
+ .field input,.field select{width:100%;}
443
+ .job-card.compact{padding:14px 8px 8px;}
444
+ .job-card.compact .field{margin-bottom:6px;}
445
+ .job-card.compact label{margin-bottom:1px;font-size:11px;}
446
+ .job-card.compact input,
447
+ .job-card.compact select{padding:5px 7px;}
448
+ .radio-row{display:flex;flex-wrap:wrap;gap:6px 14px;align-items:center;margin-bottom:10px;}
449
+ .radio-row label{display:flex;align-items:center;gap:5px;font-size:13px;color:var(--text);margin:0;text-transform:none;}
450
+ .radio-row input{width:auto;}
451
+ @media (max-width:400px){.job-card .radio-row{padding-right:76px;}}
452
+ .cap-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:6px;margin-bottom:6px;}
453
+ .cap-field label{display:block;font-size:11px;font-weight:700;color:var(--text-dim);margin-bottom:1px;}
454
+ .cap-field input{width:100%;padding:5px 6px;box-sizing:border-box;}
455
+ .btn.primary{background:var(--primary-bg);color:var(--primary-text);border-color:var(--primary-border);font-weight:700;}
456
+ .btn.primary::before,.btn.primary::after{color:var(--primary-text);opacity:0.6;}
457
+ #panel-chat .btn:disabled{opacity:0.5;cursor:not-allowed;}
458
+ .btn.primary:disabled{background:var(--btn-bg);color:var(--text-faint);border-color:var(--border);}
459
+ .btn.primary:disabled::before,.btn.primary:disabled::after{color:var(--text-faint);opacity:0.4;}
460
+ #chat-action-error:empty{display:none;}
461
+ #chat-action-error{font-size:12px;color:var(--red);margin:4px 0;overflow-wrap:anywhere;white-space:pre-wrap;}
462
+ #chat-card-error:empty{display:none;}
463
+ #chat-card-error{overflow-wrap:anywhere;white-space:pre-wrap;}
464
+
465
+ /* the ONE progress list: a step per line — label, then dots while running / check / cross, then its reason */
466
+ .chat-steps{list-style:none;margin:2px 0 10px;padding:0;font-size:12px;}
467
+ .chat-steps .step{padding:1px 0;}
468
+ .chat-steps .step-line{display:flex;flex-wrap:wrap;align-items:baseline;gap:0 10px;}
469
+ .chat-steps .step-label{color:var(--text);min-width:11em;overflow-wrap:anywhere;}
470
+ .chat-steps .step-sign{font-weight:700;}
471
+ .chat-steps .step.run .step-sign{color:var(--amber);}
472
+ .chat-steps .step.ok .step-sign{color:var(--green);}
473
+ .chat-steps .step.bad .step-sign{color:var(--red);}
474
+ .chat-steps .step.wait .step-label{color:var(--amber);}
475
+ .chat-steps .step-detail{display:block;flex-basis:100%;min-width:0;padding-left:1.2em;color:var(--text-faint);word-break:break-word;white-space:pre-wrap;}
476
+ .chat-steps .step.bad .step-detail{color:var(--red);}
477
+ .chat-steps .step.run .step-sign::after{content:"\2026";}
478
+ @keyframes step-dots{0%{content:"";}25%{content:".";}50%{content:"..";}75%{content:"...";}}
479
+ @media (prefers-reduced-motion: no-preference){
480
+ .chat-steps .step.run .step-sign::after{content:"";animation:step-dots 1.2s steps(1,end) infinite;}
481
+ }
482
+
483
+ .chat-thread{display:flex;flex-direction:column;gap:10px;margin-bottom:10px;}
484
+ .chat-thread:empty{display:none;}
485
+ .msg{padding:8px 10px;border:1px solid var(--border);max-width:100%;background:var(--panel2);font-size:13px;word-break:break-word;white-space:pre-wrap;}
486
+ .msg.bot{border-left:3px solid var(--border-strong);}
487
+ .msg.bot .who::before{content:"$ ";}
488
+ .msg .who{font-size:11px;color:var(--text-faint);margin-bottom:3px;text-transform:none;font-weight:400;}
489
+ /* borrowed-from: bareloop src/panel/index.html@c1d87ce (the "you" bubble: indented, accent left border) */
490
+ .msg.you{background:var(--bg);margin-left:20px;border-left:3px solid var(--accent);}
491
+ .msg.you .who::before{content:"> ";}
492
+ .chat-input-row{margin-top:10px;border-top:1px dotted var(--border-strong);padding-top:10px;}
493
+ .chat-input-row input{width:100%;box-sizing:border-box;}
494
+ /* borrowed-from: bareloop src/panel/index.html@d151ec7 (the ask box: a wrapping textarea, 2x height, thick border, dimmed while it cannot be used).
495
+ M4e amendment 3 item 3: it opens only on a green plan ("Ask for a change to the plan"); `hidden` closes it. */
496
+ .chat-input-row[hidden]{display:none;}
497
+ textarea[data-testid="chat-msg"]{width:100%;box-sizing:border-box;font:inherit;color:var(--text);resize:vertical;overflow-y:auto;max-height:200px;}
498
+ #chat-msg{min-height:64px;padding:8px 12px;border:2px solid var(--field-border);background:var(--field-bg);}
499
+ #chat-msg:read-only{background:var(--bg);opacity:.55;cursor:not-allowed;}
500
+ /* the card's free-text boxes wrap (textarea): grow a few rows (fitBox), then scroll inside */
501
+ .job-card textarea.jf-wrap{width:100%;box-sizing:border-box;font:inherit;padding:6px 8px;border:1px solid var(--border-strong);border-radius:0;background:var(--bg);color:var(--text);resize:vertical;overflow-y:auto;max-height:200px;}
502
+ /* the focused/selected Chat-card field gets a blue border (the accent), no outline ring */
503
+ #panel-chat :is(input,select,textarea):focus{border-color:var(--accent);outline:none;}
504
+ /* amendment 2: the job and inputs boxes have a gutter OUTSIDE them on the left (`N >` per step, `~` per guardrail; a number per input
505
+ line), one entry per logical line, as tall as that line wraps (measured from a hidden mirror, see paintGutter) */
506
+ .jf-gutbox{position:relative;display:flex;align-items:stretch;gap:4px;}
507
+ .jf-gutbox textarea.jf-wrap{flex:1 1 auto;min-width:0;width:auto;overflow-wrap:break-word;word-wrap:break-word;white-space:pre-wrap;}
508
+ .jf-gut{flex:0 0 1.8em;overflow:hidden;position:relative;color:var(--text-faint);text-align:left;user-select:none;-webkit-user-select:none;font:inherit;}
509
+ .jf-gut-in{position:absolute;left:0;right:0;top:0;}
510
+ .jf-gut-in div{white-space:nowrap;overflow:hidden;}
511
+ .jf-mirror{position:absolute;left:0;top:0;visibility:hidden;pointer-events:none;white-space:pre-wrap;overflow-wrap:break-word;word-wrap:break-word;box-sizing:content-box;padding:0;border:0;margin:0;}
512
+ .jf-mirror div{margin:0;padding:0;}
513
+ /* editable Chat-card fields get the standard soft white (a step below the ask box); disabled/readonly keep the base colour */
514
+ #panel-chat input:not(:disabled):not([readonly]):not(#chat-msg):not([type="radio"]):not([type="checkbox"]),
515
+ #panel-chat select:not(:disabled),
516
+ #panel-chat textarea:not(:disabled):not([readonly]):not(#chat-msg){background:var(--field-soft-bg);}
517
+ /* ONE wide button below the message box; its wording comes from mainButtonFor */
518
+ .btn.wide{width:100%;margin-top:10px;white-space:normal;}
519
+ /* amendment 2 item 7: the main button's label ("Sign <hash8> & run · $<cap>") stays on ONE line inside the card */
520
+ #chat-main-btn{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;min-width:0;max-width:100%;}
521
+ /* fwdloop's own additions (not bareloop): input rows, per-box refusal lines, the read-only Run-mode cap */
522
+ .jf-inrow{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,2fr) auto;gap:6px;margin-bottom:4px;align-items:start;}
523
+ .jf-inrow .btn.small{height:32px;padding:0 8px;}
524
+ .jf-inrow .jf-role-ro{padding:5px 7px;min-height:32px;overflow-wrap:anywhere;border:1px solid var(--border);background:var(--bg);color:var(--text-dim);}
525
+ .jf-inrow .jf-err{grid-column:1 / -1;}
526
+ /* M4e amendment 4/5: what a Run or a Resume cannot change shows dimmed (the signature fixes it); only the open boxes are bright */
527
+ .field.dimmed{opacity:.6;}
528
+ /* borrowed-from: bareloop src/panel/index.html@b5e37b8 — the Reuse workflow picker (search box + list, then the picked box) */
529
+ .rw-box{position:relative;margin-top:6px;}
530
+ .rw-box input{width:100%;box-sizing:border-box;}
531
+ .rw-list{list-style:none;margin:0;padding:0;border:1px solid var(--border-strong);border-top:none;background:var(--bg);max-height:220px;overflow:auto;}
532
+ .rw-list li{padding:7px 8px;border-bottom:1px dotted var(--border);cursor:pointer;}
533
+ .rw-list li:hover,.rw-list li.hl{background:var(--panel2);}
534
+ .rw-name{font-weight:700;overflow-wrap:anywhere;} .rw-name mark{background:none;color:var(--accent);text-decoration:underline;}
535
+ .rw-meta{font-size:11px;color:var(--text-dim);margin-top:2px;overflow-wrap:anywhere;}
536
+ .rw-empty{padding:7px 8px;font-size:12px;color:var(--text-dim);}
537
+ .rw-picked{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-top:6px;padding:6px 8px;border:1px solid var(--accent);}
538
+ .rw-picked span{overflow-wrap:anywhere;}
539
+ .rw-picked a{font-size:12px;cursor:pointer;flex:none;}
540
+ .ro-lines{padding:6px 8px;border:1px solid var(--border);background:var(--bg);color:var(--text-dim);font-size:12px;overflow-wrap:anywhere;max-height:160px;overflow-y:auto;}
541
+ .ro-lines .ro-line{display:flex;gap:8px;}
542
+ .ro-lines .ro-n{flex:none;min-width:1.4em;color:var(--text-faint);}
543
+ .jf-waitrow{margin-bottom:4px;}
544
+ .jf-err{font-size:11px;color:var(--red);margin-top:2px;overflow-wrap:anywhere;}
545
+ .jf-err:empty{display:none;}
546
+ .dest-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,2fr);gap:6px;}
547
+ @media (max-width: 899px){
548
+ .jf-inrow{grid-template-columns:minmax(0,1fr) auto;}
549
+ .jf-inrow .jf-path{grid-column:1 / -1;order:3;}
550
+ .jf-inrow .jf-err{order:4;}
551
+ }
417
552
 
418
553
  @media (max-width: 899px){
419
554
  .main{flex-direction:column;}
@@ -465,10 +600,11 @@
465
600
  [data-testid="audit-table"] td[data-label="Step"], .audit-group table td[data-label="Step"],
466
601
  [data-testid="audit-table"] td[data-label="Verdict"], .audit-group table td[data-label="Verdict"]{display:block;}
467
602
  [data-testid="audit-table"] td[data-label="Attempt"]::before, .audit-group table td[data-label="Attempt"]::before{content:"#";}
603
+ [data-testid="audit-table"] td[data-label="Attempt"]:empty::before, .audit-group table td[data-label="Attempt"]:empty::before{content:none;}
468
604
  [data-testid="audit-table"] td.am-glyph, .audit-group table td.am-glyph{order:1;flex:0 0 auto;}
469
605
  [data-testid="audit-table"] td[data-label="Attempt"], .audit-group table td[data-label="Attempt"]{order:2;flex:0 0 auto;color:var(--text-dim);}
470
606
  [data-testid="audit-table"] td[data-label="Step"], .audit-group table td[data-label="Step"]{order:3;flex:1 1 0;overflow:hidden;text-overflow:ellipsis;}
471
- [data-testid="audit-table"] td[data-label="Verdict"], .audit-group table td[data-label="Verdict"]{order:4;flex:0 1 auto;max-width:9em;overflow:hidden;text-overflow:ellipsis;}
607
+ [data-testid="audit-table"] td[data-label="Verdict"], .audit-group table td[data-label="Verdict"]{order:4;flex:0 1 auto;max-width:9em;white-space:normal;overflow-wrap:anywhere;}
472
608
  [data-testid="audit-table"] td.am-cost, .audit-group table td.am-cost{order:5;flex:0 0 auto;}
473
609
  [data-testid="audit-table"] td.am-time, .audit-group table td.am-time{order:6;flex:0 0 auto;color:var(--text-dim);}
474
610
  /* no step cell (grouped view): the verdict takes the slack so cost and time sit at the right */
@@ -486,6 +622,39 @@
486
622
  td.am-detail .am-d{margin:0 0 3px;}
487
623
  td.am-detail .am-d b{color:var(--text);font-weight:600;}
488
624
  }
625
+
626
+ /* M4d piece 4: the Settings view (a sibling of #main-view, opened from the header). Layout borrowed from bareloop:
627
+ one provider table inside a scrolling .table-wrap, a KEYS strip, a money strip. Inputs are 16px so a phone does not zoom. */
628
+ /* borrowed-from: bareloop src/panel/index.html@5a5a811 */
629
+ .settings-view{flex:1;min-height:0;overflow:auto;display:flex;flex-direction:column;min-width:0;}
630
+ .settings-view .pane-body{flex:none;overflow:visible;}
631
+ .settings-header{display:flex;align-items:center;gap:12px;padding:10px 16px;border-bottom:2px solid var(--border-strong);background:var(--panel);}
632
+ .settings-header h2{margin:0;font-size:15px;display:inline;}
633
+ .settings-header h2::before{content:"┤ ";color:var(--text-faint);}
634
+ .settings-header h2::after{content:" ├";color:var(--text-faint);}
635
+ .money-strip{display:grid;grid-template-columns:repeat(3, 1fr);gap:12px;align-items:end;padding:10px;border:1px solid var(--border-strong);background:var(--panel2);}
636
+ .money-item{min-width:0;}
637
+ .money-item label{display:block;font-size:11px;font-weight:700;color:var(--text-dim);margin-bottom:2px;}
638
+ .money-value{font-size:16px;font-weight:700;padding:6px 0;overflow-wrap:anywhere;}
639
+ .money-item input{width:100%;height:44px;box-sizing:border-box;}
640
+ .keyfile-strip{position:relative;border:1px solid var(--border-strong);padding:12px 12px 8px;background:var(--panel2);margin:14px 0;font-size:12px;display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;}
641
+ .keyfile-strip::before{content:"┤ KEYS ├";position:absolute;top:-9px;left:10px;background:var(--panel2);padding:0 4px;font-size:11px;color:var(--text-faint);letter-spacing:0.08em;}
642
+ .keyfile-strip-main{display:flex;flex-direction:column;gap:3px;flex:1;min-width:0;overflow-wrap:anywhere;}
643
+ .keyfile-strip-actions{display:flex;gap:6px;flex:none;}
644
+ .keyfile-strip code{background:var(--bg);border:1px solid var(--border-strong);padding:1px 5px;font-size:11px;color:var(--amber);overflow-wrap:anywhere;}
645
+ .settings-view input,.settings-view select{font:inherit;padding:6px 8px;border:1px solid var(--border-strong);border-radius:0;background:var(--bg);color:var(--text);}
646
+ .pv-table td,.pv-table th{white-space:nowrap;vertical-align:top;}
647
+ .pv-table select,.pv-table input{min-height:32px;max-width:190px;box-sizing:border-box;}
648
+ .pv-table .hint{display:block;margin-top:3px;}
649
+ /* the Test cell keeps ONE width whatever the result says ("testing…", "OK · 312 ms", a long failure note) */
650
+ .pv-table td.pv-test-cell{width:180px;min-width:180px;max-width:180px;}
651
+ .pv-table .pv-test-result,.pv-table .pv-msg,.pv-table .pv-balance-result{white-space:normal;overflow-wrap:anywhere;}
652
+ .pv-table td.pv-price-cell{width:170px;min-width:170px;max-width:170px;}
653
+ .hint.bad{color:var(--red);}
654
+ .table-wrap{overflow-x:auto;border:1px solid var(--border-strong);background:var(--panel2);max-width:100%;}
655
+ @media (max-width: 899px){
656
+ .money-strip{grid-template-columns:1fr 1fr;}
657
+ }
489
658
  </style>
490
659
  </head>
491
660
  <body>
@@ -499,10 +668,73 @@
499
668
  </div>
500
669
  <div class="topbar-right">
501
670
  <span class="hint" id="host-line"></span>
671
+ <button class="btn small" id="settings-open" type="button" data-testid="settings-open">&#9881; Settings</button>
502
672
  <button class="theme-toggle" id="theme-toggle" type="button" aria-label="Toggle light/dark theme">&#9789;</button>
503
673
  </div>
504
674
  </header>
505
675
 
676
+ <!-- borrowed-from: bareloop src/panel/index.html@5a5a811 -->
677
+ <div class="settings-view" id="settings-view" data-testid="settings-view" hidden>
678
+ <div class="settings-header">
679
+ <button class="btn small" id="settings-back" type="button" data-testid="settings-back">&larr; Back</button>
680
+ <h2>Settings</h2>
681
+ </div>
682
+ <div class="tabrow" role="tablist" aria-label="Settings views">
683
+ <button role="tab" id="stab-providers" aria-controls="spanel-providers" aria-selected="true" data-testid="settings-tab-providers">Providers</button>
684
+ <button role="tab" id="stab-money" aria-controls="spanel-money" aria-selected="false" data-testid="settings-tab-money">Money &amp; limits</button>
685
+ </div>
686
+ <div class="pane-body">
687
+ <section id="spanel-providers" class="tabpanel active" role="tabpanel" aria-labelledby="stab-providers">
688
+ <div class="keyfile-strip" data-testid="keys-strip">
689
+ <div class="keyfile-strip-main">
690
+ <span>Put <code>NAME=key</code> lines in <code id="keys-path" data-testid="keys-path">~/.config/fwdloop/.env</code>, then Reload keys &mdash; each row below says whether its key is set. Only names are listed; keys never reach this page.</span>
691
+ <span class="hint bad" id="keys-refusal" data-testid="keys-refusal"></span>
692
+ </div>
693
+ <div class="keyfile-strip-actions">
694
+ <button class="btn small" id="reload-keys" type="button" data-testid="reload-keys">Reload keys</button>
695
+ </div>
696
+ </div>
697
+ <div class="table-wrap" data-testid="provider-table-wrap">
698
+ <table class="pv-table" data-testid="provider-table">
699
+ <thead>
700
+ <tr><th>Key</th><th>Name</th><th>API shape</th><th>Base URL</th><th>Test</th><th>Tokens used</th><th>Balance</th><th>In $/1M</th><th>Out $/1M</th></tr>
701
+ </thead>
702
+ <tbody id="pv-rows"></tbody>
703
+ </table>
704
+ </div>
705
+ <div class="hint" id="pv-note" data-testid="pv-note" style="margin-top:6px;">Test asks the provider for its model list &mdash; it costs nothing. A price left empty uses the default; a typed price applies from the next model call on.</div>
706
+ </section>
707
+ <section id="spanel-money" class="tabpanel" role="tabpanel" aria-labelledby="stab-money" hidden>
708
+ <div class="money-strip" data-testid="money-strip">
709
+ <div class="money-item">
710
+ <label>$ month / to date</label>
711
+ <div class="money-value" id="ml-usd" data-testid="ml-usd">&hellip;</div>
712
+ </div>
713
+ <div class="money-item">
714
+ <label>Tokens month / to date</label>
715
+ <div class="money-value" id="ml-tokens" data-testid="ml-tokens">&hellip;</div>
716
+ </div>
717
+ <div class="money-item">
718
+ <label for="ml-money">Monthly money limit ($)</label>
719
+ <input id="ml-money" type="text" inputmode="decimal" placeholder="blank = no limit" data-testid="ml-money">
720
+ </div>
721
+ </div>
722
+ <div class="hint" id="ml-note" data-testid="ml-note" style="margin-top:6px;">Limits are yours. The agent can never change them. A run whose cap is more than what is left this month does not start.</div>
723
+ <div class="hint" id="ml-extra" data-testid="ml-extra"></div>
724
+ <div class="hint" id="ml-msg" data-testid="ml-msg"></div>
725
+ <h4 style="margin-top:20px;font-size:13px;">Per-provider breakdown</h4>
726
+ <div class="table-wrap">
727
+ <table data-testid="provider-breakdown-table">
728
+ <thead>
729
+ <tr><th>Provider</th><th>$ month / to date</th><th>minutes month / to date</th><th>tokens</th></tr>
730
+ </thead>
731
+ <tbody id="ml-breakdown"></tbody>
732
+ </table>
733
+ </div>
734
+ </section>
735
+ </div>
736
+ </div>
737
+
506
738
  <div class="main" id="main-view">
507
739
 
508
740
  <nav class="left-pane" aria-label="Job navigation" id="left-pane-anchor">
@@ -515,13 +747,161 @@
515
747
  <div class="pane-body" id="left-pane-body">
516
748
 
517
749
  <section id="panel-chat" class="tabpanel active" role="tabpanel" aria-labelledby="tab-chat">
518
- <div class="chat-thread">
519
- Authoring a flow from this page isn't built yet — the drafter is a POC. This
520
- panel shows flows and runs already started from the
521
- <code>fwdloop</code> CLI, and lets you answer an ask that is waiting on you
522
- (accept, redo or rerun, with a reason). It cannot start a run. Use the Runs
523
- tab to open one, or the Inbox tab for anything waiting on you.
750
+ <!-- borrowed-from: bareloop src/panel/index.html@ca7195e (Chat markup: the one always-there card, top-right Abandon/Clear,
751
+ the thread, the one progress list, the action-error line the poll never wipes, the ask box, the ONE wide button).
752
+ fwdloop fields: Flow name, The job, Cap $, Destination, Inputs (New job) or a signed flow's inputs (Run a signed flow). -->
753
+ <div class="job-card compact" id="chat-job-card" data-testid="job-card">
754
+ <h4 id="job-card-title">Job card</h4>
755
+ <button class="btn card-clear" type="button" id="chat-clear-btn" data-testid="chat-clear">Clear</button>
756
+
757
+ <div class="radio-row" id="jf-mode-row" role="radiogroup" aria-label="What to do" data-testid="jf-mode">
758
+ <label><input type="radio" name="jf-mode" value="new" checked> New job</label>
759
+ <label><input type="radio" name="jf-mode" value="run"> Run a signed flow</label>
760
+ </div>
761
+
762
+ <div id="jf-new" data-testid="jf-new">
763
+ <div class="field">
764
+ <label for="jf-name">Flow name</label>
765
+ <input id="jf-name" type="text" placeholder="lowercase letters, digits, - or _" autocomplete="off" spellcheck="false" data-testid="jf-name">
766
+ <div class="jf-err" id="jf-err-flowName" data-testid="jf-err-flowName"></div>
767
+ </div>
768
+ <div class="field">
769
+ <label for="jf-job">The job</label>
770
+ <div class="jf-gutbox">
771
+ <div class="jf-gut" id="jf-job-gut" data-testid="jf-job-gut" aria-hidden="true"><div class="jf-gut-in"></div></div>
772
+ <textarea class="jf-wrap" id="jf-job" rows="6" data-testid="jf-job" autocomplete="off" spellcheck="false" placeholder="Read my resume&#10;~keep it under 600 words&#10;Ask: check it with me&#10;Write it out"></textarea>
773
+ </div>
774
+ <div class="hint">One step per line. A line starting with <code>~</code> is a guardrail of the step above it. <code>Ask:</code> stops for you; <code>Ask 2h:</code> sets that ask's own wait.</div>
775
+ <div class="jf-err" id="jf-err-job" data-testid="jf-err-job"></div>
776
+ </div>
777
+ <div class="field">
778
+ <label for="jf-dest-folder">Destination</label>
779
+ <input id="jf-dest-folder" type="text" placeholder="/full/path/to/a/folder" autocomplete="off" spellcheck="false" data-testid="jf-dest-folder">
780
+ <div class="hint">Where the accepted result is placed, at the last step. Leave empty for no send.</div>
781
+ <div class="jf-err" id="jf-err-destination" data-testid="jf-err-destination"></div>
782
+ </div>
783
+ <div class="field">
784
+ <label for="jf-inputs">Inputs</label>
785
+ <div class="jf-gutbox">
786
+ <div class="jf-gut" id="jf-inputs-gut" data-testid="jf-inputs-gut" aria-hidden="true"><div class="jf-gut-in"></div></div>
787
+ <textarea class="jf-wrap" id="jf-inputs" rows="3" data-testid="jf-inputs" autocomplete="off" spellcheck="false" placeholder="resume: /full/path/to/resume.md"></textarea>
788
+ </div>
789
+ <div class="hint">One line per file: a name, a colon, its full path starting with /. The page never reads the file.</div>
790
+ <div class="jf-err" id="jf-err-inputs" data-testid="jf-err-inputs"></div>
791
+ </div>
792
+ <div class="cap-row" data-testid="cap-row">
793
+ <div class="cap-field">
794
+ <label for="jf-cap-money">Cap $</label>
795
+ <input id="jf-cap-money" type="text" inputmode="decimal" placeholder="per run" data-testid="jf-cap-money">
796
+ <div class="hint" id="jf-cap-note" data-testid="cap-note"></div>
797
+ <div class="jf-err" id="jf-err-capUsd" data-testid="jf-err-capUsd"></div>
798
+ </div>
799
+ <div class="cap-field">
800
+ <label for="jf-ask-wait">Ask wait</label>
801
+ <input id="jf-ask-wait" type="text" value="1h" autocomplete="off" spellcheck="false" data-testid="jf-ask-wait">
802
+ <div class="hint">For each <code>Ask:</code> step. Number + m or h.</div>
803
+ <div class="jf-err" id="jf-err-askWait" data-testid="jf-err-askWait"></div>
804
+ </div>
805
+ </div>
806
+ </div>
807
+
808
+ <div id="jf-run" data-testid="jf-run" hidden>
809
+ <div class="field">
810
+ <label for="jf-run-flow">Signed flow</label>
811
+ <!-- borrowed-from: bareloop src/panel/index.html@b5e37b8 (its job picker): a search box over the list, then the picked box with `change` -->
812
+ <div class="rw-box" id="rw-search" data-testid="rw-search">
813
+ <input id="jf-run-flow" type="text" placeholder="type part of a flow or run name (run-2)…" autocomplete="off" spellcheck="false" data-testid="jf-run-flow">
814
+ <ul class="rw-list" id="rw-list" data-testid="rw-list"></ul>
815
+ </div>
816
+ <div class="rw-picked" id="rw-picked" data-testid="rw-picked" hidden><span id="rw-picked-txt" data-testid="rw-picked-txt"></span><a id="rw-change" data-testid="rw-change" role="button" tabindex="0">change</a></div>
817
+ <div class="hint" id="jf-run-empty" data-testid="jf-run-empty"></div>
818
+ <div class="jf-err" id="jf-err-flow" data-testid="jf-err-flow"></div>
819
+ </div>
820
+ <div class="field dimmed" data-testid="jf-run-job-field">
821
+ <label>The job</label>
822
+ <div class="ro-lines" id="jf-run-job" data-testid="jf-run-job"></div>
823
+ <div class="hint">Fixed by the signature (the steps, the job lines and the asks). To change one, start a new job.</div>
824
+ </div>
825
+ <div class="field">
826
+ <label for="jf-run-dest">Destination</label>
827
+ <input id="jf-run-dest" type="text" placeholder="/full/path/to/a/folder" autocomplete="off" spellcheck="false" data-testid="jf-run-dest">
828
+ <div class="hint" id="jf-run-dest-hint" data-testid="jf-run-dest-hint"></div>
829
+ <div class="jf-err" id="jf-err-run-destination" data-testid="jf-err-run-destination"></div>
830
+ </div>
831
+ <div class="field">
832
+ <label>Inputs</label>
833
+ <div id="jf-run-inputs" data-testid="jf-run-inputs"></div>
834
+ <div class="jf-err" id="jf-err-run-inputs" data-testid="jf-err-run-inputs"></div>
835
+ </div>
836
+ <div class="cap-row">
837
+ <div class="cap-field">
838
+ <label for="jf-run-cap">Cap $</label>
839
+ <input id="jf-run-cap" type="text" inputmode="decimal" autocomplete="off" data-testid="jf-run-cap">
840
+ <div class="hint" id="jf-run-left" data-testid="jf-run-left"></div>
841
+ <div class="jf-err" id="jf-err-run-capUsd" data-testid="jf-err-run-capUsd"></div>
842
+ </div>
843
+ <div class="cap-field" id="jf-run-waits" data-testid="jf-run-waits"></div>
844
+ </div>
845
+ <div class="jf-err" id="jf-err-run-askWaits" data-testid="jf-err-run-askWaits"></div>
846
+ <div class="hint" id="jf-run-sign-hint" data-testid="jf-run-sign-hint">A different destination, cap or ask wait is signed for this run only: two clicks. The flow's own values never change.</div>
847
+ <div class="field">
848
+ <label for="jf-run-id">Run id</label>
849
+ <input id="jf-run-id" type="text" autocomplete="off" spellcheck="false" data-testid="jf-run-id">
850
+ <div class="jf-err" id="jf-err-runId" data-testid="jf-err-runId"></div>
851
+ </div>
852
+ </div>
853
+
854
+ <div id="jf-resume" data-testid="jf-resume" hidden>
855
+ <div class="field dimmed" data-testid="jf-resume-job-field">
856
+ <label>The job</label>
857
+ <div class="ro-lines" id="jf-resume-job" data-testid="jf-resume-job"></div>
858
+ </div>
859
+ <div class="field dimmed">
860
+ <label>Destination</label>
861
+ <div class="ro-lines" id="jf-resume-dest" data-testid="jf-resume-dest"></div>
862
+ </div>
863
+ <div class="field dimmed">
864
+ <label>Inputs</label>
865
+ <div class="ro-lines" id="jf-resume-inputs" data-testid="jf-resume-inputs"></div>
866
+ </div>
867
+ <div class="field dimmed">
868
+ <label>Ask wait</label>
869
+ <div class="ro-lines" id="jf-resume-waits" data-testid="jf-resume-waits"></div>
870
+ </div>
871
+ <div class="cap-row">
872
+ <div class="cap-field">
873
+ <label for="jf-resume-cap">Cap $</label>
874
+ <input id="jf-resume-cap" type="text" inputmode="decimal" autocomplete="off" data-testid="jf-resume-cap">
875
+ <div class="hint" id="jf-resume-left" data-testid="jf-resume-left"></div>
876
+ <div class="jf-err" id="jf-err-resume-capUsd" data-testid="jf-err-resume-capUsd"></div>
877
+ </div>
878
+ </div>
879
+ <div class="hint" id="jf-resume-hint" data-testid="jf-resume-hint"></div>
880
+ </div>
881
+
882
+ <div class="hint" id="chat-card-error" data-testid="chat-card-error"></div>
524
883
  </div>
884
+
885
+ <!-- ONE progress list: every step is one line that updates in place; a waiting step has no check -->
886
+ <ol class="chat-steps" id="chat-progress-row" data-testid="chat-steps" aria-live="polite" hidden></ol>
887
+
888
+ <!-- M4e amendment 6 item 3: bubbles (oldest first), then the current plan, then the note box and the main button: the plan sits next to Sign & run -->
889
+ <div class="chat-thread" id="chat-thread" data-testid="chat-thread"></div>
890
+
891
+ <!-- a refused draft / run / sign / abandon POST (or a refused start) shows here and STAYS: set only by this tab's own
892
+ action handlers, never cleared by the poll (the poll owns #chat-card-error instead) -->
893
+ <div class="hint" id="chat-action-error" data-testid="chat-action-error"></div>
894
+
895
+ <!-- M4e amendment 3 item 3: opens when a green plan shows (bareloop's ask box); a typed note turns the main button into Send -->
896
+ <div class="chat-input-row" id="chat-msg-row" data-testid="chat-msg-row" hidden>
897
+ <label for="chat-msg" style="display:none">Message</label>
898
+ <textarea id="chat-msg" rows="2" placeholder="Ask for a change to the plan" autocomplete="off" data-testid="chat-msg"></textarea>
899
+ </div>
900
+ <button class="btn primary wide" type="button" id="chat-main-btn" data-testid="chat-main" disabled>Draft</button>
901
+ <div class="hint" id="chat-main-hint" data-testid="chat-main-hint"></div>
902
+ <!-- M4e amendment 4 item 3: after the second change the ask box is closed; Start over drafts again from the card as it is (a fresh draft) -->
903
+ <button class="btn wide" type="button" id="chat-startover-btn" data-testid="chat-startover" hidden>Start over</button>
904
+ <div class="hint">Only your click signs.</div>
525
905
  </section>
526
906
 
527
907
  <section id="panel-inbox" class="tabpanel" role="tabpanel" aria-labelledby="tab-inbox" hidden>
@@ -572,6 +952,7 @@
572
952
  <section id="panel-run" class="tabpanel active" role="tabpanel" aria-labelledby="tab-run">
573
953
  <div id="run-empty" class="hint" style="font-size:13px;padding:24px 0;">select a run from Workflows or History</div>
574
954
  <div id="run-content" hidden>
955
+ <div class="run-actions" id="run-actions" data-testid="run-actions" hidden></div>
575
956
  <div class="counters" id="run-counters" data-testid="live-counters"></div>
576
957
  <div class="summary-box" id="run-summary" data-testid="run-summary"></div>
577
958
  <div class="map-box" data-testid="step-map" id="map-box"><div id="map-mount"></div></div>
@@ -628,7 +1009,7 @@
628
1009
  piece within a field — replaces the old split asks/sends/
629
1010
  sources/signed-lines blocks. Field order (signed): Job
630
1011
  (prose) · Ask · Model · $ cap (+ redo cap) · Source ·
631
- Destination · Guardrails · Success · Signed. At 390px every
1012
+ Destination · Success · Signed (M4e amendment 6: each guardrail sits under its own line in Job). At 390px every
632
1013
  field's own `label` already sits above its value (the
633
1014
  existing global `label{display:block}` rule — no separate
634
1015
  narrow-width override needed). -->
@@ -641,7 +1022,6 @@
641
1022
  <div class="field"><label>Ask</label><div id="details-asks"></div></div>
642
1023
  <div class="field"><label>Source</label><div id="details-sources"></div></div>
643
1024
  <div class="field"><label>Destination</label><div id="details-sends"></div></div>
644
- <div class="field"><label>Guardrails</label><div id="details-guardrails"></div></div>
645
1025
  <div class="field"><label>Success</label><div id="details-success"></div></div>
646
1026
  <div class="field"><label>Signed</label><div class="ro-value" id="details-signature">—</div></div>
647
1027
  </div>
@@ -679,8 +1059,7 @@
679
1059
  "use strict";
680
1060
 
681
1061
  var PORT = "__FWDLOOP_PANEL_PORT__";
682
- // M4c-fix item 2: the page carries NO token. The panel link sets an HttpOnly cookie; every
683
- // request (reads and the two POSTs) is authenticated by that cookie, sent by the browser itself.
1062
+ // No token, no cookie (M4e amendment 4 item 8): the panel is local and trusted; the server checks Host and, on a POST, Origin.
684
1063
  document.getElementById("host-line").textContent = "127.0.0.1:" + PORT;
685
1064
 
686
1065
  function wireTabs(tabButtons){
@@ -703,8 +1082,8 @@
703
1082
 
704
1083
  // ---- fetch helpers. Reads are GET. The ONLY non-GET requests on this page are
705
1084
  // the two POSTs below (M4b): /api/answer (a human clicking a door) and
706
- // /api/resume ("try the resume again"). Auth is the HttpOnly cookie
707
- // (never the DOM, a URL, storage or a log). Same-origin. ----
1085
+ // /api/resume ("try the resume again"). No auth header (the server checks Host and
1086
+ // Origin). Same-origin. ----
708
1087
  function getJSON(path){
709
1088
  return fetch(path, { method: "GET", headers: { accept: "application/json" } }).then(function(r){
710
1089
  if(!r.ok){ var err = new Error(path + ": HTTP " + r.status); err.status = r.status; throw err; }
@@ -715,7 +1094,7 @@
715
1094
  // message (it carries the path and the HTTP code), never a status number.
716
1095
  function loadFailureText(e){
717
1096
  var status = e && e.status;
718
- if(status === 403) return "The panel does not recognise this page. Open the link the terminal printed.";
1097
+ if(status === 403) return "The panel does not recognise this page. Reload it.";
719
1098
  if(status === 404) return "This run is no longer there.";
720
1099
  return "Could not load this; reload the page.";
721
1100
  }
@@ -758,7 +1137,15 @@
758
1137
  // recorded" in that middle slot instead of a number; a row with no model
759
1138
  // call at all (an ask/hitl row) drops the tokens slot entirely — never a
760
1139
  // fake "0 tokens".
1140
+ // a Sign & run row's ask waits read through plainWait (same as the Job tab); every other row's gap is as recorded
1141
+ function auditGapText(r){
1142
+ if(!Array.isArray(r.gapWaits) || !r.gapWaits.length) return r.gap || "";
1143
+ var waits = r.gapWaits.map(function(w){ return "line " + w.line + ": " + (typeof w.waitMs === "number" ? plainWait(w.waitMs) : w.wait); }).join(", ");
1144
+ return (r.gapHead || []).concat(["ask waits " + waits]).join(" · ");
1145
+ }
761
1146
  function auditCostCellText(r){
1147
+ if(r.setup && typeof r.usd !== "number" && r.verdict === "hitl") return "—"; // a setup row you wrote (card, note, sign) has no cost
1148
+ if(r.setup) return money(r.usd, r.spendComplete) + (typeof r.wallMs === "number" ? " \u00b7 " + duration(r.wallMs) : ""); // a draft/change row: its own booked cost ("unknown" when nobody booked it) and time (left out when not recorded)
762
1149
  var bits = [money(r.usd, r.spendComplete)];
763
1150
  var td = r.tokensDisplay;
764
1151
  if(td && td.kind === "total") bits.push(td.total + " tokens");
@@ -809,6 +1196,76 @@
809
1196
  if(m >= 1 && Number.isInteger(m)) return m + " min";
810
1197
  return duration(ms);
811
1198
  }
1199
+ // M4e amendment 7 item 7 (hamr's ruling 2026-10-06): the second line of a Signed flow row — bareloop's reuse-estimate shape
1200
+ // (borrowed-from: bareloop src/panel/server.js@1927350 `reuseLine`) with fwdloop's own first part. What is unknown is said, never
1201
+ // rendered as $0 or 0 time; the money and the time go through the page's one money() and duration().
1202
+ function countWord(n, word){ return n + " " + word + (n === 1 ? "" : "s"); }
1203
+ function flowStatLine(f){
1204
+ var s = (f && f.stats) || {};
1205
+ var head = countWord(s.steps || 0, "step") + " · " + countWord(s.asks || 0, "ask") + " · " + (s.green || 0) + " green · " + (s.notGreen || 0) + " not green";
1206
+ var cost = typeof s.avgSpendUsd === "number" ? money(s.avgSpendUsd) : null;
1207
+ var time = typeof s.avgWallMs === "number" ? duration(s.avgWallMs) : null;
1208
+ if(cost !== null && time !== null) return head + " · about " + cost + " and " + time + " a run";
1209
+ if(cost !== null) return head + " · about " + cost + " a run, time not recorded";
1210
+ if(time !== null) return head + " · about " + time + " a run, cost not recorded";
1211
+ return head + " · cost and time not recorded";
1212
+ }
1213
+ // The rows the Signed flow search shows for what is typed: a flow whose name has the text; and, for any text, each passed run whose
1214
+ // name has it (`run-2` lists every flow's run-2 as "<flow> (run-2)"; typing the whole "<flow> (run-2)" finds it too). Empty text = every flow.
1215
+ function flowChoices(flows, text){
1216
+ var q = String(text || "").trim().toLowerCase();
1217
+ var out = [];
1218
+ (flows || []).forEach(function(f){
1219
+ if(q === "" || f.flow.toLowerCase().indexOf(q) !== -1) out.push({flow: f.flow, runId: null, label: f.flow, meta: flowStatLine(f)});
1220
+ });
1221
+ if(q !== ""){
1222
+ (flows || []).forEach(function(f){
1223
+ (f.runs || []).forEach(function(r){
1224
+ var label = f.flow + " (" + r.runId + ")";
1225
+ if(r.runId.toLowerCase().indexOf(q) !== -1 || (q.indexOf("(") !== -1 && label.toLowerCase().indexOf(q) !== -1)) out.push({flow: f.flow, runId: r.runId, label: label, meta: flowStatLine(f)});
1226
+ });
1227
+ });
1228
+ }
1229
+ return out;
1230
+ }
1231
+ // M4e amendment 9: the model-calls words, ONE function for the card's line 2 and the Audit header: `<n> model calls` (`1 model call`), `at least <n> model calls`
1232
+ // when a draft/change row recorded no `calls` (it counts 1), `calls unknown` with no model row.
1233
+ function draftCallsWord(d){
1234
+ if(typeof d.calls !== "number") return "calls unknown";
1235
+ return (d.callsAtLeast ? "at least " : "") + countWord(d.calls, "model call");
1236
+ }
1237
+ // M4e amendment 7 item 2 / 9: the Draft's one line in the Audit group's header: `drafting · <time> · $<cost> · <n> model calls · ✓`.
1238
+ // `d` is the server's one Draft summary (src/panel/data.js `draftTotals`): a figure not recorded reads "unknown", never 0; a flow signed before
1239
+ // amendment 6 reads "no draft record" and no cost.
1240
+ // The Draft's three figures, ONE function for the card's line 2, the Audit header and its aria: `<time> · $<cost> · <n> model calls`.
1241
+ function draftFigures(d){
1242
+ return [typeof d.timeMs === "number" ? duration(d.timeMs) : "time unknown", d.cost || "cost unknown", draftCallsWord(d)];
1243
+ }
1244
+ // M4e amendment 11: the human-checks words, ONE function for the drafting card's line 2 and the Audit Draft header (`1 human check`, `2 human checks`).
1245
+ function draftHumanWord(d){
1246
+ return typeof d.humanChecks === "number" ? countWord(d.humanChecks, "human check") : "human checks unknown";
1247
+ }
1248
+ // M4e amendment 10 item 2: with the step card's status first: `[✓] passed · drafting · <time> · $<cost> · <n> model calls ✓` (signed), `not signed · drafting · ...`
1249
+ // plain (no sign row, no mark), `drafting · no draft record` (no draft record, no status). The Audit header's visible words come from the same
1250
+ // `auditGroupHeaderParts`, so this is the aria line too.
1251
+ function draftLineText(d){
1252
+ var p = auditGroupHeaderParts({draft: true, summary: d});
1253
+ return [p.status, p.name].concat(p.draftFigs || [p.why]).filter(function(x){ return x; }).join(" \u00b7 ") + (p.passed ? " \u2713" : "");
1254
+ }
1255
+ // M4e amendment 9: the drafting card, step 0 of the Run tab, from ONE function: `title` (`0 · drafting`, bold h4), `status` (the step card's `stateWord`: `[✓] passed`
1256
+ // with a sign row, plain `not signed` without; none for a flow with no draft record), then `lines`: `<time> · $<cost> · <n> model calls · <h> human checks · ✓`
1257
+ // (a figure not recorded reads unknown, never 0; the mark only on passed) and what happened (`d.happened`, joined by ` · `). Same `draftTotals` as the Audit header.
1258
+ function draftCardLines(d){
1259
+ if(!d || !d.present) return {title: "0 \u00b7 drafting", status: null, passed: false, lines: [(d && d.why) || "no draft record"]};
1260
+ var passed = d.ended === "done";
1261
+ var figs = draftFigures(d).concat([draftHumanWord(d)]);
1262
+ if(passed) figs.push("\u2713");
1263
+ return {title: "0 \u00b7 drafting", status: passed ? stateWord("done") : "not signed", passed: passed, lines: [figs.join(" \u00b7 "), (d.happened || []).join(" \u00b7 ")]};
1264
+ }
1265
+ // The Map's first box: the Draft, then step 1. A box with no audit attempts of its own; its state word says "no draft record" when there is none.
1266
+ function draftBox(d){
1267
+ return {draft: true, emits: "drafting", goal: "", closeClass: null, primitives: [], attempts: [], tryCount: 0, tryMarks: [], state: d && d.present ? "done" : "pending", noRecord: !(d && d.present), n: 0};
1268
+ }
812
1269
  // A readable local date/time instead of a raw ISO timestamp (fix #5) — an
813
1270
  // unparseable value still shows the raw string (never blank/nothing), so
814
1271
  // a books bug is visible rather than silently swallowed.
@@ -827,7 +1284,7 @@
827
1284
  // M4c-fix amendment 2 (g): a step's own sign + word come from the SAME one table the run rows use (the server's
828
1285
  // SIGN_WORDS, sent on the run detail as `signWords`); the page keeps no table of its own. Not started: no sign.
829
1286
  var signWords = {};
830
- var STEP_SIGN = { done: "[\u2713]", stopped: "[\u2717]", waiting: "[\u00b7]" };
1287
+ var STEP_SIGN = { done: "[\u2713]", stopped: "[\u2717]", waiting: "[\u00b7]", "user-stopped": "[\u25a0]" };
831
1288
  function stateWord(state){
832
1289
  if(state === "pending") return "not started";
833
1290
  var g = STEP_SIGN[state];
@@ -894,6 +1351,9 @@
894
1351
  if(verdict === "ask-timeout" || verdict === "ask-expired") return "expired waiting for you";
895
1352
  if(verdict === "ask-reopened") return "reopened by you";
896
1353
  if(verdict === "lock-removed") return "old lock removed by you";
1354
+ if(verdict === "stop-asked") return "stop asked by you";
1355
+ if(verdict === "stopped") return "stopped by you";
1356
+ if(verdict === "stop-not-honoured") return "stop not honoured";
897
1357
  if(verdict === "green") return "passed";
898
1358
  if(verdict === "hitl") return "human check";
899
1359
  if(verdict === "not-done") return "not done";
@@ -907,6 +1367,7 @@
907
1367
  function verdictGlyph(verdict, closeClass){
908
1368
  if(closeClass === "hitl" && verdict === "red") return null;
909
1369
  if(verdict === "paused" || verdict === "refused" || verdict === "ask-timeout" || verdict === "ask-expired" || verdict === "ask-reopened" || verdict === "lock-removed") return null;
1370
+ if(verdict === "stop-asked" || verdict === "stopped" || verdict === "stop-not-honoured") return null; // amendment 7 item 8: a Stop is neither a pass nor a failure
910
1371
  return verdictPassed(verdict) ? "✓" : "✗";
911
1372
  }
912
1373
  // The run-row glyph strings src/panel/data.js's computeGlyph emits are
@@ -934,6 +1395,7 @@
934
1395
  // (never "amber", which draws the reserved running arrow [▶]).
935
1396
  if(g === "[!]") return "expired";
936
1397
  if(g === "[II]") return "stuck";
1398
+ if(g === "[■]") return "stopped";
937
1399
  return "grey"; // "[·]" — waiting on a human, or answered-not-resumed
938
1400
  }
939
1401
 
@@ -945,6 +1407,7 @@
945
1407
  if(state === "done") return {stroke:"var(--green)", textFill:"#2e7d32"};
946
1408
  if(state === "stopped") return {stroke:"var(--red)", textFill:"var(--red)"};
947
1409
  if(state === "waiting") return {stroke:"var(--amber)", textFill:"#b8860b"};
1410
+ if(state === "user-stopped") return {stroke:"var(--grey-dot)", textFill:"var(--grey-dot)"}; // a Stop the human asked: grey, never red
948
1411
  return {stroke:"var(--border-strong)", textFill:"var(--text-faint)"}; // not started yet
949
1412
  }
950
1413
  var stepMapUidCounter = 0;
@@ -979,24 +1442,14 @@
979
1442
  // step number + name + try N + state, kept short so naturalBoxWidth stays
980
1443
  // small and the map stays compact instead of stretching to the pane width.
981
1444
  function stepTitleText(idx, s){
982
- var base = (idx + 1) + ' ' + s.emits;
1445
+ if(s.draft) return "drafting";
1446
+ var base = (s.n || idx + 1) + ' ' + s.emits;
983
1447
  var tryText = tryCountText(s.tryCount, s.attempts);
984
1448
  if(tryText) base += ' — ' + tryText;
985
1449
  return base;
986
1450
  }
987
- // The declared step's own run-state, for the map box and the summary's
988
- // "which step stopped and why" (M4a exit: "say which step stopped it and
989
- // why, from one screen"): `pending` (no attempt yet), `done` (last
990
- // attempt passed), `waiting` (the run is currently parked ON this step —
991
- // its last attempt's verdict is `paused`/`refused`, i.e. it went to a
992
- // human ask and hasn't been answered/resolved yet), `stopped` (a real
993
- // stop — the last attempt failed for any other reason).
994
- function stepBoxState(s){
995
- if(!s.attempts || !s.attempts.length) return "pending";
996
- var last = s.attempts[s.attempts.length - 1];
997
- if(last.verdict === "paused" || last.verdict === "refused") return "waiting";
998
- return verdictPassed(last.verdict) ? "done" : "stopped";
999
- }
1451
+ // The declared step's own run-state (map box, card, "which step stopped and why") is the server's `groupState` (src/panel/data.js
1452
+ // `deriveStepGroupState`, M4e amendment 10: the one decider): `pending` (no row yet), `done`, `waiting`, `stopped` (red), `user-stopped` (a Stop).
1000
1453
  // hamr's 2026-09-27 review: a step with a server-computed `tryCount > 1`
1001
1454
  // (M2/M3's runner already counts retries/redraft attempts honestly — never
1002
1455
  // recounted here from `attempts.length`, which double-counts an ask step's
@@ -1025,7 +1478,7 @@
1025
1478
  // book-derived list, never guessed from `primitives` by exclusion.
1026
1479
  toolsTotal: s.toolsTotal || null, toolsWhy: s.toolsWhy || null, ungranted: s.ungranted || [],
1027
1480
  stoppedReason: s.stoppedReason || null,
1028
- state: stepBoxState(s),
1481
+ state: s.groupState || "pending", // the server's one decider (deriveStepGroupState); no group = no row yet = not started
1029
1482
  };
1030
1483
  });
1031
1484
  }
@@ -1124,7 +1577,7 @@
1124
1577
  '" text-anchor="middle" font-size="12" fill="var(--text)">' + escapeXml(lines[1]) + '</text>';
1125
1578
  }
1126
1579
  body += '<text x="' + (x + boxW / 2) + '" y="' + stateY +
1127
- '" text-anchor="middle" font-size="10" fill="' + colors.textFill + '">' + escapeXml(stateWord(s.state)) + '</text>';
1580
+ '" text-anchor="middle" font-size="10" fill="' + colors.textFill + '">' + escapeXml(s.noRecord ? "no draft record" : stateWord(s.state)) + '</text>';
1128
1581
  body += '</g>';
1129
1582
  // hamr's 2026-09-27 retry-loop review: a step whose server-computed
1130
1583
  // tryCount is >1 gets a dashed grey self-loop under its box, labelled
@@ -1225,7 +1678,8 @@
1225
1678
  // Workflows view's per-flow expansion — the two never drift on how a run
1226
1679
  // row reads. Rekeyed from bareloop's job/runid to fwdloop's flow/runId
1227
1680
  // (GET /api/runs row shape: src/panel/data.js's listRuns).
1228
- function buildRunRowEl(r){
1681
+ // opts.sub (amendment 12): a Workflows sub-card drops the flow name from its visible text; no other caller passes opts.
1682
+ function buildRunRowEl(r, opts){
1229
1683
  var row = document.createElement("div");
1230
1684
  // Selected state is computed here, off the module's own `currentRunId`,
1231
1685
  // so a row freshly built by a RE-RENDER (switching Runs view mode, or a
@@ -1250,14 +1704,21 @@
1250
1704
  row.removeAttribute("role");
1251
1705
  return row;
1252
1706
  }
1253
- row.innerHTML =
1254
- '<span class="wf-line1"><span class="' + dotClass(r.glyph, r.pulse) + '"></span>' +
1255
- '<span class="wf-name" title="' + escapeXml(fullName) + '">' + escapeXml(fullName) + '</span></span>' +
1256
- '<span class="wf-sign-line" data-testid="run-sign-word">' + signHtml(r.word, r.line, r.label) + '</span>' +
1257
- '<span class="wf-meta-line">' +
1258
- '<span class="wf-meta">' + escapeXml(runSpendText(r)) + '</span>' +
1259
- '<span class="wf-meta">' + escapeXml(runAtText(r)) + '</span>' +
1260
- '</span>';
1707
+ if(opts && opts.sub){
1708
+ // amendment 12: line 1 `(run-<n>) <word> — <label>`; the flow name stays in title/aria only
1709
+ row.setAttribute("aria-label", fullName);
1710
+ row.innerHTML =
1711
+ '<span class="wf-line1"><span class="' + dotClass(r.glyph, r.pulse) + '"></span>' +
1712
+ '<span class="wf-name" title="' + escapeXml(fullName) + '">(' + escapeXml(r.runId) + ')</span> ' +
1713
+ '<span class="wf-sign-line" data-testid="run-sign-word">' + signHtml(r.word, (r.word === 'passed' && r.glyph === '[✓]' && !r.line) ? 'goal met' : r.line, r.label) + '</span></span>' +
1714
+ runMetaLineHtml(r, null);
1715
+ } else {
1716
+ row.innerHTML =
1717
+ '<span class="wf-line1"><span class="' + dotClass(r.glyph, r.pulse) + '"></span>' +
1718
+ '<span class="wf-name" title="' + escapeXml(fullName) + '">' + escapeXml(fullName) + '</span></span>' +
1719
+ '<span class="wf-sign-line" data-testid="run-sign-word">' + signHtml(r.word, r.line, r.label) + '</span>' +
1720
+ runMetaLineHtml(r, null);
1721
+ }
1261
1722
  row.addEventListener("click", function(){ openRunFromRuns(r, row); });
1262
1723
  row.addEventListener("keydown", function(e){ if(e.key === "Enter" || e.key === " "){ e.preventDefault(); row.click(); } });
1263
1724
  return row;
@@ -1313,6 +1774,16 @@
1313
1774
  function runSpendText(r){
1314
1775
  return r.spend || r.spendWhy || "unknown";
1315
1776
  }
1777
+ // M4e amendment 7 item 5: a run's wall time in plain units ("6m23s"), the ONE formatter (`duration`); unrecorded = no part, never a made-up one.
1778
+ function runWallText(r){
1779
+ return typeof r.wallMs === "number" ? duration(r.wallMs) : null;
1780
+ }
1781
+ // ONE builder for a Runs card's last line, job card and sub-card alike: "$0.0616 · 6m23s · 2026-10-06 · 1 run". The separators are real
1782
+ // text between the parts (a CSS ::before is not text: a text read of the card ran "2026-10-061 run" together).
1783
+ function runMetaLineHtml(r, extra){
1784
+ var bits = [runSpendText(r), runWallText(r), runAtText(r), extra].filter(function(b){ return b !== null && b !== undefined; });
1785
+ return '<span class="wf-meta-line">' + bits.map(function(b){ return '<span class="wf-meta">' + escapeXml(b) + '</span>'; }).join('<span class="wf-sep"> · </span>') + '</span>';
1786
+ }
1316
1787
  function runAtText(r){
1317
1788
  return r.at ? r.at.slice(0,10) : (r.askedAt ? "asked " + readableDateTime(r.askedAt) : (r.startedAt ? "started " + readableDateTime(r.startedAt) : (r.atWhy || "unknown")));
1318
1789
  }
@@ -1439,11 +1910,7 @@
1439
1910
  '<span class="wf-line1"><span class="wf-caret">' + (hasOtherRuns ? (expanded ? "▼" : "▶") : "") + '</span><span class="' + dotClass(g.lastGlyph, g.lastRow.pulse) + '"></span>' +
1440
1911
  '<span class="wf-name" title="' + escapeXml(wfFullName) + '">' + escapeXml(wfFullName) + '</span></span>' +
1441
1912
  '<span class="wf-sign-line" data-testid="run-sign-word">' + signHtml(g.lastRow.word, g.lastRow.line, g.lastLabel) + '</span>' +
1442
- '<span class="wf-meta-line">' +
1443
- '<span class="wf-meta">' + escapeXml(runSpendText(g.lastRow)) + '</span>' +
1444
- '<span class="wf-meta">' + escapeXml(runAtText(g.lastRow)) + '</span>' +
1445
- '<span class="wf-meta">' + g.runCount + ' run' + (g.runCount === 1 ? '' : 's') + '</span>' +
1446
- '</span>';
1913
+ runMetaLineHtml(g.lastRow, g.runCount + ' run' + (g.runCount === 1 ? '' : 's'));
1447
1914
  row.addEventListener("click", function(){
1448
1915
  // a single-run flow has nothing to expand — the click still opens
1449
1916
  // the run, it just never toggles `wfExpanded` for it.
@@ -1457,7 +1924,7 @@
1457
1924
  if(expanded){
1458
1925
  var runsWrap = document.createElement("div");
1459
1926
  runsWrap.className = "wf-runs";
1460
- childRuns.forEach(function(r){ runsWrap.appendChild(buildRunRowEl(r)); });
1927
+ childRuns.forEach(function(r){ runsWrap.appendChild(buildRunRowEl(r, { sub: true })); });
1461
1928
  wrap.appendChild(runsWrap);
1462
1929
  }
1463
1930
  el.appendChild(wrap);
@@ -1479,6 +1946,7 @@
1479
1946
  '<div class="chips" role="group" aria-label="Filter">' +
1480
1947
  '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[✓]" title="passed" data-testid="chip-' + scope + '-res-pass">✓</button>' +
1481
1948
  '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[✗]" title="stopped" data-testid="chip-' + scope + '-res-fail">✗</button>' +
1949
+ '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[■]" title="stopped, can be resumed" data-testid="chip-' + scope + '-res-stopped">■</button>' +
1482
1950
  '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[·]" title="waiting on a human" data-testid="chip-' + scope + '-res-waiting">&middot;</button>' +
1483
1951
  '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[▶]" title="running" data-testid="chip-' + scope + '-res-running">▶</button>' +
1484
1952
  '<button class="chip fchip" type="button" aria-pressed="false" data-filter-group="result" data-filter-value="[?]" title="died or unknown" data-testid="chip-' + scope + '-res-unknown">?</button>' +
@@ -1750,10 +2218,13 @@
1750
2218
  '<div class="summary-row" data-testid="summary-close"><span class="sum-label">close:</span><span class="sum-val">' + escapeXml(closeText) + '</span></div>' +
1751
2219
  '<div class="summary-row" data-testid="summary-spend"><span class="sum-label">spend:</span><span class="sum-val">' + spendSummaryText(detail.spendSummary) + '</span></div>';
1752
2220
 
1753
- renderStepMap(stepBoxes);
2221
+ renderRunActions(detail);
2222
+ // amendment 7 item 2: the Draft is the first box of the Map (an arrow runs on to step 1); the steps keep their own numbers
2223
+ renderStepMap(stepBoxes.length ? [draftBox(detail.draft)].concat(stepBoxes.map(function(b, i){ return Object.assign({}, b, {n: i + 1}); })) : stepBoxes);
1754
2224
 
1755
2225
  var listEl = document.getElementById("step-list");
1756
2226
  listEl.innerHTML = "";
2227
+ if(stepBoxes.length) listEl.appendChild(buildDraftCardEl(detail.draft));
1757
2228
  stepBoxes.forEach(function(box, idx){
1758
2229
  var card = document.createElement("div");
1759
2230
  card.className = "step-card" + (box.state === "waiting" ? " running" : "");
@@ -1787,6 +2258,51 @@
1787
2258
  listEl.appendChild(card);
1788
2259
  });
1789
2260
  }
2261
+ // M4e amendment 4 item 4: the Run tab's top action row. Stop shows only while the server says the run is running or waiting at its ask
2262
+ // (`detail.controls.canStop`, the same decision the door reads; amendment 13) and reads "stopping after this step…" once asked;
2263
+ // Resume shows on a stopped or cap-halted run. The server is the arbiter: a refusal is shown in its own words.
2264
+ var stopSay = null;
2265
+ // Walk fix 4: after Sign & resume click 2 is accepted the run is still "stopped" for a few seconds. `window.fwdloopResuming`
2266
+ // ({key, at}, set by the Chat card, the one writer) keeps Resume from being offered again until a detail read shows the run live or
2267
+ // ended (canResume false), or the start was refused, or 30 s pass (a child that died leaves the run stopped; Resume must come back).
2268
+ var RESUMING_MAX_MS = 30000;
2269
+ function resumeWaiting(m, key, canResume, now){
2270
+ return !!m && m.key === key && canResume && now - m.at < RESUMING_MAX_MS;
2271
+ }
2272
+ function renderRunActions(detail){
2273
+ var el = document.getElementById("run-actions");
2274
+ var c = detail.controls || {};
2275
+ el.innerHTML = "";
2276
+ // amendment 7 item 6: Run again sits first, with Stop and Resume — every run control in this one row
2277
+ el.appendChild(makeButton("Run again", "run-again", function(){ if(window.fwdloopRunAgain) window.fwdloopRunAgain(detail); }));
2278
+ if(stopSay && stopSay.key !== detail.flow + "/" + detail.runId) stopSay = null;
2279
+ if(c.canStop){
2280
+ var stopBtn = makeButton(c.stopRequested ? "stopping after this step\u2026" : "Stop", "run-stop", function(){
2281
+ stopBtn.disabled = true;
2282
+ postJSON("/api/stop", { flow: detail.flow, runId: detail.runId }).then(function(r){
2283
+ if(r.status === 202 && r.body && r.body.ok){ stopSay = null; }
2284
+ else { stopSay = { key: detail.flow + "/" + detail.runId, text: (r.body && r.body.say) || "The run could not be stopped." }; }
2285
+ return reloadRun(detail.flow, detail.runId);
2286
+ }).catch(function(){
2287
+ stopSay = { key: detail.flow + "/" + detail.runId, text: networkText() };
2288
+ return reloadRun(detail.flow, detail.runId);
2289
+ });
2290
+ });
2291
+ stopBtn.disabled = !!c.stopRequested;
2292
+ el.appendChild(stopBtn);
2293
+ }
2294
+ var runKey = detail.flow + "/" + detail.runId;
2295
+ if(window.fwdloopResuming && window.fwdloopResuming.key === runKey && !c.canResume) window.fwdloopResuming = null;
2296
+ if(resumeWaiting(window.fwdloopResuming, runKey, !!c.canResume, Date.now())){
2297
+ var rb = makeButton("resuming\u2026", "run-resuming", function(){});
2298
+ rb.disabled = true;
2299
+ el.appendChild(rb);
2300
+ } else if(c.canResume){
2301
+ el.appendChild(makeButton("Resume", "run-resume", function(){ if(window.fwdloopOpenResume) window.fwdloopOpenResume(detail); }));
2302
+ }
2303
+ if(stopSay){ var m = document.createElement("div"); m.className = "answer-msg refused"; m.setAttribute("data-testid", "run-stop-say"); m.textContent = stopSay.text; el.appendChild(m); }
2304
+ el.hidden = el.children.length === 0;
2305
+ }
1790
2306
  // A plain lower-case, non-bold data line (hamr's 2026-09-27 styling
1791
2307
  // ruling: only the header is upper case/bold) — every non-header line on
1792
2308
  // a step card is built through this ONE helper so none of them can drift
@@ -1798,6 +2314,35 @@
1798
2314
  div.textContent = text;
1799
2315
  return div;
1800
2316
  }
2317
+ // M4e amendment 9: the first card under the Map, shaped like a step card: head `0 · drafting` (bold h4) + status (`draftCardLines`), then its two lines; the rows
2318
+ // stay in Audit → Draft. A click opens the Audit tab on that group, like a step card's.
2319
+ function buildDraftCardEl(d){
2320
+ var card = document.createElement("div");
2321
+ card.className = "step-card";
2322
+ card.setAttribute("data-testid", "step-card-draft");
2323
+ var c = draftCardLines(d);
2324
+ var head = document.createElement("div");
2325
+ head.className = "step-head";
2326
+ var h4 = document.createElement("h4");
2327
+ h4.textContent = c.title;
2328
+ head.appendChild(h4);
2329
+ if(c.status !== null){
2330
+ var badge = document.createElement("span");
2331
+ badge.className = "badge " + (c.passed ? auditStateClass("done") + " sign-badge" : auditStateClass("pending"));
2332
+ badge.setAttribute("data-testid", "step-card-draft-state");
2333
+ badge.textContent = c.status;
2334
+ head.appendChild(badge);
2335
+ }
2336
+ card.appendChild(head);
2337
+ c.lines.forEach(function(t, i){
2338
+ if(t !== "") card.appendChild(textLineEl("step-meta", t, "step-card-draft-line-" + (i + 2)));
2339
+ });
2340
+ card.setAttribute("tabindex", "0");
2341
+ card.setAttribute("role", "button");
2342
+ card.addEventListener("click", function(){ openAuditGroup("drafting"); });
2343
+ card.addEventListener("keydown", function(e){ if(e.key === "Enter" || e.key === " "){ e.preventDefault(); card.click(); } });
2344
+ return card;
2345
+ }
1801
2346
  // The card's HEADER line: "N · step-name [state] [close class]" — real
1802
2347
  // case, bold from CSS (`.step-card .step-head`), the state/close chips
1803
2348
  // keeping their own `.badge` color. `auditStateClass` is the SAME
@@ -1923,13 +2468,13 @@
1923
2468
  // What a phone tap shows under the one-line entry: everything the line cut short, in full, as wrapped lines.
1924
2469
  // Only fields the row actually has — a line with nothing to say is left out, never filled with a made-up value.
1925
2470
  function auditDetailHtml(r, word, actionText, isRejectRow){
1926
- var lines = [["step", r.step], ["result", word], ["action", actionText]];
1927
- if(!isRejectRow && r.gap) lines.push(["gap", r.gap]);
2471
+ var lines = (typeof r.step === "string" && r.step.length > 0 ? [["step", r.step]] : []).concat([["result", word], ["action", actionText]]);
2472
+ if(!isRejectRow && r.gap) lines.push(["gap", auditGapText(r)]);
1928
2473
  if(Array.isArray(r.refused) && r.refused.length > 0){
1929
2474
  lines.push(["refused", r.refused.map(function(x){ return x.verb + " " + x.path + " (" + x.rule + ")"; }).join("; ")]);
1930
2475
  }
1931
2476
  if(Array.isArray(r.ungranted) && r.ungranted.length > 0) lines.push(["not granted, called anyway", r.ungranted.join(", ")]);
1932
- lines.push(["close", closeClassLabel(r.class)], ["cost", auditCostCellText(r)]);
2477
+ lines.push(["close", auditCloseText(r)], ["cost", auditCostCellText(r)]);
1933
2478
  var when = readableDateTime(r.at);
1934
2479
  lines.push(["time", (typeof r.atWhy === "string" && r.atWhy.length > 0) ? r.atWhy : (when || "unknown")]);
1935
2480
  return lines.map(function(l){ return "<div class=\"am-d\"><b>" + escapeXml(l[0]) + ":</b> " + escapeXml(l[1]) + "</div>"; }).join("");
@@ -1941,6 +2486,10 @@
1941
2486
  // the mobile (max-width:480px) stacked-card CSS reads via `attr()` —
1942
2487
  // review item #4: the Time cell (and every other cell) must stay inside
1943
2488
  // its own card at 390px, never truncated or pushed off the page edge.
2489
+ // The one place the Attempt and Close cells get their text: a row that is not an attempt (a Stop's note, a setup row) has no attempt
2490
+ // number and no close class — it shows nothing / "—", never "null", "unknown" or "#null".
2491
+ function auditAttemptText(r){ return (typeof r.attempt === "number" || (typeof r.attempt === "string" && r.attempt.length > 0)) ? String(r.attempt) : ""; }
2492
+ function auditCloseText(r){ return (r.setup || r.class === null || r.class === undefined) ? "—" : closeClassLabel(r.class); }
1944
2493
  function buildAuditRowEl(r, includeStep){
1945
2494
  var tr = document.createElement("tr");
1946
2495
  var glyph = verdictGlyph(r.verdict, r.class);
@@ -1954,17 +2503,17 @@
1954
2503
  // pre-M4a-3 row or a non-model row appends nothing at all.
1955
2504
  var actionText = action + (typeof r.toolsPhrase === "string" ? " · " + r.toolsPhrase : "");
1956
2505
  var cells =
1957
- "<td data-label=\"Attempt\">" + escapeXml(String(r.attempt)) + "</td>" +
1958
- (includeStep ? "<td data-label=\"Step\">" + escapeXml(r.step) + "</td>" : "") +
2506
+ "<td data-label=\"Attempt\">" + escapeXml(auditAttemptText(r)) + "</td>" +
2507
+ (includeStep ? "<td data-label=\"Step\">" + escapeXml(r.stepName || r.step) + "</td>" : "") +
1959
2508
  "<td data-label=\"Action\">" + escapeXml(actionText) + "</td>" +
1960
- "<td data-label=\"Gap\">" + escapeXml(isRejectRow ? "" : (r.gap || "")) + "</td>" +
2509
+ "<td data-label=\"Gap\">" + escapeXml(isRejectRow ? "" : auditGapText(r)) + "</td>" +
1961
2510
  "<td data-label=\"Cost\">" + escapeXml(auditCostCellText(r)) + "</td>" +
1962
2511
  "<td data-label=\"Verdict\"><span class=\"badge " + badgeClass + "\">" + escapeXml(word) + "</span></td>" +
1963
- "<td data-label=\"Close\">" + escapeXml(closeClassLabel(r.class)) + "</td>" +
2512
+ "<td data-label=\"Close\">" + escapeXml(auditCloseText(r)) + "</td>" +
1964
2513
  "<td data-label=\"Time\">" + auditTimeCellHtml(r) + "</td>" +
1965
2514
  // phone-only one-line cells (CSS shows these and hides the rest below 640px; hidden on desktop)
1966
2515
  "<td class=\"am am-glyph\" aria-hidden=\"true\">" + escapeXml(glyph || "·") + "</td>" +
1967
- "<td class=\"am am-cost\">" + escapeXml(money(r.usd, r.spendComplete)) + "</td>" +
2516
+ "<td class=\"am am-cost\">" + escapeXml(r.setup ? auditCostCellText(r) : money(r.usd, r.spendComplete)) + "</td>" +
1968
2517
  "<td class=\"am am-time\">" + escapeXml(auditShortTime(r)) + "</td>" +
1969
2518
  "<td class=\"am am-detail\">" + auditDetailHtml(r, word, actionText, isRejectRow) + "</td>";
1970
2519
  tr.innerHTML = cells;
@@ -2006,13 +2555,27 @@
2006
2555
  // presentational formatter; nothing here re-derives state/cost/tries).
2007
2556
  // Tokens are appended ONLY when the server sent a real total (omitted,
2008
2557
  // never "0 tokens", for a pre-M4a-2 row or a no-model-call step).
2558
+ // M4e amendment 10: ONE function for each header line's words, `auditGroupHeaderParts` (status in the step card's `stateWord`, name, then the Draft's figures
2559
+ // or the step's cost and tries); `buildAuditGroupHeaderEl` draws these parts and `auditGroupHeaderText` joins them, so the visible line and its aria are
2560
+ // the same words. `status` is null with no draft record; `state` colors it (`auditStateClass`); `signed`: the status carries its own brackets.
2561
+ function auditGroupHeaderParts(g){
2562
+ var AUDIT_DOT = "\u00b7"; // the separator between the status badge and the name, read by the visible header and the aria line alike
2563
+ if(g.draft){
2564
+ var ds = g.summary;
2565
+ if(!(ds && ds.present)) return {status: null, name: "drafting", why: (ds && ds.why) || "no draft record"};
2566
+ var passed = ds.ended === "done";
2567
+ return {status: passed ? stateWord("done") : "not signed", state: passed ? "done" : "pending", signed: true, name: "drafting", dot: AUDIT_DOT, draftFigs: draftFigures(ds).concat([draftHumanWord(ds)]), passed: passed};
2568
+ }
2569
+ var parts = {status: stateWord(g.state), state: g.state, signed: true, dot: AUDIT_DOT, name: g.step, cost: g.cost || "cost unknown"};
2570
+ if(!g.run) parts.tries = {n: g.tryCount, marks: g.tryMarks}; // the run's own group has no tries
2571
+ return parts;
2572
+ }
2009
2573
  function auditGroupHeaderText(g){
2010
- var bits = [
2011
- "[" + g.state + "]", g.step, duration(g.timeMs), (g.cost || "cost unknown"),
2012
- "try " + g.tryCount + " " + g.tryMarks.join(""),
2013
- ];
2014
- if(typeof g.tokensTotal === "number") bits.splice(4, 0, g.tokensTotal + " tokens");
2015
- return bits.join(" · ");
2574
+ var p = auditGroupHeaderParts(g);
2575
+ if(g.draft) return draftLineText(g.summary);
2576
+ var line = [p.status, p.name, p.cost].join(" " + p.dot + " ");
2577
+ if(p.tries) line += " \u00b7 try " + p.tries.n + " " + p.tries.marks.join("");
2578
+ return line;
2016
2579
  }
2017
2580
  // hamr's 2026-09-27 review: the header's status word gets the SAME color
2018
2581
  // vocabulary the runs list already uses (glyphClass's green/red/amber/
@@ -2024,51 +2587,70 @@
2024
2587
  if(state === "done") return "green";
2025
2588
  if(state === "waiting") return "amber";
2026
2589
  if(state === "stopped") return "red";
2027
- return "grey";
2590
+ return "grey"; // user-stopped (the same --grey-dot as the [■] dot), pending
2028
2591
  }
2029
2592
  function auditMarkClass(mark){
2030
2593
  if(mark === "✓") return "green";
2031
2594
  if(mark === "✗") return "red";
2032
2595
  return "grey"; // "·" — still open, no resolution row yet
2033
2596
  }
2597
+ // The Draft group's header tail (amendment 7 item 2, 10): `· <time> · $<cost> · <n> model calls ✓` from `auditGroupHeaderParts`' figures (the one
2598
+ // `draftFigures`, `draftCallsWord`); a flow with no draft record says so and has no cost. Apart from buildAuditGroupHeaderEl so the step groups' title keeps no time in it.
2599
+ function draftTailInto(tail, p){
2600
+ function part(cls, text){ var sp = document.createElement("span"); sp.className = cls; sp.textContent = text; tail.appendChild(sp); }
2601
+ part("audit-fold-sep", "\u00b7 ");
2602
+ if(!p.draftFigs){ tail.appendChild(document.createTextNode(p.why)); return; }
2603
+ tail.appendChild(document.createTextNode(p.draftFigs.join(" \u00b7 ") + (p.passed ? " " : "")));
2604
+ if(p.passed) part("mark green", "\u2713");
2605
+ }
2034
2606
  // Builds the SAME header line `auditGroupHeaderText` renders as plain
2035
2607
  // text (used as this header's aria-label, for a screen reader), but as
2036
- // real DOM: the status word is its own `<span class="badge STATE">`
2037
- // (reusing the existing `.badge` bracket/color CSS, never a second
2038
- // "[state]" string built here) and each try mark is its own colored
2608
+ // real DOM: the status (the step card's sign and word, amendment 10) is its own `<span class="badge STATE sign-badge">`
2609
+ // (the sign carries its own brackets, so `.sign-badge` draws no second pair) and each try mark is its own colored
2039
2610
  // `<span class="mark STATE">` — built directly off `g.state`/`g.tryMarks`,
2040
2611
  // never by parsing `auditGroupHeaderText`'s own string back apart.
2041
2612
  function buildAuditGroupHeaderEl(g){
2042
2613
  var h4 = document.createElement("h4");
2043
2614
  h4.className = "audit-status-header";
2044
- var stateSpan = document.createElement("span");
2045
- stateSpan.className = "badge " + auditStateClass(g.state);
2046
- stateSpan.setAttribute("data-testid", "audit-group-state");
2047
- stateSpan.textContent = g.state;
2048
- h4.appendChild(stateSpan);
2615
+ var p = auditGroupHeaderParts(g);
2616
+ if(p.status !== null){
2617
+ var stateSpan = document.createElement("span");
2618
+ stateSpan.className = "badge " + auditStateClass(p.state) + " sign-badge";
2619
+ stateSpan.setAttribute("data-testid", "audit-group-state");
2620
+ stateSpan.textContent = p.status;
2621
+ h4.appendChild(stateSpan);
2622
+ var dotSpan = document.createElement("span");
2623
+ dotSpan.className = "audit-fold-dot";
2624
+ dotSpan.textContent = p.dot;
2625
+ h4.appendChild(dotSpan);
2626
+ }
2049
2627
  // M4c-fix amendment 2 (l): the title is `[sign] name · cost · try N ✗✓` — the name alone is cut with … (own flex child),
2050
2628
  // cost and tries never; time and tokens live in each try's detail. The whole name is in the title attribute and aria-label.
2051
2629
  var nameSpan = document.createElement("span");
2052
2630
  nameSpan.className = "audit-fold-name";
2053
2631
  nameSpan.setAttribute("data-testid", "audit-group-name");
2054
- nameSpan.title = g.step;
2055
- nameSpan.textContent = g.step;
2632
+ nameSpan.title = p.name;
2633
+ nameSpan.textContent = p.name;
2056
2634
  h4.appendChild(nameSpan);
2057
2635
  var tail = document.createElement("span");
2058
2636
  tail.className = "audit-fold-tail";
2059
2637
  // the dots and the word "try" are their own spans so a phone can drop them (keeping cost, N and the marks)
2060
2638
  function tailPart(cls, text){ var sp = document.createElement("span"); sp.className = cls; sp.textContent = text; tail.appendChild(sp); }
2061
- tailPart("audit-fold-sep", "· ");
2062
- tail.appendChild(document.createTextNode(g.cost || "cost unknown"));
2063
- tailPart("audit-fold-sep", " · ");
2064
- tailPart("audit-fold-try", "try ");
2065
- tailPart("audit-fold-n", g.tryCount + " ");
2066
- g.tryMarks.forEach(function(mark){
2067
- var markSpan = document.createElement("span");
2068
- markSpan.className = "mark " + auditMarkClass(mark);
2069
- markSpan.textContent = mark;
2070
- tail.appendChild(markSpan);
2071
- });
2639
+ if(g.draft) draftTailInto(tail, p);
2640
+ else if(!p.tries){ tailPart("audit-fold-sep", "· "); tail.appendChild(document.createTextNode(p.cost)); } // the run's own group: no tries, no dots
2641
+ else {
2642
+ tailPart("audit-fold-sep", "· ");
2643
+ tail.appendChild(document.createTextNode(p.cost));
2644
+ tailPart("audit-fold-sep", " · ");
2645
+ tailPart("audit-fold-try", "try ");
2646
+ tailPart("audit-fold-n", p.tries.n + " ");
2647
+ p.tries.marks.forEach(function(mark){
2648
+ var markSpan = document.createElement("span");
2649
+ markSpan.className = "mark " + auditMarkClass(mark);
2650
+ markSpan.textContent = mark;
2651
+ tail.appendChild(markSpan);
2652
+ });
2653
+ }
2072
2654
  h4.appendChild(tail);
2073
2655
  return h4;
2074
2656
  }
@@ -2083,10 +2665,17 @@
2083
2665
  if(auditExpandedRun !== runKey){ auditExpanded = {}; auditExpandedRun = runKey; }
2084
2666
  var container = document.getElementById("audit-groups");
2085
2667
  container.innerHTML = "";
2086
- if(!result || result.empty) return;
2668
+ if(!result) return;
2087
2669
  var anyVisible = false;
2088
- (result.groups || []).forEach(function(g){
2670
+ // amendment 7 item 2: the Draft is the first group, a normal card (collapsed by default); a run with no audit rows yet still has it
2671
+ var draftG = draftGroupFor(result);
2672
+ var groups = (draftG ? [draftG] : []).concat(result.empty ? [] : (result.groups || []));
2673
+ groups.forEach(function(g){
2089
2674
  var rows = (g.rows || []).filter(auditRowMatchesFilter);
2675
+ // a flow with no draft record: a header-only card that says so (shown under All; there is nothing to filter)
2676
+ var noRecord = !!g.draft && !(g.summary && g.summary.present);
2677
+ if(noRecord && auditFilterMode !== "all") return;
2678
+ if(noRecord) rows = [{}]; // one placeholder so the card is drawn; it has no table
2090
2679
  if(rows.length === 0) return; // a group with no matching rows is hidden, never an empty shell
2091
2680
  anyVisible = true;
2092
2681
  var wrap = document.createElement("div");
@@ -2101,8 +2690,9 @@
2101
2690
  // map/step-card jump) does, never the initial state.
2102
2691
  // M4c-fix amendment 2 (f): a step with any failed try (a row with a gap) starts OPEN so its gap is
2103
2692
  // seen without a click; the rest start closed. A manual toggle wins on re-render (auditExpanded).
2104
- var failed = (g.rows || []).some(function(r){ return !!r.gap; });
2693
+ var failed = (g.rows || []).some(function(r){ return !!r.gap && !/^stop/.test(r.verdict || ""); }); // a Stop's own words are not a failed try
2105
2694
  var isOpen = Object.prototype.hasOwnProperty.call(auditExpanded, g.step) ? auditExpanded[g.step] : failed;
2695
+ if(g.draft && !Object.prototype.hasOwnProperty.call(auditExpanded, g.step)) isOpen = false; // the Draft starts closed: its card row has a "gap" (the job text)
2106
2696
  wrap.classList.add("audit-fold");
2107
2697
  if(!isOpen) wrap.classList.add("closed");
2108
2698
  var header = buildAuditGroupHeaderEl(g);
@@ -2112,6 +2702,7 @@
2112
2702
  header.setAttribute("aria-label", auditGroupHeaderText(g));
2113
2703
  header.style.cursor = "pointer";
2114
2704
  wrap.appendChild(header);
2705
+ if(noRecord){ container.appendChild(wrap); return; } // nothing to open: the header already says "no draft record"
2115
2706
  var table = document.createElement("table");
2116
2707
  table.hidden = !isOpen;
2117
2708
  table.innerHTML = "<thead><tr><th>Attempt</th><th>Action</th><th>Gap</th><th>Cost</th><th>Verdict</th><th>Close</th><th>Time</th></tr></thead><tbody></tbody>";
@@ -2147,8 +2738,9 @@
2147
2738
  function renderAuditFlat(result){
2148
2739
  var tbody = document.getElementById("audit-tbody");
2149
2740
  tbody.innerHTML = "";
2150
- if(!result || result.empty) return false;
2151
- var rows = result.rows.filter(auditRowMatchesFilter);
2741
+ if(!result) return false;
2742
+ var dr = result.draft && result.draft.present ? result.draft.rows : [];
2743
+ var rows = dr.concat(result.empty ? [] : result.rows).filter(auditRowMatchesFilter);
2152
2744
  rows.forEach(function(r){ tbody.appendChild(buildAuditRowEl(r, true)); });
2153
2745
  return rows.length > 0;
2154
2746
  }
@@ -2181,17 +2773,27 @@
2181
2773
  filterEmpty.hidden = true;
2182
2774
  }
2183
2775
  }
2776
+ // M4e amendment 7 item 2: the Draft as the first Audit group (one card like the steps', collapsed by default): the group header reads the server's one
2777
+ // Draft summary; its rows (card, draft, notes, changes, sign, then this run's own Sign & run rows) come from the same row builder as the run's rows.
2778
+ function draftGroupFor(result){
2779
+ var d = result && result.draft;
2780
+ if(!d) return null;
2781
+ return {step: "drafting", draft: true, summary: d.summary, rows: d.rows || []};
2782
+ }
2184
2783
  function renderAudit(result){
2185
2784
  var empty = document.getElementById("audit-empty");
2186
2785
  var content = document.getElementById("audit-content");
2187
2786
  lastAuditResult = result;
2188
- if(!result || result.empty){
2787
+ // a run with no audit rows yet still has its Draft: say so in words, and show the card
2788
+ var hasDraft = !!(result && result.draft);
2789
+ if(!result || (result.empty && !hasDraft)){
2189
2790
  empty.hidden = false;
2190
2791
  empty.textContent = (result && result.why) || "no audit rows for this run";
2191
2792
  content.hidden = true;
2192
2793
  return;
2193
2794
  }
2194
- empty.hidden = true;
2795
+ empty.hidden = !result.empty;
2796
+ if(result.empty) empty.textContent = result.why || "no audit rows for this run";
2195
2797
  content.hidden = false;
2196
2798
  // a fresh run's own view keeps whatever mode (Grouped/Flat) the chips
2197
2799
  // are already showing, defaulting to Grouped on first load.
@@ -2204,9 +2806,13 @@
2204
2806
  // getRunJob (src/panel/data.js), which reads fwdloop's own signed
2205
2807
  // declaration.json + signature.json (one per flow, unlike bareloop's
2206
2808
  // multi-source provenance chain — DROPPED per the M4a fit-check). ----
2207
- function ttlLabel(ms){
2208
- if(typeof ms !== "number") return "unknown";
2209
- return duration(ms);
2809
+ // M4e amendment 6 item 6: ONE wait formatter for the Job block's "~ waits" row and the Ask row: "1h", "30m", "1h 30m", never "60m00s".
2810
+ // A wait that is not a whole number of seconds falls back to `duration`.
2811
+ function plainWait(ms){
2812
+ if(typeof ms !== "number" || !(ms > 0)) return "unknown";
2813
+ if(ms % 1000 !== 0) return duration(ms);
2814
+ var t = ms / 1000, h = Math.floor(t / 3600), m = Math.floor((t % 3600) / 60), sec = t % 60;
2815
+ return [h ? h + "h" : "", m ? m + "m" : "", sec ? sec + "s" : ""].filter(Boolean).join(" ");
2210
2816
  }
2211
2817
  // hamr's 2026-09-27 exit-check review #5: ONE row-per-piece renderer,
2212
2818
  // shared by every multi-row Job field (prose/asks/sources/sends/
@@ -2235,12 +2841,29 @@
2235
2841
  document.getElementById("details-title").textContent = "Job — " + job.flow + " (signed)";
2236
2842
  // review #5: "Job (prose)" — the signed lines, numbered, WITHOUT their
2237
2843
  // guardrail mixed in (guardrails get their own field below).
2238
- renderRowsField("details-prose", job.prose, "no signed prose lines", function(l){
2239
- return l.line + ". " + l.text;
2240
- });
2844
+ // M4e amendment 6 item 6: the Job block reads like the card: each numbered line, then its own `~` rows: its guardrail, an ask line's
2845
+ // wait, a send line's destination. (The separate Guardrails field is gone.) `job` already carries the values in force for this run.
2846
+ var jobEl = document.getElementById("details-prose");
2847
+ jobEl.innerHTML = "";
2848
+ if(!job.prose || !job.prose.length){
2849
+ jobEl.appendChild(textDiv("hint", "no signed prose lines"));
2850
+ } else {
2851
+ job.prose.forEach(function(l){
2852
+ jobEl.appendChild(textDiv("ro-value", l.line + ". " + l.text));
2853
+ (job.guardrails || []).filter(function(g){ return g.line === l.line; }).forEach(function(g){
2854
+ jobEl.appendChild(textDiv("ro-value sub", "~ " + g.guardrail));
2855
+ });
2856
+ (job.asks || []).filter(function(ak){ return ak.line === l.line; }).forEach(function(ak){
2857
+ jobEl.appendChild(textDiv("ro-value sub", "~ waits " + plainWait(ak.waitMs)));
2858
+ });
2859
+ (job.sends || []).filter(function(sd){ return sd.line === l.line; }).forEach(function(sd){
2860
+ jobEl.appendChild(textDiv("ro-value sub", "~ writes out to " + (sd.target || "unknown")));
2861
+ });
2862
+ });
2863
+ }
2241
2864
  // review #5: "Ask" — one row per signed ask line.
2242
2865
  renderRowsField("details-asks", job.asks, "no signed asks", function(ak){
2243
- return "line " + ak.line + " · \"" + ak.question + "\" · waits " + ttlLabel(ak.waitMs);
2866
+ return "line " + ak.line + " · \"" + ak.question + "\" · waits " + plainWait(ak.waitMs);
2244
2867
  });
2245
2868
  // hamr review #7: no declaration/signature book records a model on the
2246
2869
  // flow itself (checked against `src/panel/data.js`'s own
@@ -2249,17 +2872,13 @@
2249
2872
  document.getElementById("details-model").textContent = job.model
2250
2873
  ? ("model used: " + job.model + " (from this run's rows)")
2251
2874
  : (job.modelWhy || "no model call recorded yet");
2252
- // hamr's 2026-09-27 final tweak #1: "$ cap" — bareloop-style "$ cap /
2253
- // Time cap" row: money (signed capUsd + redo cap) THEN time. Checked
2254
- // against src/declaration.js and src/types.js's own Arbiter typedef:
2255
- // fwdloop's signed arbiter carries `capUsd`/`redoCap` (and per-ask
2256
- // `ttlMs`, which is an ask's own wait, not a run-wide time cap) — there
2257
- // is no signed run-wide time-cap field anywhere in the grammar, so this
2258
- // NEVER invents one; it says so in words instead.
2875
+ // M4e amendment 6 item 5 + amendment 7 item 4: "$<cap> per run · 1h wait · redo up to <n>"; several asks: "waits 1h, 30m", each through plainWait.
2876
+ // fwdloop has no run-wide time limit (each ask has its own wait), so no ask means no wait part at all.
2877
+ var waitParts = (job.asks || []).filter(function(ak){ return typeof ak.waitMs === "number"; }).map(function(ak){ return plainWait(ak.waitMs); });
2878
+ var waitText = waitParts.length === 0 ? "" : (waitParts.length === 1 ? waitParts[0] + " wait" : "waits " + waitParts.join(", "));
2259
2879
  document.getElementById("details-cap").textContent =
2260
2880
  (typeof job.capUsd === "number" ? ("$" + job.capUsd.toFixed(2)) : "unknown")
2261
- + " · redo cap " + (typeof job.redoCap === "number" ? job.redoCap : "unknown")
2262
- + " · time cap: no time cap signed";
2881
+ + " per run" + (waitText ? " · " + waitText : "") + " · redo up to " + (typeof job.redoCap === "number" ? job.redoCap : "unknown");
2263
2882
  // review #5: "Source" — role -> basename only (never the full signed path).
2264
2883
  renderRowsField("details-sources", job.sources, "no signed sources", function(s){
2265
2884
  return s.role + " → " + s.basename;
@@ -2268,10 +2887,6 @@
2268
2887
  renderRowsField("details-sends", job.sends, "no signed sends", function(s){
2269
2888
  return "line " + s.line + " · " + (s.kind || "unknown") + " → " + (s.target || "unknown");
2270
2889
  });
2271
- // review #5: "Guardrails" — ONE field, one row per numbered-line guardrail.
2272
- renderRowsField("details-guardrails", job.guardrails, "no numbered-line guardrails signed", function(g){
2273
- return "line " + g.line + " · " + g.guardrail;
2274
- });
2275
2890
  // review #5: "Success" — one row per declared step, off data.js's own
2276
2891
  // deriveStepSuccessText (never re-derived client-side).
2277
2892
  renderRowsField("details-success", job.success, "no declared steps", function(s){
@@ -2383,7 +2998,7 @@
2383
2998
  var wasHidden = false;
2384
2999
  // One writer of `openRunLive`: every paint of the open run's detail goes through here.
2385
3000
  function paintRun(d){
2386
- openRunLive = !(d && (d.glyph === "[\u2713]" || d.glyph === "[\u2717]"));
3001
+ openRunLive = !(d && (d.glyph === "[\u2713]" || d.glyph === "[\u2717]" || d.glyph === "[\u25A0]"));
2387
3002
  var next = sig(d);
2388
3003
  if(next !== null && next === lastSig.detail) return;
2389
3004
  lastSig.detail = next;
@@ -2464,6 +3079,7 @@
2464
3079
  if(detail && detail.glyph === "[✓]") return { done: true, cls: "info", text: "run finished [✓] — the sent artifact is in the Run tab" };
2465
3080
  if(detail && detail.outcome === "rerun") return { done: true, cls: "info", text: "rerun: this run ended and a fresh run was started — find it in Runs" };
2466
3081
  if(detail && detail.glyph === "[✗]") return { done: true, cls: "info", text: "run ended [✗] " + (detail.label || "") };
3082
+ if(detail && detail.glyph === "[■]") return { done: true, cls: "info", text: "run stopped [■] — " + (detail.line || detail.label || "") };
2467
3083
  var st = asks && asks.resume ? asks.resume.label : null;
2468
3084
  return { done: false, cls: "info", text: (st || "answer applied") + " — run: " + ((detail && detail.label) || "state unknown") };
2469
3085
  }
@@ -2505,7 +3121,7 @@
2505
3121
  runsFilterBar.setItems(runs);
2506
3122
  var first = runs.find(function(r){ return r.runId !== null; });
2507
3123
  if(first){
2508
- document.getElementById("tab-runs").click();
3124
+ // the LEFT side is not switched here: a load or refresh always opens on the Chat tab (hamr 2026-10-06)
2509
3125
  // newest run overall, opened directly — the Workflows view starts
2510
3126
  // collapsed, but its flow row still renders "selected" since
2511
3127
  // `runsFilterBar.refresh()` re-renders AFTER currentFlow/currentRunId
@@ -2734,9 +3350,8 @@
2734
3350
  "askid-required": "That click was not understood. Reload the page and try again.",
2735
3351
  "body-not-json": "That click was not understood. Reload the page and try again.",
2736
3352
  "body-too-large": "That is too long to send. Please shorten your reason.",
2737
- "cookie-missing-or-wrong": "The panel does not recognise this page. Open the link the terminal printed.",
2738
- "origin-not-own": "The panel does not recognise this page. Open the link the terminal printed.",
2739
- "host-not-own-address": "The panel does not recognise this page. Open the link the terminal printed.",
3353
+ "origin-not-own": "The panel does not recognise this page. Reload it.",
3354
+ "host-not-own-address": "The panel does not recognise this page. Reload it.",
2740
3355
  "internal": "Something went wrong inside the panel. Nothing was changed."
2741
3356
  };
2742
3357
  var byWords = [
@@ -2947,7 +3562,7 @@
2947
3562
  if(evidence.draft){
2948
3563
  var draftEl = document.createElement("div");
2949
3564
  draftEl.className = "ro-value scroll";
2950
- draftEl.textContent = evidence.draft;
3565
+ fillArtifactText(draftEl, evidence.draft);
2951
3566
  // hamr's 2026-09-27 exit-check review #3: "the box headers should be
2952
3567
  // bolder" — a real heading class (same weight/size/uppercase posture
2953
3568
  // as the Job tab's own field `<label>`s), never the plain `.hint`
@@ -2973,11 +3588,54 @@
2973
3588
  }
2974
3589
  var art = document.createElement("div");
2975
3590
  art.className = "ro-value scroll";
2976
- art.textContent = typeof u.text === "string" ? u.text : "no artifact text on file";
3591
+ if(typeof u.text === "string"){ fillArtifactText(art, u.text); } else { art.textContent = "no artifact text on file"; }
2977
3592
  ev.appendChild(art);
2978
3593
  });
2979
3594
  return ev;
2980
3595
  }
3596
+ // M4e amendment 4 item 7: a section header of the artifact shows in the panel's blue accent. The signed text gives no
3597
+ // rule for what a header is, so the simplest honest one: a paragraph (text between blank lines) that is one short line
3598
+ // (60 characters or fewer), does not end in a sentence stop, and has another paragraph after it. The text itself is
3599
+ // untouched (textContent still equals the artifact, byte for byte); only the colour of those lines changes.
3600
+ var ART_HEAD_MAX = 60;
3601
+ // A markdown heading line (1-6 "#", a space, then text) is a header wherever it sits, single newlines included, last paragraph too.
3602
+ var ART_MD_HEAD = /^#{1,6} \S/;
3603
+ function isArtifactHeader(para, hasNext){
3604
+ if(ART_MD_HEAD.test(para) && para.indexOf("\n") === -1) return true;
3605
+ return hasNext && para.length > 0 && para.length <= ART_HEAD_MAX && para.indexOf("\n") === -1 && !/[.!?:;,]$/.test(para.trim());
3606
+ }
3607
+ function fillArtifactText(el, text){
3608
+ el.textContent = "";
3609
+ var paras = String(text).split("\n\n");
3610
+ paras.forEach(function(para, i){
3611
+ if(i > 0) el.appendChild(document.createTextNode("\n\n"));
3612
+ if(para.indexOf("\n") !== -1){
3613
+ // several lines in one paragraph: only markdown heading lines are headers; the "\n" between lines stays in the text
3614
+ var plain = "";
3615
+ para.split("\n").forEach(function(line, j){
3616
+ var sep = j > 0 ? "\n" : "";
3617
+ if(ART_MD_HEAD.test(line)){
3618
+ el.appendChild(document.createTextNode(plain + sep));
3619
+ plain = "";
3620
+ var hh = document.createElement("span");
3621
+ hh.className = "art-head";
3622
+ hh.textContent = line;
3623
+ el.appendChild(hh);
3624
+ } else {
3625
+ plain += sep + line;
3626
+ }
3627
+ });
3628
+ if(plain !== "") el.appendChild(document.createTextNode(plain));
3629
+ } else if(isArtifactHeader(para, i < paras.length - 1)){
3630
+ var h = document.createElement("span");
3631
+ h.className = "art-head";
3632
+ h.textContent = para;
3633
+ el.appendChild(h);
3634
+ } else {
3635
+ el.appendChild(document.createTextNode(para));
3636
+ }
3637
+ });
3638
+ }
2981
3639
  // M4c item 5: "your answers so far" — one line per answered draft, every field from
2982
3640
  // the server's block (data.js groupAskBlocks); the page only lays it out.
2983
3641
  function answerLineText(a){
@@ -3129,6 +3787,1297 @@
3129
3787
  return true;
3130
3788
  }
3131
3789
 
3790
+ // ---- Chat tab: describe, draft, sign and run a job from this page (M4e piece 3). ----
3791
+ // borrowed-from: bareloop src/panel/index.html@ca7195e — `mainButtonFor`, `renderMain`, `renderProgress`, the
3792
+ // scroll-on-change block in `renderActions`, `attachSession`/`reattachLive` (without the reuse/auto-sign branch), `syncCardLock`,
3793
+ // `CLIENT_TERMINAL_PHASES`, `openNewCard`/`resetCard`/`refreshStartEnabled`, `authorPost`/`authorGet`, `fitBox`. fwdloop differs where its shape does: the draft is a detached CLI child whose state is
3794
+ // READ from files (GET /api/author/live and /:id), a start is polled (GET /api/author/start/:id), no token or cookie. Sign is two clicks, no typed name (M4e amendment 2); the ask box is bareloop's "Ask for a change to the plan" (amendment 3 item 3).
3795
+ (function(){
3796
+ var card = document.getElementById("chat-job-card");
3797
+ var clearBtn = document.getElementById("chat-clear-btn");
3798
+ var thread = document.getElementById("chat-thread");
3799
+ var jobEl = document.getElementById("jf-job");
3800
+ var inputsBox = document.getElementById("jf-inputs"); // the New-job inputs textarea (`name: path` per line)
3801
+ var destEl = document.getElementById("jf-dest-folder");
3802
+ var askWaitEl = document.getElementById("jf-ask-wait");
3803
+ var mainBtn = document.getElementById("chat-main-btn");
3804
+ var mainHint = document.getElementById("chat-main-hint");
3805
+ var startOverBtn = document.getElementById("chat-startover-btn");
3806
+ var msgEl = document.getElementById("chat-msg"); // the ask box: a note asking for a change to the green plan
3807
+ var msgRow = document.getElementById("chat-msg-row");
3808
+ var errEl = document.getElementById("chat-card-error"); // POLL-OWNED: the draft's own sentence (red / stopped)
3809
+ var actionErrEl = document.getElementById("chat-action-error"); // ACTION-OWNED: only a click's refusal; the poll never wipes it
3810
+ var progressRow = document.getElementById("chat-progress-row");
3811
+ var newBox = document.getElementById("jf-new");
3812
+ var runBox = document.getElementById("jf-run");
3813
+ var runInputsEl = document.getElementById("jf-run-inputs");
3814
+ var runFlowSel = document.getElementById("jf-run-flow"); // the Signed flow search box (amendment 7 item 7); nothing is picked until the human picks
3815
+ var rwSearchEl = document.getElementById("rw-search");
3816
+ var rwListEl = document.getElementById("rw-list");
3817
+ var rwPickedEl = document.getElementById("rw-picked");
3818
+ var rwPickedTxt = document.getElementById("rw-picked-txt");
3819
+ var capNoteEl = document.getElementById("jf-cap-note");
3820
+ var runDestEl = document.getElementById("jf-run-dest"); // Run a signed flow: the open Destination box (amendment 5)
3821
+ var runCapEl = document.getElementById("jf-run-cap"); // ... and the open Cap $ box
3822
+ var runWaitsEl = document.getElementById("jf-run-waits"); // ... and one wait box per ask
3823
+ var resumeBox = document.getElementById("jf-resume"); // the "Resume run-<n>" form (amendment 4 item 4): only Cap $ is open
3824
+ var resumeCapEl = document.getElementById("jf-resume-cap");
3825
+ var modeRow = document.getElementById("jf-mode-row");
3826
+ var titleEl = document.getElementById("job-card-title");
3827
+
3828
+ var mode = "new"; // "new" | "run" | "resume"
3829
+ var runSignInfo = null; // Run form, first Sign & run click: { hash } (cleared by any edit)
3830
+ var resumeCtx = null; // the run being resumed: { flow, runId, form }
3831
+ var resumeSignInfo = null; // Resume form, first Sign & resume click: { hash }
3832
+ var modeBeforeResume = "new";
3833
+ var mainAction = "none";
3834
+ var startOk = false;
3835
+ var sessionId = null; // the draft's id (GET /api/author/<id>)
3836
+ var sessionLive = false; // a draft exists that is not abandoned or signed
3837
+ var lastState = null; // the draft as the server last described it
3838
+ var signInfo = null; // the first Sign click's reply: { hash, flowName, capUsd, runId }
3839
+ var signClickedOnce = false;
3840
+ var busy = false; // a POST is in flight (disabled from the click until the reply)
3841
+ var startId = null; // the run start being watched (GET /api/author/start/<id>)
3842
+ var refusedStartId = null; // a refused start whose sentence is on the card; Clear dismisses it on the server (cleared.json)
3843
+ var pollTimer = null;
3844
+ var startTimer = null;
3845
+ var drafterModel = "";
3846
+ var flows = [];
3847
+ // a draft that is abandoned or signed ends the card's life; red/stopped drafts stay on the card (to read, to fix, to retry)
3848
+ var CLIENT_TERMINAL_PHASES = ["abandoned", "signed"];
3849
+
3850
+ function authorPost(path, body){
3851
+ return postJSON(path, body || {}).then(function(r){ return {status: r.status, body: r.body}; });
3852
+ }
3853
+ function authorGet(path){
3854
+ return fetch(path, { method: "GET", headers: { accept: "application/json" } }).then(function(r){
3855
+ return r.text().then(function(t){
3856
+ var j = null;
3857
+ try{ j = JSON.parse(t); }catch(e){}
3858
+ return j;
3859
+ });
3860
+ });
3861
+ }
3862
+
3863
+ // ---- the pure decisions (no DOM) ----
3864
+ // ONE wide button below the card. Its wording, action and enabled state are ONE pure function of
3865
+ // state = { mode, session, startOk, busy, phase, signClicked, hash, capUsd }.
3866
+ // Actions: draft | run | run-sign-prepare | run-sign | resume-sign-prepare | resume-sign | revise | sign-prepare | sign | none.
3867
+ function mainButtonFor(st){
3868
+ var cap = st.capUsd;
3869
+ var spends = (cap !== undefined && cap !== null && cap !== "") ? " — spends up to $" + cap : "";
3870
+ var blocked = !st.startOk || !!st.busy;
3871
+ if(st.mode === "run"){
3872
+ // amendment 5 item 3: inputs alone = Run (one click); a Destination, Cap $ or ask wait different from the flow's = Sign & run (two clicks, bound to a hash)
3873
+ if(st.runDiffers){
3874
+ if(st.runSignClicked){
3875
+ var runCap = (cap !== undefined && cap !== null && cap !== "") ? " \u00b7 $" + cap : "";
3876
+ return {text: "Sign " + String(st.hash || "").slice(0, 8) + " & run" + runCap, action: "run-sign", disabled: !!st.busy};
3877
+ }
3878
+ return {text: "Sign & run", action: "run-sign-prepare", disabled: blocked};
3879
+ }
3880
+ return {text: "Run" + spends, action: "run", disabled: blocked};
3881
+ }
3882
+ if(st.mode === "resume"){
3883
+ if(st.runSignClicked){
3884
+ var resCap = (cap !== undefined && cap !== null && cap !== "") ? " \u00b7 $" + cap : "";
3885
+ return {text: "Sign " + String(st.hash || "").slice(0, 8) + " & resume" + resCap, action: "resume-sign", disabled: !!st.busy};
3886
+ }
3887
+ return {text: "Sign & resume", action: "resume-sign-prepare", disabled: blocked};
3888
+ }
3889
+ if(!st.session){
3890
+ return {text: "Draft", action: "draft", disabled: blocked};
3891
+ }
3892
+ if(st.phase === "drafting"){
3893
+ return {text: "Draft", action: "none", disabled: true};
3894
+ }
3895
+ if(st.phase === "red"){
3896
+ return {text: "Fix and draft again", action: "draft", disabled: blocked};
3897
+ }
3898
+ if(st.phase === "stopped"){
3899
+ return {text: "Draft again", action: "draft", disabled: blocked};
3900
+ }
3901
+ if(st.phase === "revising"){
3902
+ return {text: "Sign & run", action: "none", disabled: true};
3903
+ }
3904
+ if(st.phase === "green"){
3905
+ // amendment 3 item 3: a note in the ask box makes the one button Send (a change to the plan); empty, it is Sign & run
3906
+ if(st.boxOpen && !st.textEmpty){
3907
+ return {text: "Send", action: "revise", disabled: !!st.busy};
3908
+ }
3909
+ if(st.signClicked){
3910
+ var signCap = (cap !== undefined && cap !== null && cap !== "") ? " \u00b7 $" + cap : "";
3911
+ return {text: "Sign " + String(st.hash || "").slice(0, 8) + " & run" + signCap, action: "sign", disabled: !!st.busy};
3912
+ }
3913
+ return {text: "Sign & run", action: "sign-prepare", disabled: !!st.busy};
3914
+ }
3915
+ return {text: "Draft", action: "none", disabled: true};
3916
+ }
3917
+ // pure: the ask box is open on a green plan with changes left (bareloop: it closes at 0); the hint under the button says how many.
3918
+ function askBoxOpenFor(st){
3919
+ return st.mode === "new" && !!st.session && st.phase === "green" && (st.left || 0) > 0;
3920
+ }
3921
+ // pure: Start over shows only when the plan on show has used both changes (the ask box is closed): the second choice beside Sign & run
3922
+ function startOverShownFor(st){
3923
+ return st.mode === "new" && !!st.session && st.phase === "green" && st.left === 0;
3924
+ }
3925
+ // borrowed-from: bareloop src/panel/index.html@c1d87ce (renderMessages: "you" / bot bubbles, each with a who label)
3926
+ // pure: the bubbles above the plan (amendment 6 item 3), from the draft's notes: each note is a you bubble in the human's words, each green change a fwdloop bubble.
3927
+ // A red or stopped change gets no bubble of its own: its reds are in the progress list, shown once.
3928
+ function bubblesFor(state){
3929
+ var out = [];
3930
+ if(!state || (state.phase !== "green" && state.phase !== "revising")) return out;
3931
+ (state.notes || []).forEach(function(nt){
3932
+ out.push({role: "you", who: "you", text: String(nt.text || "").replace(/\s+$/, "")});
3933
+ if(nt.phase === "green") out.push({role: "bot", who: "fwdloop", text: "New plan, hash " + String(nt.hash || "").slice(0, 8) + ". " + changesLeftText(nt.left) + "."});
3934
+ });
3935
+ return out;
3936
+ }
3937
+ function changesLeftText(left){
3938
+ return left + (left === 1 ? " change left" : " changes left");
3939
+ }
3940
+ // pure: the gutter beside a box (amendment 2, plain numbers by amendment 3), one entry per LOGICAL line. The job: `N` on a step line (numbers go on), `~` on a
3941
+ // guardrail line, nothing on an empty line. The inputs: a number per non-empty line.
3942
+ function gutterMarks(kind, text){
3943
+ var n = 0;
3944
+ return String(text).split("\n").map(function(line){
3945
+ var t = line.trim();
3946
+ if(t === "") return "";
3947
+ if(kind === "job" && t.charAt(0) === "~") return "~";
3948
+ n += 1;
3949
+ return String(n);
3950
+ });
3951
+ }
3952
+ // pure: the progress list for a draft. Chronological; a waiting step has no check; a step's detail lines sit under it; no two
3953
+ // identical lines in a row. `ctx` = { model, starting }.
3954
+ function stepsFor(state, ctx){
3955
+ var out = [];
3956
+ var who = ctx.model ? ctx.model : "the drafter";
3957
+ var cap = state && state.card && state.card.capUsd !== undefined && state.card.capUsd !== "" ? state.card.capUsd : "";
3958
+ var capPart = cap !== "" ? ", run cap $" + cap : "";
3959
+ if(state){
3960
+ if(state.phase === "drafting"){
3961
+ out.push({id: "drafting", label: "drafting with " + who + capPart, status: "running", details: []});
3962
+ } else if(state.phase === "red"){
3963
+ out.push({id: "drafted", label: "drafted with " + who, status: "done", details: []});
3964
+ out.push({id: "checks", label: "plan checks", status: "failed", details: (state.reds || []).slice()});
3965
+ } else if(state.phase === "stopped"){
3966
+ out.push({id: "drafting", label: "drafting with " + who + capPart, status: "failed", details: []});
3967
+ } else if(state.phase === "green" || state.phase === "revising"){
3968
+ out.push({id: "drafted", label: "drafted with " + who, status: "done", details: []});
3969
+ // amendment 3 item 3: each note the human sent is a line of its own, with its result (a red change shows its reds)
3970
+ (state.notes || []).forEach(function(nt){
3971
+ var body = String(nt.text || "").replace(/\s+$/, "");
3972
+ var label = "change " + nt.n + ": " + body;
3973
+ if(nt.phase === "running") out.push({id: "change-" + nt.n, label: label, status: "running", details: []});
3974
+ else if(nt.phase === "green") out.push({id: "change-" + nt.n, label: label, status: "done", details: []});
3975
+ else out.push({id: "change-" + nt.n, label: label, status: "failed", details: (nt.reds && nt.reds.length ? nt.reds.slice() : []).concat(nt.say ? [nt.say] : [])});
3976
+ });
3977
+ if(state.phase === "revising"){
3978
+ // the last green plan stays on show; nothing to sign until the change comes back
3979
+ } else if(ctx.starting){
3980
+ out.push({id: "signed", label: "signed", status: "done", details: []});
3981
+ } else {
3982
+ out.push({id: "sign", label: ctx.signClicked ? "waiting for your second click" : "waiting for your signature", status: "waiting", details: []});
3983
+ }
3984
+ }
3985
+ }
3986
+ if(ctx.starting) out.push({id: "starting", label: "starting the run", status: "running", details: []});
3987
+ return out.filter(function(s, i){ return i === 0 || JSON.stringify(s) !== JSON.stringify(out[i - 1]); });
3988
+ }
3989
+ // pure: did this POST succeed (one decision for every handler)
3990
+ function chatPostOutcome(r){
3991
+ var ok = !!(r && r.status >= 200 && r.status < 300 && r.body && r.body.ok === true);
3992
+ return {ok: ok, error: ok ? "" : refusalText(r)};
3993
+ }
3994
+ var FIX_BOXES_SAY = "Not started. Fix the marked boxes. Nothing spent.";
3995
+ // the banner that only points at marked boxes goes when the last marked box clears; any other sentence (a refusal with no box) stays
3996
+ function dropFixBoxesBanner(){
3997
+ if(actionErrEl.textContent !== FIX_BOXES_SAY) return;
3998
+ var any = false;
3999
+ card.querySelectorAll(".jf-err").forEach(function(x){ if(x.textContent) any = true; });
4000
+ if(!any) actionErrEl.textContent = "";
4001
+ }
4002
+ // pure: the one sentence for a refused call — the server's own `say`, else its field refusals, else a plain fallback
4003
+ function refusalText(r){
4004
+ var b = r && r.body;
4005
+ if(b && typeof b.say === "string" && b.say !== "") return b.say;
4006
+ if(b && Array.isArray(b.refusals) && b.refusals.length) return FIX_BOXES_SAY;
4007
+ return "The request failed. Nothing was sent.";
4008
+ }
4009
+
4010
+ // grow a text box with its text (a few rows, then it scrolls inside); ONE function for the card boxes.
4011
+ // A box that is hidden (or not laid out) measures 0 and gets no inline height.
4012
+ function fitBox(el){
4013
+ el.style.height = "auto";
4014
+ if(!el.scrollHeight){ el.style.height = ""; return; }
4015
+ var border = el.offsetHeight - el.clientHeight;
4016
+ el.style.height = Math.min(el.scrollHeight + border, 200) + "px";
4017
+ }
4018
+ // Paint a gutter: a hidden mirror of the textarea (same font, same content width, same wrapping) measures each logical line's height;
4019
+ // the gutter gets one entry of exactly that height, its mark on the first visual line. Re-run on every input, resize and fit.
4020
+ function paintGutter(ta, kind){
4021
+ var gut = document.getElementById(ta.id + "-gut");
4022
+ if(!gut || !ta.clientWidth) return; // hidden (the other mode): painted when it is shown
4023
+ var inner = gut.firstChild;
4024
+ var cs = getComputedStyle(ta);
4025
+ var mir = ta.jfMirror;
4026
+ if(!mir){ mir = document.createElement("div"); mir.className = "jf-mirror"; ta.parentNode.appendChild(mir); ta.jfMirror = mir; }
4027
+ ["fontFamily", "fontSize", "fontWeight", "fontStyle", "letterSpacing", "wordSpacing", "lineHeight", "tabSize"].forEach(function(k){ mir.style[k] = cs[k]; });
4028
+ gut.style.lineHeight = cs.lineHeight;
4029
+ var padT = (parseFloat(cs.paddingTop) || 0) + (parseFloat(cs.borderTopWidth) || 0);
4030
+ mir.style.width = Math.max(0, ta.clientWidth - (parseFloat(cs.paddingLeft) || 0) - (parseFloat(cs.paddingRight) || 0)) + "px";
4031
+ mir.innerHTML = "";
4032
+ var lines = ta.value.split("\n");
4033
+ lines.forEach(function(l){ var d = document.createElement("div"); d.textContent = l === "" ? "\u200b" : l; mir.appendChild(d); });
4034
+ var marks = gutterMarks(kind, ta.value);
4035
+ var hs = Array.prototype.map.call(mir.children, function(d){ return d.getBoundingClientRect().height; });
4036
+ inner.innerHTML = "";
4037
+ inner.style.paddingTop = padT + "px";
4038
+ marks.forEach(function(m, i){ var d = document.createElement("div"); d.style.height = hs[i] + "px"; d.textContent = m; inner.appendChild(d); });
4039
+ inner.style.transform = "translateY(" + (-ta.scrollTop) + "px)";
4040
+ }
4041
+ function fitCardBoxes(){
4042
+ fitBox(jobEl); fitBox(inputsBox);
4043
+ paintGutter(jobEl, "job"); paintGutter(inputsBox, "inputs");
4044
+ }
4045
+ [[jobEl, "job"], [inputsBox, "inputs"]].forEach(function(pair){
4046
+ pair[0].addEventListener("scroll", function(){
4047
+ var inner = document.getElementById(pair[0].id + "-gut").firstChild;
4048
+ inner.style.transform = "translateY(" + (-pair[0].scrollTop) + "px)";
4049
+ });
4050
+ });
4051
+
4052
+ // ---- the card's boxes ----
4053
+ function byId(id){ return document.getElementById(id); }
4054
+ function setVal(id, v){ byId(id).value = (v === undefined || v === null) ? "" : String(v); }
4055
+ function makeInput(cls, placeholder, value){
4056
+ var el = document.createElement("input");
4057
+ el.type = "text"; el.className = cls; el.placeholder = placeholder; el.autocomplete = "off"; el.spellcheck = false;
4058
+ el.value = (value === undefined || value === null) ? "" : String(value);
4059
+ return el;
4060
+ }
4061
+ function makeErr(){ var d = document.createElement("div"); d.className = "jf-err"; return d; }
4062
+ // Run a signed flow: one row per DECLARED role (the role is fixed), the path prefilled from the last run
4063
+ function paintRunRows(f, sources){
4064
+ runInputsEl.innerHTML = "";
4065
+ ((f && f.roles) || []).forEach(function(role){
4066
+ var row = document.createElement("div");
4067
+ row.className = "jf-inrow";
4068
+ var ro = document.createElement("div");
4069
+ ro.className = "jf-role-ro"; ro.textContent = role; ro.setAttribute("data-role", role);
4070
+ row.appendChild(ro);
4071
+ row.appendChild(makeInput("jf-path", "/full/path/to/file", sources ? sources[role] : ""));
4072
+ row.appendChild(makeErr());
4073
+ runInputsEl.appendChild(row);
4074
+ });
4075
+ syncCardLock();
4076
+ }
4077
+ function readRows(container){
4078
+ return Array.prototype.map.call(container.children, function(row){
4079
+ var roleEl = row.querySelector(".jf-role");
4080
+ var role = roleEl ? roleEl.value.trim() : row.querySelector(".jf-role-ro").getAttribute("data-role");
4081
+ return {role: role, path: row.querySelector(".jf-path").value.trim()};
4082
+ });
4083
+ }
4084
+ function currentCard(){
4085
+ return {
4086
+ flowName: byId("jf-name").value.trim(),
4087
+ job: jobEl.value,
4088
+ destination: destEl.value.trim(),
4089
+ inputs: inputsBox.value,
4090
+ capUsd: byId("jf-cap-money").value.trim(),
4091
+ askWait: askWaitEl.value.trim()
4092
+ };
4093
+ }
4094
+ function runWaits(){
4095
+ var waits = {};
4096
+ runWaitsEl.querySelectorAll("input.jf-wait").forEach(function(el){ waits[el.getAttribute("data-line")] = el.value.trim(); });
4097
+ return waits;
4098
+ }
4099
+ function currentRun(){
4100
+ return {
4101
+ flow: pickedFlow || "", inputs: readRows(runInputsEl), runId: (byId("jf-run-id").value.trim() === autoRunId ? "" : byId("jf-run-id").value.trim()),
4102
+ destination: runDestEl.value.trim(), capUsd: runCapEl.value.trim(), askWaits: runWaits()
4103
+ };
4104
+ }
4105
+ // pure-ish (reads the boxes): does the Run form differ from the flow's own signed values? Only a convenience that picks the button's wording
4106
+ // (Run vs Sign & run); the server decides again and never trusts this.
4107
+ function runDiffers(){
4108
+ var f = selectedFlow();
4109
+ if(!f || !f.values) return false;
4110
+ var dest = runDestEl.value.trim();
4111
+ if(f.hasSend && dest !== "" && dest !== f.values.destination) return true;
4112
+ var cap = runCapEl.value.trim();
4113
+ if(cap !== "" && !(isFinite(Number(cap)) && Number(cap) === f.values.capUsd)) return true;
4114
+ var waits = runWaits();
4115
+ return Object.keys(waits).some(function(k){ return waits[k] !== "" && waits[k].toLowerCase() !== f.values.askWaits[k]; });
4116
+ }
4117
+ function capValid(text){
4118
+ var v = Number(text);
4119
+ return text !== "" && isFinite(v) && v > 0;
4120
+ }
4121
+ function selectedFlow(){
4122
+ if(pickedFlow === null) return null;
4123
+ for(var i = 0; i < flows.length; i++){ if(flows[i].flow === pickedFlow) return flows[i]; }
4124
+ return (againEntry && againEntry.flow === pickedFlow) ? againEntry : null;
4125
+ }
4126
+ // client-side convenience only (the server's $0 checks are the real gate): is there enough on the card to click?
4127
+ function startReady(){
4128
+ if(moneyRed) return false; // amendment 4 item 1: a cap that does not fit this month stops you before the click (the server still refuses)
4129
+ if(mode === "run"){
4130
+ return !!selectedFlow() && readRows(runInputsEl).every(function(r){ return r.path !== ""; }) && capValid(runCapEl.value.trim());
4131
+ }
4132
+ if(mode === "resume"){
4133
+ return !!resumeCtx && capValid(resumeCapEl.value.trim());
4134
+ }
4135
+ var c = currentCard();
4136
+ var v = Number(c.capUsd);
4137
+ return c.flowName !== "" && c.job.trim() !== "" && c.capUsd !== "" && isFinite(v) && v > 0;
4138
+ }
4139
+
4140
+ // ---- the money note under Cap (M4e amendment 4 items 1-2) ----
4141
+ // borrowed-from: bareloop src/panel/index.html@c1d87ce — `refreshCapNote` (debounced re-read as the cap is typed), without its
4142
+ // plain-text-only rule: here a note that is red turns the main button off. The words and the numbers come from the server
4143
+ // (GET /api/author/monthly-check, one read-only check); the page decides nothing but where to show them. A fetch error clears the note.
4144
+ var moneyRed = false;
4145
+ var capNoteSeq = 0;
4146
+ var capNoteTimer = null;
4147
+ function setMoneyNote(text, red){
4148
+ var els = [capNoteEl, byId("jf-run-left"), byId("jf-resume-left")];
4149
+ els.forEach(function(el){ el.textContent = ""; el.classList.remove("money-red"); });
4150
+ var el = els[mode === "run" ? 1 : (mode === "resume" ? 2 : 0)];
4151
+ el.textContent = text;
4152
+ el.classList.toggle("money-red", !!red && text !== "");
4153
+ var was = moneyRed;
4154
+ moneyRed = !!red && text !== "";
4155
+ if(was !== moneyRed) refreshStartEnabled();
4156
+ }
4157
+ // a job with a step that is not an Ask needs a model round (the server's own rule decides; this only skips the floor line for an empty box)
4158
+ function jobHasModelStep(){
4159
+ return byId("jf-job").value.split("\n").some(function(l){ var t = l.trim(); return t !== "" && t.charAt(0) !== "~" && !/^ask\b/i.test(t); });
4160
+ }
4161
+ function refreshCapNote(){
4162
+ var cap = mode === "run" ? runCapEl.value.trim() : (mode === "resume" ? resumeCapEl.value.trim() : byId("jf-cap-money").value.trim());
4163
+ var seq = ++capNoteSeq;
4164
+ if(cap === ""){ setMoneyNote("", false); return; }
4165
+ // a Resume holds only what the run has still to spend (amendment 4 item 1): the server is told what is already spent
4166
+ var spent = (mode === "resume" && resumeCtx) ? "&spent=" + encodeURIComponent(String(resumeCtx.form.spentUsd)) : "";
4167
+ authorGet("/api/author/monthly-check?cap=" + encodeURIComponent(cap) + spent).then(function(j){
4168
+ if(seq !== capNoteSeq) return;
4169
+ if(!j || j.ok !== true){ setMoneyNote("", false); return; }
4170
+ var v = Number(cap);
4171
+ if(mode === "new" && j.floorText && isFinite(v) && v > 0 && v < j.floorUsd && jobHasModelStep()){ setMoneyNote(j.floorText, true); return; }
4172
+ // a Run's own cap is never judged against the floor (an old flow signed lower still runs plain); a changed cap below it is red
4173
+ var sf = selectedFlow();
4174
+ if(mode === "run" && sf && j.floorText && isFinite(v) && v > 0 && v !== sf.capUsd && v < sf.capFloorUsd){ setMoneyNote(sf.floorText, true); return; }
4175
+ if(mode === "resume" && resumeCtx && j.floorText && isFinite(v) && v > resumeCtx.form.spentUsd && v < resumeCtx.form.floorUsd){ setMoneyNote(resumeCtx.form.floorText, true); return; }
4176
+ setMoneyNote(typeof j.text === "string" ? j.text : "", j.red === true);
4177
+ }).catch(function(){ if(seq === capNoteSeq) setMoneyNote("", false); });
4178
+ }
4179
+ function scheduleCapNote(){
4180
+ if(capNoteTimer) clearTimeout(capNoteTimer);
4181
+ capNoteTimer = setTimeout(refreshCapNote, 250);
4182
+ }
4183
+
4184
+ // ---- a refusal shows next to its box ----
4185
+ function clearFieldErrors(){
4186
+ card.querySelectorAll(".jf-err").forEach(function(e){ e.textContent = ""; });
4187
+ }
4188
+ function errElFor(field){
4189
+ var m = /^inputs\.(\d+)$/.exec(field);
4190
+ if(m){ // a Run-a-signed-flow row (the New job card reports "inputs" by line number)
4191
+ var row = runInputsEl.children[Number(m[1])];
4192
+ return row ? row.querySelector(".jf-err") : null;
4193
+ }
4194
+ if(field === "inputs") return byId(mode === "run" ? "jf-err-run-inputs" : "jf-err-inputs");
4195
+ if(mode === "run" && (field === "destination" || field === "capUsd")) return byId("jf-err-run-" + field);
4196
+ if(mode === "run" && /^askWaits/.test(field)) return byId("jf-err-run-askWaits");
4197
+ if(mode === "resume" && field === "capUsd") return byId("jf-err-resume-capUsd");
4198
+ return byId("jf-err-" + field);
4199
+ }
4200
+ // returns the sentences that had no box to sit next to
4201
+ function showRefusals(list){
4202
+ var unplaced = [];
4203
+ list.forEach(function(r){
4204
+ var el = errElFor(String(r.field));
4205
+ if(el){ el.textContent = el.textContent ? el.textContent + " " + r.say : r.say; } else { unplaced.push(r.say); }
4206
+ });
4207
+ return unplaced;
4208
+ }
4209
+
4210
+ // ---- the lock: while a draft is drafting or waiting to be signed, a start is in flight, or a POST is out, NOTHING on the card
4211
+ // is editable (the draft was made from these values). ONE function owns it. A red or stopped draft unlocks the card (fix, draft again).
4212
+ function cardLocked(){
4213
+ var ph = (sessionLive && lastState) ? lastState.phase : null;
4214
+ return busy || startId !== null || (mode === "new" && (ph === "drafting" || ph === "revising" || ph === "green"));
4215
+ }
4216
+ function syncCardLock(){
4217
+ var on = cardLocked();
4218
+ card.querySelectorAll("input[type=text], textarea").forEach(function(el){ el.readOnly = on; el.classList.toggle("locked", on); });
4219
+ runFlowSel.disabled = on;
4220
+ runFlowSel.classList.toggle("locked", on);
4221
+ rwPickedEl.classList.toggle("locked", on);
4222
+ card.querySelectorAll('input[name="jf-mode"]').forEach(function(r){ r.disabled = on || sessionLive; });
4223
+ }
4224
+ // top-right: Abandon while a draft is live and unsigned, else Clear
4225
+ function clearButtonFor(live, hasId){
4226
+ return live ? {text: "Abandon", disabled: !hasId || busy} : {text: "Clear", disabled: busy};
4227
+ }
4228
+ function refreshClearBtn(){
4229
+ var b = mode === "resume" ? {text: "Cancel", disabled: busy} : clearButtonFor(sessionLive, !!sessionId);
4230
+ clearBtn.textContent = b.text;
4231
+ clearBtn.disabled = b.disabled;
4232
+ }
4233
+ function refreshStartEnabled(){
4234
+ startOk = startReady();
4235
+ syncCardLock();
4236
+ renderMain();
4237
+ refreshClearBtn();
4238
+ }
4239
+
4240
+ // ---- Run a signed flow: the list comes from the server (only flows whose signature checks out) ----
4241
+ var paintedFlow = null;
4242
+ // the Signed flow search (amendment 7 item 7): what is picked is a flow, and optionally one of its runs (then that run's values fill the boxes)
4243
+ var pickedFlow = null, pickedRun = null, pickedLabel = "", againEntry = null, rwShown = [], rwHl = 0;
4244
+ function pickedKey(){ return pickedFlow === null ? "" : pickedFlow + "/" + (pickedRun ? pickedRun.runId : ""); }
4245
+ var autoRunId = ""; // the prefilled next name (amendment 3): an untouched box sends "" and the server claims the next number itself
4246
+ // the signed job as the dimmed read-only block both forms show (amendment 4/5: what a run cannot change is shown, not editable)
4247
+ function paintJobDim(el, lines){
4248
+ el.innerHTML = "";
4249
+ (lines || []).forEach(function(l){
4250
+ var row = document.createElement("div");
4251
+ row.className = "ro-line";
4252
+ var n = document.createElement("span"); n.className = "ro-n"; n.textContent = String(l.n);
4253
+ var t = document.createElement("span"); t.textContent = (l.ask ? "Ask: " : "") + l.text + (l.guardrail ? " ~ " + l.guardrail : "");
4254
+ row.appendChild(n); row.appendChild(t);
4255
+ el.appendChild(row);
4256
+ });
4257
+ }
4258
+ function paintRunFlow(){
4259
+ var f = selectedFlow();
4260
+ var v = f ? (pickedRun ? pickedRun.values : f.values) : null; // a picked run's own values, else the flow's own
4261
+ paintedFlow = pickedKey();
4262
+ runSignInfo = null;
4263
+ paintJobDim(byId("jf-run-job"), f ? f.jobLines : []);
4264
+ runDestEl.value = v && v.destination ? v.destination : "";
4265
+ runDestEl.readOnly = !(f && f.hasSend);
4266
+ runDestEl.classList.toggle("locked", !(f && f.hasSend));
4267
+ byId("jf-run-dest-hint").textContent = !f ? "" : (f.hasSend ? "Where the accepted result is placed, at the last step. A different folder is signed for this run only." : "This flow has no send step, so there is no destination to set.");
4268
+ runCapEl.value = v ? String(v.capUsd) : "";
4269
+ runWaitsEl.innerHTML = "";
4270
+ Object.keys((v && v.askWaits) || {}).forEach(function(line){
4271
+ var row = document.createElement("div");
4272
+ row.className = "jf-waitrow";
4273
+ var lab = document.createElement("label");
4274
+ lab.textContent = "Ask wait \u00b7 line " + line;
4275
+ var inp = makeInput("jf-wait", "e.g. 30m", v.askWaits[line]);
4276
+ inp.setAttribute("data-line", line);
4277
+ inp.setAttribute("data-testid", "jf-run-wait-" + line);
4278
+ row.appendChild(lab); row.appendChild(inp);
4279
+ runWaitsEl.appendChild(row);
4280
+ });
4281
+ paintRunRows(f, pickedRun ? pickedRun.sources : (f ? f.lastSources : null));
4282
+ autoRunId = f && f.nextRunId ? f.nextRunId : "";
4283
+ byId("jf-run-id").value = autoRunId;
4284
+ clearFieldErrors();
4285
+ refreshCapNote();
4286
+ }
4287
+ // borrowed-from: bareloop src/panel/index.html@b5e37b8 — the Reuse workflow picker: ONE function shows the search box + list before a pick and the
4288
+ // picked box after; a row is the name (the typed part marked) over the flow's track record line.
4289
+ function rwMark(name, q){
4290
+ var i = q ? name.toLowerCase().indexOf(q.toLowerCase()) : -1;
4291
+ if(i < 0) return escapeXml(name);
4292
+ return escapeXml(name.slice(0, i)) + "<mark>" + escapeXml(name.slice(i, i + q.length)) + "</mark>" + escapeXml(name.slice(i + q.length));
4293
+ }
4294
+ function renderFlowSearch(){
4295
+ var picked = pickedFlow !== null;
4296
+ rwSearchEl.hidden = picked;
4297
+ rwPickedEl.hidden = !picked;
4298
+ rwPickedTxt.innerHTML = picked ? "<b>" + escapeXml(pickedLabel) + "</b>" : "";
4299
+ if(picked) return;
4300
+ var q = runFlowSel.value.trim();
4301
+ rwShown = flowChoices(flows, q);
4302
+ if(rwHl >= rwShown.length) rwHl = 0;
4303
+ rwListEl.innerHTML = rwShown.length ? rwShown.map(function(c, i){
4304
+ return '<li data-i="' + i + '" data-testid="rw-item" class="' + (i === rwHl ? "hl" : "") + '"><div class="rw-name">' + rwMark(c.label, q) + '</div><div class="rw-meta">' + escapeXml(c.meta) + "</div></li>";
4305
+ }).join("") : '<div class="rw-empty" data-testid="rw-empty">' + (flows.length === 0 ? "No signed flow has a passed run yet." : 'No flow or run matches "' + escapeXml(q) + '".') + "</div>";
4306
+ }
4307
+ function pickFlowChoice(c){
4308
+ if(!c || cardLocked()) return;
4309
+ var entry = null;
4310
+ flows.forEach(function(f){ if(f.flow === c.flow) entry = f; });
4311
+ if(entry === null) return;
4312
+ var run = null;
4313
+ (entry.runs || []).forEach(function(r){ if(r.runId === c.runId) run = r; });
4314
+ pickedFlow = c.flow; pickedRun = c.runId ? run : null; pickedLabel = c.label; againEntry = null;
4315
+ runFlowSel.value = c.label;
4316
+ byId("jf-err-flow").textContent = "";
4317
+ renderFlowSearch(); paintRunFlow(); refreshStartEnabled();
4318
+ }
4319
+ function unpickFlow(){
4320
+ if(cardLocked()) return;
4321
+ pickedFlow = null; pickedRun = null; pickedLabel = ""; againEntry = null; rwHl = 0;
4322
+ runFlowSel.value = "";
4323
+ renderFlowSearch(); paintRunFlow(); refreshStartEnabled();
4324
+ }
4325
+ function loadFlows(force){
4326
+ authorGet("/api/author/flows").then(function(j){
4327
+ if(!j || j.ok !== true) return;
4328
+ flows = j.flows || [];
4329
+ if(pickedFlow !== null && !selectedFlow()){ pickedFlow = null; pickedRun = null; againEntry = null; pickedLabel = ""; runFlowSel.value = ""; }
4330
+ byId("jf-run-empty").textContent = flows.length ? "" : "No signed flow has a passed run yet. Run a job first, or use Run again on one of its runs.";
4331
+ renderFlowSearch();
4332
+ if(force || paintedFlow !== pickedKey() || (flows.length === 0 && runInputsEl.children.length > 0)) paintRunFlow();
4333
+ refreshCapNote();
4334
+ refreshStartEnabled();
4335
+ }).catch(function(){ /* the card keeps what it had */ });
4336
+ }
4337
+ // the drafting line names the model the drafter really uses (Settings' deepseek row), never a guess
4338
+ function loadModel(){
4339
+ authorGet("/api/settings/providers").then(function(j){
4340
+ var rows = (j && j.ok === true && Array.isArray(j.rows)) ? j.rows : [];
4341
+ for(var i = 0; i < rows.length; i++){ if(rows[i].slot === "deepseek" && rows[i].model){ drafterModel = String(rows[i].model); } }
4342
+ }).catch(function(){ /* the line then says "the drafter" */ });
4343
+ }
4344
+ function setMode(m){
4345
+ mode = m;
4346
+ runSignInfo = null; resumeSignInfo = null;
4347
+ document.querySelectorAll('input[name="jf-mode"]').forEach(function(r){ r.checked = (r.value === m); });
4348
+ newBox.hidden = (m !== "new");
4349
+ runBox.hidden = (m !== "run");
4350
+ resumeBox.hidden = (m !== "resume");
4351
+ modeRow.hidden = (m === "resume");
4352
+ titleEl.textContent = (m === "resume" && resumeCtx) ? "Resume " + resumeCtx.runId + " \u00b7 " + resumeCtx.flow : "Job card";
4353
+ clearFieldErrors();
4354
+ if(m === "run") loadFlows();
4355
+ refreshCapNote();
4356
+ refreshStartEnabled();
4357
+ fitCardBoxes();
4358
+ }
4359
+
4360
+ // ---- render: the progress list, the readout and the one main button ----
4361
+ // Returns true when the list's content actually changed (a new line, or the latest line changed) so the caller can scroll only
4362
+ // then; an identical poll tick returns false and leaves the person's scroll position alone.
4363
+ function renderProgress(steps){
4364
+ var before = progressRow.innerHTML;
4365
+ progressRow.hidden = steps.length === 0;
4366
+ progressRow.innerHTML = steps.map(function(st){
4367
+ var cls = st.status === "waiting" ? "wait" : (st.status === "running" ? "run" : (st.status === "failed" ? "bad" : "ok"));
4368
+ var sign = cls === "ok" ? "✓" : (cls === "bad" ? "✗" : "");
4369
+ return '<li class="step ' + cls + '" data-step="' + escapeXml(st.id) + '"><div class="step-line"><span class="step-label">' + escapeXml(st.label) + '</span>' +
4370
+ '<span class="step-sign">' + sign + '</span></div>' +
4371
+ (st.details || []).map(function(d){ return '<div class="step-detail">' + escapeXml("> " + d) + '</div>'; }).join("") + '</li>';
4372
+ }).join("");
4373
+ return progressRow.innerHTML !== before;
4374
+ }
4375
+ // the plan the human is about to sign: the drafter's readout and the hash; nothing else goes in the thread
4376
+ var threadKey = "";
4377
+ // M4e amendment 7 item 3: the readout is plain text; the server names which lines are headings (one list, authoring.js), shown bold.
4378
+ function readoutHtml(state){
4379
+ var heads = Array.isArray(state.readoutHeads) ? state.readoutHeads : [];
4380
+ return String(state.readout).replace(/\s+$/, "").split("\n").map(function(l, i){
4381
+ return heads.indexOf(i) >= 0 ? '<b class="readout-head">' + escapeXml(l) + '</b>' : escapeXml(l);
4382
+ }).join("\n");
4383
+ }
4384
+ function renderThread(state){
4385
+ var html = "";
4386
+ if(state && (state.phase === "green" || state.phase === "revising") && state.readout){
4387
+ // M4e amendment 6 item 3: bubbles (oldest first), THEN the current plan, so the plan sits right above the note box and the button
4388
+ html = bubblesFor(state).map(function(m){
4389
+ return '<div class="msg ' + m.role + '"><div class="who">' + escapeXml(m.who) + '</div>' + escapeXml(m.text) + '</div>';
4390
+ }).join("") +
4391
+ '<div class="msg bot" data-testid="chat-plan"><div class="who">fwdloop</div>' + readoutHtml(state) +
4392
+ '\n\nPlan hash: ' + escapeXml(state.hash || "") + '</div>';
4393
+ }
4394
+ if(html !== threadKey){ threadKey = html; thread.innerHTML = html; }
4395
+ }
4396
+ function renderMain(){
4397
+ var st = {mode: mode, session: sessionLive, startOk: startOk, busy: busy || startId !== null, signClicked: signClickedOnce, textEmpty: msgEl.value.trim() === ""};
4398
+ if(sessionLive && lastState){
4399
+ st.phase = lastState.phase;
4400
+ st.hash = signInfo ? signInfo.hash : lastState.hash;
4401
+ st.left = lastState.changesLeft;
4402
+ }
4403
+ st.boxOpen = askBoxOpenFor(st);
4404
+ if(mode === "run"){
4405
+ st.capUsd = runCapEl.value.trim();
4406
+ st.runDiffers = runDiffers();
4407
+ st.runSignClicked = !!runSignInfo;
4408
+ st.hash = runSignInfo ? runSignInfo.hash : "";
4409
+ } else if(mode === "resume"){
4410
+ st.capUsd = resumeCapEl.value.trim();
4411
+ st.runSignClicked = !!resumeSignInfo;
4412
+ st.hash = resumeSignInfo ? resumeSignInfo.hash : "";
4413
+ } else if(signInfo){
4414
+ st.capUsd = signInfo.capUsd;
4415
+ } else if(lastState && lastState.card){
4416
+ st.capUsd = lastState.card.capUsd;
4417
+ }
4418
+ var b = mainButtonFor(st);
4419
+ mainBtn.textContent = b.text;
4420
+ mainBtn.disabled = b.disabled;
4421
+ mainAction = b.action;
4422
+ // the ask box: open on a green plan with changes left, shown but locked while a change is being drafted, closed at 0 left
4423
+ var boxShown = st.boxOpen || (mode === "new" && sessionLive && st.phase === "revising");
4424
+ msgRow.hidden = !boxShown;
4425
+ msgEl.readOnly = !st.boxOpen || !!busy;
4426
+ mainHint.textContent = st.boxOpen ? changesLeftText(st.left) : "";
4427
+ startOverBtn.hidden = !startOverShownFor(st);
4428
+ startOverBtn.disabled = !!st.busy;
4429
+ fitCardBoxes();
4430
+ if(boxShown) fitBox(msgEl);
4431
+ }
4432
+ function renderActions(state){
4433
+ lastState = state;
4434
+ // a newer plan than the one the first Sign click showed (a change came back, or another tab): the first click is void; sign re-checks on the server too
4435
+ if(signInfo && state.hash && state.hash !== signInfo.hash){ signInfo = null; signClickedOnce = false; }
4436
+ // #chat-card-error is POLL-OWNED: it carries only the draft's own sentence (a red plan or a stopped child), written here and
4437
+ // nowhere else. A refused click goes to #chat-action-error, which this function never touches.
4438
+ errEl.textContent = ((state.phase === "red" || state.phase === "stopped") && state.say) ? state.say : "";
4439
+ var progressChanged = renderProgress(stepsFor(state, {model: drafterModel, starting: startId !== null, signClicked: signClickedOnce}));
4440
+ sessionLive = CLIENT_TERMINAL_PHASES.indexOf(state.phase) === -1;
4441
+ refreshStartEnabled();
4442
+ // while the draft is live and the list changed, bring the newest progress line into view.
4443
+ // Never moves keyboard focus, and an unchanged poll tick never scrolls.
4444
+ if(progressChanged && sessionLive && progressRow.lastElementChild){
4445
+ progressRow.lastElementChild.scrollIntoView({block: "nearest"});
4446
+ }
4447
+ }
4448
+
4449
+ // ---- actions ----
4450
+ function stopPoll(){ if(pollTimer){ clearInterval(pollTimer); pollTimer = null; } }
4451
+ function startPoll(){ stopPoll(); pollTimer = setInterval(poll, 2000); }
4452
+ function stopStart(){ if(startTimer){ clearInterval(startTimer); startTimer = null; } startId = null; }
4453
+ // the card's draft is over (abandoned or signed somewhere else, or signed here and its run refused): forget the session, keep
4454
+ // the boxes. Touches neither error line, so a refusal on screen stays on screen.
4455
+ function endSession(){
4456
+ stopPoll();
4457
+ sessionId = null; sessionLive = false; lastState = null; signInfo = null; signClickedOnce = false;
4458
+ threadKey = ""; thread.innerHTML = "";
4459
+ errEl.textContent = "";
4460
+ progressRow.hidden = true; progressRow.innerHTML = "";
4461
+ refreshStartEnabled();
4462
+ }
4463
+ function openNewCard(){
4464
+ thread.innerHTML = ""; threadKey = "";
4465
+ msgEl.value = "";
4466
+ errEl.textContent = "";
4467
+ actionErrEl.textContent = "";
4468
+ clearFieldErrors();
4469
+ stopStart();
4470
+ sessionId = null; sessionLive = false; lastState = null; signInfo = null; signClickedOnce = false; busy = false;
4471
+ stopPoll();
4472
+ progressRow.hidden = true;
4473
+ progressRow.innerHTML = "";
4474
+ refreshStartEnabled();
4475
+ }
4476
+ // back to a fresh empty card: every box, the inputs, the progress list, the ask box
4477
+ function resetCard(){
4478
+ if(mode === "resume"){ resumeCtx = null; setMode(modeBeforeResume === "resume" ? "new" : modeBeforeResume); }
4479
+ ["jf-name", "jf-job", "jf-cap-money", "jf-dest-folder", "jf-inputs"].forEach(function(id){ byId(id).value = ""; });
4480
+ askWaitEl.value = "1h";
4481
+ refreshCapNote();
4482
+ openNewCard();
4483
+ loadFlows(mode === "run");
4484
+ fitCardBoxes();
4485
+ }
4486
+ function chatActionFailed(message){
4487
+ actionErrEl.textContent = message || "The request failed. Nothing was sent.";
4488
+ }
4489
+ function chatActionOk(){
4490
+ actionErrEl.textContent = "";
4491
+ }
4492
+ // a refused POST: field refusals next to their boxes, one sentence in the action line (and any red lines under it)
4493
+ function failFrom(r){
4494
+ var b = r && r.body;
4495
+ var unplaced = (b && Array.isArray(b.refusals)) ? showRefusals(b.refusals) : [];
4496
+ var text = refusalText(r);
4497
+ if(unplaced.length) text += " " + unplaced.join(" ");
4498
+ if(b && Array.isArray(b.reds) && b.reds.length) text += "\n" + b.reds.map(function(x){ return "> " + x; }).join("\n");
4499
+ chatActionFailed(text);
4500
+ }
4501
+ var NETWORK_SAY = "Could not reach the panel. Nothing was sent.";
4502
+
4503
+ function poll(){
4504
+ if(!sessionId) return;
4505
+ var polledId = sessionId;
4506
+ authorGet("/api/author/" + polledId).then(function(j){
4507
+ if(!j || j.ok !== true || polledId !== sessionId) return;
4508
+ if(CLIENT_TERMINAL_PHASES.indexOf(j.phase) !== -1){
4509
+ // abandoned or signed from elsewhere; a start of ours is being watched by pollStart instead
4510
+ if(startId === null) endSession();
4511
+ return;
4512
+ }
4513
+ renderThread(j);
4514
+ renderActions(j);
4515
+ }).catch(function(){ /* transient — next poll tries again */ });
4516
+ }
4517
+
4518
+ // a run start (after a sign, or Run a signed flow): the CLI child may refuse before its run exists, so ask until the start says
4519
+ function beginStart(id){
4520
+ stopStart();
4521
+ startId = id;
4522
+ refusedStartId = null;
4523
+ busy = false;
4524
+ startTimer = setInterval(pollStart, 1000);
4525
+ if(lastState){ renderActions(lastState); } else {
4526
+ renderProgress(stepsFor(null, {model: drafterModel, starting: true, signClicked: false}));
4527
+ refreshStartEnabled();
4528
+ }
4529
+ pollStart();
4530
+ }
4531
+ function pollStart(){
4532
+ var watching = startId;
4533
+ if(!watching) return;
4534
+ authorGet("/api/author/start/" + watching).then(function(j){
4535
+ if(watching !== startId) return;
4536
+ if(!j) return;
4537
+ if(j.ok === true && j.phase === "started"){
4538
+ // the run lives in Runs now; the card goes back to the empty card
4539
+ stopStart();
4540
+ resetCard();
4541
+ document.getElementById("tab-runs").click();
4542
+ reloadLists();
4543
+ return;
4544
+ }
4545
+ if(j.ok === true && j.phase === "refused"){
4546
+ // the CLI's own sentence ("Nothing spent." is in it); it STAYS until the next action
4547
+ var signed = j.kind === "sign";
4548
+ stopStart();
4549
+ window.fwdloopResuming = null; // a refused start leaves the run stopped: Resume is offered again
4550
+ refusedStartId = j.startId;
4551
+ chatActionFailed(signed ? j.say + " The flow is signed; start it from \"Run a signed flow\"." : j.say);
4552
+ if(signed){ endSession(); loadFlows(true); } else { progressRow.hidden = true; progressRow.innerHTML = ""; refreshStartEnabled(); }
4553
+ return;
4554
+ }
4555
+ if(j.ok === false && j.refused === "no-such-start"){
4556
+ stopStart();
4557
+ chatActionFailed("The panel could not find this start. Look in the Runs tab to see whether the run began.");
4558
+ refreshStartEnabled();
4559
+ }
4560
+ }).catch(function(){ /* transient — next tick tries again */ });
4561
+ }
4562
+
4563
+ function doDraft(){
4564
+ clearFieldErrors();
4565
+ chatActionOk();
4566
+ // disabled from the click until the reply; unlocked below only if the draft is refused
4567
+ busy = true;
4568
+ refreshStartEnabled();
4569
+ var body = currentCard();
4570
+ authorPost("/api/author/draft", body).then(function(r){
4571
+ busy = false;
4572
+ var o = chatPostOutcome(r);
4573
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4574
+ sessionId = r.body.draftId;
4575
+ sessionLive = true;
4576
+ signInfo = null; signClickedOnce = false;
4577
+ thread.innerHTML = ""; threadKey = "";
4578
+ renderActions({draftId: sessionId, phase: "drafting", card: {capUsd: body.capUsd}});
4579
+ startPoll();
4580
+ poll();
4581
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4582
+ }
4583
+ function doRun(){
4584
+ clearFieldErrors();
4585
+ chatActionOk();
4586
+ busy = true;
4587
+ refreshStartEnabled();
4588
+ authorPost("/api/author/run", currentRun()).then(function(r){
4589
+ var o = chatPostOutcome(r);
4590
+ if(!o.ok){ busy = false; failFrom(r); refreshStartEnabled(); return; }
4591
+ beginStart(r.body.startId);
4592
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4593
+ }
4594
+ // Run a signed flow with a Destination, Cap $ or ask wait that differs from the flow's (amendment 5 item 3): click 1 asks the server what
4595
+ // is about to be signed (a hash; signs nothing), click 2 is the ONLY call that signs and starts, carrying that hash.
4596
+ function doRunSign(){
4597
+ clearFieldErrors();
4598
+ chatActionOk();
4599
+ busy = true;
4600
+ refreshStartEnabled();
4601
+ if(!runSignInfo){
4602
+ authorPost("/api/author/run-prepare", currentRun()).then(function(r){
4603
+ busy = false;
4604
+ var o = chatPostOutcome(r);
4605
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4606
+ if(r.body.needsSign !== true){ doRun(); return; } // the server sees nothing to sign after all: a plain Run
4607
+ runSignInfo = {hash: r.body.hash};
4608
+ refreshStartEnabled();
4609
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4610
+ return;
4611
+ }
4612
+ var body = currentRun();
4613
+ body.hash = runSignInfo.hash;
4614
+ authorPost("/api/author/run", body).then(function(r){
4615
+ var o = chatPostOutcome(r);
4616
+ runSignInfo = null;
4617
+ if(!o.ok){ busy = false; failFrom(r); refreshStartEnabled(); return; }
4618
+ beginStart(r.body.startId);
4619
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4620
+ }
4621
+ // the Resume form (amendment 4 item 4, "Sign & resume"): the same two clicks; the cap is the only thing in the body besides the run
4622
+ function resumeBody(){ return {flow: resumeCtx.flow, runId: resumeCtx.runId, capUsd: resumeCapEl.value.trim()}; }
4623
+ function doResumeSign(){
4624
+ if(!resumeCtx) return;
4625
+ clearFieldErrors();
4626
+ chatActionOk();
4627
+ busy = true;
4628
+ refreshStartEnabled();
4629
+ if(!resumeSignInfo){
4630
+ authorPost("/api/author/resume-prepare", resumeBody()).then(function(r){
4631
+ busy = false;
4632
+ var o = chatPostOutcome(r);
4633
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4634
+ resumeSignInfo = {hash: r.body.hash};
4635
+ refreshStartEnabled();
4636
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4637
+ return;
4638
+ }
4639
+ var body = resumeBody();
4640
+ body.hash = resumeSignInfo.hash;
4641
+ var resumingKey = resumeCtx.flow + "/" + resumeCtx.runId;
4642
+ authorPost("/api/author/resume", body).then(function(r){
4643
+ var o = chatPostOutcome(r);
4644
+ resumeSignInfo = null;
4645
+ if(!o.ok){ busy = false; failFrom(r); refreshStartEnabled(); return; }
4646
+ window.fwdloopResuming = {key: resumingKey, at: Date.now()};
4647
+ beginStart(r.body.startId);
4648
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4649
+ }
4650
+ // the Run tab's Resume button: read the form's facts from the server (it refuses a run that is not stopped), then show the card in resume mode
4651
+ function openResume(detail){
4652
+ authorGet("/api/author/resume-form?flow=" + encodeURIComponent(detail.flow) + "&runId=" + encodeURIComponent(detail.runId)).then(function(j){
4653
+ document.getElementById("tab-chat").click();
4654
+ if(!j || j.ok !== true){ chatActionFailed((j && j.say) || "This run cannot be resumed."); return; }
4655
+ if(startId !== null || sessionLive){ chatActionFailed("Finish or clear what is on the card first, then Resume."); return; }
4656
+ if(mode !== "resume") modeBeforeResume = mode;
4657
+ resumeCtx = {flow: detail.flow, runId: detail.runId, form: j};
4658
+ chatActionOk();
4659
+ paintJobDim(byId("jf-resume-job"), j.jobLines);
4660
+ byId("jf-resume-dest").textContent = j.values.destination || "no send step";
4661
+ byId("jf-resume-inputs").innerHTML = "";
4662
+ (j.inputs || []).forEach(function(i){ var d = document.createElement("div"); d.className = "ro-line"; d.textContent = i.role + ": " + i.path; byId("jf-resume-inputs").appendChild(d); });
4663
+ byId("jf-resume-waits").textContent = Object.keys(j.values.askWaits || {}).map(function(k){ return "line " + k + ": " + j.values.askWaits[k]; }).join(" \u00b7 ") || "no ask";
4664
+ resumeCapEl.value = String(j.values.capUsd);
4665
+ byId("jf-resume-hint").textContent = "Already spent $" + Number(j.spentUsd).toFixed(4) + ". Same run, same steps, nothing is redrawn; a new cap is signed for this run. Other changes are a new run or a new job.";
4666
+ setMode("resume");
4667
+ }).catch(function(){ document.getElementById("tab-chat").click(); chatActionFailed(NETWORK_SAY); });
4668
+ }
4669
+ window.fwdloopOpenResume = openResume;
4670
+ // the Run tab's Run again button (amendment 7 item 6; bareloop's Reuse workflow): the server reads the run's flow and the run's own values
4671
+ // (any outcome), then the card opens in Run a signed flow with that flow picked and the boxes filled in. A flow the run's preflight
4672
+ // would refuse is refused here with its reason.
4673
+ function openRunAgain(detail){
4674
+ authorGet("/api/author/run-again?flow=" + encodeURIComponent(detail.flow) + "&runId=" + encodeURIComponent(detail.runId)).then(function(j){
4675
+ document.getElementById("tab-chat").click();
4676
+ if(!j || j.ok !== true){ chatActionFailed((j && j.say) || "This run cannot be run again."); return; }
4677
+ if(startId !== null || sessionLive || mode === "resume"){ chatActionFailed("Finish or clear what is on the card first, then Run again."); return; }
4678
+ chatActionOk();
4679
+ againEntry = j.flow; pickedFlow = j.flow.flow; pickedRun = j.pick; pickedLabel = j.flow.flow + " (" + j.pick.runId + ")";
4680
+ runFlowSel.value = pickedLabel;
4681
+ setMode("run");
4682
+ renderFlowSearch(); paintRunFlow(); refreshStartEnabled();
4683
+ }).catch(function(){ document.getElementById("tab-chat").click(); chatActionFailed(NETWORK_SAY); });
4684
+ }
4685
+ window.fwdloopRunAgain = openRunAgain;
4686
+ function doSign(){
4687
+ if(!sessionId) return;
4688
+ var id = sessionId;
4689
+ if(!signClickedOnce){
4690
+ // click 1: what is about to be signed (the hash, the cap). Signs nothing.
4691
+ busy = true;
4692
+ refreshStartEnabled();
4693
+ authorPost("/api/author/" + id + "/sign-prepare", {}).then(function(r){
4694
+ busy = false;
4695
+ var o = chatPostOutcome(r);
4696
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4697
+ chatActionOk();
4698
+ signInfo = {hash: r.body.hash, flowName: r.body.flowName, capUsd: r.body.capUsd, runId: r.body.runId};
4699
+ signClickedOnce = true;
4700
+ if(lastState) renderActions(lastState); else refreshStartEnabled();
4701
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4702
+ return;
4703
+ }
4704
+ // click 2: the ONLY call that signs. It carries the hash this page showed; the server signs only if it is still the draft's hash on disk.
4705
+ busy = true;
4706
+ refreshStartEnabled();
4707
+ authorPost("/api/author/" + id + "/sign", {hash: signInfo.hash}).then(function(r){
4708
+ var o = chatPostOutcome(r);
4709
+ if(!o.ok){
4710
+ busy = false;
4711
+ failFrom(r);
4712
+ if(r.body && r.body.signed === true){ endSession(); loadFlows(true); } else { refreshStartEnabled(); }
4713
+ return;
4714
+ }
4715
+ chatActionOk();
4716
+ stopPoll();
4717
+ signClickedOnce = false;
4718
+ beginStart(r.body.startId);
4719
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4720
+ }
4721
+ // amendment 3 item 3: send the note; the server drafts a changed plan beside the old one (the old one stays signable until a new green one exists).
4722
+ // A refused note stays in the box (unsent input is never wiped).
4723
+ function doRevise(){
4724
+ if(!sessionId) return;
4725
+ var id = sessionId;
4726
+ var text = msgEl.value;
4727
+ chatActionOk();
4728
+ busy = true;
4729
+ refreshStartEnabled();
4730
+ authorPost("/api/author/" + id + "/revise", {text: text}).then(function(r){
4731
+ busy = false;
4732
+ var o = chatPostOutcome(r);
4733
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4734
+ msgEl.value = "";
4735
+ signInfo = null; signClickedOnce = false;
4736
+ refreshStartEnabled();
4737
+ poll();
4738
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4739
+ }
4740
+ function doAbandon(){
4741
+ var id = sessionId;
4742
+ busy = true;
4743
+ refreshStartEnabled();
4744
+ authorPost("/api/author/" + id + "/abandon", {}).then(function(r){
4745
+ busy = false;
4746
+ var o = chatPostOutcome(r);
4747
+ if(!o.ok){ failFrom(r); refreshStartEnabled(); return; }
4748
+ resetCard();
4749
+ }).catch(function(){ busy = false; chatActionFailed(NETWORK_SAY); refreshStartEnabled(); });
4750
+ }
4751
+
4752
+ // Re-attach after a page load/refresh or a panel restart: the server reads the newest unsigned draft from its files, so ask it.
4753
+ // If one exists, this tab takes it over as if it had started it: the card filled from the draft's own copy, the poll loop, the
4754
+ // progress list, the readout and the main button. A signed or abandoned draft never comes back (empty card).
4755
+ function attachSession(d){
4756
+ var c = d.card || {};
4757
+ openNewCard();
4758
+ setMode("new");
4759
+ setVal("jf-name", c.flowName); setVal("jf-job", c.job); setVal("jf-cap-money", c.capUsd);
4760
+ refreshCapNote();
4761
+ setVal("jf-dest-folder", typeof c.destination === "string" ? c.destination : ""); setVal("jf-inputs", typeof c.inputs === "string" ? c.inputs : ""); setVal("jf-ask-wait", c.askWait || "1h");
4762
+ sessionId = d.draftId;
4763
+ sessionLive = CLIENT_TERMINAL_PHASES.indexOf(d.phase) === -1;
4764
+ renderThread(d);
4765
+ renderActions(d);
4766
+ startPoll();
4767
+ poll();
4768
+ }
4769
+ function reattachLive(){
4770
+ if(sessionId || sessionLive || startId !== null) return;
4771
+ authorGet("/api/author/live").then(function(j){
4772
+ if(sessionId || sessionLive || startId !== null || !j || j.ok !== true) return;
4773
+ if(j.draft){ attachSession(j.draft); return; }
4774
+ // no draft: the newest start the human has not cleared — still starting (watch it) or refused (show its sentence)
4775
+ var st = j.start;
4776
+ if(!st) return;
4777
+ if(st.phase === "starting"){ beginStart(st.startId); return; }
4778
+ if(st.phase === "refused"){
4779
+ refusedStartId = st.startId;
4780
+ chatActionFailed(st.kind === "sign" ? st.say + " The flow is signed; start it from \"Run a signed flow\"." : st.say);
4781
+ if(st.kind === "sign") loadFlows(true);
4782
+ }
4783
+ }).catch(function(){ /* nothing to attach to — the empty card stays */ });
4784
+ }
4785
+
4786
+ // ---- wiring ----
4787
+ clearBtn.addEventListener("click", function(){
4788
+ if(mode === "resume"){ resumeCtx = null; actionErrEl.textContent = ""; setMode(modeBeforeResume === "resume" ? "new" : modeBeforeResume); return; }
4789
+ if(clearBtn.textContent === "Abandon" && sessionId){ doAbandon(); return; }
4790
+ // a refused start's sentence is dismissed on the server too, or a reload would bring it back
4791
+ if(refusedStartId){ var rid = refusedStartId; refusedStartId = null; authorPost("/api/author/start/" + rid + "/clear", {}).catch(function(){}); }
4792
+ resetCard();
4793
+ });
4794
+ // Start over (amendment 4 item 3): the same draft call as Draft, from the card as it is now; the old draft's files stay (a new draft id)
4795
+ startOverBtn.addEventListener("click", function(){ if(!startOverBtn.disabled) doDraft(); });
4796
+ mainBtn.addEventListener("click", function(){
4797
+ if(mainBtn.disabled) return;
4798
+ if(mainAction === "draft") doDraft();
4799
+ else if(mainAction === "run") doRun();
4800
+ else if(mainAction === "run-sign-prepare" || mainAction === "run-sign") doRunSign();
4801
+ else if(mainAction === "resume-sign-prepare" || mainAction === "resume-sign") doResumeSign();
4802
+ else if(mainAction === "revise") doRevise();
4803
+ else if(mainAction === "sign-prepare" || mainAction === "sign") doSign();
4804
+ });
4805
+ msgEl.addEventListener("input", function(){ fitBox(msgEl); renderMain(); });
4806
+ // Enter sends the note, Shift+Enter is a newline (bareloop's ask box)
4807
+ msgEl.addEventListener("keydown", function(e){
4808
+ if(e.key === "Enter" && !e.shiftKey && mainAction === "revise"){ e.preventDefault(); if(!mainBtn.disabled) doRevise(); }
4809
+ });
4810
+ card.addEventListener("input", function(e){
4811
+ var grp = e.target && e.target.closest ? e.target.closest(".field, .cap-field, .jf-inrow") : null;
4812
+ if(grp) grp.querySelectorAll(".jf-err").forEach(function(x){ x.textContent = ""; });
4813
+ dropFixBoxesBanner();
4814
+ fitCardBoxes();
4815
+ if(e.target && (e.target.id === "jf-cap-money" || e.target.id === "jf-job" || e.target.id === "jf-run-cap" || e.target.id === "jf-resume-cap")) scheduleCapNote();
4816
+ // any edit voids the first Sign click of the Run / Resume form: what is shown must be what is signed
4817
+ runSignInfo = null; resumeSignInfo = null;
4818
+ refreshStartEnabled();
4819
+ });
4820
+ document.querySelectorAll('input[name="jf-mode"]').forEach(function(r){
4821
+ r.addEventListener("change", function(){ if(r.checked) setMode(r.value); });
4822
+ });
4823
+ runFlowSel.addEventListener("input", function(){ rwHl = 0; renderFlowSearch(); });
4824
+ runFlowSel.addEventListener("keydown", function(e){
4825
+ if(e.key === "ArrowDown"){ rwHl = Math.min(rwHl + 1, rwShown.length - 1); renderFlowSearch(); e.preventDefault(); }
4826
+ else if(e.key === "ArrowUp"){ rwHl = Math.max(rwHl - 1, 0); renderFlowSearch(); e.preventDefault(); }
4827
+ else if(e.key === "Enter" && rwShown[rwHl]){ e.preventDefault(); pickFlowChoice(rwShown[rwHl]); }
4828
+ });
4829
+ rwListEl.addEventListener("click", function(e){
4830
+ var li = e.target.closest ? e.target.closest("li") : null;
4831
+ if(li) pickFlowChoice(rwShown[Number(li.getAttribute("data-i"))]);
4832
+ });
4833
+ document.getElementById("rw-change").addEventListener("click", unpickFlow);
4834
+ document.getElementById("rw-change").addEventListener("keydown", function(e){ if(e.key === "Enter" || e.key === " "){ e.preventDefault(); unpickFlow(); } });
4835
+ window.addEventListener("resize", fitCardBoxes);
4836
+ document.getElementById("tab-chat").addEventListener("click", function(){ fitCardBoxes(); reattachLive(); loadFlows(); });
4837
+ // the monthly limit changed in Settings: re-read the note for whatever cap is on the card (no reload; the button follows)
4838
+ document.addEventListener("fwdloop-limit-changed", function(){ refreshCapNote(); });
4839
+
4840
+ loadModel();
4841
+ loadFlows();
4842
+ reattachLive();
4843
+ refreshStartEnabled();
4844
+ })();
4845
+
4846
+ // ---- M4d piece 4: Settings. Nothing here is re-rendered by the page's refresh tick: the Settings DOM is
4847
+ // painted only when it is opened, a tab is chosen, or a button here is pressed — and a price/limit box the
4848
+ // person has typed in ("dirty") is never overwritten by a repaint. No key value ever reaches this page. ----
4849
+ function fmtUsd(n, atLeast){
4850
+ if(typeof n !== "number" || !isFinite(n)) return "unknown";
4851
+ return (atLeast ? "≥" : "") + "$" + n.toFixed(4);
4852
+ }
4853
+ function fmtMinutes(m, atLeast){
4854
+ if(typeof m !== "number" || !isFinite(m)) return "not recorded";
4855
+ return (atLeast ? "≥" : "") + (m < 10 ? m.toFixed(1) : String(Math.round(m))) + " min";
4856
+ }
4857
+ // borrowed-from: bareloop src/panel/index.html@5a5a811 (tokensText)
4858
+ function tokensText(n){
4859
+ if(!n) return "0";
4860
+ if(n >= 1e6) return (n / 1e6).toFixed(1) + "M";
4861
+ if(n >= 1e3) return (n / 1e3).toFixed(1) + "k";
4862
+ return String(n);
4863
+ }
4864
+ // The server's own plain sentence (`say`) when it sent one; else the same words every other refusal uses.
4865
+ function settingsRefusal(r){
4866
+ var b = r && r.body;
4867
+ if(b && typeof b.say === "string" && b.say) return b.say;
4868
+ return refusalText(r, null);
4869
+ }
4870
+ // borrowed-from: bareloop src/panel/index.html@5a5a811 (Settings: one provider table, a money strip)
4871
+ // A hint line: plain text, red when it is a refusal. Empty text hides nothing and shows nothing.
4872
+ function setNote(el, bad, text){
4873
+ el.className = "hint" + (bad ? " bad" : "");
4874
+ el.textContent = text || "";
4875
+ }
4876
+ var settingsView = document.getElementById("settings-view");
4877
+ var mainView = document.getElementById("main-view");
4878
+ var pvRows = document.getElementById("pv-rows");
4879
+ var pvNote = document.getElementById("pv-note");
4880
+ var PV_NOTE_DEFAULT = pvNote.textContent;
4881
+ document.getElementById("settings-open").addEventListener("click", function(){
4882
+ mainView.hidden = true; settingsView.hidden = false;
4883
+ loadProviders(); loadMoney();
4884
+ });
4885
+ document.getElementById("settings-back").addEventListener("click", function(){
4886
+ settingsView.hidden = true; mainView.hidden = false;
4887
+ });
4888
+ wireTabs([document.getElementById("stab-providers"), document.getElementById("stab-money")]);
4889
+ document.getElementById("stab-money").addEventListener("click", function(){ loadMoney(); });
4890
+ document.getElementById("stab-providers").addEventListener("click", function(){ loadProviders(); });
4891
+
4892
+ function loadProviders(){
4893
+ return getJSON("/api/settings/providers").then(paintProviders, function(e){
4894
+ setNote(document.getElementById("keys-refusal"), true, loadFailureText(e));
4895
+ });
4896
+ }
4897
+ document.getElementById("reload-keys").addEventListener("click", function(){ loadProviders(); });
4898
+
4899
+ function sourceWord(src){
4900
+ if(src === "table") return "default";
4901
+ if(src === "ceiling") return "highest known rate, the model has no listed price";
4902
+ return "set here";
4903
+ }
4904
+ var PRICE_FIELDS = ["inPerM", "outPerM"];
4905
+ // Name, API shape and Base URL are editable (M4d amendment 1), saved on change one field at a time.
4906
+ var PROV_FIELDS = ["name", "shape", "baseUrl"];
4907
+ function buildProviderRow(row){
4908
+ var tr = document.createElement("tr");
4909
+ tr.setAttribute("data-slot", row.slot);
4910
+ tr.setAttribute("data-testid", "provider-row-" + row.slot);
4911
+ var balance = row.canBalance
4912
+ ? '<button class="btn small" type="button" data-act="balance" data-testid="prov-balance">Check</button><div class="hint pv-balance-result" data-f="balance-result"></div>'
4913
+ : '<span class="hint">not offered by this provider</span>';
4914
+ var prices = PRICE_FIELDS.map(function(f){
4915
+ return '<td class="pv-price-cell"><input type="text" inputmode="decimal" data-field="' + f + '" data-testid="price-' + f + '" aria-label="' + escapeXml(row.label + " " + f) + '">' +
4916
+ '<div class="hint pv-msg" data-f="msg-' + f + '" data-testid="price-msg-' + f + '"></div></td>';
4917
+ }).join("");
4918
+ tr.innerHTML =
4919
+ '<td><code>' + escapeXml(row.envVar) + '</code><div class="hint" data-f="status" data-testid="pv-status-' + escapeXml(row.slot) + '"></div></td>' +
4920
+ '<td class="pv-price-cell"><input type="text" data-prov="name" data-testid="prov-name" aria-label="' + escapeXml(row.label + " name") + '" autocomplete="off" spellcheck="false"><div class="hint pv-msg" data-f="msg-name" data-testid="prov-msg-name"></div></td>' +
4921
+ '<td class="pv-price-cell"><select data-prov="shape" data-testid="prov-shape" aria-label="' + escapeXml(row.label + " API shape") + '"></select><div class="hint pv-msg" data-f="msg-shape" data-testid="prov-msg-shape"></div></td>' +
4922
+ '<td class="pv-price-cell"><input type="text" data-prov="baseUrl" data-testid="prov-baseurl" aria-label="' + escapeXml(row.label + " Base URL") + '" autocomplete="off" spellcheck="false"><div class="hint pv-msg" data-f="msg-baseUrl" data-testid="prov-msg-baseUrl"></div></td>' +
4923
+ '<td class="pv-test-cell"><button class="btn small" type="button" data-act="test" data-testid="prov-test">Test</button><div class="hint pv-test-result" data-f="test" data-testid="prov-test-result"></div></td>' +
4924
+ '<td data-f="tokens" data-testid="pv-tokens-' + escapeXml(row.slot) + '"></td>' +
4925
+ '<td>' + balance + '</td>' + prices;
4926
+ tr.querySelectorAll("input").forEach(function(inp){
4927
+ inp.addEventListener("input", function(){ inp.setAttribute("data-dirty", "1"); });
4928
+ });
4929
+ return tr;
4930
+ }
4931
+ var STATUS_WORD = { "set in file": "set in file", "found in shell": "found in shell", "not set": "not set", "refused": "refused — see above" };
4932
+ function paintProviders(data){
4933
+ var path = data.keysFile && data.keysFile.path ? data.keysFile.path : "~/.config/fwdloop/.env";
4934
+ document.getElementById("keys-path").textContent = path;
4935
+ setNote(document.getElementById("keys-refusal"), true, data.keysFile && data.keysFile.refusal);
4936
+ setNote(pvNote, !!data.configProblem, data.configProblem || PV_NOTE_DEFAULT);
4937
+ data.rows.forEach(function(row){
4938
+ var tr = pvRows.querySelector('[data-slot="' + row.slot + '"]');
4939
+ if(!tr){ tr = buildProviderRow(row); pvRows.appendChild(tr); }
4940
+ tr.querySelector("[data-f=status]").textContent = STATUS_WORD[row.keyStatus] || row.keyStatus;
4941
+ var nameIn = tr.querySelector('[data-prov=name]');
4942
+ var shapeSel = tr.querySelector('[data-prov=shape]');
4943
+ var urlIn = tr.querySelector('[data-prov=baseUrl]');
4944
+ if(shapeSel.options.length !== data.shapes.length){
4945
+ shapeSel.innerHTML = "";
4946
+ data.shapes.forEach(function(sh){
4947
+ var o = document.createElement("option");
4948
+ o.value = sh.id; o.textContent = sh.label; shapeSel.appendChild(o);
4949
+ });
4950
+ }
4951
+ nameIn.placeholder = row.defaults.model;
4952
+ urlIn.placeholder = row.defaults.baseUrl !== "" ? row.defaults.baseUrl : "the vendor's own address";
4953
+ // a box the person is typing in is never overwritten by a repaint
4954
+ if(nameIn.getAttribute("data-dirty") !== "1") nameIn.value = row.model;
4955
+ if(urlIn.getAttribute("data-dirty") !== "1") urlIn.value = row.savedBaseUrl;
4956
+ if(document.activeElement !== shapeSel) shapeSel.value = row.shape;
4957
+ tr.querySelector("[data-f=tokens]").textContent = tokensText(row.tokens);
4958
+ PRICE_FIELDS.forEach(function(f){
4959
+ var inp = tr.querySelector('input[data-field="' + f + '"]');
4960
+ var pr = row.price[f];
4961
+ inp.placeholder = String(pr.value) + " (" + sourceWord(pr.source) + ")";
4962
+ inp.title = inp.placeholder;
4963
+ // a box the person has typed in is never overwritten by a repaint
4964
+ if(inp.getAttribute("data-dirty") !== "1") inp.value = pr.source === "settings" ? String(pr.value) : "";
4965
+ });
4966
+ });
4967
+ }
4968
+ pvRows.addEventListener("click", function(ev){
4969
+ var b = ev.target.closest && ev.target.closest("button[data-act]");
4970
+ if(!b) return;
4971
+ var tr = b.closest("tr");
4972
+ if(b.getAttribute("data-act") === "test") runTest(tr, tr.getAttribute("data-slot"));
4973
+ else if(b.getAttribute("data-act") === "balance") runBalance(tr, tr.getAttribute("data-slot"));
4974
+ });
4975
+ // Saved like bareloop saves a row field: on change (blur or Enter), no Save button.
4976
+ pvRows.addEventListener("change", function(ev){
4977
+ var inp = ev.target;
4978
+ if(!inp.getAttribute) return;
4979
+ if(inp.getAttribute("data-prov")){ saveProvider(inp.closest("tr"), inp); return; }
4980
+ if(!inp.getAttribute("data-field")) return;
4981
+ savePrice(inp.closest("tr"), inp.getAttribute("data-field"));
4982
+ });
4983
+ function runTest(tr, slot){
4984
+ var out = tr.querySelector("[data-f=test]");
4985
+ out.textContent = "testing…";
4986
+ postJSON("/api/settings/test", { slot: slot }).then(function(r){
4987
+ var b = r.body;
4988
+ out.textContent = b && b.ok ? "OK · " + b.ms + " ms" : (b && b.why ? b.why : settingsRefusal(r));
4989
+ }, function(){ out.textContent = networkText(); });
4990
+ }
4991
+ // Balance is read on a click, never on render (signed M4d: "read on a click").
4992
+ function runBalance(tr, slot){
4993
+ var out = tr.querySelector("[data-f=balance-result]");
4994
+ out.textContent = "checking…";
4995
+ getJSON("/api/settings/balance?slot=" + encodeURIComponent(slot)).then(function(b){
4996
+ if(b.ok) out.textContent = b.balances.map(function(x){ return x.total + " " + x.currency; }).join(" + ");
4997
+ else out.textContent = b.why || "Could not check the balance.";
4998
+ }, function(e){ out.textContent = loadFailureText(e); });
4999
+ }
5000
+ // A box the person typed: empty = back to the default (null); a number is sent as a number; anything else is
5001
+ // sent as the text typed, so the server refuses it by naming the box.
5002
+ function priceValue(text){
5003
+ var t = String(text).trim();
5004
+ if(t === "") return null;
5005
+ var n = Number(t);
5006
+ return isFinite(n) ? n : t;
5007
+ }
5008
+ function savePrice(tr, changed){
5009
+ var msg = tr.querySelector("[data-f=msg-" + changed + "]");
5010
+ var payload = { slot: tr.getAttribute("data-slot") };
5011
+ tr.querySelectorAll("input[data-field]").forEach(function(inp){ payload[inp.getAttribute("data-field")] = priceValue(inp.value); });
5012
+ postJSON("/api/settings/price", payload).then(function(r){
5013
+ if(r.body && r.body.ok){
5014
+ tr.querySelectorAll("input[data-field]").forEach(function(inp){ inp.removeAttribute("data-dirty"); });
5015
+ loadProviders();
5016
+ setNote(msg, false, "saved — applies from the next model call");
5017
+ } else setNote(msg, true, settingsRefusal(r));
5018
+ }, function(){ setNote(msg, true, networkText()); });
5019
+ }
5020
+
5021
+ // One field per save: {slot, name|shape|baseUrl}. An empty Base URL means the default; a refusal is the cell's hint line.
5022
+ function saveProvider(tr, inp){
5023
+ var key = inp.getAttribute("data-prov");
5024
+ var msg = tr.querySelector("[data-f=msg-" + key + "]");
5025
+ var payload = { slot: tr.getAttribute("data-slot") };
5026
+ payload[key] = inp.value.trim();
5027
+ postJSON("/api/settings/provider", payload).then(function(r){
5028
+ if(r.body && r.body.ok){
5029
+ inp.removeAttribute("data-dirty");
5030
+ loadProviders();
5031
+ setNote(msg, false, "saved — applies from the next model call");
5032
+ } else setNote(msg, true, settingsRefusal(r));
5033
+ }, function(){ setNote(msg, true, networkText()); });
5034
+ }
5035
+
5036
+ function loadMoney(){
5037
+ return getJSON("/api/settings/money").then(paintMoney, function(e){
5038
+ setNote(document.getElementById("ml-msg"), true, loadFailureText(e));
5039
+ });
5040
+ }
5041
+ var mlLimit = document.getElementById("ml-money");
5042
+ function paintMoney(d){
5043
+ var m = d.month, t = d.total;
5044
+ document.getElementById("ml-usd").textContent = fmtUsd(m.usd, m.atLeast) + " / " + fmtUsd(t.usd, t.atLeast);
5045
+ document.getElementById("ml-tokens").textContent = tokensText(m.tokens) + " / " + tokensText(t.tokens);
5046
+ var notes = [];
5047
+ if(d.preM4dRunsNotCounted) notes.push("Runs from before Settings existed are not counted here.");
5048
+ if(d.undatedRows > 0) notes.push(d.undatedRows + (d.undatedRows === 1 ? " older spend row has no date; it counts in to date only." : " older spend rows have no date; they count in to date only."));
5049
+ document.getElementById("ml-extra").textContent = notes.join(" ");
5050
+ if(document.activeElement !== mlLimit && mlLimit.getAttribute("data-dirty") !== "1") mlLimit.value = typeof d.monthlyLimitUsd === "number" ? String(d.monthlyLimitUsd) : "";
5051
+ if(d.configProblem) setNote(document.getElementById("ml-msg"), true, d.configProblem);
5052
+ var names = Object.keys(d.byProvider || {});
5053
+ document.getElementById("ml-breakdown").innerHTML = names.length ? names.map(function(k){
5054
+ var p = d.byProvider[k];
5055
+ return '<tr data-testid="break-row"><td>' + escapeXml(p.label) + '</td>' +
5056
+ '<td>' + escapeXml(fmtUsd(p.month.usd, p.month.atLeast) + " / " + fmtUsd(p.total.usd, p.total.atLeast)) + '</td>' +
5057
+ '<td>' + escapeXml(breakMinutes(p.month) + " / " + breakMinutes(p.total)) + '</td>' +
5058
+ '<td>' + escapeXml(tokensText(p.total.tokens)) + '</td></tr>';
5059
+ }).join("") : '<tr><td colspan="4" class="hint">no spend yet</td></tr>';
5060
+ }
5061
+ // "not recorded" only when there was spend but no minutes; a period with no spend at all is "0 min".
5062
+ function breakMinutes(b){
5063
+ if(b.modelMinutes === null && b.usd === 0 && !b.atLeast && b.tokens === 0) return "0 min";
5064
+ return fmtMinutes(b.modelMinutes, b.modelMinutesAtLeast);
5065
+ }
5066
+ mlLimit.addEventListener("input", function(){ this.setAttribute("data-dirty", "1"); });
5067
+ // Saved like bareloop saves it: on change (blur or Enter).
5068
+ mlLimit.addEventListener("change", function(){
5069
+ var msg = document.getElementById("ml-msg");
5070
+ postJSON("/api/settings/money", { monthlyLimitUsd: priceValue(mlLimit.value) }).then(function(r){
5071
+ if(r.body && r.body.ok){
5072
+ mlLimit.removeAttribute("data-dirty");
5073
+ loadMoney().then(function(){
5074
+ setNote(msg, false, r.body.monthlyLimitUsd === null ? "saved — no monthly limit" : "saved — the limit is now $" + r.body.monthlyLimitUsd);
5075
+ document.dispatchEvent(new CustomEvent("fwdloop-limit-changed"));
5076
+ });
5077
+ } else setNote(msg, true, settingsRefusal(r));
5078
+ }, function(){ setNote(msg, true, networkText()); });
5079
+ });
5080
+
3132
5081
  // theme toggle
3133
5082
  (function(){
3134
5083
  var root = document.documentElement;