fwdloop 0.15.0 → 0.16.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 (52) hide show
  1. package/bin/fwdloop +106 -31
  2. package/package.json +2 -2
  3. package/src/authoring.js +23 -11
  4. package/src/closers.js +5 -0
  5. package/src/config.js +66 -4
  6. package/src/declaration.js +25 -1
  7. package/src/draft-steps.js +79 -0
  8. package/src/drafter.js +54 -15
  9. package/src/flowmodel.js +30 -0
  10. package/src/input-facts.js +12 -3
  11. package/src/keysfile.js +51 -16
  12. package/src/model-step.js +13 -11
  13. package/src/monthly.js +9 -1
  14. package/src/panel/author.js +81 -22
  15. package/src/panel/authorcard.js +25 -17
  16. package/src/panel/authorflows.js +33 -18
  17. package/src/panel/authorresume.js +9 -8
  18. package/src/panel/authorstart.js +11 -9
  19. package/src/panel/data.js +3 -3
  20. package/src/panel/index.html +516 -146
  21. package/src/panel/resume.js +3 -3
  22. package/src/panel/server.js +4 -3
  23. package/src/panel/settings.js +138 -80
  24. package/src/panel/spawn.js +15 -9
  25. package/src/provider.js +136 -178
  26. package/src/providershapes.js +7 -7
  27. package/src/runner.js +38 -22
  28. package/src/thinking.js +55 -0
  29. package/types/authoring.d.ts +11 -4
  30. package/types/closers.d.ts +2 -0
  31. package/types/config.d.ts +9 -1
  32. package/types/draft-steps.d.ts +14 -0
  33. package/types/drafter.d.ts +13 -10
  34. package/types/flowmodel.d.ts +16 -0
  35. package/types/input-facts.d.ts +6 -1
  36. package/types/keysfile.d.ts +23 -6
  37. package/types/model-step.d.ts +1 -1
  38. package/types/monthly.d.ts +1 -0
  39. package/types/panel/author.d.ts +44 -6
  40. package/types/panel/authorcard.d.ts +21 -8
  41. package/types/panel/authorflows.d.ts +29 -6
  42. package/types/panel/authorresume.d.ts +2 -1
  43. package/types/panel/authorstart.d.ts +16 -6
  44. package/types/panel/data.d.ts +2 -2
  45. package/types/panel/resume.d.ts +2 -1
  46. package/types/panel/server.d.ts +3 -1
  47. package/types/panel/settings.d.ts +3 -1
  48. package/types/panel/spawn.d.ts +13 -4
  49. package/types/provider.d.ts +94 -284
  50. package/types/providershapes.d.ts +3 -4
  51. package/types/runner.d.ts +2 -4
  52. package/types/thinking.d.ts +25 -0
@@ -499,6 +499,7 @@
499
499
  .chat-steps .step.wait .step-label{color:var(--amber);}
500
500
  .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;}
501
501
  .chat-steps .step.bad .step-detail{color:var(--red);}
502
+ .chat-steps .step[data-step="thinking"].bad .step-label{color:var(--red);font-weight:600;}
502
503
  .chat-steps .step-raw{margin-top:2px;color:var(--text-faint);}
503
504
  .chat-steps .step-raw summary{cursor:pointer;}
504
505
  .chat-steps .step.run .step-sign::after{content:"\2026";}
@@ -668,20 +669,92 @@
668
669
  .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;}
669
670
  .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;}
670
671
  .keyfile-strip-main{display:flex;flex-direction:column;gap:3px;flex:1;min-width:0;overflow-wrap:anywhere;}
671
- .keyfile-strip-actions{display:flex;gap:6px;flex:none;}
672
+ .keyfile-strip-actions{display:flex;flex-wrap:wrap;gap:6px;flex:none;max-width:100%;}
672
673
  .keyfile-strip code{background:var(--bg);border:1px solid var(--border-strong);padding:1px 5px;font-size:11px;color:var(--amber);overflow-wrap:anywhere;}
673
674
  .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);}
674
- .pv-table td,.pv-table th{white-space:nowrap;vertical-align:top;}
675
- .pv-table select,.pv-table input{min-height:32px;max-width:190px;box-sizing:border-box;}
676
- .pv-table .hint{display:block;margin-top:3px;}
677
- /* the Test cell keeps ONE width whatever the result says ("testing…", "OK · 312 ms", a long failure note) */
678
- .pv-table td.pv-test-cell{width:180px;min-width:180px;max-width:180px;}
679
- .pv-table .pv-test-result,.pv-table .pv-msg,.pv-table .pv-balance-result{white-space:normal;overflow-wrap:anywhere;}
680
- .pv-table td.pv-price-cell{width:170px;min-width:170px;max-width:170px;}
675
+ /* M4d Providers layout F (hamr approved 2026-10-11, the design lab's Variant F): ONE shared grid, so a key row, the model sub-head and
676
+ every model row sit on the same column edges. Key band: KEY | API SHAPE | BASE URL (two columns) | OLD MAX_TOKENS | TOKENS | refresh.
677
+ Model row: [USE 44px][MODEL] under KEY, IN + OUT side by side under BASE URL, TOKENS on the key band's TOKENS edge. A key row has a
678
+ solid 1px line, a model row a dotted 1px hairline. Below 1280px every row collapses to stacked label : value lines. */
679
+ .pv-grid{--pv-cols:minmax(0,2.8fr) minmax(0,1.5fr) minmax(0,.95fr) minmax(0,.95fr) minmax(0,.9fr) minmax(0,.6fr) 272px;font-size:13px;}
680
+ .pv-head,.pv-krow,.pv-mhead,.pv-mrow{display:grid;grid-template-columns:var(--pv-cols);column-gap:8px;align-items:center;padding:0 8px;min-width:0;}
681
+ .pv-head > *,.pv-krow > *,.pv-mhead > *,.pv-mrow > *{min-width:0;}
682
+ .pv-head,.pv-mhead{font-size:11px;font-weight:700;color:var(--text-dim);letter-spacing:0.04em;min-height:26px;}
683
+ .pv-head{background:var(--panel2);border-bottom:1px solid var(--border-strong);}
684
+ .pv-mhead{background:var(--bg);border-bottom:1px dotted var(--border-strong);}
685
+ .pv-key{border-top:1px solid var(--border-strong);}
686
+ .pv-krow{min-height:40px;padding-top:4px;padding-bottom:4px;}
687
+ .pv-c-url{grid-column:3 / span 2;}
688
+ .pv-lbl{display:none;}
689
+ .pv-name{display:flex;align-items:center;flex-wrap:wrap;gap:4px 6px;min-width:0;overflow-wrap:anywhere;}
690
+ .pv-name code{font-weight:700;}
691
+ .pv-ok{color:var(--green);font-weight:700;}
692
+ .pv-fold{border:0;background:none;color:var(--text);font:inherit;padding:0 4px 0 0;min-width:22px;min-height:24px;cursor:pointer;text-align:left;}
693
+ .pv-krow select,.pv-krow input[type=text]{width:100%;max-width:100%;min-height:28px;box-sizing:border-box;}
694
+ .pv-grid select,.pv-grid input[type=text]{font-size:12px;height:28px;padding:2px 6px;}
695
+ .pv-legacy{display:inline-flex;align-items:center;gap:6px;cursor:pointer;min-height:28px;text-transform:none;letter-spacing:0;font-weight:400;font-size:12px;}
696
+ .pv-legacy input,.pv-m-use input{width:16px;height:16px;margin:0;accent-color:var(--accent);cursor:pointer;}
697
+ .pv-tok{text-align:right;font-variant-numeric:tabular-nums;}
698
+ .pv-refcell{display:flex;justify-content:flex-end;}
699
+ .pv-refbox{display:flex;flex-direction:column;align-items:flex-start;max-width:100%;}
700
+ .pv-refbtns{display:flex;gap:6px;}
701
+ .pv-refbox .pv-msg{width:0;min-width:100%;overflow-wrap:anywhere;margin:2px 0 0;}
702
+ .pv-refbox .pv-msg:empty{display:none;}
703
+ .pv-refbtn{white-space:nowrap;flex:0 0 auto;}
704
+ .pv-refbtn:disabled{opacity:.5;cursor:not-allowed;}
705
+ .pv-sum{color:var(--text-faint);font-size:11px;font-weight:400;}
706
+ .pv-key[data-open="1"] .pv-sum{display:none;}
707
+ .pv-knote{padding:0 8px 4px 34px;margin:0;}
708
+ .pv-knote:empty{display:none;}
709
+ .pv-knote > .hint:empty{display:none;}
710
+ .pv-key[data-open="0"] .pv-models{display:none;}
711
+ .pv-mrow{border-top:1px dotted var(--border-strong);min-height:32px;}
712
+ .pv-mrow:hover,.pv-mrow:focus-within{background:var(--panel2);}
713
+ .pv-um{grid-column:1;display:flex;align-items:center;gap:0;min-width:0;}
714
+ .pv-uh,.pv-m-use{flex:0 0 44px;width:44px;display:flex;align-items:center;justify-content:center;}
715
+ .pv-m-use{min-height:32px;}
716
+ .pv-m-name{min-width:0;overflow-wrap:anywhere;font-size:12px;}
717
+ .pv-pair{grid-column:3 / span 2;display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);column-gap:8px;align-items:center;min-width:0;}
718
+ .pv-pair > *{min-width:0;}
719
+ .pv-pair input[type=text]{width:100%;text-align:right;}
720
+ .pv-mhead .pv-tok{text-align:right;}
721
+ .pv-mhead .pv-tok,.pv-m-tok{grid-column:6;}
722
+ .pv-m-msg{grid-column:1 / -1;padding:2px 8px 2px 52px;margin:0;}
723
+ .pv-m-msg:empty{display:none;}
724
+ .pv-more{padding:3px 8px 3px 34px;border-top:1px dotted var(--border-strong);}
725
+ .pv-more:empty{display:none;}
726
+ .pv-more .pv-add{border:0;background:none;color:var(--accent);font:inherit;font-size:12px;padding:2px 0;min-height:24px;cursor:pointer;text-decoration:underline;}
727
+ .pv-more.pv-failed{color:var(--amber);background:var(--amber-bg);font-size:12px;}
728
+ .pv-typed{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;margin-top:4px;}
729
+ .pv-typed input{flex:1 1 160px;min-width:0;max-width:260px;min-height:28px;box-sizing:border-box;}
730
+ .pv-typed .hint{flex:1 1 100%;margin:0;}
731
+ .field label.jf-thinking{display:flex;flex-direction:row;align-items:center;justify-content:flex-start;gap:6px;margin-top:6px;font-size:12px;text-transform:none;letter-spacing:0;}
732
+ .field label.jf-thinking input{width:auto;min-height:0;margin:0;}
681
733
  .hint.bad{color:var(--red);}
682
734
  .table-wrap{overflow-x:auto;border:1px solid var(--border-strong);background:var(--panel2);max-width:100%;}
683
735
  @media (max-width: 899px){
684
736
  .money-strip{grid-template-columns:1fr 1fr;}
737
+ .keyfile-strip-main{flex:1 1 100%;}
738
+ }
739
+ @media (max-width: 1279px){
740
+ .pv-head,.pv-mhead{display:none;}
741
+ .pv-krow,.pv-mrow{display:block;padding:2px 8px;}
742
+ .pv-cell{display:grid;grid-template-columns:104px minmax(0,1fr);gap:8px;align-items:center;min-height:44px;border-top:1px dotted var(--border);}
743
+ .pv-cell:first-child{border-top:none;}
744
+ .pv-lbl{display:block;font-size:11px;text-transform:uppercase;letter-spacing:.04em;color:var(--text-dim);font-weight:700;}
745
+ .pv-cell.nolbl{display:flex;}
746
+ .pv-tok{text-align:left;}
747
+ .pv-grid select,.pv-grid input[type=text]{height:44px;font-size:14px;}
748
+ .pv-krow select,.pv-krow input[type=text]{min-height:44px;}
749
+ .pv-legacy{min-height:44px;gap:10px;}
750
+ .pv-legacy input,.pv-m-use input{width:24px;height:24px;}
751
+ .pv-um{min-height:44px;}
752
+ .pv-uh,.pv-m-use{min-height:44px;}
753
+ .pv-cell.pv-pair{display:grid;grid-template-columns:104px minmax(0,1fr) minmax(0,1fr);}
754
+ .pv-cell.pv-pair::before{content:"In / Out $/1M";font-size:11px;text-transform:uppercase;letter-spacing:.04em;color:var(--text-dim);font-weight:700;}
755
+ .pv-fold,.pv-refbtn,.pv-more .pv-add{min-height:44px;min-width:44px;}
756
+ .pv-knote,.pv-more{padding-left:8px;}
757
+ .pv-m-msg{padding-left:8px;}
685
758
  }
686
759
  </style>
687
760
  </head>
@@ -717,20 +790,20 @@
717
790
  <div class="keyfile-strip-main">
718
791
  <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>
719
792
  <span class="hint bad" id="keys-refusal" data-testid="keys-refusal"></span>
793
+ <span class="hint" id="keys-open-note" data-testid="keys-open-note"></span>
720
794
  </div>
721
795
  <div class="keyfile-strip-actions">
796
+ <button class="btn small" id="open-keys-folder" type="button" data-testid="open-keys-folder" aria-label="Open keys folder">Open keys folder</button>
722
797
  <button class="btn small" id="reload-keys" type="button" data-testid="reload-keys">Reload keys</button>
723
798
  </div>
724
799
  </div>
725
800
  <div class="table-wrap" data-testid="provider-table-wrap">
726
- <table class="pv-table" data-testid="provider-table">
727
- <thead>
728
- <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>
729
- </thead>
730
- <tbody id="pv-rows"></tbody>
731
- </table>
801
+ <div class="pv-grid" data-testid="provider-table">
802
+ <div class="pv-head" aria-hidden="true"><span>KEY</span><span>API SHAPE</span><span class="pv-c-url">BASE URL</span><span>OLD MAX_TOKENS</span><span class="pv-tok">TOKENS</span><span></span></div>
803
+ <div id="pv-rows"></div>
804
+ </div>
732
805
  </div>
733
- <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>
806
+ <div class="hint" id="pv-note" data-testid="pv-note" style="margin-top:6px;">⟳ refresh models (free) · old max_tokens: tick if the server wants the old field name</div>
734
807
  </section>
735
808
  <section id="spanel-money" class="tabpanel" role="tabpanel" aria-labelledby="stab-money" hidden>
736
809
  <div class="money-strip" data-testid="money-strip">
@@ -789,6 +862,13 @@
789
862
 
790
863
  <div id="jf-new" data-testid="jf-new">
791
864
  <div class="hint edit-banner" id="jf-edit-banner" data-testid="jf-edit-banner" hidden></div>
865
+ <div class="field">
866
+ <label for="jf-model">Model</label>
867
+ <select id="jf-model" data-testid="jf-model" disabled><option value="">Reading your models…</option></select>
868
+ <label class="jf-thinking"><input type="checkbox" id="jf-thinking" data-testid="jf-thinking"> Thinking on</label>
869
+ <div class="hint" id="jf-thinking-note" data-testid="jf-thinking-note"></div>
870
+ <div class="jf-err" id="jf-err-model" data-testid="jf-err-model"></div>
871
+ </div>
792
872
  <div class="field">
793
873
  <label for="jf-name">Flow name</label>
794
874
  <input id="jf-name" type="text" placeholder="lowercase letters, digits, - or _" autocomplete="off" spellcheck="false" data-testid="jf-name">
@@ -800,15 +880,9 @@
800
880
  <div class="jf-gut" id="jf-job-gut" data-testid="jf-job-gut" aria-hidden="true"><div class="jf-gut-in"></div></div>
801
881
  <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>
802
882
  </div>
803
- <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>
883
+ <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. With a Destination, the last line writes the result there.</div>
804
884
  <div class="jf-err" id="jf-err-job" data-testid="jf-err-job"></div>
805
885
  </div>
806
- <div class="field">
807
- <label for="jf-dest-folder">Destination</label>
808
- <input id="jf-dest-folder" type="text" placeholder="/full/path/to/a/folder" autocomplete="off" spellcheck="false" data-testid="jf-dest-folder">
809
- <div class="hint">Where the accepted result is placed, at the last step. Leave empty for no send.</div>
810
- <div class="jf-err" id="jf-err-destination" data-testid="jf-err-destination"></div>
811
- </div>
812
886
  <div class="field">
813
887
  <label for="jf-inputs">Inputs</label>
814
888
  <div class="jf-gutbox">
@@ -818,6 +892,12 @@
818
892
  <div class="hint">One line per file: a name, a colon, its full path starting with /. The page never reads the file.</div>
819
893
  <div class="jf-err" id="jf-err-inputs" data-testid="jf-err-inputs"></div>
820
894
  </div>
895
+ <div class="field">
896
+ <label for="jf-dest-folder">Destination</label>
897
+ <input id="jf-dest-folder" type="text" placeholder="/full/path/to/a/folder" autocomplete="off" spellcheck="false" data-testid="jf-dest-folder">
898
+ <div class="hint">Where the accepted result is placed, at the last step. Leave empty for no send.</div>
899
+ <div class="jf-err" id="jf-err-destination" data-testid="jf-err-destination"></div>
900
+ </div>
821
901
  <div class="cap-row" data-testid="cap-row">
822
902
  <div class="cap-field">
823
903
  <label for="jf-cap-money">Cap $</label>
@@ -849,6 +929,9 @@
849
929
  <div class="field dimmed" data-testid="jf-run-job-field">
850
930
  <label>The job</label>
851
931
  <div class="ro-lines" id="jf-run-job" data-testid="jf-run-job"></div>
932
+ <div class="hint" id="jf-run-model" data-testid="jf-run-model"></div>
933
+ <select id="jf-run-pick" data-testid="jf-run-pick" aria-label="Model to run this job with" hidden disabled><option value="">Reading your models…</option></select>
934
+ <div class="jf-err" id="jf-err-run-model" data-testid="jf-err-run-model"></div>
852
935
  <div class="hint">Fixed by the signature (the steps, the job lines and the asks). To change them, edit the job: the AI drafts a new plan, and signing it replaces this job.</div>
853
936
  <button class="btn" type="button" id="jf-run-edit" data-testid="jf-run-edit">Edit this job</button>
854
937
  <div class="hint" id="jf-run-edit-why" data-testid="jf-run-edit-why"></div>
@@ -886,6 +969,7 @@
886
969
  <div class="field dimmed" data-testid="jf-resume-job-field">
887
970
  <label>The job</label>
888
971
  <div class="ro-lines" id="jf-resume-job" data-testid="jf-resume-job"></div>
972
+ <div class="hint" id="jf-resume-model" data-testid="jf-resume-model"></div>
889
973
  </div>
890
974
  <div class="field dimmed">
891
975
  <label>Destination</label>
@@ -2882,8 +2966,22 @@
2882
2966
  // One last-payload signature per render. Equal payload = the DOM is not touched. `selectRun` resets
2883
2967
  // the ones a different selection invalidates.
2884
2968
  var lastSig = { inbox: null, runs: null, detail: null, asks: null, audit: null };
2969
+ // `timeLeftMs` differs on every poll and is not part of what a page draw is built from (the words move in place: `liveLeft`/`tickLeft`),
2970
+ // so it is left out: a poll that changed nothing else is "unchanged" and rebuilds nothing (a rebuild resets every scrolled box).
2885
2971
  function sig(obj){
2886
- try { return JSON.stringify(obj); } catch(e){ return null; }
2972
+ try { return JSON.stringify(obj, function(k, v){ return k === "timeLeftMs" ? undefined : v; }); } catch(e){ return null; }
2973
+ }
2974
+ // "time left" counts down IN PLACE. ONE writer: `liveLeft` stamps the element with when its time ends and how to say it; `tickLeft` (the page's
2975
+ // 2 s tick) says it again. Nothing else re-draws these words, so the countdown never costs a rebuild over what the human is reading.
2976
+ function liveLeft(el, timeLeftMs, say){
2977
+ if(typeof timeLeftMs !== "number") { say(timeLeftMs); return; }
2978
+ el.classList.add("live-left");
2979
+ el._endsAt = Date.now() + timeLeftMs;
2980
+ el._say = say;
2981
+ say(timeLeftMs);
2982
+ }
2983
+ function tickLeft(){
2984
+ document.querySelectorAll(".live-left").forEach(function(el){ el._say(Math.max(0, el._endsAt - Date.now())); });
2887
2985
  }
2888
2986
  // Saves/restores scrollTop of the given element ids around a re-render.
2889
2987
  function withScrollPreserved(ids, fn){
@@ -2939,9 +3037,9 @@
2939
3037
  document.getElementById("run-content").hidden = true;
2940
3038
  });
2941
3039
  // the same late-reply guard on audit, job and asks: a reply for a run the user already left paints nothing
2942
- getJSON(base + "/audit").then(function(a){ if(still()) renderAudit(a); }).catch(function(){ if(still()) renderAudit(null); });
3040
+ getJSON(base + "/audit").then(function(a){ if(still()){ lastSig.audit = sig(a); renderAudit(a); } }).catch(function(){ if(still()) renderAudit(null); });
2943
3041
  getJSON(base + "/job").then(function(j){ if(still()) renderJob(j); }).catch(function(){ if(still()) renderJob(null); });
2944
- getJSON(base + "/asks").then(function(result){ if(still()) renderAsk(result, focusAskId || null); }).catch(function(e){
3042
+ getJSON(base + "/asks").then(function(result){ if(still()) paintAsks(result, focusAskId || null); }).catch(function(e){
2945
3043
  if(still()) renderAsk(null, null, loadFailureText(e));
2946
3044
  });
2947
3045
  }
@@ -2986,17 +3084,21 @@
2986
3084
  withScrollPreserved(["left-pane-body"], function(){ runsFilterBar.setItems(rows); runsFilterBar.refresh(); });
2987
3085
  }).catch(function(){});
2988
3086
  }
3087
+ // The ONE way the Ask tab is drawn from the books: the Ask tab is drawn from the books AND the page's own pending answer ("working…" block).
3088
+ // The signature is stamped only when renderAsk REALLY drew (it returns false when held over a typed reason): a held redraw leaves the stamp
3089
+ // unset, so the next tick retries it against the same payload. Both the selection's first draw and every poll come through here, so the
3090
+ // first poll after a click finds the stamp and rebuilds nothing (an unstamped first draw was a second, needless rebuild 2 s later).
3091
+ function paintAsks(a, focusAskId){
3092
+ var next = sig({ asks: a, pending: pendingAnswer });
3093
+ if(focusAskId || next === null || next !== lastSig.asks){ lastSig.asks = renderAsk(a, focusAskId) ? next : null; }
3094
+ }
2989
3095
  function reloadRun(flow, runId, skipLists){
2990
3096
  var base = "/api/runs/" + encodeURIComponent(flow) + "/" + encodeURIComponent(runId);
2991
3097
  var still = function(){ return currentFlow === flow && currentRunId === runId; };
2992
3098
  var detailP = getJSON(base).then(function(d){ if(still()) paintRun(d); return d; }).catch(function(){ if(still()) openRunLive = false; return null; }); // unreadable books: the list rate, not 2 s forever
2993
3099
  var asksP = getJSON(base + "/asks").then(function(a){
2994
3100
  if(still()){
2995
- // the Ask tab is drawn from the books AND the page's own pending answer ("working…" block)
2996
- var next = sig({ asks: a, pending: pendingAnswer });
2997
- // the signature is stamped only when renderAsk REALLY drew (it returns false when held over a typed
2998
- // reason): a held redraw leaves the stamp unset, so the next tick retries it against the same payload
2999
- if(next === null || next !== lastSig.asks){ lastSig.asks = renderAsk(a, null) ? next : null; }
3101
+ paintAsks(a, null);
3000
3102
  }
3001
3103
  return a;
3002
3104
  }).catch(function(e){ if(still()){ lastSig.asks = null; renderAsk(null, null, loadFailureText(e)); } return null; });
@@ -3016,6 +3118,7 @@
3016
3118
  if(document.hidden){ wasHidden = true; schedulePoll(LIVE_POLL_MS); return; }
3017
3119
  var catchUp = wasHidden; // first tick after the tab came back: force both
3018
3120
  wasHidden = false;
3121
+ tickLeft();
3019
3122
  var watch = live;
3020
3123
  var sel = currentFlow !== null && currentRunId !== null;
3021
3124
  var watchIsSelected = watch && sel && watch.flow === currentFlow && watch.runId === currentRunId;
@@ -3167,7 +3270,11 @@
3167
3270
  wrap.appendChild(head);
3168
3271
  var meta = textDiv("wf-sign-line", "");
3169
3272
  meta.setAttribute("data-testid", "inbox-sign-word");
3170
- meta.innerHTML = signHtml(row.word, stopStatusLine(row), stopStatusLine(row));
3273
+ if(row.waiting){
3274
+ liveLeft(meta, row.timeLeftMs, function(ms){ var h = signHtml(row.word, "time left: " + duration(ms), "time left: " + duration(ms)); if(meta._h !== h){ meta._h = h; meta.innerHTML = h; } });
3275
+ } else {
3276
+ meta.innerHTML = signHtml(row.word, stopStatusLine(row), stopStatusLine(row));
3277
+ }
3171
3278
  wrap.appendChild(meta);
3172
3279
  if(typeof row.question === "string"){
3173
3280
  wrap.appendChild(textDiv("step-meta", "question: " + row.question));
@@ -3224,7 +3331,11 @@
3224
3331
  // role="button" (never a real <button>), same posture as the step-map's
3225
3332
  // own SVG nodes elsewhere on this page. ----
3226
3333
  function askStatusBlock(ask){
3227
- if(ask.waiting) return textDiv("wf-meta", "time left: " + duration(ask.timeLeftMs));
3334
+ if(ask.waiting){
3335
+ var left = textDiv("wf-meta", "");
3336
+ liveLeft(left, ask.timeLeftMs, function(ms){ var t = "time left: " + duration(ms); if(left.textContent !== t) left.textContent = t; });
3337
+ return left;
3338
+ }
3228
3339
  // an open ask with a saved answer: the header meta line already says the resume label (stuck or starting) — once.
3229
3340
  if(ask.open && ask.resume) return null;
3230
3341
  var bits = [ask.statusText || ask.status];
@@ -3722,7 +3833,17 @@
3722
3833
  kept[w.getAttribute("data-testid")] = { open: w.getAttribute("data-open"), expanded: w.firstChild.getAttribute("aria-expanded") === "true" };
3723
3834
  });
3724
3835
  }
3836
+ // A redraw (the books really changed) must not move what the human is reading either: every evidence box keeps its scrollTop (same run only),
3837
+ // and so does the pane. The rebuilt boxes are filled below, per block, once they are in the page.
3838
+ var sameRun = askDrawnFor === result.flow + "/" + result.runId;
3839
+ var tops = {};
3840
+ if(sameRun){
3841
+ list.querySelectorAll("[data-testid^='ask-block-']").forEach(function(w){
3842
+ tops[w.getAttribute("data-testid")] = Array.prototype.map.call(w.querySelectorAll(".scroll"), function(b){ return b.scrollTop; });
3843
+ });
3844
+ }
3725
3845
  askDrawnFor = result.flow + "/" + result.runId;
3846
+ var paneTop = (document.getElementById("right-pane-body") || {}).scrollTop;
3726
3847
  list.innerHTML = "";
3727
3848
  // Default expansion: the block holding the ask a click from the Inbox
3728
3849
  // (`focusAskId`) named wins; otherwise a block with an open ask expands;
@@ -3745,6 +3866,8 @@
3745
3866
  row.classList.add("audit-group-highlight");
3746
3867
  }
3747
3868
  list.appendChild(row);
3869
+ var savedTops = tops[row.getAttribute("data-testid")];
3870
+ if(savedTops) Array.prototype.forEach.call(row.querySelectorAll(".scroll"), function(b, i){ if(savedTops[i]) b.scrollTop = savedTops[i]; });
3748
3871
  if(expanded){
3749
3872
  // Scroll the focused ask into view (M4a-1 design: clicking a stop
3750
3873
  // on the left "focuses" it on the right) — never on a run's own
@@ -3754,6 +3877,7 @@
3754
3877
  }
3755
3878
  }
3756
3879
  });
3880
+ if(sameRun && paneTop){ var pane = document.getElementById("right-pane-body"); if(pane) pane.scrollTop = paneTop; }
3757
3881
  return true;
3758
3882
  }
3759
3883
 
@@ -3975,6 +4099,16 @@
3975
4099
  function stepsFor(state, ctx){
3976
4100
  var out = [];
3977
4101
  var who = ctx.model ? ctx.model : "the drafter";
4102
+ // M4d am10: when the server sent the draft's own list (state.stepList, built by one function in src/draft-steps.js) it is rendered as it is,
4103
+ // each ✗ plan-check refusal turned into its plain sentence; a draft with no log lists what it always did (`fallback`).
4104
+ function draftLines(fallback){
4105
+ if(!state || !Array.isArray(state.stepList) || state.stepList.length === 0) return fallback();
4106
+ state.stepList.forEach(function(st){
4107
+ var row = {id: st.id, label: st.label, status: st.status === "failed" ? "failed" : "done", details: st.details || []};
4108
+ if(Array.isArray(st.reds)){ var fd = failedDetails(st.reds); row.details = fd.details; row.raw = fd.raw; }
4109
+ out.push(row);
4110
+ });
4111
+ }
3978
4112
  var cap = state && state.card && state.card.capUsd !== undefined && state.card.capUsd !== "" ? state.card.capUsd : "";
3979
4113
  var capPart = cap !== "" ? ", run cap $" + cap : "";
3980
4114
  if(state){
@@ -3982,7 +4116,7 @@
3982
4116
  out.push({id: "drafting", label: "drafting with " + who + capPart, status: "running", details: []});
3983
4117
  } else if(Array.isArray(state.revises)){
3984
4118
  // amendment 14: a draft whose first plan was green. One line per revise with its result; a red one shows its reds (its sentence is on the card error line).
3985
- out.push({id: "drafted", label: "drafted with " + who, status: "done", details: []});
4119
+ draftLines(function(){ out.push({id: "drafted", label: "drafted with " + who, status: "done", details: []}); });
3986
4120
  var reviseNo = 0;
3987
4121
  state.revises.forEach(function(rv){
3988
4122
  // an answer redraft (amendment 24 item 4) is not a revise and is not counted as one
@@ -3997,13 +4131,15 @@
3997
4131
  }
3998
4132
  if(state.phase === "questions-open") out.push({id: "question", label: "waiting for your answer (" + state.openK + " of " + state.total + ")", status: "waiting", details: []});
3999
4133
  } else if(state.phase === "red"){
4000
- out.push({id: "drafted", label: "drafted with " + who, status: "done", details: []});
4001
- var cf = failedDetails(state.reds);
4002
- out.push({id: "checks", label: "plan checks", status: "failed", details: cf.details, raw: cf.raw});
4134
+ draftLines(function(){
4135
+ out.push({id: "drafted", label: "drafted with " + who, status: "done", details: []});
4136
+ var cf = failedDetails(state.reds);
4137
+ out.push({id: "checks", label: "plan checks", status: "failed", details: cf.details, raw: cf.raw});
4138
+ });
4003
4139
  } else if(state.phase === "stopped"){
4004
4140
  out.push({id: "drafting", label: "drafting with " + who + capPart, status: "failed", details: []});
4005
4141
  } else if(state.phase === "green" || state.phase === "revising"){
4006
- out.push({id: "drafted", label: "drafted with " + who, status: "done", details: []});
4142
+ draftLines(function(){ out.push({id: "drafted", label: "drafted with " + who, status: "done", details: []}); });
4007
4143
  if(ctx.starting){
4008
4144
  out.push({id: "signed", label: "signed", status: "done", details: []});
4009
4145
  } else if(state.phase !== "revising"){
@@ -4147,6 +4283,9 @@
4147
4283
  inputs: inputsBox.value,
4148
4284
  capUsd: byId("jf-cap-money").value.trim(),
4149
4285
  askWait: askWaitEl.value.trim(),
4286
+ provider: modelPick().provider,
4287
+ model: modelPick().model,
4288
+ thinking: thinkingEl.checked && !thinkingEl.disabled,
4150
4289
  editOf: editOf
4151
4290
  };
4152
4291
  }
@@ -4158,7 +4297,9 @@
4158
4297
  function currentRun(){
4159
4298
  return {
4160
4299
  flow: pickedFlow || "", inputs: readRows(runInputsEl), runId: (byId("jf-run-id").value.trim() === autoRunId ? "" : byId("jf-run-id").value.trim()),
4161
- destination: runDestEl.value.trim(), capUsd: runCapEl.value.trim(), askWaits: runWaits()
4300
+ destination: runDestEl.value.trim(), capUsd: runCapEl.value.trim(), askWaits: runWaits(),
4301
+ // a flow with no recorded model runs with the pick (am7b); a flow with one sends none
4302
+ ...(runPickEl.hidden ? {} : { provider: runPickChoice().provider, model: runPickChoice().model })
4162
4303
  };
4163
4304
  }
4164
4305
  // 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
@@ -4222,8 +4363,10 @@
4222
4363
  var seq = ++capNoteSeq;
4223
4364
  if(cap === ""){ setMoneyNote("", false); return; }
4224
4365
  // a Resume holds only what the run has still to spend (amendment 4 item 1): the server is told what is already spent
4225
- var spent = (mode === "resume" && resumeCtx) ? "&spent=" + encodeURIComponent(String(resumeCtx.form.spentUsd)) : "";
4226
- authorGet("/api/author/monthly-check?cap=" + encodeURIComponent(cap) + spent).then(function(j){
4366
+ var spent = (mode === "resume" && resumeCtx) ? "&spent=" + encodeURIComponent(String(resumeCtx.form.spentUsd)) + "&flow=" + encodeURIComponent(resumeCtx.flow) : "";
4367
+ var pk = modelPick();
4368
+ var picked = (mode === "new" && pk.provider !== "") ? "&provider=" + encodeURIComponent(pk.provider) + "&model=" + encodeURIComponent(pk.model) : "";
4369
+ authorGet("/api/author/monthly-check?cap=" + encodeURIComponent(cap) + spent + picked).then(function(j){
4227
4370
  if(seq !== capNoteSeq) return;
4228
4371
  if(!j || j.ok !== true){ setMoneyNote("", false); return; }
4229
4372
  var v = Number(cap);
@@ -4251,6 +4394,7 @@
4251
4394
  return row ? row.querySelector(".jf-err") : null;
4252
4395
  }
4253
4396
  if(field === "inputs") return byId(mode === "run" ? "jf-err-run-inputs" : "jf-err-inputs");
4397
+ if(mode === "run" && field === "model") return byId("jf-err-run-model");
4254
4398
  if(mode === "run" && (field === "destination" || field === "capUsd")) return byId("jf-err-run-" + field);
4255
4399
  if(mode === "run" && /^askWaits/.test(field)) return byId("jf-err-run-askWaits");
4256
4400
  if(mode === "resume" && field === "capUsd") return byId("jf-err-resume-capUsd");
@@ -4356,6 +4500,8 @@
4356
4500
  paintedFlow = pickedKey();
4357
4501
  runSignInfo = null;
4358
4502
  paintJobDim(byId("jf-run-job"), f ? f.jobLines : []);
4503
+ byId("jf-run-model").textContent = f && f.model ? "Model: " + f.model.label : (f ? "No model is recorded for this job. Pick the one to run it with; it is then remembered for this job." : "");
4504
+ runPickEl.hidden = !(f && !f.model);
4359
4505
  runDestEl.value = v && v.destination ? v.destination : "";
4360
4506
  runDestEl.readOnly = !(f && f.hasSend);
4361
4507
  runDestEl.classList.toggle("locked", !(f && f.hasSend));
@@ -4412,10 +4558,14 @@
4412
4558
  byId("jf-err-flow").textContent = "";
4413
4559
  renderFlowSearch(); paintRunFlow(); refreshStartEnabled();
4414
4560
  }
4415
- function unpickFlow(){
4416
- if(cardLocked()) return;
4561
+ // the one writer of the Run-a-signed-flow pick (the Change link and Clear both go through it)
4562
+ function clearPick(){
4417
4563
  pickedFlow = null; pickedRun = null; pickedLabel = ""; againEntry = null; rwHl = 0;
4418
4564
  runFlowSel.value = "";
4565
+ }
4566
+ function unpickFlow(){
4567
+ if(cardLocked()) return;
4568
+ clearPick();
4419
4569
  renderFlowSearch(); paintRunFlow(); refreshStartEnabled();
4420
4570
  }
4421
4571
  function loadFlows(force){
@@ -4430,12 +4580,76 @@
4430
4580
  refreshStartEnabled();
4431
4581
  }).catch(function(){ /* the card keeps what it had */ });
4432
4582
  }
4433
- // the drafting line names the model the drafter really uses (Settings' deepseek row), never a guess
4434
- function loadModel(){
4435
- authorGet("/api/settings/providers").then(function(j){
4436
- var rows = (j && j.ok === true && Array.isArray(j.rows)) ? j.rows : [];
4437
- for(var i = 0; i < rows.length; i++){ if(rows[i].slot === "deepseek" && rows[i].model){ drafterModel = String(rows[i].model); } }
4438
- }).catch(function(){ /* the line then says "the drafter" */ });
4583
+ // ---- the Model menu and the per-job "Thinking on" box (M4d amendments 6 and 7) ----
4584
+ // The menu is the ticked lines of Settings > Providers, "provider · model"; the server decides what is listed (GET /api/author/models) and
4585
+ // whether Thinking can change for a line (one function over bareagent's answer, src/thinking.js). The page decides nothing.
4586
+ var modelEl = byId("jf-model");
4587
+ var thinkingEl = byId("jf-thinking");
4588
+ var modelLines = [];
4589
+ function modelPick(){
4590
+ var l = modelLines[Number(modelEl.value)];
4591
+ return l ? {provider: l.slot, model: l.model} : {provider: "", model: ""};
4592
+ }
4593
+ // the box's state for a menu line: unticked by default; greyed with the server's sentence when thinking cannot change for that model
4594
+ function thinkingBoxState(line, wasChecked){
4595
+ if(!line || !line.thinking) return {disabled: true, checked: false, note: ""};
4596
+ if(line.thinking.canChange !== true) return {disabled: true, checked: false, note: line.thinking.say || ""};
4597
+ // an unchecked model's note (am11 item 2) says "thinking off"; ticked, it would be wrong, so it goes
4598
+ return {disabled: false, checked: wasChecked === true, note: wasChecked === true ? "" : (line.thinking.say || "")};
4599
+ }
4600
+ function paintThinking(){
4601
+ var st = thinkingBoxState(modelLines[Number(modelEl.value)], thinkingEl.checked);
4602
+ thinkingEl.disabled = st.disabled; thinkingEl.checked = st.checked;
4603
+ byId("jf-thinking-note").textContent = st.note;
4604
+ drafterModel = modelPick().model;
4605
+ }
4606
+ modelEl.addEventListener("change", function(){ paintThinking(); refreshCapNote(); });
4607
+ thinkingEl.addEventListener("change", paintThinking);
4608
+ function setModelPick(provider, model){
4609
+ for(var i = 0; i < modelLines.length; i += 1){ if(modelLines[i].slot === provider && modelLines[i].model === model){ modelEl.value = String(i); break; } }
4610
+ paintThinking();
4611
+ }
4612
+ // M4d amendment 7b: an old signed flow with no recorded model is run with the model picked here. This menu is the New job menu's twin:
4613
+ // the same ticked lines (values are indexes into `modelLines`), the pick kept across a re-read. Shown only for a flow with no record (paintRunFlow).
4614
+ var runPickEl = byId("jf-run-pick");
4615
+ var runPicked = {provider: "", model: ""}; // what the person chose here, by identity (the indexes change when the list is re-read)
4616
+ function runPickChoice(){
4617
+ var l = runPickEl.hidden ? null : modelLines[Number(runPickEl.value)];
4618
+ return l ? {provider: l.slot, model: l.model} : {provider: "", model: ""};
4619
+ }
4620
+ runPickEl.addEventListener("change", function(){ runPicked = runPickChoice(); });
4621
+ function syncRunPick(){
4622
+ runPickEl.innerHTML = modelEl.innerHTML; runPickEl.disabled = modelEl.disabled;
4623
+ for(var i = 0; i < modelLines.length; i += 1){ if(modelLines[i].slot === runPicked.provider && modelLines[i].model === runPicked.model){ runPickEl.value = String(i); break; } }
4624
+ }
4625
+ // `tries` counts the reads that failed in a row (a click passes an Event, which is not a number: that is a fresh read).
4626
+ // A failed read never leaves the menu blank: it says so and reads again by itself, a few times, so the first load fills it.
4627
+ function loadModel(tries){
4628
+ var failed = typeof tries === "number" ? tries : 0;
4629
+ function unread(){
4630
+ if(modelLines.length > 0) return; // a menu that was filled keeps what it had
4631
+ modelEl.innerHTML = ""; modelEl.disabled = true;
4632
+ var o = document.createElement("option"); o.value = "";
4633
+ o.textContent = failed < 5 ? "Could not read your models. Trying again\u2026" : "Could not read your models. Reload the page.";
4634
+ modelEl.appendChild(o);
4635
+ syncRunPick();
4636
+ if(failed < 5) setTimeout(function(){ loadModel(failed + 1); }, 1500);
4637
+ }
4638
+ authorGet("/api/author/models").then(function(j){
4639
+ if(!j || j.ok !== true){ failed += 1; unread(); return; }
4640
+ var was = modelPick();
4641
+ modelLines = j.lines || [];
4642
+ modelEl.innerHTML = "";
4643
+ if(modelLines.length === 0){
4644
+ var none = document.createElement("option"); none.value = ""; none.textContent = j.say || "Tick a model in Settings > Providers."; modelEl.appendChild(none);
4645
+ modelEl.disabled = true;
4646
+ } else {
4647
+ modelEl.disabled = false;
4648
+ modelLines.forEach(function(l, i){ var o = document.createElement("option"); o.value = String(i); o.textContent = l.label; modelEl.appendChild(o); });
4649
+ }
4650
+ setModelPick(was.provider, was.model);
4651
+ syncRunPick();
4652
+ }).catch(function(){ failed += 1; unread(); });
4439
4653
  }
4440
4654
  function setMode(m){
4441
4655
  mode = m;
@@ -4524,7 +4738,7 @@
4524
4738
  var v = extrasFor(state);
4525
4739
  var html = v ? v.blocks.map(function(b){
4526
4740
  return '<div class="msg" id="' + b.id + '" data-testid="' + b.id + '"><b class="readout-head">' + escapeXml(b.head) + '</b>' +
4527
- (b.sub ? ' <span class="hint">(' + escapeXml(b.sub) + ')</span>' : '') + '\n' + b.lines.map(escapeXml).join("\n") + '</div>';
4741
+ (b.sub ? ' <span class="hint">(' + escapeXml(b.sub) + ')</span>' : '') + (b.lines.length ? '\n' + b.lines.map(escapeXml).join("\n") : '') + '</div>';
4528
4742
  }).join("") : "";
4529
4743
  if(html !== extrasKey){ extrasKey = html; extrasEl.innerHTML = html; }
4530
4744
  }
@@ -4615,6 +4829,8 @@
4615
4829
  leaveEdit();
4616
4830
  ["jf-name", "jf-job", "jf-cap-money", "jf-dest-folder", "jf-inputs"].forEach(function(id){ byId(id).value = ""; });
4617
4831
  askWaitEl.value = "1h";
4832
+ thinkingEl.checked = false; // per job: unticked for the next one
4833
+ clearPick(); // a flow picked in Run a signed flow (Run again too) goes with the rest
4618
4834
  refreshCapNote();
4619
4835
  openNewCard();
4620
4836
  loadFlows(mode === "run");
@@ -4808,6 +5024,7 @@
4808
5024
  resumeCtx = {flow: detail.flow, runId: detail.runId, form: j};
4809
5025
  chatActionOk();
4810
5026
  paintJobDim(byId("jf-resume-job"), j.jobLines);
5027
+ byId("jf-resume-model").textContent = j.model ? "Model: " + j.model.label : "No model is recorded for this job.";
4811
5028
  byId("jf-resume-dest").textContent = j.values.destination || "no send step";
4812
5029
  byId("jf-resume-inputs").innerHTML = "";
4813
5030
  (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); });
@@ -4909,6 +5126,7 @@
4909
5126
  openNewCard();
4910
5127
  setMode("new");
4911
5128
  setVal("jf-name", c.flowName); setVal("jf-job", c.job); setVal("jf-cap-money", c.capUsd);
5129
+ setModelPick(c.provider || "", c.model || ""); thinkingEl.checked = c.thinking === true && !thinkingEl.disabled;
4912
5130
  refreshCapNote();
4913
5131
  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");
4914
5132
  if(c.editOf && typeof c.editOf.flow === "string"){
@@ -4997,6 +5215,8 @@
4997
5215
  document.addEventListener("fwdloop-limit-changed", function(){ refreshCapNote(); });
4998
5216
 
4999
5217
  loadModel();
5218
+ document.getElementById("settings-back").addEventListener("click", loadModel); // the menu re-reads after Settings changed what is ticked
5219
+ document.getElementById("tab-chat").addEventListener("click", loadModel);
5000
5220
  loadFlows();
5001
5221
  reattachLive();
5002
5222
  refreshStartEnabled();
@@ -5039,7 +5259,7 @@
5039
5259
  var PV_NOTE_DEFAULT = pvNote.textContent;
5040
5260
  document.getElementById("settings-open").addEventListener("click", function(){
5041
5261
  mainView.hidden = true; settingsView.hidden = false;
5042
- loadProviders(); loadMoney();
5262
+ loadProviders(true); loadMoney();
5043
5263
  });
5044
5264
  document.getElementById("settings-back").addEventListener("click", function(){
5045
5265
  settingsView.hidden = true; mainView.hidden = false;
@@ -5048,114 +5268,247 @@
5048
5268
  document.getElementById("stab-money").addEventListener("click", function(){ loadMoney(); });
5049
5269
  document.getElementById("stab-providers").addEventListener("click", function(){ loadProviders(); });
5050
5270
 
5051
- function loadProviders(){
5052
- return getJSON("/api/settings/providers").then(paintProviders, function(e){
5271
+ // `list` true = also ask each provider for its model list (free): on page open, on Reload keys. A save repaints without asking again.
5272
+ function loadProviders(list){
5273
+ return getJSON("/api/settings/providers").then(function(d){ paintProviders(d, list === true); }, function(e){
5053
5274
  setNote(document.getElementById("keys-refusal"), true, loadFailureText(e));
5054
5275
  });
5055
5276
  }
5056
- document.getElementById("reload-keys").addEventListener("click", function(){ loadProviders(); });
5277
+ // borrowed-from: bareloop src/panel/index.html@07c298f (Open keys folder): the server opens the FOLDER in the file manager; if it cannot, the path shows as text.
5278
+ document.getElementById("open-keys-folder").addEventListener("click", function(){
5279
+ var out = document.getElementById("keys-open-note");
5280
+ out.textContent = "";
5281
+ postJSON("/api/settings/open-keys-folder", {}).then(function(r){
5282
+ var b = r.body || {};
5283
+ if(b.ok === true) out.textContent = b.opened ? "" : "Could not open it here. Your keys folder: " + (b.path || "(unknown)");
5284
+ else out.textContent = settingsRefusal(r);
5285
+ }, function(){ out.textContent = networkText(); });
5286
+ });
5287
+ document.getElementById("reload-keys").addEventListener("click", function(){ loadProviders(true); });
5057
5288
 
5058
- function sourceWord(src){
5059
- if(src === "table") return "default";
5060
- if(src === "ceiling") return "highest known rate, the model has no listed price";
5061
- return "set here";
5062
- }
5063
- var PRICE_FIELDS = ["inPerM", "outPerM"];
5064
- // Name, API shape and Base URL are editable (M4d amendment 1), saved on change one field at a time.
5065
- var PROV_FIELDS = ["name", "shape", "baseUrl"];
5289
+ // M4d Providers layout F. One parent block per key (.pv-key): its key band (name, API shape select, Base URL box, the legacy tick, tokens,
5290
+ // the Refresh button), a folded summary, and its model lines as child rows (.pv-mrow). The key row owns shape, Base URL and the legacy
5291
+ // tick, so a model line can never drift from them. Shape and Base URL are always editable; a change of either saves both (judged together).
5292
+ var folds = {}; // slot -> true (unfolded) / false (folded): set once, on first paint (a key with a ticked model starts unfolded), then only the person changes it
5293
+ var typedOpen = {}; // slot -> true while "+ type a model name" is open
5066
5294
  function buildProviderRow(row){
5067
- var tr = document.createElement("tr");
5068
- tr.setAttribute("data-slot", row.slot);
5069
- tr.setAttribute("data-testid", "provider-row-" + row.slot);
5070
- var balance = row.canBalance
5071
- ? '<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>'
5072
- : '<span class="hint">not offered by this provider</span>';
5073
- var prices = PRICE_FIELDS.map(function(f){
5074
- return '<td class="pv-price-cell"><input type="text" inputmode="decimal" data-field="' + f + '" data-testid="price-' + f + '" aria-label="' + escapeXml(row.label + " " + f) + '">' +
5075
- '<div class="hint pv-msg" data-f="msg-' + f + '" data-testid="price-msg-' + f + '"></div></td>';
5076
- }).join("");
5077
- tr.innerHTML =
5078
- '<td><code>' + escapeXml(row.envVar) + '</code><div class="hint" data-f="status" data-testid="pv-status-' + escapeXml(row.slot) + '"></div></td>' +
5079
- '<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>' +
5080
- '<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>' +
5081
- '<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>' +
5082
- '<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>' +
5083
- '<td data-f="tokens" data-testid="pv-tokens-' + escapeXml(row.slot) + '"></td>' +
5084
- '<td>' + balance + '</td>' + prices;
5085
- tr.querySelectorAll("input").forEach(function(inp){
5295
+ var key = document.createElement("div");
5296
+ key.className = "pv-key";
5297
+ key.setAttribute("data-slot", row.slot);
5298
+ key.setAttribute("data-testid", "provider-row-" + row.slot);
5299
+ key.innerHTML =
5300
+ '<div class="pv-krow">' +
5301
+ '<div class="pv-cell pv-name nolbl"><button class="pv-fold" type="button" data-act="fold" data-testid="pv-fold"></button><code></code><span class="pv-status" data-f="status" data-testid="pv-status-' + escapeXml(row.slot) + '"></span><span class="pv-sum" data-f="sum" data-testid="pv-sum"></span></div>' +
5302
+ '<div class="pv-cell"><span class="pv-lbl">API shape</span><select data-prov="shape" data-testid="prov-shape" aria-label="' + escapeXml(row.label + " API shape") + '"></select></div>' +
5303
+ '<div class="pv-cell pv-c-url"><span class="pv-lbl">Base URL</span><input type="text" data-prov="baseUrl" data-testid="prov-baseurl" aria-label="' + escapeXml(row.label + " Base URL") + '" autocomplete="off" spellcheck="false" placeholder="type the Base URL"></div>' +
5304
+ '<div class="pv-cell"><span class="pv-lbl">Old max_tokens</span><label class="pv-legacy"><input type="checkbox" data-prov="legacyMaxTokens" data-testid="prov-legacy" aria-label="' + escapeXml(row.label + " legacy max_tokens") + '"><span data-f="legacy-word">off</span></label></div>' +
5305
+ '<div class="pv-cell pv-tok pv-ktok"><span class="pv-lbl">Tokens</span><span data-f="tokens" data-testid="pv-tokens-' + escapeXml(row.slot) + '"></span></div>' +
5306
+ '<div class="pv-cell pv-refcell nolbl"><div class="pv-refbox"><div class="pv-refbtns"><button class="btn small pv-refbtn" type="button" data-act="test-key" data-testid="prov-test" aria-label="' + escapeXml("Test " + row.envVar) + '">Test</button><button class="btn small pv-refbtn" type="button" data-act="refresh-models" data-testid="prov-refresh" aria-label="' + escapeXml("Refresh models for " + row.label) + '">&#10227; Refresh</button></div><div class="hint pv-msg" data-f="msg-test" data-testid="prov-msg-test" role="status"></div></div></div>' +
5307
+ '</div>' +
5308
+ '<div class="pv-knote"><div class="hint bad pv-msg" data-f="msg-edit" data-testid="prov-msg-edit"></div><div class="hint pv-msg" data-f="msg-legacyMaxTokens" data-testid="prov-msg-legacyMaxTokens"></div></div>' +
5309
+ '<div class="pv-models" data-models-for="' + escapeXml(row.slot) + '" data-testid="models-row-' + escapeXml(row.slot) + '">' +
5310
+ '<div class="pv-mhead" aria-hidden="true"><span class="pv-um"><span class="pv-uh">USE</span><span>MODEL</span></span><span class="pv-pair"><span>IN $/1M</span><span>OUT $/1M</span></span><span class="pv-tok">TOKENS</span></div>' +
5311
+ '<div data-f="models"></div>' +
5312
+ '<div class="pv-more"><button class="pv-add" type="button" data-act="typed-open" data-testid="model-typed-open">+ type a model name</button>' +
5313
+ '<div class="pv-typed" data-f="typed" hidden><input type="text" data-typed="1" data-testid="model-typed" autocomplete="off" spellcheck="false" aria-label="' + escapeXml(row.label + " model name") + '" placeholder="type a model name"> ' +
5314
+ '<button class="btn small" type="button" data-act="add-model" data-testid="model-add">Add</button><div class="hint pv-msg" data-f="typed-msg" data-testid="model-typed-msg"></div></div></div>' +
5315
+ '</div>';
5316
+ key.querySelector("code").textContent = row.envVar;
5317
+ key.querySelectorAll("input").forEach(function(inp){
5086
5318
  inp.addEventListener("input", function(){ inp.setAttribute("data-dirty", "1"); });
5087
5319
  });
5088
- return tr;
5320
+ key.querySelector("select").addEventListener("change", function(ev){ ev.target.setAttribute("data-dirty", "1"); });
5321
+ return key;
5322
+ }
5323
+ // One child row per model: [Use][name], In + Out side by side, Tokens. The price pair is both-or-neither; the server's one rule says why not.
5324
+ function buildModelLine(slot, m){
5325
+ var d = document.createElement("div");
5326
+ d.className = "pv-mrow";
5327
+ d.setAttribute("data-model", m.model);
5328
+ d.setAttribute("data-testid", "model-line");
5329
+ d.innerHTML =
5330
+ '<div class="pv-cell pv-um nolbl"><span class="pv-m-use"><input type="checkbox" data-mf="use" data-testid="model-use"></span><code class="pv-m-name"></code></div>' +
5331
+ '<div class="pv-cell pv-pair"><label><input type="text" inputmode="decimal" data-mf="inPerM" data-testid="model-in" autocomplete="off"></label>' +
5332
+ '<label><input type="text" inputmode="decimal" data-mf="outPerM" data-testid="model-out" autocomplete="off"></label></div>' +
5333
+ '<div class="pv-cell pv-tok pv-m-tok"><span class="pv-lbl">Tokens</span><span data-f="model-tokens" data-testid="model-tokens"></span></div>' +
5334
+ '<div class="hint pv-msg pv-m-msg" data-f="msg-model" data-testid="model-msg"></div>';
5335
+ d.querySelector(".pv-m-name").textContent = m.model;
5336
+ d.querySelector("[data-mf=use]").setAttribute("aria-label", slot + " " + m.model + " use");
5337
+ d.querySelector("[data-mf=inPerM]").setAttribute("aria-label", m.model + " price in per 1M tokens");
5338
+ d.querySelector("[data-mf=outPerM]").setAttribute("aria-label", m.model + " price out per 1M tokens");
5339
+ d.querySelectorAll("input[type=text]").forEach(function(inp){
5340
+ inp.addEventListener("input", function(){ inp.setAttribute("data-dirty", "1"); });
5341
+ });
5342
+ return d;
5343
+ }
5344
+ // The provider's own model list per key (asked on page open, Reload keys, Refresh models): { models: [ids] } or { why }. Not saved: only ticked or typed lines are.
5345
+ var listed = {};
5346
+ var lastData = null;
5347
+ function linesFor(row){
5348
+ var l = listed[row.slot];
5349
+ var have = {};
5350
+ row.models.forEach(function(m){ have[m.model] = true; });
5351
+ var extra = (l && l.models ? l.models : []).filter(function(id){ return !have[id]; }).map(function(id){ return { model: id, use: false }; });
5352
+ return row.models.concat(extra);
5353
+ }
5354
+ // "3 models · none ticked", "2 models · 1 ticked"; a list that failed with nothing saved says so.
5355
+ function sumText(row){
5356
+ var l = listed[row.slot];
5357
+ var lines = linesFor(row);
5358
+ if(l && l.why && lines.length === 0) return "failed — type a name";
5359
+ var ticked = lines.filter(function(m){ return m.use === true; }).length;
5360
+ return lines.length + (lines.length === 1 ? " model" : " models") + " · " + (ticked === 0 ? "none ticked" : ticked + " ticked");
5361
+ }
5362
+ function paintModels(row, mr){
5363
+ var box = mr.querySelector("[data-f=models]");
5364
+ var lines = linesFor(row);
5365
+ var l = listed[row.slot];
5366
+ var typed = mr.querySelector("[data-f=typed]");
5367
+ typed.hidden = typedOpen[row.slot] !== true;
5368
+ var wanted = lines.map(function(m){ return m.model; });
5369
+ Array.prototype.slice.call(box.querySelectorAll(".pv-mrow")).forEach(function(el){
5370
+ if(wanted.indexOf(el.getAttribute("data-model")) < 0) box.removeChild(el);
5371
+ });
5372
+ var note = box.querySelector("[data-f=models-note]");
5373
+ lines.forEach(function(m){
5374
+ var line = Array.prototype.find.call(box.querySelectorAll(".pv-mrow"), function(el){ return el.getAttribute("data-model") === m.model; });
5375
+ if(!line){ line = buildModelLine(row.slot, m); box.insertBefore(line, note); }
5376
+ var use = line.querySelector("[data-mf=use]");
5377
+ use.checked = m.use === true;
5378
+ ["inPerM", "outPerM"].forEach(function(f){
5379
+ var inp = line.querySelector('[data-mf="' + f + '"]');
5380
+ inp.placeholder = "—";
5381
+ if(inp.getAttribute("data-dirty") !== "1") inp.value = typeof m[f] === "number" ? String(m[f]) : "";
5382
+ });
5383
+ line.querySelector("[data-f=model-tokens]").textContent = typeof m.tokens === "number" ? tokensText(m.tokens) : "—";
5384
+ });
5385
+ note = box.querySelector("[data-f=models-note]");
5386
+ if(!note){ note = document.createElement("div"); note.className = "hint pv-more"; note.setAttribute("data-f", "models-note"); note.setAttribute("data-testid", "models-note"); box.appendChild(note); }
5387
+ setNote(note, false, l && l.why ? l.why + " Type the model name below." : (lines.length === 0 ? "No models yet. Press ⟳ to refresh models, or type a name." : ""));
5388
+ note.className += " pv-more" + (l && l.why ? " pv-failed" : "");
5389
+ box.parentNode.querySelector(".pv-mhead").hidden = lines.length === 0;
5089
5390
  }
5090
5391
  var STATUS_WORD = { "set in file": "set in file", "found in shell": "found in shell", "not set": "not set", "refused": "refused — see above" };
5091
- function paintProviders(data){
5392
+ // The Refresh button: "[ ⟳ Refresh ]", disabled "[ ⟳ refreshing… ]" while the free list call is out.
5393
+ function setRefreshBtn(key, pending){
5394
+ var b = key.querySelector("[data-act=refresh-models]");
5395
+ b.disabled = pending === true;
5396
+ b.innerHTML = pending === true ? "&#10227; refreshing&hellip;" : "&#10227; Refresh";
5397
+ }
5398
+ // The Test button: "[ Test ]", disabled "[ testing… ]" while the free call is out. The route says ok + ms or a plain-words why; written on the key row's own note.
5399
+ function testKey(slot, key){
5400
+ var b = key.querySelector("[data-act=test-key]");
5401
+ var msg = key.querySelector("[data-f=msg-test]");
5402
+ var row = lastData && lastData.rows.filter(function(r){ return r.slot === slot; })[0];
5403
+ if(row && row.baseUrl === ""){
5404
+ setNote(msg, true, "Type a Base URL for " + row.envVar + " in Settings.");
5405
+ return;
5406
+ }
5407
+ b.disabled = true;
5408
+ b.innerHTML = "testing&hellip;";
5409
+ setNote(msg, false, "");
5410
+ postJSON("/api/settings/test", { slot: slot }).then(function(r){
5411
+ var d = r.body;
5412
+ if(d && d.ok === true) setNote(msg, false, "OK \u00b7 " + d.ms + " ms");
5413
+ else setNote(msg, true, d && d.why ? d.why : settingsRefusal(r));
5414
+ }, function(){ setNote(msg, true, networkText()); }).then(function(){
5415
+ b.disabled = false;
5416
+ b.innerHTML = "Test";
5417
+ });
5418
+ }
5419
+ function refreshModels(slot, tr){
5420
+ listed[slot] = { pending: true };
5421
+ setRefreshBtn(tr, true);
5422
+ return postJSON("/api/settings/models", { slot: slot }).then(function(r){
5423
+ var b = r.body;
5424
+ listed[slot] = b && b.ok ? { models: b.models } : { why: (b && b.why) ? b.why : settingsRefusal(r) };
5425
+ }, function(){ listed[slot] = { why: networkText() }; }).then(function(){
5426
+ if(lastData) paintProviders(lastData, false);
5427
+ });
5428
+ }
5429
+ function paintProviders(data, list){
5430
+ lastData = data;
5092
5431
  var path = data.keysFile && data.keysFile.path ? data.keysFile.path : "~/.config/fwdloop/.env";
5093
5432
  document.getElementById("keys-path").textContent = path;
5094
5433
  setNote(document.getElementById("keys-refusal"), true, data.keysFile && data.keysFile.refusal);
5095
5434
  setNote(pvNote, !!data.configProblem, data.configProblem || PV_NOTE_DEFAULT);
5096
5435
  data.rows.forEach(function(row){
5097
- var tr = pvRows.querySelector('[data-slot="' + row.slot + '"]');
5098
- if(!tr){ tr = buildProviderRow(row); pvRows.appendChild(tr); }
5099
- tr.querySelector("[data-f=status]").textContent = STATUS_WORD[row.keyStatus] || row.keyStatus;
5100
- var nameIn = tr.querySelector('[data-prov=name]');
5101
- var shapeSel = tr.querySelector('[data-prov=shape]');
5102
- var urlIn = tr.querySelector('[data-prov=baseUrl]');
5103
- if(shapeSel.options.length !== data.shapes.length){
5104
- shapeSel.innerHTML = "";
5105
- data.shapes.forEach(function(sh){
5106
- var o = document.createElement("option");
5107
- o.value = sh.id; o.textContent = sh.label; shapeSel.appendChild(o);
5108
- });
5436
+ var key = pvRows.querySelector('.pv-key[data-slot="' + row.slot + '"]');
5437
+ if(!key){ key = buildProviderRow(row); pvRows.appendChild(key); }
5438
+ if(folds[row.slot] === undefined) folds[row.slot] = row.models.some(function(m){ return m.use === true; });
5439
+ key.setAttribute("data-open", folds[row.slot] ? "1" : "0");
5440
+ var fold = key.querySelector("[data-act=fold]");
5441
+ fold.textContent = folds[row.slot] ? "▾" : "▸";
5442
+ fold.setAttribute("aria-expanded", folds[row.slot] ? "true" : "false");
5443
+ fold.setAttribute("aria-label", (folds[row.slot] ? "Fold " : "Unfold ") + row.label + " models");
5444
+ paintModels(row, key.querySelector(".pv-models"));
5445
+ setRefreshBtn(key, !!(listed[row.slot] && listed[row.slot].pending));
5446
+ key.querySelector("[data-f=sum]").textContent = sumText(row);
5447
+ var st = key.querySelector("[data-f=status]");
5448
+ var word = STATUS_WORD[row.keyStatus] || row.keyStatus;
5449
+ st.className = row.keyStatus === "set in file" || row.keyStatus === "found in shell" ? "pv-status pv-ok" : "pv-status hint";
5450
+ st.textContent = st.className.indexOf("pv-ok") >= 0 ? "✓" : word;
5451
+ st.setAttribute("title", word);
5452
+ if(st.className.indexOf("pv-ok") >= 0) st.setAttribute("aria-label", word); else st.removeAttribute("aria-label");
5453
+ var legacyIn = key.querySelector('[data-prov=legacyMaxTokens]');
5454
+ if(document.activeElement !== legacyIn) legacyIn.checked = row.legacyMaxTokens === true;
5455
+ key.querySelector("[data-f=legacy-word]").textContent = legacyIn.checked ? "on" : "off";
5456
+ // shape + Base URL: the key row's own boxes, written from the server's row unless the person has typed in them (a refused value stays typed, with its sentence)
5457
+ var sel = key.querySelector("[data-prov=shape]");
5458
+ if(sel.options.length !== data.shapes.length || data.shapes.some(function(sh, i){ return sel.options[i].value !== sh.id; })){
5459
+ sel.textContent = "";
5460
+ data.shapes.forEach(function(sh){ var o = document.createElement("option"); o.value = sh.id; o.textContent = sh.label; sel.appendChild(o); });
5109
5461
  }
5110
- nameIn.placeholder = row.defaults.model;
5111
- urlIn.placeholder = row.defaults.baseUrl !== "" ? row.defaults.baseUrl : "the vendor's own address";
5112
- // a box the person is typing in is never overwritten by a repaint
5113
- if(nameIn.getAttribute("data-dirty") !== "1") nameIn.value = row.model;
5114
- if(urlIn.getAttribute("data-dirty") !== "1") urlIn.value = row.savedBaseUrl;
5115
- if(document.activeElement !== shapeSel) shapeSel.value = row.shape;
5116
- tr.querySelector("[data-f=tokens]").textContent = tokensText(row.tokens);
5117
- PRICE_FIELDS.forEach(function(f){
5118
- var inp = tr.querySelector('input[data-field="' + f + '"]');
5119
- var pr = row.price[f];
5120
- inp.placeholder = String(pr.value) + " (" + sourceWord(pr.source) + ")";
5121
- inp.title = inp.placeholder;
5122
- // a box the person has typed in is never overwritten by a repaint
5123
- if(inp.getAttribute("data-dirty") !== "1") inp.value = pr.source === "settings" ? String(pr.value) : "";
5124
- });
5462
+ if(sel.getAttribute("data-dirty") !== "1") sel.value = row.shape;
5463
+ var urlIn = key.querySelector("[data-prov=baseUrl]");
5464
+ if(urlIn.getAttribute("data-dirty") !== "1" && document.activeElement !== urlIn) urlIn.value = row.baseUrl;
5465
+ key.querySelector("[data-f=tokens]").textContent = tokensText(row.tokens);
5466
+ });
5467
+ // rows that left the keys file leave the page
5468
+ Array.prototype.slice.call(pvRows.querySelectorAll(".pv-key")).forEach(function(key){
5469
+ if(!data.rows.some(function(r){ return r.slot === key.getAttribute("data-slot"); })) pvRows.removeChild(key);
5125
5470
  });
5471
+ if(list) data.rows.forEach(function(row){
5472
+ var key = pvRows.querySelector('.pv-key[data-slot="' + row.slot + '"]');
5473
+ if(row.baseUrl === ""){ listed[row.slot] = { why: "Type a Base URL for " + row.slot + " in Settings." }; paintProviders(lastData, false); }
5474
+ else refreshModels(row.slot, key);
5475
+ });
5476
+ }
5477
+ // Shape and Base URL save together, on change of either (blur / Enter / pick); the server judges them as a pair and says which sentence on
5478
+ // a refusal (nothing saved, the typed value stays so the person can fix it).
5479
+ function saveEndpoint(key){
5480
+ var msg = key.querySelector("[data-f=msg-edit]");
5481
+ var payload = { slot: key.getAttribute("data-slot"), shape: key.querySelector("[data-prov=shape]").value, baseUrl: key.querySelector("[data-prov=baseUrl]").value.trim() };
5482
+ postJSON("/api/settings/provider", payload).then(function(r){
5483
+ if(r.body && r.body.ok){
5484
+ key.querySelector("[data-prov=shape]").removeAttribute("data-dirty");
5485
+ key.querySelector("[data-prov=baseUrl]").removeAttribute("data-dirty");
5486
+ setNote(msg, true, "");
5487
+ loadProviders();
5488
+ } else setNote(msg, true, settingsRefusal(r));
5489
+ }, function(){ setNote(msg, true, networkText()); });
5126
5490
  }
5127
5491
  pvRows.addEventListener("click", function(ev){
5128
5492
  var b = ev.target.closest && ev.target.closest("button[data-act]");
5129
5493
  if(!b) return;
5130
- var tr = b.closest("tr");
5131
- if(b.getAttribute("data-act") === "test") runTest(tr, tr.getAttribute("data-slot"));
5132
- else if(b.getAttribute("data-act") === "balance") runBalance(tr, tr.getAttribute("data-slot"));
5494
+ var key = b.closest(".pv-key");
5495
+ var slot = key.getAttribute("data-slot");
5496
+ var act = b.getAttribute("data-act");
5497
+ if(act === "refresh-models") refreshModels(slot, key);
5498
+ else if(act === "test-key") testKey(slot, key);
5499
+ else if(act === "fold"){ folds[slot] = !folds[slot]; paintProviders(lastData, false); }
5500
+ else if(act === "typed-open"){ typedOpen[slot] = !typedOpen[slot]; paintProviders(lastData, false); }
5501
+ else if(act === "add-model") addTypedModel(slot, b.closest("[data-f=typed]"));
5133
5502
  });
5134
- // Saved like bareloop saves a row field: on change (blur or Enter), no Save button.
5503
+ // Saved like bareloop saves a row field: on change (blur or Enter), no Save button. The legacy tick saves alone; shape and Base URL save as a pair.
5135
5504
  pvRows.addEventListener("change", function(ev){
5136
5505
  var inp = ev.target;
5137
5506
  if(!inp.getAttribute) return;
5138
- if(inp.getAttribute("data-prov")){ saveProvider(inp.closest("tr"), inp); return; }
5139
- if(!inp.getAttribute("data-field")) return;
5140
- savePrice(inp.closest("tr"), inp.getAttribute("data-field"));
5507
+ if(inp.getAttribute("data-prov") === "legacyMaxTokens"){ saveProvider(inp.closest(".pv-key"), inp); return; }
5508
+ if(inp.getAttribute("data-prov") === "shape" || inp.getAttribute("data-prov") === "baseUrl"){ saveEndpoint(inp.closest(".pv-key")); return; }
5509
+ if(!inp.getAttribute("data-mf")) return;
5510
+ saveModel(inp.closest(".pv-models") ? inp.closest(".pv-models").getAttribute("data-models-for") : "", inp.closest(".pv-mrow"));
5141
5511
  });
5142
- function runTest(tr, slot){
5143
- var out = tr.querySelector("[data-f=test]");
5144
- out.textContent = "testing…";
5145
- postJSON("/api/settings/test", { slot: slot }).then(function(r){
5146
- var b = r.body;
5147
- out.textContent = b && b.ok ? "OK · " + b.ms + " ms" : (b && b.why ? b.why : settingsRefusal(r));
5148
- }, function(){ out.textContent = networkText(); });
5149
- }
5150
- // Balance is read on a click, never on render (signed M4d: "read on a click").
5151
- function runBalance(tr, slot){
5152
- var out = tr.querySelector("[data-f=balance-result]");
5153
- out.textContent = "checking…";
5154
- getJSON("/api/settings/balance?slot=" + encodeURIComponent(slot)).then(function(b){
5155
- if(b.ok) out.textContent = b.balances.map(function(x){ return x.total + " " + x.currency; }).join(" + ");
5156
- else out.textContent = b.why || "Could not check the balance.";
5157
- }, function(e){ out.textContent = loadFailureText(e); });
5158
- }
5159
5512
  // A box the person typed: empty = back to the default (null); a number is sent as a number; anything else is
5160
5513
  // sent as the text typed, so the server refuses it by naming the box.
5161
5514
  function priceValue(text){
@@ -5164,25 +5517,42 @@
5164
5517
  var n = Number(t);
5165
5518
  return isFinite(n) ? n : t;
5166
5519
  }
5167
- function savePrice(tr, changed){
5168
- var msg = tr.querySelector("[data-f=msg-" + changed + "]");
5169
- var payload = { slot: tr.getAttribute("data-slot") };
5170
- tr.querySelectorAll("input[data-field]").forEach(function(inp){ payload[inp.getAttribute("data-field")] = priceValue(inp.value); });
5171
- postJSON("/api/settings/price", payload).then(function(r){
5520
+ // One model line per save: {slot, model, use, inPerM, outPerM}. A refusal is the line's hint (the server's one rule),
5521
+ // and nothing was saved: the repaint puts the tick back.
5522
+ function saveModel(slot, line){
5523
+ var msg = line.querySelector("[data-f=msg-model]");
5524
+ var payload = {
5525
+ slot: slot,
5526
+ model: line.getAttribute("data-model"),
5527
+ use: line.querySelector("[data-mf=use]").checked,
5528
+ inPerM: priceValue(line.querySelector("[data-mf=inPerM]").value),
5529
+ outPerM: priceValue(line.querySelector("[data-mf=outPerM]").value)
5530
+ };
5531
+ postJSON("/api/settings/model", payload).then(function(r){
5172
5532
  if(r.body && r.body.ok){
5173
- tr.querySelectorAll("input[data-field]").forEach(function(inp){ inp.removeAttribute("data-dirty"); });
5533
+ line.querySelectorAll("input[type=text]").forEach(function(inp){ inp.removeAttribute("data-dirty"); });
5174
5534
  loadProviders();
5175
5535
  setNote(msg, false, "saved — applies from the next model call");
5176
- } else setNote(msg, true, settingsRefusal(r));
5536
+ } else { setNote(msg, true, settingsRefusal(r)); loadProviders(); }
5537
+ }, function(){ setNote(msg, true, networkText()); });
5538
+ }
5539
+
5540
+ // A model name typed because the list failed: saved as an unticked, empty line (typed lines are saved); the person then fills the prices and ticks it.
5541
+ function addTypedModel(slot, box){
5542
+ var inp = box.querySelector("input");
5543
+ var msg = box.querySelector("[data-f=typed-msg]");
5544
+ postJSON("/api/settings/model", { slot: slot, model: inp.value.trim(), use: false }).then(function(r){
5545
+ if(r.body && r.body.ok){ inp.value = ""; setNote(msg, false, "added"); loadProviders(); }
5546
+ else setNote(msg, true, settingsRefusal(r));
5177
5547
  }, function(){ setNote(msg, true, networkText()); });
5178
5548
  }
5179
5549
 
5180
- // One field per save: {slot, name|shape|baseUrl}. An empty Base URL means the default; a refusal is the cell's hint line.
5181
- function saveProvider(tr, inp){
5182
- var key = inp.getAttribute("data-prov");
5183
- var msg = tr.querySelector("[data-f=msg-" + key + "]");
5184
- var payload = { slot: tr.getAttribute("data-slot") };
5185
- payload[key] = inp.value.trim();
5550
+ // The legacy tick saves alone: {slot, legacyMaxTokens}. A refusal is the cell's hint line.
5551
+ function saveProvider(key, inp){
5552
+ var field = inp.getAttribute("data-prov");
5553
+ var msg = key.querySelector("[data-f=msg-" + field + "]");
5554
+ var payload = { slot: key.getAttribute("data-slot") };
5555
+ payload[field] = inp.checked;
5186
5556
  postJSON("/api/settings/provider", payload).then(function(r){
5187
5557
  if(r.body && r.body.ok){
5188
5558
  inp.removeAttribute("data-dirty");