heartcode 0.1.27 → 0.1.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/settings.html CHANGED
@@ -16,6 +16,7 @@
16
16
  --accent: #16824c; --accent-soft: #e8f5ee; --on-accent: #ffffff;
17
17
  --brand: var(--accent); --brand-soft: var(--accent-soft); --on-brand: var(--on-accent);
18
18
  --ok: #1d8a4b; --ok-soft: #e7f5ec; --err: #d1242f; --err-soft: #fdecee;
19
+ --warn: #a16207; /* in progress, or needs a look: not green (works) and not red (broken) */
19
20
  --ring: 0 0 0 3px rgba(22, 130, 76, .18);
20
21
  --shadow: 0 1px 2px rgba(20, 22, 30, .04), 0 8px 24px rgba(20, 22, 30, .06);
21
22
  --shadow-pop: 0 24px 64px rgba(20, 22, 30, .18), 0 2px 6px rgba(20, 22, 30, .06);
@@ -31,6 +32,7 @@
31
32
  --line: #23252c; --line-strong: #2f323a; --hover: #1c1e24; --input: #101115;
32
33
  --accent: #5ccf8a; --accent-soft: rgba(92, 207, 138, .13); --on-accent: #07140d;
33
34
  --ok: #62cf8b; --ok-soft: rgba(98, 207, 139, .12); --err: #ff7a7a; --err-soft: rgba(255, 122, 122, .12);
35
+ --warn: #e3b341;
34
36
  --ring: 0 0 0 3px rgba(92, 207, 138, .25);
35
37
  --shadow: 0 1px 2px rgba(0, 0, 0, .3);
36
38
  --shadow-pop: 0 28px 72px rgba(0, 0, 0, .55), 0 0 0 1px rgba(255, 255, 255, .03);
@@ -42,6 +44,7 @@
42
44
  --line: #23252c; --line-strong: #2f323a; --hover: #1c1e24; --input: #101115;
43
45
  --accent: #5ccf8a; --accent-soft: rgba(92, 207, 138, .13); --on-accent: #07140d;
44
46
  --ok: #62cf8b; --ok-soft: rgba(98, 207, 139, .12); --err: #ff7a7a; --err-soft: rgba(255, 122, 122, .12);
47
+ --warn: #e3b341;
45
48
  --ring: 0 0 0 3px rgba(92, 207, 138, .25);
46
49
  --shadow: 0 1px 2px rgba(0, 0, 0, .3);
47
50
  --shadow-pop: 0 28px 72px rgba(0, 0, 0, .55), 0 0 0 1px rgba(255, 255, 255, .03);
@@ -69,6 +72,14 @@
69
72
  nav a.on::before { content: ''; position: absolute; left: -14px; top: 9px; bottom: 9px; width: 3px; border-radius: 0 3px 3px 0; background: var(--accent); }
70
73
  nav a .ic { width: 18px; text-align: center; opacity: .7; font-size: 13px; }
71
74
  nav a.on .ic { color: var(--accent); opacity: 1; }
75
+ .nav-group { height: 1px; margin: 10px 12px; background: var(--line); }
76
+ .nav-group:first-child { display: none; }
77
+ .subtabs { display: flex; gap: 4px; margin: -4px 0 18px; border-bottom: 1px solid var(--line); }
78
+ .subtabs a { position: relative; padding: 8px 12px 10px; color: var(--muted); text-decoration: none; font-weight: 500; font-size: 13.5px; transition: color .15s; }
79
+ .subtabs a:hover { color: var(--text); }
80
+ .subtabs a.on { color: var(--text); font-weight: 600; }
81
+ .subtabs a.on::after { content: ''; position: absolute; left: 10px; right: 10px; bottom: -1px; height: 2px; border-radius: 2px; background: var(--accent); }
82
+ .subtabs a .count { margin-left: 6px; font-size: 11.5px; color: var(--faint); font-weight: 500; font-variant-numeric: tabular-nums; }
72
83
  nav a .count { margin-left: auto; font-size: 11.5px; color: var(--faint); font-weight: 500; font-variant-numeric: tabular-nums; }
73
84
  .using:empty { visibility: hidden; } /* until your settings are in */
74
85
  .using { margin: auto 0 0; padding: 12px 14px; border: 1px solid var(--line); border-radius: 12px; font-size: 12px; background: var(--panel); }
@@ -316,7 +327,7 @@
316
327
  .olist .test .spin { flex: none; }
317
328
  .olist .test button { flex: none; }
318
329
  .olist .test.ok { color: var(--ok); }
319
- .olist .test.warn { color: var(--accent); }
330
+ .olist .test.warn { color: var(--warn); }
320
331
  dialog { width: 70vw; max-width: none; max-height: calc(100vh - 32px); overflow: auto; border: 1px solid var(--line); border-radius: 18px; background: var(--panel); color: var(--text); padding: 26px 28px 24px; box-shadow: var(--shadow-pop); }
321
332
  dialog[open] { animation: pop-in .18s cubic-bezier(.2, .8, .3, 1); }
322
333
  @keyframes pop-in { from { opacity: 0; transform: translateY(6px) scale(.985); } to { opacity: 1; transform: none; } }
@@ -330,7 +341,7 @@
330
341
  #pr-list li.dragging { opacity: .4; }
331
342
  dialog .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 22px; padding-top: 18px; border-top: 1px solid var(--line); }
332
343
  .olist .test.failed { color: var(--err); }
333
- .olist .test.testing, .olist .test.waiting { color: var(--accent); }
344
+ .olist .test.testing, .olist .test.waiting { color: var(--warn); }
334
345
  .olist .test button { padding: 0 7px; font-size: 11px; }
335
346
  .spin { width: 10px; height: 10px; border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: spin .8s linear infinite; }
336
347
  @keyframes spin { to { transform: rotate(360deg); } }
@@ -404,7 +415,7 @@
404
415
  .mtable .yes { color: var(--ok); }
405
416
  .mtable .no { color: var(--faint); }
406
417
  .mtable .src { font-size: 12px; color: var(--muted); display: flex; align-items: center; gap: 6px; white-space: nowrap; }
407
- .mtable .src.warn { color: var(--accent); }
418
+ .mtable .src.warn { color: var(--warn); }
408
419
  .mtable button { padding: 2px 8px; font-size: 11.5px; border-color: transparent; background: transparent; color: var(--muted); }
409
420
  .mtable li:hover button, .mtable li.picked button { border-color: var(--line-strong); background: var(--panel); color: var(--text); }
410
421
  .mtable li:hover button.danger { color: var(--err); }
@@ -412,7 +423,10 @@
412
423
  .mtable .try .msg { flex: 1; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
413
424
  .mtable .try.ok { color: var(--ok); }
414
425
  .mtable .try.bad { color: var(--err); }
415
- .mtable .try.going { color: var(--accent); }
426
+ .mtable .try.going { color: var(--warn); }
427
+ .mtable .try.going .msg { animation: pulse 1.4s ease-in-out infinite; }
428
+ @keyframes pulse { 50% { opacity: .45; } }
429
+ @media (prefers-reduced-motion: reduce) { .mtable .try.going .msg { animation: none; } }
416
430
  .mt-empty { padding: 28px 18px; color: var(--muted); }
417
431
  .olist .grip { cursor: grab; color: var(--faint); padding: 0 2px; user-select: none; }
418
432
  .olist .n { font-weight: 800; color: var(--brand); min-width: 24px; }
@@ -443,9 +457,24 @@
443
457
 
444
458
  /* choices as cards (permissions, colors) */
445
459
  .choices { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; }
460
+ .choices.three { grid-template-columns: repeat(3, minmax(0, 1fr)); }
461
+ .choices.four { grid-template-columns: repeat(4, minmax(0, 1fr)); }
462
+ /* General: cards in pairs on rows that line up (related ones side by side: permissions | colors,
463
+ behavior | model, voice | tools), the full width; one column when there isn't room for two */
464
+ .settings-col { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px; align-items: stretch; }
465
+ @media (max-width: 1280px) { .settings-col { grid-template-columns: minmax(0, 1fr); } }
466
+ .settings-col .card h2 { margin-bottom: 4px; }
467
+ .settings-col #g-toggles { margin-top: 8px; }
468
+ .setting { display: flex; align-items: center; gap: 18px; padding: 14px 0; border-bottom: 1px solid var(--line); }
469
+ .setting:last-child { border-bottom: 0; padding-bottom: 2px; }
470
+ .setting .t { flex: 1; min-width: 0; cursor: default; }
471
+ .setting .t b { display: block; font-weight: 600; }
472
+ .setting .t span { display: block; margin-top: 2px; color: var(--muted); font-size: 13px; line-height: 1.45; text-wrap: pretty; }
473
+ .setting select, .setting input { flex: none; width: 240px; }
446
474
  .choice { position: relative; border: 1px solid var(--line-strong); border-radius: 12px; padding: 13px 15px; cursor: pointer; background: var(--panel); transition: border-color .15s, box-shadow .15s, background .15s; }
447
475
  .choice:hover { border-color: color-mix(in srgb, var(--accent) 45%, var(--line-strong)); }
448
- .choice.on { border-color: var(--accent); background: var(--accent-soft); box-shadow: var(--ring); }
476
+ .choice.on { border-color: var(--accent); background: color-mix(in srgb, var(--accent-soft) 60%, var(--panel)); }
477
+ .choice:has(input:focus-visible) { box-shadow: var(--ring); }
449
478
  .choice b { display: block; }
450
479
  .choice span { display: block; margin-top: 2px; color: var(--muted); font-size: 12.5px; line-height: 1.45; }
451
480
  .choice input { position: absolute; opacity: 0; }
@@ -499,11 +528,14 @@
499
528
  nav { display: flex; overflow-x: auto; gap: 4px; padding-bottom: 4px; }
500
529
  nav a { flex: none; margin: 0; }
501
530
  nav a.on::before { display: none; } /* a strip of tabs: the highlighted one is enough */
502
- nav a .count, .using { display: none; }
531
+ nav a .count, .using, .nav-group { display: none; }
503
532
  .theme-pick { margin: 6px 0 4px; max-width: 280px; }
504
533
  main { padding: 20px 16px 60px; }
505
534
  .steps { grid-template-columns: 1fr; }
506
- .choices { grid-template-columns: 1fr; }
535
+ .choices, .choices.three { grid-template-columns: 1fr; }
536
+ .choices.four { grid-template-columns: 1fr 1fr; }
537
+ .setting { flex-direction: column; align-items: stretch; gap: 10px; }
538
+ .setting select, .setting input { width: 100%; }
507
539
  .grid, .cols { grid-template-columns: 1fr; }
508
540
  .md { grid-template-columns: 1fr; }
509
541
  .md .list { position: static; max-height: 300px; }
@@ -552,6 +584,10 @@
552
584
  .imp-row { display: flex; align-items: baseline; gap: 10px; padding: 7px 8px; border-radius: var(--radius-s); cursor: pointer; }
553
585
  .imp-row:hover { background: var(--hover); }
554
586
  .imp-row input { margin: 0; flex: none; align-self: center; }
587
+ .tg-steps { margin: 4px 0 0; padding-left: 20px; display: grid; gap: 14px; line-height: 1.55; }
588
+ .tg-steps li::marker { color: var(--muted); }
589
+ .tg-conn { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin: 4px 0 12px; }
590
+ .opt.tg-off { opacity: .5; }
555
591
  .imp-row .imp-label { font-weight: 500; font-family: var(--mono); font-size: 12.5px; flex: none; }
556
592
  .imp-row .imp-desc { color: var(--muted); font-size: 12.5px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
557
593
  </style>
@@ -561,15 +597,17 @@
561
597
  <aside>
562
598
  <div class="brand"><span>♥</span> HeartCode <small>settings</small></div>
563
599
  <nav id="nav">
564
- <a href="#providers" data-page="providers"><span class="ic">◉</span> Providers &amp; models <span class="count" id="n-providers"></span></a>
565
- <a href="#models" data-page="models"><span class="ic">☰</span> Your models <span class="count" id="n-mine"></span></a>
566
- <a href="#general" data-page="general"><span class="ic">⚙</span> General</a>
567
- <a href="#statusbar" data-page="statusbar"><span class="ic">▭</span> Status bar</a>
568
- <a href="#logging" data-page="logging"><span class="ic">▤</span> Logging <span class="count" id="n-failed"></span></a>
569
- <a href="#prompts" data-page="prompts"><span class="ic">✎</span> System prompt</a>
570
- <a href="#mcp" data-page="mcp"><span class="ic">⧉</span> MCP servers <span class="count" id="n-mcp"></span></a>
600
+ <div class="nav-group" role="separator"></div>
601
+ <a href="#models" data-page="models" data-tabs="models providers"><span class="ic">☰</span> Models <span class="count" id="n-mine"></span></a>
602
+ <div class="nav-group" role="separator"></div>
603
+ <a href="#general" data-page="general" data-tabs="general statusbar"><span class="ic">⚙</span> General</a>
604
+ <a href="#notify" data-page="notify"><span class="ic">✉</span> Notifications</a>
605
+ <div class="nav-group" role="separator"></div>
571
606
  <a href="#skills" data-page="skills"><span class="ic">✦</span> Skills <span class="count" id="n-skills"></span></a>
572
- <a href="#files" data-page="files"><span class="ic">≡</span> Advanced files</a>
607
+ <a href="#mcp" data-page="mcp"><span class="ic">⧉</span> MCP servers <span class="count" id="n-mcp"></span></a>
608
+ <a href="#prompts" data-page="prompts"><span class="ic">✎</span> System prompt</a>
609
+ <div class="nav-group" role="separator"></div>
610
+ <a href="#logging" data-page="logging" data-tabs="logging files"><span class="ic">▤</span> Advanced <span class="count" id="n-failed"></span></a>
573
611
  </nav>
574
612
  <div class="using" id="using"></div>
575
613
  <div class="seg theme-pick" id="theme-pick" role="radiogroup" aria-label="Light or dark">
@@ -582,7 +620,7 @@
582
620
  <!-- Providers & models -->
583
621
  <section class="page" id="page-providers">
584
622
  <div class="head">
585
- <div><h1>Providers &amp; models</h1><p class="lead">Click a model to add it to your list, or tick several. HeartCode tries your list in order: #1 first, the next when one fails.</p></div>
623
+ <div><h1>Providers</h1><p class="lead">Click a model to add it to your list, or tick several. HeartCode tries your list in order: #1 first, the next when one fails.</p></div>
586
624
  <div class="head-actions"><button id="p-mine" type="button"></button><button class="primary" id="p-open">+ Add a provider</button></div>
587
625
  </div>
588
626
  <div class="steps" id="steps"></div>
@@ -609,9 +647,30 @@
609
647
  <div class="card mt-card" id="mt"></div>
610
648
  </section>
611
649
 
650
+ <!-- Notifications -->
651
+ <section class="page" id="page-notify">
652
+ <div class="head"><div><h1>Notifications</h1><p class="lead">A message on your phone when HeartCode finishes a task, fails, or needs you, so you can step away while it works.</p></div></div>
653
+ <div class="cols">
654
+ <div class="stack">
655
+ <div class="card">
656
+ <h2>Telegram</h2>
657
+ <p class="sub">Through a bot of your own: only you get its messages.</p>
658
+ <div id="tg-setup"></div>
659
+ </div>
660
+ </div>
661
+ <div class="stack">
662
+ <div class="card">
663
+ <h2>When to send one</h2>
664
+ <p class="sub">Each on its own. A running HeartCode follows changes right away.</p>
665
+ <div id="tg-events"></div>
666
+ </div>
667
+ </div>
668
+ </div>
669
+ </section>
670
+
612
671
  <!-- Logging -->
613
672
  <section class="page" id="page-logging">
614
- <div class="head"><div><h1>Logging</h1><p class="lead">What HeartCode writes down, for finding out what went wrong. Off unless you switch it on.</p></div><div class="disk" id="l-disk"></div></div>
673
+ <div class="head"><div><h1>Logs</h1><p class="lead">What HeartCode writes down, for finding out what went wrong. Off unless you switch it on.</p></div><div class="disk" id="l-disk"></div></div>
615
674
  <div class="card">
616
675
  <div class="log-opts">
617
676
  <div>
@@ -655,48 +714,56 @@
655
714
  </div>
656
715
  </section>
657
716
 
658
- <!-- General -->
717
+ <!-- General: one column, a card per topic, every setting saved as it changes -->
659
718
  <section class="page" id="page-general">
660
- <div class="head"><div><h1>General</h1><p class="lead">How HeartCode works for you. Saved for next time; a running HeartCode takes changes right away.</p></div></div>
661
- <div class="cols">
662
- <div class="stack">
663
- <div class="card">
664
- <h2>What can HeartCode do without asking?</h2>
665
- <p class="sub">Shift+Tab in HeartCode switches between these too (and to plan mode).</p>
666
- <div class="choices" id="g-perm"></div>
667
- </div>
668
- <div class="card">
669
- <h2>Colors</h2>
670
- <p class="sub">Your own colors on top of a theme: theme.json in <a href="#files">Advanced files</a>.</p>
671
- <div class="choices" id="g-theme"></div>
719
+ <div class="head"><div><h1>General</h1><p class="lead">How HeartCode works for you. Every change saves on its own, and a running HeartCode picks it up right away.</p></div></div>
720
+ <div class="settings-col">
721
+ <div class="card">
722
+ <h2>Permissions</h2>
723
+ <p class="sub">What HeartCode may do without asking you first. <span class="mono">Shift+Tab</span> in HeartCode switches between these too.</p>
724
+ <div class="choices three" id="g-perm"></div>
725
+ </div>
726
+ <div class="card">
727
+ <h2>Terminal colors</h2>
728
+ <p class="sub">Your own colors on top of one: theme.json in <a href="#files">Advanced → Files</a>.</p>
729
+ <div class="choices four" id="g-theme"></div>
730
+ </div>
731
+ <div class="card">
732
+ <h2>Behavior</h2>
733
+ <div id="g-toggles"></div>
734
+ </div>
735
+ <div class="card">
736
+ <h2>Model</h2>
737
+ <div class="setting">
738
+ <label class="t" for="g-effort"><b>Thinking effort</b><span>How hard a thinking model thinks before it answers.</span></label>
739
+ <select id="g-effort"></select>
672
740
  </div>
673
- <div class="card">
674
- <h2>Thinking and context</h2>
675
- <div class="row">
676
- <div class="grow"><label class="f" for="g-effort">How hard a thinking model thinks</label><select id="g-effort"></select></div>
677
- <div class="grow"><label class="f" for="g-context">Context window (tokens)</label><input type="number" id="g-context" min="1" placeholder="as the model says"></div>
678
- </div>
679
- <div class="hint">Leave the context window empty unless HeartCode gets it wrong for your model.</div>
741
+ <div class="setting">
742
+ <label class="t" for="g-context"><b>Context window</b><span>How many tokens the model can hold. Leave it on auto unless HeartCode gets it wrong.</span></label>
743
+ <input type="number" id="g-context" min="1" placeholder="Auto">
680
744
  </div>
681
745
  </div>
682
- <div class="stack">
683
- <div class="card">
684
- <h2>Features</h2>
685
- <p class="sub">Switch each one on or off.</p>
686
- <div id="g-toggles"></div>
746
+ <div class="card">
747
+ <h2>Voice input</h2>
748
+ <p class="sub">Press Space in an empty input box (or type /voice), talk, and Enter. Your words land in the box.</p>
749
+ <div class="setting">
750
+ <label class="t" for="v-src"><b>Transcribe with</b><span id="v-src-about"></span></label>
751
+ <select id="v-src"></select>
687
752
  </div>
688
- <div class="card">
689
- <h2>Voice input</h2>
690
- <p class="sub">/voice in HeartCode. Empty: whisper-cli on this machine. Or a provider's transcription API: <span class="mono">{ "provider": "groq", "model": "whisper-large-v3" }</span>; add <span class="mono">"language": "auto"</span> for other languages.</p>
691
- <textarea id="v-text" spellcheck="false" rows="3" placeholder="(whisper-cli on this machine)"></textarea>
692
- <div class="actions"><button class="primary" id="v-save">Save voice</button></div>
753
+ <div class="setting">
754
+ <label class="t" for="v-model"><b>Model</b><span id="v-model-about"></span></label>
755
+ <input type="text" id="v-model" spellcheck="false" autocomplete="off">
693
756
  </div>
694
- <div class="card">
695
- <h2>External tools</h2>
696
- <p class="sub">Some features need a tool or service on your machine. Ready ones are ticked; the rest show what to install.</p>
697
- <div id="g-caps"></div>
757
+ <div class="setting">
758
+ <label class="t" for="v-lang"><b>Language</b><span id="v-lang-about"></span></label>
759
+ <input type="text" id="v-lang" spellcheck="false" autocomplete="off">
698
760
  </div>
699
761
  </div>
762
+ <div class="card">
763
+ <h2>External tools</h2>
764
+ <p class="sub">Some features need a tool on your machine. Ready ones are ticked; the rest say what to install.</p>
765
+ <div id="g-caps"></div>
766
+ </div>
700
767
  </div>
701
768
  </section>
702
769
 
@@ -765,7 +832,7 @@
765
832
 
766
833
  <!-- Advanced files -->
767
834
  <section class="page" id="page-files">
768
- <div class="head"><div><h1>Advanced files</h1><p class="lead">The rest of HeartCode's settings, as the files they're kept in (<span class="mono" id="f-home"></span>). A JSON file that doesn't parse isn't saved; save one empty to delete it.</p></div></div>
835
+ <div class="head"><div><h1>Settings files</h1><p class="lead">The rest of HeartCode's settings, as the files they're kept in (<span class="mono" id="f-home"></span>). A JSON file that doesn't parse isn't saved; save one empty to delete it.</p></div></div>
769
836
  <div class="md">
770
837
  <div class="list"><div class="items" id="f-items"></div></div>
771
838
  <div class="detail" id="f-detail"></div>
@@ -953,6 +1020,8 @@ const DOING = {
953
1020
  '/api/provider/on': 'Switching the provider',
954
1021
  '/api/order': 'Saving your models',
955
1022
  '/api/mcp/login': 'Signing in — your browser will open',
1023
+ '/api/telegram/connect': 'Checking the token with Telegram',
1024
+ '/api/telegram/test': 'Sending a test message',
956
1025
  '/api/models-dev': null, // its own strip
957
1026
  }
958
1027
  let acting = 0
@@ -1010,12 +1079,13 @@ addEventListener('scroll', drawVirtual, { capture: true, passive: true }) // the
1010
1079
  addEventListener('resize', drawVirtual)
1011
1080
 
1012
1081
  // pages: one at a time, from the address (#providers…)
1013
- const PAGES = ['providers', 'models', 'general', 'statusbar', 'logging', 'prompts', 'mcp', 'skills', 'files']
1082
+ const PAGES = ['providers', 'models', 'general', 'statusbar', 'notify', 'logging', 'prompts', 'mcp', 'skills', 'files']
1014
1083
  const page = () => (PAGES.includes(location.hash.slice(1)) ? location.hash.slice(1) : 'providers')
1015
1084
  function showPage() {
1016
1085
  for (const p of PAGES) $('page-' + p).classList.toggle('on', p === page())
1017
1086
  $('page-' + page()).querySelector('.head').after(document.querySelector('.job-slot[data-where="page"]')) // what's loading: under this page's title
1018
- for (const a of document.querySelectorAll('nav a')) a.classList.toggle('on', a.dataset.page === page())
1087
+ for (const a of document.querySelectorAll('nav a')) a.classList.toggle('on', (a.dataset.tabs?.split(' ') ?? [a.dataset.page]).includes(page()))
1088
+ for (const a of document.querySelectorAll('.subtabs a')) a.classList.toggle('on', a.dataset.tab === page())
1019
1089
  if (S) drawUsing(S)
1020
1090
  if (page() === 'logging') drawDisk()
1021
1091
  scrollTo(0, 0)
@@ -1024,6 +1094,16 @@ function showPage() {
1024
1094
  document.querySelector('nav a.on')?.scrollIntoView({ inline: 'center', block: 'nearest' }) // on a phone the pages scroll sideways
1025
1095
  }
1026
1096
  addEventListener('hashchange', showPage)
1097
+ // A sidebar item with several pages (data-tabs): a tab bar on top of each of them. Each page keeps
1098
+ // its own address (#providers, #statusbar, #files…), so links to one still open it.
1099
+ const TAB_NAMES = { models: 'Your list', providers: 'Providers', general: 'Settings', statusbar: 'Status bar', logging: 'Logs', files: 'Files' }
1100
+ const TAB_COUNTS = { providers: 'n-providers' } // a count shown on the tab, not the sidebar item
1101
+ for (const a of document.querySelectorAll('nav a[data-tabs]')) {
1102
+ const tabs = a.dataset.tabs.split(' ')
1103
+ for (const p of tabs) {
1104
+ $('page-' + p).prepend(h('div', { className: 'subtabs', role: 'tablist' }, tabs.map((t) => h('a', { href: '#' + t, role: 'tab', 'data-tab': t }, TAB_NAMES[t], TAB_COUNTS[t] ? h('span', { className: 'count', 'data-count': TAB_COUNTS[t] }) : null))))
1105
+ }
1106
+ }
1027
1107
 
1028
1108
  // A list on the left, the chosen one on the right (prompts, skills, files). Unsaved text in the
1029
1109
  // editor is kept per item while you look at others, marked with a dot in the list.
@@ -1461,7 +1541,7 @@ function drawProviders(s) {
1461
1541
  catalogShape = shape
1462
1542
  markCatalog()
1463
1543
  $('m-search').placeholder = `Search ${Object.values(MODELS).reduce((n, m) => n + (m.list?.length ?? 0), 0) || 'all'} models…`
1464
- $('n-providers').textContent = s.providers.length || ''
1544
+ for (const el of document.querySelectorAll('[data-count="n-providers"]')) el.textContent = s.providers.length || ''
1465
1545
  }
1466
1546
  // Your models: pick one up (anywhere on it with a mouse, by its ⋮⋮ on a touch screen) and the
1467
1547
  // others move aside as it goes; let go and it's saved, already in its place (no jump when the
@@ -2051,7 +2131,7 @@ function drawGeneral(s) {
2051
2131
  put($('g-toggles'), Object.entries(s.choices.toggles).map(([k, d]) => h('label', { className: 'opt' },
2052
2132
  h('div', { className: 't' }, h('b', { textContent: TOGGLE_INFO[k] ?? k }), h('span', { textContent: d[0].toUpperCase() + d.slice(1) })),
2053
2133
  sw({ checked: s.settings[k], onchange: (e) => act('/api/setting', { name: k, value: e.target.checked }, `${TOGGLE_INFO[k] ?? k}: ${e.target.checked ? 'on' : 'off'}`) }))))
2054
- if (document.activeElement !== $('v-text')) $('v-text').value = s.voice
2134
+ drawVoice(s)
2055
2135
  put($('g-caps'), ...(s.capabilities || []).map((c) =>
2056
2136
  h('div', { className: 'cap' + (c.ok ? '' : ' cap-off') },
2057
2137
  h('div', { className: 'cap-h' }, h('span', { className: 'cap-mark', textContent: c.ok ? '✓' : '✗' }), h('b', { textContent: c.name }), h('span', { className: c.ok ? 'tag ok' : 'tag need', textContent: c.ok ? 'ready' : 'needs setup' })),
@@ -2060,7 +2140,81 @@ function drawGeneral(s) {
2060
2140
  }
2061
2141
  $('g-effort').onchange = (e) => act('/api/setting', { name: 'effort', value: e.target.value }, 'effort saved')
2062
2142
  $('g-context').onchange = (e) => act('/api/setting', { name: 'context', value: e.target.value.trim() ? Number(e.target.value) : null }, 'context window saved')
2063
- $('v-save').onclick = () => act('/api/voice', { text: $('v-text').value }, 'voice saved')
2143
+ // Voice: this machine (whisper-cli and a ggml model) or a provider's transcription API, a model and a
2144
+ // language: kept as config's "voice" ({ provider, model, language }; nothing set: this machine).
2145
+ function voiceNow() {
2146
+ try {
2147
+ return S?.voice ? JSON.parse(S.voice) : {}
2148
+ } catch {
2149
+ return {}
2150
+ }
2151
+ }
2152
+ function drawVoice(s) {
2153
+ const v = voiceNow()
2154
+ const names = (s.providers ?? []).map((p) => p.name)
2155
+ put($('v-src'), h('option', { value: '', textContent: 'This machine (whisper-cli)' }), names.map((n) => h('option', { value: n, textContent: `${n} (its transcription API)` })))
2156
+ $('v-src').value = v.provider && names.includes(v.provider) ? v.provider : ''
2157
+ const remote = Boolean($('v-src').value)
2158
+ $('v-src-about').textContent = remote ? 'Sent to that provider to turn into text: fast, needs its key.' : 'Runs on your computer: private, free, slower. Needs whisper-cli and a model.'
2159
+ $('v-model-about').textContent = remote ? 'Its speech-to-text model, like whisper-large-v3 (Groq) or whisper-1 (OpenAI).' : 'A whisper model file (ggml-….bin). Empty: the best one in ~/.whisper-models.'
2160
+ $('v-lang-about').textContent = remote ? 'What you speak, like en or bn. Empty: worked out from what you say.' : 'What you speak, like en or bn; auto works it out. Empty: English.'
2161
+ $('v-model').placeholder = remote ? 'whisper-large-v3' : 'auto'
2162
+ $('v-lang').placeholder = remote ? 'auto' : 'en'
2163
+ for (const [id, k] of [['v-model', 'model'], ['v-lang', 'language']]) if (document.activeElement !== $(id)) $(id).value = v[k] ?? ''
2164
+ }
2165
+ function saveVoice(what) {
2166
+ const v = { provider: $('v-src').value || undefined, model: $('v-model').value.trim() || undefined, language: $('v-lang').value.trim() || undefined }
2167
+ const set = Object.fromEntries(Object.entries(v).filter(([, x]) => x !== undefined))
2168
+ act('/api/voice', { text: Object.keys(set).length ? JSON.stringify(set) : '' }, what)
2169
+ }
2170
+ $('v-src').onchange = (e) => {
2171
+ $('v-model').value = '' // a local model's path means nothing to a provider, and the other way round
2172
+ saveVoice(`voice: ${e.target.value || 'this machine'}`)
2173
+ }
2174
+ $('v-model').onchange = () => saveVoice('voice model saved')
2175
+ $('v-lang').onchange = () => saveVoice('voice language saved')
2176
+
2177
+ // --- Notifications: Telegram set up in three steps (a bot from @BotFather, its token, Start in the
2178
+ // bot), then on/off, a test, and which events send one ---
2179
+ function drawNotify(s) {
2180
+ const t = s.telegram ?? { events: {}, names: {} }
2181
+ const tokenRow = (label) => h('div', { className: 'row', style: 'align-items:flex-end;gap:10px' },
2182
+ h('div', { className: 'grow' }, h('label', { className: 'f', for: 'tg-token', textContent: label }),
2183
+ h('input', { type: 'password', id: 'tg-token', autocomplete: 'off', spellcheck: false, placeholder: t.hint ? `saved: ${t.hint}` : '123456789:AAH…' })),
2184
+ h('button', { className: 'primary', type: 'button', textContent: 'Connect', onclick: tgConnect }))
2185
+ const typed = $('tg-token')?.value ?? '' // a redraw keeps what's being typed
2186
+ const focused = document.activeElement === $('tg-token')
2187
+ if (!t.connected) {
2188
+ put($('tg-setup'), h('ol', { className: 'tg-steps' },
2189
+ h('li', {}, 'In Telegram, open ', h('a', { href: 'https://t.me/BotFather', target: '_blank', rel: 'noopener', textContent: '@BotFather' }), ', send ', h('span', { className: 'mono', textContent: '/newbot' }), ', pick a name, and copy the token it gives you.'),
2190
+ h('li', {}, tokenRow('Paste the token here')),
2191
+ h('li', { className: t.bot ? '' : 'muted' }, t.bot ? ['Open ', h('a', { href: `https://t.me/${t.bot}`, target: '_blank', rel: 'noopener', textContent: `@${t.bot}` }), ' and press ', h('b', { textContent: 'Start' }), ' (or send it any message), then ', h('button', { className: 'small', type: 'button', textContent: 'Find my chat', onclick: () => tgConnect(true) })] : 'Then press Start in your bot, so HeartCode knows where to send.')))
2192
+ $('tg-token').value = typed
2193
+ if (focused) $('tg-token').focus()
2194
+ } else {
2195
+ put($('tg-setup'),
2196
+ h('div', { className: 'tg-conn' }, h('span', { className: 'tag ok', textContent: 'connected' }), h('span', {}, 'Sending to ', h('b', { textContent: t.chatName }), ' through ', h('a', { href: `https://t.me/${t.bot}`, target: '_blank', rel: 'noopener', textContent: `@${t.bot}` })), h('span', { className: 'mono muted', textContent: t.hint })),
2197
+ h('label', { className: 'opt' }, h('div', { className: 't' }, h('b', { textContent: 'Send notifications' }), h('span', { textContent: 'Off: nothing is sent, the setup stays.' })),
2198
+ sw({ checked: t.on, 'aria-label': 'Send notifications', onchange: (e) => act('/api/telegram/set', { on: e.target.checked }, `Telegram notifications: ${e.target.checked ? 'on' : 'off'}`) })),
2199
+ h('div', { className: 'actions' },
2200
+ h('button', { type: 'button', textContent: 'Send a test', onclick: () => act('/api/telegram/test', {}, 'Test sent: check Telegram') }),
2201
+ h('button', { className: 'ghost', type: 'button', textContent: 'Disconnect', onclick: () => confirm('Stop sending notifications to Telegram and forget the bot token?') && act('/api/telegram/remove', {}, 'Telegram disconnected') })))
2202
+ }
2203
+ put($('tg-events'), Object.entries(t.names ?? {}).map(([k, label]) => h('label', { className: 'opt' + (t.connected ? '' : ' tg-off') },
2204
+ h('div', { className: 't' }, h('b', { textContent: label }), h('span', { textContent: TG_EVENT_INFO[k] ?? '' })),
2205
+ sw({ checked: t.events?.[k] !== false, disabled: !t.connected, 'aria-label': label, onchange: (e) => act('/api/telegram/set', { event: k, value: e.target.checked }, `${label}: ${e.target.checked ? 'on' : 'off'}`) }))))
2206
+ }
2207
+ const TG_EVENT_INFO = {
2208
+ done: 'The task, how long it took, and the answer.',
2209
+ failed: 'The task and the error.',
2210
+ waiting: 'The question or permission it stopped at, so you can come back and answer.',
2211
+ }
2212
+ async function tgConnect(again = false) {
2213
+ const token = again === true ? '' : $('tg-token')?.value.trim()
2214
+ const r = await act('/api/telegram/connect', { token })
2215
+ if (!r) return
2216
+ toast(r.found ? `Connected: sending to ${r.found}` : r.telegram?.bot ? `Token works. Now press Start in @${r.telegram.bot}, then Find my chat` : 'Saved')
2217
+ }
2064
2218
 
2065
2219
  // --- Logging: the two switches, how much of each request; the requests logged (live) ---
2066
2220
  const logSwitch = (s, k, title, about) => h('label', { className: 'opt' },
@@ -2511,6 +2665,7 @@ function render(s) {
2511
2665
  drawUsing(s)
2512
2666
  drawGeneral(s)
2513
2667
  drawStatusBar(s)
2668
+ drawNotify(s)
2514
2669
  drawLogging(s)
2515
2670
  if (REQS) drawReqs()
2516
2671
  drawPrompts(s)
package/src/settings.js CHANGED
@@ -19,6 +19,7 @@ import { THEMES, PERMISSIONS } from './ui.js'
19
19
  import { loadSkills, frontMatter } from './skills.js'
20
20
  import { installSkill, findImports } from './importer.js'
21
21
  import { capabilities } from './capabilities.js'
22
+ import { connect, sendTelegram, tokenHint, tgReady, EVENTS } from './telegram.js'
22
23
  import { log, LOGS, REQUESTS, useRequestLog, listRequests, readRequest, pruneLogs, logDays, logSize, clearLogs } from './log.js'
23
24
 
24
25
  const PAGE = new URL('./settings.html', import.meta.url)
@@ -361,6 +362,8 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
361
362
  logs: { runs: tilde(path.join(LOGS, 'runs')), requests: tilde(REQUESTS) },
362
363
  voice: cfg.voice ? JSON.stringify(cfg.voice, null, 2) : '',
363
364
  statusBar: cfg.statusBar === undefined ? null : cfg.statusBar, // false (off), a list of lines, or null (default)
365
+ // Telegram notifications: never the token itself, only a hint of it
366
+ telegram: (({ token, bot, chatName, chatId, on, events } = {}) => ({ hint: tokenHint(token), bot: bot ?? null, chatName: chatName ?? null, connected: Boolean(token && chatId), on: on !== false, events: Object.fromEntries(Object.keys(EVENTS).map((k) => [k, events?.[k] !== false])), names: EVENTS }))(cfg.telegram),
364
367
  capabilities: capabilities(cfg), // features that need outside tools, and whether they're here
365
368
  choices: { permissions: PERMISSIONS, effort: EFFORTS, theme: Object.keys(THEMES), toggles: TOGGLES, statusItems: STATUS_ITEMS },
366
369
  files: FILES.map(([name, about, json, example]) => ({ name, about, json, example, text: fs.existsSync(path.join(HOME, name)) ? fs.readFileSync(path.join(HOME, name), 'utf8') : '' })),
@@ -651,6 +654,41 @@ export function startSettings({ cfg, apply = () => {}, port = 0, root = process.
651
654
  },
652
655
  // The status bar's layout from the visual editor: false (off), null (back to default), or a list
653
656
  // of lines ({ left:[item ids], right:[item ids] }). Unknown item ids are dropped; empty = off.
657
+ // Telegram: a bot token checked (or the saved one, to look again for the chat once you pressed
658
+ // Start in the bot); the newest chat that wrote to the bot is the one notifications go to, and
659
+ // it gets a first message saying so.
660
+ 'POST /api/telegram/connect': async ({ token }) => {
661
+ const tk = String(token ?? '').trim() || cfg.telegram?.token
662
+ if (!tk) throw new Error('paste the token @BotFather gave you')
663
+ if (!/^\d+:[\w-]{20,}$/.test(tk)) throw new Error("that doesn't look like a bot token (it's like 123456789:AAH…, from @BotFather)")
664
+ const r = await connect(tk)
665
+ const chat = r.chats[0]
666
+ const was = cfg.telegram?.token === tk ? cfg.telegram : {}
667
+ cfg.telegram = { ...was, token: tk, bot: r.bot, ...(chat ? { chatId: chat.id, chatName: chat.name } : { chatId: undefined, chatName: undefined }), on: was.on ?? true }
668
+ save('setting:telegram')
669
+ if (chat) await sendTelegram(cfg.telegram, "✅ HeartCode is connected. You'll get a message here when a task finishes, fails, or waits for you.")
670
+ return { ...state(), found: chat?.name ?? null }
671
+ },
672
+ 'POST /api/telegram/test': async () => {
673
+ if (!tgReady({ ...cfg.telegram, on: true })) throw new Error('connect Telegram first')
674
+ await sendTelegram(cfg.telegram, '🔔 A test from HeartCode\'s settings: notifications reach you.')
675
+ return state()
676
+ },
677
+ 'POST /api/telegram/set': ({ on, event, value }) => {
678
+ if (!cfg.telegram) throw new Error('connect Telegram first')
679
+ if (typeof on === 'boolean') cfg.telegram.on = on
680
+ if (event !== undefined) {
681
+ if (!EVENTS[event] || typeof value !== 'boolean') throw new Error(`event: ${Object.keys(EVENTS).join(', ')}, on or off`)
682
+ cfg.telegram.events = { ...cfg.telegram.events, [event]: value }
683
+ }
684
+ save('setting:telegram')
685
+ return state()
686
+ },
687
+ 'POST /api/telegram/remove': () => {
688
+ cfg.telegram = undefined
689
+ save('setting:telegram')
690
+ return state()
691
+ },
654
692
  'POST /api/statusbar': ({ statusBar }) => {
655
693
  const clean = (a) => (Array.isArray(a) ? a.filter((x) => STATUS_IDS.has(x)) : [])
656
694
  if (statusBar === false) cfg.statusBar = false
@@ -0,0 +1,81 @@
1
+ // Telegram notifications: HeartCode messages you through your own bot when a task finishes, fails
2
+ // or waits for you (a question, a permission). Telegram's Bot API (https://core.telegram.org/bots/api):
3
+ // getMe checks the token, getUpdates finds your chat once you've pressed Start in the bot,
4
+ // sendMessage sends (plain text, 4096 characters at most). Set up on the settings page
5
+ // (cfg.telegram: { token, chatId, chatName, bot, on, events }). The token is never logged or shown whole.
6
+ import { log } from './log.js'
7
+ import { saveConfig } from './config.js'
8
+
9
+ const API = process.env.HEART_TELEGRAM_API || 'https://api.telegram.org' // the env: a stand-in server, for tests
10
+ export const EVENTS = {
11
+ done: 'A task finished',
12
+ failed: 'A task failed',
13
+ waiting: 'HeartCode is waiting for you (a question or a permission)',
14
+ }
15
+
16
+ async function call(token, method, body = {}, timeout = 15_000) {
17
+ let res
18
+ try {
19
+ res = await fetch(`${API}/bot${token}/${method}`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(timeout) })
20
+ } catch (e) {
21
+ throw new Error(`can't reach Telegram (${e.cause?.code || e.name})`) // not e.message: the URL has the token in it
22
+ }
23
+ const j = await res.json().catch(() => ({ ok: false, description: `HTTP ${res.status}` }))
24
+ if (!j.ok) throw Object.assign(new Error(j.error_code === 401 || j.error_code === 404 ? 'Telegram refused the bot token (check it in @BotFather)' : j.description || `HTTP ${res.status}`), { code: j.error_code, retryAfter: j.parameters?.retry_after })
25
+ return j.result
26
+ }
27
+
28
+ // The token shown to people: its bot's number and the last 4 characters.
29
+ export const tokenHint = (token) => (token ? `${String(token).split(':')[0]}:…${String(token).slice(-4)}` : '')
30
+
31
+ // A token checked, and the chats that have written to the bot (newest first): { bot, chats: [{ id, name }] }.
32
+ // None yet: the user hasn't pressed Start in the bot (or wrote to it more than a day ago).
33
+ export async function connect(token) {
34
+ const me = await call(token, 'getMe')
35
+ const updates = await call(token, 'getUpdates', { limit: 100, allowed_updates: ['message'] }).catch((e) => {
36
+ if (e.code === 409) throw new Error('this bot is set up with a webhook, so its messages can\'t be read here: use a bot of its own for HeartCode')
37
+ throw e
38
+ })
39
+ const chats = new Map()
40
+ for (const u of [...updates].reverse()) {
41
+ const chat = u.message?.chat
42
+ if (!chat || chats.has(chat.id)) continue
43
+ chats.set(chat.id, { id: chat.id, name: chat.title || [chat.first_name, chat.last_name].filter(Boolean).join(' ') || (chat.username ? `@${chat.username}` : String(chat.id)) })
44
+ }
45
+ return { bot: me.username, chats: [...chats.values()] }
46
+ }
47
+
48
+ export const tgReady = (t) => Boolean(t?.token && t?.chatId && t.on !== false)
49
+
50
+ // One message; a rate limit is waited out once (Telegram says how long).
51
+ export async function sendTelegram(t, text, { silent = false } = {}) {
52
+ const body = { chat_id: t.chatId, text: String(text).slice(0, 4096), disable_notification: silent, link_preview_options: { is_disabled: true } }
53
+ try {
54
+ return await call(t.token, 'sendMessage', body)
55
+ } catch (e) {
56
+ if (!e.retryAfter) throw e
57
+ await new Promise((r) => setTimeout(r, Math.min(e.retryAfter, 60) * 1000))
58
+ return await call(t.token, 'sendMessage', body)
59
+ }
60
+ }
61
+
62
+ // An event, if Telegram is set up and that event is on. Never waits on it, never throws: a
63
+ // notification that can't be sent is logged, the work goes on.
64
+ // A token saved before Start was pressed in the bot has no chat yet: it's looked up then (and kept).
65
+ export function notify(cfg, event, text) {
66
+ const t = cfg?.telegram
67
+ if (!t?.token || t.on === false || t.events?.[event] === false) return
68
+ const chat = t.chatId ? Promise.resolve(t) : findChat(cfg)
69
+ chat.then((ready) => ready && sendTelegram(ready, text)).catch((e) => log('telegram', `${event}: couldn't send (${e.message})`))
70
+ }
71
+ async function findChat(cfg) {
72
+ const { chats } = await connect(cfg.telegram.token)
73
+ if (!chats.length) {
74
+ log('telegram', "no chat yet: press Start in the bot (Telegram), then HeartCode finds it")
75
+ return null
76
+ }
77
+ Object.assign(cfg.telegram, { chatId: chats[0].id, chatName: chats[0].name })
78
+ saveConfig(cfg)
79
+ log('telegram', `found the chat: ${chats[0].name}`)
80
+ return cfg.telegram
81
+ }