Compare commits
49
Commits
2dbb3fe23e
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56be86391b | ||
|
|
0fad0a2e4e | ||
|
|
dc5dcc9cc6 | ||
|
|
1b12550d04 | ||
|
|
0263eca263 | ||
|
|
1a78b5dcf3 | ||
|
|
89ac517cab | ||
|
|
2631d86f0e | ||
|
|
f1102524cc | ||
|
|
3f78fe912d | ||
|
|
56fa39dd18 | ||
|
|
02f7f2465b | ||
|
|
a4c7f25307 | ||
|
|
f379b9470c | ||
|
|
000df780be | ||
|
|
bb86c74995 | ||
|
|
7e23b8a79c | ||
|
|
f880f7ef06 | ||
|
|
989fa88345 | ||
|
|
fa44ec0bf7 | ||
|
|
3c65a4f577 | ||
|
|
52d2259060 | ||
|
|
3292b04989 | ||
|
|
68fa3677d1 | ||
|
|
76004542ab | ||
|
|
a404829261 | ||
|
|
3b457aad1c | ||
|
|
6b1f946d25 | ||
|
|
4bb0e85612 | ||
|
|
7fc7d0202c | ||
|
|
ad8c25c713 | ||
|
|
d083cbf88b | ||
|
|
ba22bc2ef2 | ||
|
|
48779cb930 | ||
|
|
df4605bac1 | ||
|
|
cfd9ffe943 | ||
|
|
7ec0c20989 | ||
|
|
74c1dfaeb8 | ||
|
|
6beecaac83 | ||
|
|
75025c2406 | ||
|
|
02d579c8b8 | ||
|
|
44521e478d | ||
|
|
406f00f0e4 | ||
|
|
360d93f589 | ||
|
|
568db3d02d | ||
|
|
e6afb3ebf9 | ||
|
|
f3250e594e | ||
|
|
d0dda5b670 | ||
|
|
dfe5101451 |
No files matched your search
+1
-1
@@ -1,2 +1,2 @@
|
||||
mod/ovis-composer/gpui-kit.d.ts
|
||||
herdr/herdr-composer/mods/herdr-composer/gpui-kit.d.ts
|
||||
node_modules/
|
||||
@@ -1,43 +1,158 @@
|
||||
# herdrMario
|
||||
# herdr-composer
|
||||
|
||||
Source of the `ovis-composer` Herdr mod (Unified Prompt Experience).
|
||||
Pasek wiadomości dla agentów w [Herdr](https://herdr.dev). Jedno pole pod terminalem pisze do agenta, który ma fokus. Do tego:
|
||||
|
||||
- `mod/ovis-composer/` - the mod (ES modules; Herdr does not see changes behind the junction - see Reload)
|
||||
- `layouts/ovis-composer.json` - its layout
|
||||
- `tests/` - Node tests for the pure modules (`npm test`)
|
||||
- `docs/superpowers/` - spec and plan
|
||||
- drafty per agent, które przetrwają restart,
|
||||
- kolejka czekająca na koniec tury agenta,
|
||||
- historia i ulubione,
|
||||
- dock z przyciskami do często wysyłanych komend (np. `/handoff`),
|
||||
- podpowiedzi `/` i `@`,
|
||||
- jeden sposób dodawania załączników: upuszczenie, przycisk `+`, Ctrl+V.
|
||||
|
||||
## Install
|
||||

|
||||
|
||||
```powershell
|
||||
.\scripts\install.ps1
|
||||
## Wymagania
|
||||
|
||||
- **Windows.** Przycisk `+` i wklejanie obrazów przez Ctrl+V używają PowerShell. Reszta działa wszędzie, gdzie działa Herdr.
|
||||
- **Herdr** (`herdr-app`, `hc`) w `PATH`. Sprawdzone na herdr-core 0.1.21.
|
||||
- **Git** z dostępem do `http://git.mkali.pl/Factor/herdrMario.git` (repo prywatne). Klonowanie użyje Twoich zapisanych poświadczeń.
|
||||
- Do testów: **Node.js ≥ 20**.
|
||||
|
||||
## Instalacja
|
||||
|
||||
Obie drogi dają ten sam wynik.
|
||||
|
||||
**1. Przez agenta** (tak jak layouty z herdr.dev). Wklej agentowi w Herdr:
|
||||
|
||||
```text
|
||||
Read ~/.config/herdr-app/AGENTS.md, then add this layout: clone http://git.mkali.pl/Factor/herdrMario.git and use the folder herdr/herdr-composer
|
||||
```
|
||||
|
||||
Idempotent. An existing real `mods\ovis-composer` directory is renamed to
|
||||
`ovis-composer.bak-20261119` (never deleted), a junction to `mod\ovis-composer`
|
||||
takes its place, and the layout is copied to `~\.config\herdr-app\layouts\`
|
||||
(existing file backed up once as `.bak-20261119`).
|
||||
**2. Jedną komendą** (`cmd`):
|
||||
|
||||
The script ends with `herdr-app do layout.switch '{"name":"ovis-composer"}'`.
|
||||
Check with `herdr-app check <mods>\ovis-composer` and `herdr-app status`.
|
||||
|
||||
## Reload
|
||||
|
||||
Herdr does **not** see changes to the mod files behind the junction: a running
|
||||
copy keeps the code it loaded. After every edit of `mod\ovis-composer`:
|
||||
|
||||
```powershell
|
||||
.\scripts\install.ps1 -Reload
|
||||
```cmd
|
||||
git clone http://git.mkali.pl/Factor/herdrMario.git "%USERPROFILE%\herdrMario" && "%USERPROFILE%\herdrMario\install.cmd"
|
||||
```
|
||||
|
||||
It removes the junction and makes it again (the repo files stay), and Herdr
|
||||
loads the mod from scratch.
|
||||
`install.cmd` uruchamia `scripts\install.ps1` z `-ExecutionPolicy Bypass`, tylko dla tego jednego wywołania. Działa więc także tam, gdzie uruchamianie skryptów `.ps1` jest wyłączone. Instalator:
|
||||
|
||||
## Uninstall
|
||||
- **Aktualizuje repo:** robi `git pull --ff-only`, ale tylko w czystym klonie. Błąd pull to ostrzeżenie, nie przerwanie.
|
||||
- **Kopiuje mod i layout:** mod trafia do `~\.config\herdr-app\mods\herdr-composer` (kopia lustrzana), layout do `layouts\herdr-composer.json`. Herdr sam wczytuje nowe pliki. Jeśli istnieje inny layout o tej nazwie, najpierw robi jego kopię zapasową.
|
||||
- **Dopisuje skrót** do Twojego `keys.json`: `ctrl-shift-space` przenosi fokus do composera. Przed zapisem robi kopię. Klawisza, który masz przypisany do czegoś innego, nie rusza i wypisuje ostrzeżenie. Formatowanie `keys.json` się zmienia, znaczenie nie.
|
||||
- **Usuwa poprzednią wersję `ovis-composer`:** junction albo katalog modu, layout i skrót. Historia, ulubione, drafty i kolejki zostają (patrz [Przejście z ovis-composer](#przejście-z-ovis-composer)).
|
||||
- **Sprawdza i przełącza:** uruchamia `herdr-app check`. Na layout `herdr-composer` przełącza tylko przy pierwszej instalacji albo wtedy, gdy aktywny był `ovis-composer`. W pozostałych przypadkach podpowiada `ctrl-shift-l`.
|
||||
|
||||
```powershell
|
||||
.\scripts\install.ps1 -Uninstall
|
||||
Wszystkie kopie zapasowe trafiają do `~\.config\herdr-app\backups\herdr-composer\<rrrrMMdd-HHmmss>\`, nigdy do `mods\` ani `layouts\`, bo Herdr wczytałby je jako mod lub layout. Pliki repo nigdy nie są usuwane.
|
||||
|
||||
## Aktualizacja
|
||||
|
||||
Uruchom ponownie `install.cmd` albo poproś agenta jeszcze raz. Herdr sam przeładuje mod, bez restartu.
|
||||
|
||||
## Odinstalowanie
|
||||
|
||||
```cmd
|
||||
install.cmd -Uninstall
|
||||
```
|
||||
|
||||
Removes the junction (the repo files stay), restores the `.bak-20261119` mod
|
||||
directory, layout and `keys.json` backups, and switches to the `main` layout.
|
||||
Usuwa `mods\herdr-composer`, `layouts\herdr-composer.json` i skrót z `keys.json`, a potem przełącza na layout `main`. Zostają tylko kopie w `backups\herdr-composer\`.
|
||||
|
||||
## Użycie
|
||||
|
||||
| Klawisz / akcja | Co robi |
|
||||
|---|---|
|
||||
| klik w pole, `Ctrl+Shift+Space` | fokus w composerze (klik w terminal oddaje klawiaturę terminalowi) |
|
||||
| `Enter` / `Shift+Enter` | wyślij / nowa linia |
|
||||
| `Ctrl+Enter` | wyślij teraz, z pominięciem kolejki |
|
||||
| `Alt+Enter` | do kolejki jako wstrzymana (wyślesz ręcznie) |
|
||||
| `Esc` | zamyka menu lub panel; przy pustym polu przerywa pracującego agenta |
|
||||
| `/`, `@` | podpowiedzi komend, skilli i plików; `↑` `↓` wybór, `Enter`/`Tab` wstaw |
|
||||
| `Ctrl+R` albo 🕘 | panel Historia / Ulubione: `↑` `↓`, `Enter` wstawia w miejscu kursora (bez wysyłania), `Tab` przełącza zakładki, `Ctrl+D` dodaje do ulubionych, `Esc` lub ✕ zamyka |
|
||||
| ☆ | zapisuje bieżący tekst w ulubionych; prawy klik przypina go do docka |
|
||||
| dock (przyciski za ☆) | klik wysyła zapisany tekst do agenta (jak Enter, przez kolejkę) albo, w trybie ✎, wstawia go w miejscu kursora; tekst w polu zostaje |
|
||||
| prawy klik na przycisk docka | Zmień nazwę, Tylko wstawiaj / Wysyłaj od razu, Przesuń w lewo / w prawo, Usuń z docka |
|
||||
| prawy klik na wiersz panelu | Wstaw, Dodaj do ulubionych / Usuń z ulubionych; w Ulubionych także Przypnij do docka / Odepnij z docka |
|
||||
| `+`, upuszczenie pliku, `Ctrl+V` obrazu | załącznik: kopiowany do agenta przez `hc put` i dopisywany jako `@ścieżka` |
|
||||
|
||||
**Kolejka:** gdy agent pracuje, `Enter` dodaje wiadomość do kolejki. Po zakończeniu tury pojawia się odliczanie 3 s z przyciskiem Anuluj, a potem wiadomość wychodzi. Stop albo `Esc` wstrzymuje całą kolejkę. Gdy agent czeka na Twoją odpowiedź (`blocked`), `Enter` wysyła ją od razu (`hc send --force`).
|
||||
|
||||
**Dock:** wspólny dla wszystkich agentów, do 30 przycisków. Przyciski dodajesz prawym klikiem na wpis w Ulubionych („Przypnij do docka”) albo na ☆ (bieżący tekst). Gdy przycisków jest dużo, dock przewija się w bok.
|
||||
|
||||
**Dane:** historia (500 wpisów), ulubione (100), dock (30 przycisków), drafty i kolejki zapisują się lokalnie w `~\.config\herdr-app\shared.json` (klucze `herdr-composer.*`). Obrazy ze schowka trafiają do `~\.config\herdr-app\data\herdr-composer\paste\` i są usuwane po 7 dniach. Nic nie jest wysyłane poza ten komputer.
|
||||
|
||||
## Inni agenci
|
||||
|
||||
Menu `/` podpowiada komendy według **profilu agenta**. Domyślne profile są dla Claude Code (alias `claude`) i `codex`. Dla innego agenta menu pokazuje komendy, które wysłałeś mu wcześniej (grupa „Z historii”) oraz szary wiersz „Nieznany agent `<klucz>` – dodaj profil w ~/.config/herdr-app/composer-agents.json”. Klucz z tego wiersza wpisz w polu `match`.
|
||||
|
||||
Profile dopisujesz w pliku `~\.config\herdr-app\composer-agents.json` (albo `$HERDR_APP_HOME\composer-agents.json`) na komputerze, na którym działa agent. Zmiana pojawia się w menu w ciągu minuty, bez restartu i bez reinstalacji.
|
||||
|
||||
```json
|
||||
{
|
||||
"agents": [
|
||||
{
|
||||
"id": "nazwa-profilu",
|
||||
"match": ["klucz-agenta"],
|
||||
"builtins": [{ "key": "model", "desc": "Wybiera model." }],
|
||||
"sources": [
|
||||
{ "scope": "project", "path": ".agent/prompts", "pattern": "*.md" },
|
||||
{ "scope": "home", "path": ".agent/prompts", "pattern": "*/SKILL.md", "prefix": "@" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
- `id` (wymagany): nazwa profilu. Profil z tym samym `id` co domyślny **zastępuje go w całości**, bez łączenia list.
|
||||
- `match` (wymagany, niepusta lista): klucze agenta, bez rozróżniania wielkości liter. Najpierw sprawdzane są profile z pliku, potem domyślne.
|
||||
- `builtins` (opcjonalny): `{ "key", "desc" }`, grupa „Wbudowane”.
|
||||
- `sources` (opcjonalny): `scope` to `"project"` (względem folderu panelu; grupa „Projekt”) albo `"home"` (względem folderu domowego; grupa „Użytkownik”). `path` jest względna, bez `..`. `pattern` to `"*.md"` (nazwa komendy = nazwa pliku bez `.md`) albo `"*/SKILL.md"` (nazwa skilla z `name:` we frontmatterze, a w projekcie z nazwy folderu). `prefix` (domyślnie `"/"`) to tekst wstawiany przed nazwą. Źródło `{ "scope": "home", "kind": "claude-plugins" }` czyta pluginy Claude Code.
|
||||
- Brak pliku to norma. Uszkodzony plik jest ignorowany (działają profile domyślne), a menu pokazuje wiersz „`composer-agents.json`: <powód>”.
|
||||
|
||||
**Przykład dla kiro-cli: niesprawdzony.** Nie znamy klucza ani komend tego agenta, więc poniższe wartości są tylko ilustracją. Klucz weź z wiersza „Nieznany agent …” na maszynie z kiro.
|
||||
|
||||
```json
|
||||
{
|
||||
"agents": [
|
||||
{
|
||||
"id": "kiro",
|
||||
"match": ["kiro-cli", "kiro"],
|
||||
"builtins": [{ "key": "context" }, { "key": "model" }],
|
||||
"sources": [
|
||||
{ "scope": "project", "path": ".kiro/prompts", "pattern": "*.md" },
|
||||
{ "scope": "home", "path": ".kiro/prompts", "pattern": "*.md", "prefix": "@" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Co mod uruchamia i czyta
|
||||
|
||||
Agent instalujący paczkę poinformuje o tym przed instalacją.
|
||||
|
||||
- **`hc`:** `send`, `put`, `get`, `interrupt`, `keys`. Tak mod rozmawia z terminalami agentów.
|
||||
- **`powershell`:** odczyt schowka, okno wyboru pliku, rozmiary plików, odczyt komend i skilli z folderów projektu wskazanych w profilu agenta (dla Claude Code `.claude/`). Ścieżki trafiają do skryptów wyłącznie jako Base64.
|
||||
- **`git ls-files`** w folderze agenta: podpowiedzi `@`.
|
||||
- **Pliki spoza folderu modu:** pliki, które sam dodajesz jako załączniki, foldery komend z profilu agenta (dla Claude Code `.claude/commands`, `.claude/skills` projektu i `~\.claude`) oraz `composer-agents.json` w `~\.config\herdr-app\`.
|
||||
- **Sieć:** mod nie korzysta z sieci.
|
||||
|
||||
## Przejście z ovis-composer
|
||||
|
||||
Wcześniejsza wersja nazywała się `ovis-composer`. Instalator usuwa ją automatycznie. Mod przy pierwszym odczycie przenosi dane z kluczy `ovis-composer.*` do `herdr-composer.*`; starych kluczy nie kasuje. Instalator nie rusza starych kopii `mods\ovis-composer.bak-*` i `layouts\ovis-composer.json.bak-*`. Możesz je usunąć ręcznie.
|
||||
|
||||
## Rozwiązywanie problemów
|
||||
|
||||
- **Composer się nie pokazuje:** sprawdź `herdr-app status`. Pole `"layout"` powinno mieć wartość `herdr-composer`, a `"errors"` powinno być puste. Layout przełączysz przez `ctrl-shift-l`.
|
||||
- **Mod nie reaguje po zmianie plików:** uruchom ponownie `install.cmd`. Herdr widzi tylko pliki w `~\.config\herdr-app\mods\`, a nie te w repo.
|
||||
- **`Ctrl+Shift+Space` nie działa:** sprawdź, czy w `~\.config\herdr-app\keys.json` (sekcja `global`) jest `"ctrl-shift-space": "herdr-composer.focus"` i czy obok nie powstał plik `keys.error`.
|
||||
- **Coś nie gra po instalacji:** `install.cmd -Uninstall`, a potem przywróć potrzebny plik z `backups\herdr-composer\`. Awaryjnie `ctrl-alt-shift-escape` zawsze wraca do layoutu `main`.
|
||||
|
||||
## Rozwój
|
||||
|
||||
Struktura repo:
|
||||
|
||||
- `herdr/herdr-composer/`: paczka w formacie Herdr (`layouts/`, `mods/herdr-composer/`, `keys.json`, `RECIPE.md`, `preview.png`).
|
||||
- `tests/`: testy czystych modułów (`npm test`).
|
||||
- `scripts/install.ps1`: instalator, wywoływany przez `install.cmd`.
|
||||
- `docs/superpowers/`: specyfikacja, plany, makieta, raporty weryfikacji.
|
||||
|
||||
Cykl pracy: edytuj pliki w `herdr/herdr-composer/mods/herdr-composer/`, uruchom `npm test`, potem `install.cmd`, żeby skopiować zmianę do Herdr. Problemy pokażą `herdr-app check "%USERPROFILE%\.config\herdr-app\mods\herdr-composer"` i `herdr-app status`.
|
||||
@@ -0,0 +1,325 @@
|
||||
<title>Composer Dock</title>
|
||||
<meta name="claude:viewport-fit-sides" content="cover">
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&family=JetBrains+Mono:wght@400;500&display=swap">
|
||||
<style>
|
||||
/* Layout: makieta okna Herdr (terminal + blok composera) po lewej, legenda stanów po prawej; jeden ciemny wygląd jak w aplikacji. */
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #0c0e12;
|
||||
--bg: #11141a; /* tło pola tekstowego */
|
||||
--raised: #181c24; /* karta composera */
|
||||
--chrome: #222833; /* przyciski */
|
||||
--hover: #2c3442;
|
||||
--border: #2f3746;
|
||||
--fg: #e3e7ee;
|
||||
--muted: #9aa4b4;
|
||||
--dim: #5f6878;
|
||||
--accent: #7aa2f7;
|
||||
--working: #e0af68;
|
||||
--ok: #9ece6a;
|
||||
--danger: #f7768e;
|
||||
--sans: "Inter", system-ui, sans-serif;
|
||||
--mono: "JetBrains Mono", ui-monospace, Consolas, monospace;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
body { background: var(--page); color: var(--fg); font-family: var(--sans); font-size: 14px;
|
||||
padding-block: 24px; padding-left: max(16px, env(safe-area-inset-left, 0px)); padding-right: max(16px, env(safe-area-inset-right, 0px)); }
|
||||
h1 { font-size: 20px; font-weight: 600; margin: 0 0 4px; text-wrap: balance; }
|
||||
h2 { font-size: 13px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); margin: 0 0 10px; }
|
||||
p.lead { color: var(--muted); margin: 0 0 20px; max-width: 70ch; line-height: 1.5; }
|
||||
.wrap { max-width: 1180px; margin: 0 auto; }
|
||||
.grid { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 24px; align-items: start; }
|
||||
@media (max-width: 900px) { .grid { grid-template-columns: minmax(0, 1fr); } }
|
||||
|
||||
/* okno Herdr */
|
||||
.win { border: 1px solid var(--border); border-radius: 10px; overflow: hidden; background: var(--bg); }
|
||||
.titlebar { display: flex; gap: 8px; align-items: center; padding: 8px 12px; background: var(--raised); border-bottom: 1px solid var(--border); font-size: 12px; color: var(--muted); }
|
||||
.tab { padding: 3px 10px; border-radius: 6px; }
|
||||
.tab.on { background: var(--chrome); color: var(--fg); }
|
||||
.term { font-family: var(--mono); font-size: 12px; line-height: 1.6; color: var(--muted); padding: 12px 14px; height: 190px; overflow: auto; }
|
||||
.term .me { color: var(--accent); }
|
||||
.term .ag { color: var(--fg); }
|
||||
.term .sys { color: var(--dim); }
|
||||
.composer { padding: 10px; border-top: 1px solid var(--border); background: var(--page); position: relative; }
|
||||
.card { display: flex; flex-direction: column; gap: 8px; padding: 10px; border-radius: 12px; border: 1px solid var(--border); background: var(--raised); }
|
||||
textarea { width: 100%; min-height: 56px; resize: none; border: 0; outline: none; border-radius: 8px; padding: 8px 10px; background: var(--bg); color: var(--fg); font: 13px/1.5 var(--sans); }
|
||||
textarea:focus-visible { box-shadow: 0 0 0 1px var(--accent); }
|
||||
.bar { display: flex; align-items: center; gap: 8px; min-width: 0; }
|
||||
.icon { flex: none; width: 28px; height: 28px; border-radius: 999px; border: 0; background: var(--chrome); color: var(--muted); font-size: 14px; cursor: pointer; display: grid; place-items: center; }
|
||||
.icon:hover, .icon.on { background: var(--hover); color: var(--fg); }
|
||||
.sep { flex: none; width: 1px; height: 18px; background: var(--border); margin: 0 2px; }
|
||||
|
||||
/* dock */
|
||||
.dock { flex: 1; min-width: 0; display: flex; gap: 6px; overflow-x: auto; scrollbar-width: thin; padding: 2px 0; }
|
||||
.dbtn { flex: none; height: 28px; max-width: 150px; padding: 0 11px; border-radius: 8px; border: 1px solid transparent; background: var(--chrome); color: var(--fg); font: 500 12px var(--sans); cursor: pointer; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
|
||||
.dbtn span.l { overflow: hidden; text-overflow: ellipsis; }
|
||||
.dbtn:hover { background: var(--hover); }
|
||||
.dbtn:focus-visible { outline: 1px solid var(--accent); }
|
||||
.dbtn.insert { background: transparent; border: 1px dashed var(--border); color: var(--muted); }
|
||||
.dbtn.insert:hover { color: var(--fg); border-color: var(--muted); }
|
||||
.dbtn .g { font-size: 11px; color: var(--dim); }
|
||||
.dbtn.flash { background: var(--accent); color: #0c0e12; }
|
||||
.dbtn.sel { outline: 1px solid var(--accent); }
|
||||
.dbtn input { width: 110px; background: var(--bg); color: var(--fg); border: 0; outline: none; font: 500 12px var(--sans); padding: 2px 4px; border-radius: 4px; }
|
||||
.empty { color: var(--dim); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; padding-left: 4px; }
|
||||
.chip { flex: none; display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 10px; border-radius: 999px; background: var(--chrome); font-size: 12px; color: var(--muted); }
|
||||
.dot { width: 7px; height: 7px; border-radius: 99px; background: var(--ok); }
|
||||
.dot.working { background: var(--working); }
|
||||
.send { flex: none; height: 28px; padding: 0 14px; border-radius: 8px; border: 0; background: var(--accent); color: #0c0e12; font: 600 12px var(--sans); cursor: pointer; }
|
||||
|
||||
/* menu kontekstowe */
|
||||
.menu { position: absolute; z-index: 5; min-width: 210px; background: var(--raised); border: 1px solid var(--border); border-radius: 8px; padding: 4px; box-shadow: 0 8px 24px rgba(0,0,0,.45); }
|
||||
.menu button { display: flex; width: 100%; justify-content: space-between; gap: 12px; padding: 6px 10px; border: 0; border-radius: 5px; background: transparent; color: var(--fg); font: 13px var(--sans); text-align: left; cursor: pointer; }
|
||||
.menu button:hover, .menu button:focus-visible { background: var(--hover); outline: none; }
|
||||
.menu button.danger { color: var(--danger); }
|
||||
.menu button .k { color: var(--dim); font-size: 12px; }
|
||||
.menu hr { border: 0; border-top: 1px solid var(--border); margin: 4px 2px; }
|
||||
|
||||
/* panel ulubionych */
|
||||
.panel { display: flex; flex-direction: column; gap: 6px; padding: 10px; border-radius: 12px; border: 1px solid var(--border); background: var(--raised); margin-bottom: 8px; }
|
||||
.ptabs { display: flex; gap: 6px; align-items: center; }
|
||||
.ptabs .t { padding: 3px 10px; border-radius: 6px; font-size: 12px; color: var(--muted); }
|
||||
.ptabs .t.on { background: var(--chrome); color: var(--fg); }
|
||||
.ptabs .x { margin-left: auto; }
|
||||
.row { display: flex; justify-content: space-between; gap: 10px; padding: 7px 10px; border-radius: 6px; font-size: 13px; cursor: context-menu; }
|
||||
.row:hover { background: var(--hover); }
|
||||
.row .pin { color: var(--accent); font-size: 11px; white-space: nowrap; }
|
||||
|
||||
/* prawa kolumna */
|
||||
.side { display: flex; flex-direction: column; gap: 16px; min-width: 0; }
|
||||
.box { border: 1px solid var(--border); border-radius: 10px; padding: 14px; background: var(--raised); }
|
||||
.box ul { margin: 0; padding-left: 18px; line-height: 1.55; color: var(--muted); }
|
||||
.box li b { color: var(--fg); font-weight: 500; }
|
||||
.legend { display: flex; flex-direction: column; gap: 10px; }
|
||||
.legend div { display: flex; gap: 10px; align-items: center; color: var(--muted); font-size: 13px; }
|
||||
.log { font-family: var(--mono); font-size: 12px; color: var(--muted); min-height: 60px; line-height: 1.6; }
|
||||
.log .new { color: var(--fg); }
|
||||
.states { margin-top: 24px; display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 16px; }
|
||||
.state .card { pointer-events: none; }
|
||||
.state p { color: var(--muted); font-size: 12px; margin: 8px 2px 0; line-height: 1.5; }
|
||||
code { font-family: var(--mono); font-size: 12px; color: var(--fg); }
|
||||
@media (prefers-reduced-motion: no-preference) { .dbtn { transition: background .12s, color .12s; } }
|
||||
</style>
|
||||
|
||||
<div class="wrap">
|
||||
<h1>Composer Dock</h1>
|
||||
<p class="lead">Makieta paska przycisków na środku belki composera. Kliknij przycisk w docku, kliknij go prawym przyciskiem albo otwórz 🕘 i przypnij wpis z Ulubionych. Wszystko poniżej to przykładowe dane.</p>
|
||||
|
||||
<div class="grid">
|
||||
<div>
|
||||
<div class="win">
|
||||
<div class="titlebar"><span class="tab">Ovis Opus</span><span class="tab on">Ovis Fast</span><span class="tab">shell</span></div>
|
||||
<div class="term" id="term">
|
||||
<div class="sys">╭─ Claude Code · herdrMario</div>
|
||||
<div class="me">› dodaj test migracji kluczy dock</div>
|
||||
<div class="ag">● Dodałem tests/dock.test.mjs, 6 przypadków, wszystkie zielone.</div>
|
||||
<div class="sys"> 155 → 161 pass · 0 fail</div>
|
||||
</div>
|
||||
<div class="composer" id="composer">
|
||||
<div class="panel" id="panel" hidden>
|
||||
<div class="ptabs"><span class="t">Historia</span><span class="t on">Ulubione</span><button class="icon x" id="pclose" aria-label="Zamknij panel">✕</button></div>
|
||||
<div id="favs"></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<textarea id="field" aria-label="Wiadomość do agenta" placeholder="Napisz do Ovis Fast…"></textarea>
|
||||
<div class="bar">
|
||||
<button class="icon" aria-label="Dodaj plik">+</button>
|
||||
<button class="icon" id="hist" aria-label="Historia i ulubione">🕘</button>
|
||||
<button class="icon" id="star" aria-label="Dodaj do ulubionych">☆</button>
|
||||
<span class="sep"></span>
|
||||
<div class="dock" id="dock" role="toolbar" aria-label="Dock"></div>
|
||||
<span class="chip" id="chip"><span class="dot" id="dot"></span><span id="chipt">Ovis Fast · idle</span></span>
|
||||
<button class="send">Wyślij</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="menu" id="menu" hidden></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="side">
|
||||
<div class="box">
|
||||
<h2>Tryby przycisku</h2>
|
||||
<div class="legend">
|
||||
<div><button class="dbtn" tabindex="-1">/handoff</button> wysyła od razu (jak Enter)</div>
|
||||
<div><button class="dbtn insert" tabindex="-1"><span class="g">✎</span>Review @</button> tylko wstawia w miejsce kursora</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="box">
|
||||
<h2>Co się stało</h2>
|
||||
<div class="log" id="log"><div>Kliknij przycisk w docku.</div></div>
|
||||
<div style="margin-top:10px;display:flex;gap:8px;align-items:center;font-size:12px;color:var(--muted)">
|
||||
Stan agenta:
|
||||
<button class="dbtn" id="toggleState" style="height:24px">przełącz idle / working</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="box">
|
||||
<h2>Zasady</h2>
|
||||
<ul>
|
||||
<li><b>Wysyłanie</b> idzie tą samą drogą co Enter: agent pracuje → kolejka z odliczaniem 3 s, <code>blocked</code> → od razu.</li>
|
||||
<li><b>Tekst w polu</b> zostaje nietknięty przy przycisku „wysyła od razu”.</li>
|
||||
<li><b>Dock jest wspólny</b> dla wszystkich agentów, zapis w <code>shared.json</code> pod <code>herdr-composer.dock</code>.</li>
|
||||
<li><b>Nazwa</b> domyślnie to początek tekstu, do 16 znaków.</li>
|
||||
<li><b>Za dużo przycisków</b>: dock przewija się poziomo, chip i Wyślij stoją w miejscu.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<h2 style="margin-top:28px">Stany do porównania</h2>
|
||||
<div class="states">
|
||||
<div class="state">
|
||||
<div class="card"><div class="bar">
|
||||
<button class="icon">+</button><button class="icon">🕘</button><button class="icon">☆</button><span class="sep"></span>
|
||||
<div class="dock"><span class="empty">Prawy klik w Ulubionych → Przypnij do docka</span></div>
|
||||
<span class="chip"><span class="dot"></span>idle</span><button class="send">Wyślij</button>
|
||||
</div></div>
|
||||
<p>Pusty dock: szara podpowiedź zamiast przycisków.</p>
|
||||
</div>
|
||||
<div class="state">
|
||||
<div class="card"><div class="bar">
|
||||
<button class="icon">+</button><button class="icon">🕘</button><button class="icon">☆</button><span class="sep"></span>
|
||||
<div class="dock"><button class="dbtn">/handoff</button><button class="dbtn">/clear</button><button class="dbtn insert"><span class="g">✎</span>Review @</button><button class="dbtn">npm test i ra…</button><button class="dbtn">/compact</button></div>
|
||||
<span class="chip"><span class="dot"></span>idle</span><button class="send">Wyślij</button>
|
||||
</div></div>
|
||||
<p>Dużo przycisków: dock przewija się poziomo (kółkiem lub Shift+kółkiem).</p>
|
||||
</div>
|
||||
<div class="state">
|
||||
<div class="card"><div class="bar">
|
||||
<button class="icon">+</button><button class="icon">🕘</button><button class="icon">☆</button><span class="sep"></span>
|
||||
<div class="dock"><button class="dbtn sel"><input value="Handoff" aria-label="Nazwa"></button><button class="dbtn">/clear</button></div>
|
||||
<span class="chip"><span class="dot"></span>idle</span><button class="send">Wyślij</button>
|
||||
</div></div>
|
||||
<p>Zmiana nazwy w miejscu: Enter zapisuje, Esc anuluje. Tekst wysyłany się nie zmienia.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const dockEl = document.getElementById("dock"), menu = document.getElementById("menu"), field = document.getElementById("field");
|
||||
const logEl = document.getElementById("log"), composer = document.getElementById("composer"), panel = document.getElementById("panel");
|
||||
let working = false, editing = -1, queue = 0;
|
||||
let dock = [
|
||||
{ label: "/handoff", text: "/handoff", mode: "send" },
|
||||
{ label: "/clear", text: "/clear", mode: "send" },
|
||||
{ label: "Review @", text: "Zrób review pliku @", mode: "insert" },
|
||||
];
|
||||
const favorites = [
|
||||
"/handoff", "/clear", "Zrób review pliku @", "npm test i raport po polsku", "/compact",
|
||||
];
|
||||
const short = (s) => (s.length > 16 ? s.slice(0, 14) + "…" : s);
|
||||
|
||||
function log(msg) {
|
||||
[...logEl.children].forEach((d) => d.classList.remove("new"));
|
||||
const d = document.createElement("div"); d.className = "new"; d.textContent = msg;
|
||||
logEl.prepend(d);
|
||||
while (logEl.children.length > 4) logEl.lastChild.remove();
|
||||
}
|
||||
|
||||
function render() {
|
||||
dockEl.innerHTML = "";
|
||||
if (!dock.length) {
|
||||
const e = document.createElement("span"); e.className = "empty";
|
||||
e.textContent = "Prawy klik w Ulubionych → Przypnij do docka"; dockEl.append(e);
|
||||
}
|
||||
dock.forEach((b, i) => {
|
||||
const el = document.createElement("button");
|
||||
el.className = "dbtn" + (b.mode === "insert" ? " insert" : "") + (editing === i ? " sel" : "");
|
||||
el.title = b.text + (b.mode === "insert" ? " (wstawia)" : " (wysyła)");
|
||||
if (editing === i) {
|
||||
const inp = document.createElement("input"); inp.id = "rename"; inp.value = b.label; inp.setAttribute("aria-label", "Nazwa przycisku");
|
||||
inp.addEventListener("keydown", (ev) => {
|
||||
if (ev.key === "Enter") { b.label = inp.value.trim() || short(b.text); editing = -1; render(); log(`Zmieniono nazwę na „${b.label}”`); }
|
||||
if (ev.key === "Escape") { editing = -1; render(); }
|
||||
});
|
||||
inp.addEventListener("blur", () => { if (editing === i) { editing = -1; render(); } });
|
||||
el.append(inp); dockEl.append(el); setTimeout(() => { inp.focus(); inp.select(); }); return;
|
||||
}
|
||||
if (b.mode === "insert") { const g = document.createElement("span"); g.className = "g"; g.textContent = "✎"; el.append(g); }
|
||||
const l = document.createElement("span"); l.className = "l"; l.textContent = b.label; el.append(l);
|
||||
el.addEventListener("click", () => press(b, el));
|
||||
el.addEventListener("contextmenu", (ev) => { ev.preventDefault(); openMenu(ev, dockMenu(i)); });
|
||||
dockEl.append(el);
|
||||
});
|
||||
}
|
||||
|
||||
function press(b, el) {
|
||||
el.classList.add("flash"); setTimeout(() => el.classList.remove("flash"), 180);
|
||||
if (b.mode === "insert") {
|
||||
const s = field.selectionStart ?? field.value.length, e = field.selectionEnd ?? s;
|
||||
field.value = field.value.slice(0, s) + b.text + field.value.slice(e);
|
||||
field.focus(); field.selectionStart = field.selectionEnd = s + b.text.length;
|
||||
log(`Wstawiono „${b.text}” w miejscu kursora`); return;
|
||||
}
|
||||
if (working) { queue++; log(`Agent pracuje: „${b.text}” w kolejce (${queue}), wyjdzie po turze`); return; }
|
||||
log(`hc send t5 -- ${b.text} → Ovis Fast`);
|
||||
const t = document.getElementById("term"); const d = document.createElement("div"); d.className = "me"; d.textContent = "› " + b.text; t.append(d); t.scrollTop = t.scrollHeight;
|
||||
}
|
||||
|
||||
function dockMenu(i) {
|
||||
const b = dock[i];
|
||||
return [
|
||||
["Zmień nazwę", "F2", () => { editing = i; render(); }],
|
||||
[b.mode === "send" ? "Tylko wstawiaj" : "Wysyłaj od razu", "", () => { b.mode = b.mode === "send" ? "insert" : "send"; render(); log(`„${b.label}”: ${b.mode === "send" ? "wysyła od razu" : "tylko wstawia"}`); }],
|
||||
["Przesuń w lewo", "", () => { if (i > 0) { [dock[i - 1], dock[i]] = [dock[i], dock[i - 1]]; render(); } }, i === 0],
|
||||
["Przesuń w prawo", "", () => { if (i < dock.length - 1) { [dock[i + 1], dock[i]] = [dock[i], dock[i + 1]]; render(); } }, i === dock.length - 1],
|
||||
"hr",
|
||||
["Usuń z docka", "", () => { log(`Usunięto „${b.label}”`); dock.splice(i, 1); render(); }, false, "danger"],
|
||||
];
|
||||
}
|
||||
|
||||
function openMenu(ev, items) {
|
||||
menu.innerHTML = "";
|
||||
items.forEach((it) => {
|
||||
if (it === "hr") { menu.append(document.createElement("hr")); return; }
|
||||
const [label, key, fn, disabled, cls] = it;
|
||||
const b = document.createElement("button"); if (cls) b.className = cls;
|
||||
b.innerHTML = `<span></span><span class="k"></span>`; b.firstChild.textContent = label; b.lastChild.textContent = key;
|
||||
if (disabled) b.style.opacity = .4;
|
||||
b.addEventListener("click", () => { closeMenu(); if (!disabled) fn(); });
|
||||
menu.append(b);
|
||||
});
|
||||
const r = composer.getBoundingClientRect();
|
||||
menu.hidden = false;
|
||||
const x = Math.min(ev.clientX - r.left, r.width - menu.offsetWidth - 8);
|
||||
menu.style.left = Math.max(8, x) + "px";
|
||||
menu.style.top = (ev.clientY - r.top - menu.offsetHeight - 6) + "px";
|
||||
menu.querySelector("button").focus();
|
||||
}
|
||||
function closeMenu() { menu.hidden = true; }
|
||||
document.addEventListener("click", (e) => { if (!menu.contains(e.target)) closeMenu(); });
|
||||
document.addEventListener("keydown", (e) => { if (e.key === "Escape") { closeMenu(); } });
|
||||
|
||||
function renderFavs() {
|
||||
const box = document.getElementById("favs"); box.innerHTML = "";
|
||||
favorites.forEach((f) => {
|
||||
const pinned = dock.some((b) => b.text === f);
|
||||
const r = document.createElement("div"); r.className = "row";
|
||||
r.innerHTML = `<span></span><span class="pin"></span>`; r.firstChild.textContent = f; r.lastChild.textContent = pinned ? "w docku" : "";
|
||||
r.addEventListener("contextmenu", (ev) => {
|
||||
ev.preventDefault();
|
||||
openMenu(ev, [
|
||||
["Wstaw", "Enter", () => { field.value += f; }],
|
||||
pinned ? ["Odepnij z docka", "", () => { dock = dock.filter((b) => b.text !== f); render(); renderFavs(); log(`Odpięto „${f}”`); }]
|
||||
: ["Przypnij do docka", "", () => { dock.push({ label: short(f), text: f, mode: "send" }); render(); renderFavs(); log(`Przypięto „${short(f)}” na końcu docka`); }],
|
||||
"hr",
|
||||
["Usuń z ulubionych", "Ctrl+D", () => {}, true, "danger"],
|
||||
]);
|
||||
});
|
||||
box.append(r);
|
||||
});
|
||||
}
|
||||
document.getElementById("hist").addEventListener("click", () => { panel.hidden = !panel.hidden; renderFavs(); });
|
||||
document.getElementById("pclose").addEventListener("click", () => { panel.hidden = true; });
|
||||
document.getElementById("star").addEventListener("contextmenu", (ev) => {
|
||||
ev.preventDefault();
|
||||
const t = field.value.trim();
|
||||
openMenu(ev, [["Przypnij bieżący tekst do docka", "", () => { dock.push({ label: short(t), text: t, mode: "send" }); render(); log(`Przypięto „${short(t)}”`); }, !t]]);
|
||||
});
|
||||
document.getElementById("toggleState").addEventListener("click", () => {
|
||||
working = !working; if (!working && queue) { log(`Tura skończona: odliczanie 3 s, potem ${queue} z kolejki`); queue = 0; }
|
||||
document.getElementById("dot").className = "dot" + (working ? " working" : "");
|
||||
document.getElementById("chipt").textContent = "Ovis Fast · " + (working ? "working" : "idle");
|
||||
});
|
||||
render();
|
||||
</script>
|
||||
@@ -0,0 +1,149 @@
|
||||
# Wszystkie komendy w menu `/` — plan implementacji
|
||||
|
||||
**Cel:** po wpisaniu `/` composer pokazuje wszystkie komendy Claude Code, czyli:
|
||||
- pełną listę wbudowanych,
|
||||
- komendy i skille projektu,
|
||||
- globalne komendy i skille użytkownika (`~/.claude`),
|
||||
- komendy i skille włączonych pluginów.
|
||||
|
||||
Menu pokazuje wszystkie trafienia jako przewijaną listę.
|
||||
|
||||
**Zaakceptowane przez użytkownika (2026-11-19):**
|
||||
- pełna statyczna lista wbudowanych;
|
||||
- globalne `~/.claude/commands` i `~/.claude/skills`;
|
||||
- pluginy włączone w `~/.claude/settings.json`, nazwy `plugin:nazwa`;
|
||||
- menu przewijane, bez ucinania do 20;
|
||||
- katalog globalny czytany raz i odświeżany w tle, nie przy każdym klawiszu.
|
||||
|
||||
## Ograniczenia globalne
|
||||
- Nie zmieniamy Herdr ani jego plików. Pracujemy tylko na gałęzi `feature/composer-dock`. Bez push.
|
||||
- Testowalna logika jest w `catalog.js` (czysty moduł; `exec` i odczyt pliku wstrzyknięte). GPUI jest tylko w `main.js`.
|
||||
- Ścieżki w skryptach PowerShell przekazujemy wyłącznie przez `decode()` z `powershell.js` (Base64), jak w `readScript`.
|
||||
- Błąd odczytu katalogu globalnego nie psuje menu. Wbudowane i projekt dalej się pokazują, a błąd idzie do `onReadError`.
|
||||
- Opisy wbudowanych komend są po polsku.
|
||||
|
||||
## Fakty o środowisku (sprawdzone)
|
||||
- `herdr` eksportuje:
|
||||
- `home()`: katalog domowy;
|
||||
- `readTextFile(path)`: UTF-8 do 1 MiB albo `null`, poza wątkiem UI, bez exec;
|
||||
- `exec(cmd,args,{cwd,timeout})`.
|
||||
- `~/.claude/settings.json` zawiera `enabledPlugins`, np. `{ "superpowers@claude-plugins-official": true, ... }`. Nazwa pluginu to część przed `@`.
|
||||
- `~/.claude/plugins/installed_plugins.json` ma postać `{ "version": 2, "plugins": { "<id>": [ { "installPath": "C:\\...\\superpowers\\7.0.2", ... } ] } }`. Bierzemy pierwszy wpis z `installPath`.
|
||||
- `<installPath>/.claude-plugin/plugin.json` może mieć pola `skills` i `commands`:
|
||||
- tablica ścieżek względnych to katalogi skilli (każdy z `SKILL.md`) albo pliki `.md` komend;
|
||||
- string to katalog do przejrzenia jak domyślny;
|
||||
- brak pola oznacza domyślne `skills/*/SKILL.md` i `commands/*.md`.
|
||||
- Przykład: mattpocock-skills ma `"skills": ["./skills/engineering/tdd", ...]`.
|
||||
- Frontmatter `SKILL.md`:
|
||||
- `name:` (gdy jest) wygrywa z nazwą katalogu;
|
||||
- `description:` to opis;
|
||||
- `user-invocable: false` znaczy: nie pokazywać w menu.
|
||||
- Grupy w `suggest.js`: `GROUPS = [Wbudowane, Projekt, Użytkownik, Terminal]`. Dodajemy `GROUP_PLUGIN = "Pluginy"` po `Użytkownik`.
|
||||
|
||||
## Task 1 — katalog (`catalog.js`, `suggest.js`, testy)
|
||||
|
||||
**Interfejsy:**
|
||||
- `BUILTINS["claude-code"]`: pełna lista (poniżej), alfabetycznie. Komentarz nad listą mówi, że lista jest ręczna i że przy nowej wersji Claude Code trzeba ją uzupełnić.
|
||||
- `export const GROUP_PLUGIN = "Pluginy"` w `suggest.js`, dopisana do `GROUPS` po `GROUP_USER`.
|
||||
- `export async function globalCommands(home, exec, readText, options = {})` zwraca `Promise<Item[]>`:
|
||||
1. Odczytuje `settings.json` oraz `installed_plugins.json`, a dla każdego włączonego pluginu jego `plugin.json` (przez `readText`; brak pliku albo zły JSON to pusta lista z tego źródła, bez wyjątku).
|
||||
2. Zbiera katalogi i pliki do przejrzenia:
|
||||
- użytkownik: `~/.claude/commands/*.md`, `~/.claude/skills/*/SKILL.md`;
|
||||
- pluginy według reguł `plugin.json` wyżej.
|
||||
3. Jednym wywołaniem `exec` (PowerShell, a `sh` jako zapas, wzór `listProjectFiles`) wypisuje istniejące pliki. Wszystkie wzorce trafiają do skryptu przez Base64.
|
||||
4. Każdy plik czyta przez `readText`. Pomija `user-invocable: false`.
|
||||
5. Item:
|
||||
- użytkownik: `{key, desc, group: GROUP_USER, insert: "/key "}`;
|
||||
- plugin: `key = "<plugin>:<name>"`, `group: GROUP_PLUGIN`.
|
||||
6. Błąd listowania to wyjątek, chyba że jest `options.onReadError`: wtedy go wywołuje i zwraca to, co się da.
|
||||
- `commands(cwd, exec, options)` przyjmuje `options.global` (Item[], gotowe z cache). Kolejność: builtins, project, global, snippets. Duplikaty `key` usuwa: pierwszy wygrywa.
|
||||
|
||||
**Lista wbudowanych `claude-code`:** zostaw obecne 6 i dodaj resztę. `key`, potem polski opis:
|
||||
- `add-dir`: Dodaje katalog roboczy.
|
||||
- `agents`: Zarządza subagentami.
|
||||
- `bashes`: Pokazuje zadania w tle.
|
||||
- `bug`: Zgłasza błąd Claude Code.
|
||||
- `clear`: Czyści historię rozmowy.
|
||||
- `code-review`: Przegląd zmian pod kątem błędów.
|
||||
- `compact`: Zwija historię do podsumowania.
|
||||
- `config`: Otwiera ustawienia.
|
||||
- `context`: Pokazuje zużycie kontekstu.
|
||||
- `cost`: Pokazuje koszt i zużycie tokenów.
|
||||
- `doctor`: Sprawdza instalację Claude Code.
|
||||
- `exit`: Kończy sesję.
|
||||
- `export`: Eksportuje rozmowę.
|
||||
- `fast`: Przełącza tryb szybki.
|
||||
- `feedback`: Wysyła opinię o Claude Code.
|
||||
- `fewer-permission-prompts`: Dodaje bezpieczne komendy do listy dozwolonych.
|
||||
- `help`: Pomoc.
|
||||
- `hooks`: Zarządza hookami.
|
||||
- `ide`: Łączy z IDE.
|
||||
- `init`: Tworzy CLAUDE.md dla projektu.
|
||||
- `install-github-app`: Instaluje aplikację GitHub.
|
||||
- `keybindings`: Ustawia skróty klawiszowe.
|
||||
- `login`: Logowanie.
|
||||
- `logout`: Wylogowanie.
|
||||
- `loop`: Uruchamia polecenie cyklicznie.
|
||||
- `mcp`: Zarządza serwerami MCP.
|
||||
- `memory`: Edytuje pliki pamięci.
|
||||
- `model`: Wybiera model.
|
||||
- `output-style`: Ustawia styl odpowiedzi.
|
||||
- `permissions`: Ustawia uprawnienia narzędzi.
|
||||
- `plugin`: Zarządza pluginami.
|
||||
- `pr-comments`: Pokazuje komentarze PR.
|
||||
- `privacy-settings`: Ustawienia prywatności.
|
||||
- `release-notes`: Pokazuje informacje o wydaniu.
|
||||
- `resume`: Wznawia wcześniejszą sesję.
|
||||
- `review`: Przegląd pull requesta.
|
||||
- `rewind`: Cofa rozmowę lub kod.
|
||||
- `schedule`: Planuje zadania w chmurze.
|
||||
- `security-review`: Przegląd bezpieczeństwa zmian.
|
||||
- `simplify`: Upraszcza zmieniony kod.
|
||||
- `status`: Pokazuje stan sesji.
|
||||
- `statusline`: Ustawia linię statusu.
|
||||
- `terminal-setup`: Konfiguruje terminal.
|
||||
- `todos`: Pokazuje listę zadań.
|
||||
- `upgrade`: Zmienia plan.
|
||||
- `usage`: Pokazuje limity użycia.
|
||||
- `vim`: Przełącza tryb vim.
|
||||
- `workflows`: Pokazuje przebieg workflow.
|
||||
|
||||
**Testy** (`tests/catalog*.test.mjs` albo istniejący plik testów katalogu; fałszywe `exec` i `readText`):
|
||||
- `GROUPS` zawiera `"Pluginy"` po `"Użytkownik"`.
|
||||
- Builtiny `claude-code` zawierają co najmniej `context`, `help`, `mcp`, `rewind` i `clear`; klucze są unikalne.
|
||||
- `globalCommands`:
|
||||
- plugin włączony daje `superpowers:brainstorming`;
|
||||
- plugin wyłączony (`false`) albo nieobecny w `enabledPlugins` nic nie daje;
|
||||
- `plugin.json` z tablicą `skills` bierze tylko wymienione katalogi;
|
||||
- `user-invocable: false` jest pominięty;
|
||||
- `name:` z frontmattera wygrywa z nazwą katalogu;
|
||||
- komenda użytkownika `~/.claude/commands/handoff.md` daje `handoff` w grupie `Użytkownik`;
|
||||
- brak `settings.json` daje tylko pozycje użytkownika, bez wyjątku;
|
||||
- błąd listowania z `onReadError` wywołuje handler i zwraca resztę.
|
||||
- `commands` z `options.global` usuwa duplikat `key` (pierwszy wygrywa).
|
||||
|
||||
Commit: `feat: the / menu offers user, plugin and all built-in commands`.
|
||||
|
||||
## Task 2 — menu i cache (`main.js`)
|
||||
|
||||
- Cache katalogu globalnego:
|
||||
- `this.globalCommands = null`, `this.globalLoadedAt = 0`, `this.globalLoading = false`;
|
||||
- przy otwarciu menu `/`: brak cache albo cache starszy niż 60 s uruchamia `refreshGlobal(cx)` (jedno naraz, w tle);
|
||||
- `loadSuggestions` używa tego, co już jest (`options.global: this.globalCommands ?? []`);
|
||||
- po zakończeniu odświeżenia, gdy menu `/` jest otwarte, przelicz je (`loadSuggestions` dla bieżącego tokenu);
|
||||
- w `checking()` nie odpalaj.
|
||||
- Menu:
|
||||
- usuń ucinanie do `MENU_LIMIT` i wiersz „…i jeszcze N”; renderuj wszystkie trafienia;
|
||||
- `ScrollHandle.new()` z `gpui-kit` w `init()`, `.track_scroll(handle)` na `composer-menu-list`;
|
||||
- przy zmianie `menu.index` (strzałki) wołaj `handle.scroll_to_item(index)` (licz z wierszem błędu/pustki, jeśli jest dzieckiem przed pozycjami);
|
||||
- wysokość menu bez zmian.
|
||||
- Nagłówki grup / kolejność: `merge(groupItems(...))` z nową grupą działa bez zmian (sprawdź).
|
||||
|
||||
Commit: `feat: the / menu scrolls through every match and caches the global catalog`.
|
||||
|
||||
## Review Focus
|
||||
1. Brak `~/.claude/settings.json` albo `installed_plugins.json`, uszkodzony JSON: menu dalej działa.
|
||||
2. Ścieżki ze spacjami i polskimi znakami (`D:\Development\workspace - Mariusz`) w listowaniu.
|
||||
3. Szybkie pisanie po `/`: żadnego exec na każdy klawisz dla katalogu globalnego.
|
||||
4. Strzałka w dół za widoczny obszar: zaznaczenie widoczne (scroll).
|
||||
5. Plugin z `skills` jako tablicą (mattpocock-skills) i jako brak pola (superpowers).
|
||||
@@ -0,0 +1,123 @@
|
||||
# Composer Dock Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Konfigurowalny dock przycisków w belce herdr-composer: klik wysyła lub wstawia zapisany tekst, a zarządzanie odbywa się z menu pod prawym klikiem.
|
||||
|
||||
**Architecture:** Czysta logika docka i menu w nowym `dock.js`, zapis w `storage.js` (`herdr-composer.dock`). `main.js` rysuje dock i menu, a wysyłanie przekazuje do istniejącego `finish()` (kolejka, `--force`, strażnik agenta), z pominięciem pola tekstowego.
|
||||
|
||||
**Tech Stack:** mod Herdr (ES modules, `gpui-kit`), `node --test`.
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-19-composer-dock-design.md` · makieta `docs/superpowers/mockups/herdr-composer-dock.html`
|
||||
|
||||
## Global Constraints
|
||||
- Bez rekompilacji Herdr i bez zmian w plikach dostarczanych z Herdr. Zmiany tylko w `herdr/herdr-composer/`, `tests/`, `README.md` i `docs/`.
|
||||
- Kod modu: `herdr/herdr-composer/mods/herdr-composer/`. Moduły czyste (`dock.js`, `storage.js`) nie importują `gpui-kit`, `gpui-base` ani `herdr`.
|
||||
- Klucz zapisu `herdr-composer.dock`, bez odczytu `ovis-composer.*` (nowa funkcja, brak migracji).
|
||||
- Limit 30 przycisków. Nazwa domyślna ma najwyżej 16 znaków (15 + `…`), białe znaki są zwinięte do jednej spacji.
|
||||
- Teksty UI po polsku, dosłownie: „Przypnij do docka”, „Odepnij z docka”, „Przypnij bieżący tekst do docka”, „Odepnij bieżący tekst z docka”, „Zmień nazwę”, „Tylko wstawiaj”, „Wysyłaj od razu”, „Przesuń w lewo”, „Przesuń w prawo”, „Usuń z docka”, „Wstaw”, „Dodaj do ulubionych”, „Usuń z ulubionych”, „Prawy klik w Ulubionych → Przypnij do docka”.
|
||||
- Dock ma wysokość 28 px i nie może zwiększać wysokości bloku composera (auto-fit).
|
||||
- Skróty klawiszowe modu zostają w kontekście `herdr-composer > Input`. Nie dodajemy nowych globalnych.
|
||||
- Testy: `npm test` (dziś 155 pass) musi być zielone po każdym zadaniu.
|
||||
- Po zmianie modu: `install.cmd` (kopia do `~/.config/herdr-app/mods/herdr-composer`), `herdr-app status` → `"errors": []`.
|
||||
|
||||
## Review Focus
|
||||
- Klik przycisku `send`, gdy w polu jest niewysłany szkic: szkic i załączniki zostają nietknięte, a wysyła się tylko tekst przycisku.
|
||||
- Klik `send`, gdy agent `working` albo kolejka niepusta: wiadomość trafia do kolejki, a nie wychodzi od razu. Agent `blocked` dostaje ją od razu z `--force`.
|
||||
- Klik tuż po przełączeniu agenta (okno 500 ms): `syncOk` blokuje wysyłkę i pokazuje komunikat, bez wysłania do złego agenta.
|
||||
- Uszkodzony albo ręcznie zmieniony `herdr-composer.dock` w `shared.json` (nie-tablica, brak pól, duplikaty, ponad 30): dock ładuje to, co poprawne, i nie wywraca modu.
|
||||
- Edycja nazwy w miejscu: Esc anuluje tylko edycję i nie przerywa agenta. Enter zapisuje i niczego nie wysyła.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: `dock.js` + zapis w `storage.js`
|
||||
|
||||
**Files:**
|
||||
- Create: `herdr/herdr-composer/mods/herdr-composer/dock.js`
|
||||
- Modify: `herdr/herdr-composer/mods/herdr-composer/storage.js` (`KEYS`, nowe `loadDock`/`saveDock`)
|
||||
- Test: `tests/dock.test.mjs`, `tests/storage.test.mjs`
|
||||
|
||||
**Interfaces — Produces:**
|
||||
- `DockButton = { id: string, label: string, text: string, mode: "send" | "insert" }`
|
||||
- `MenuItem = { command: string, label: string, disabled?: boolean, danger?: boolean }`
|
||||
- `DOCK_LIMIT = 30`, `LABEL_MAX = 16`
|
||||
- `defaultLabel(text: string): string`
|
||||
- `normalize(raw: unknown): DockButton[]`: przepuszcza tylko poprawne wpisy (`id` i `text` niepuste, `mode` z listy). Pusty `label` zamienia na `defaultLabel(text)`. Odrzuca duplikaty `text` (porównanie po `trim()`, pierwszy wygrywa) i obcina do 30.
|
||||
- `isPinned(dock, text): boolean` (porównanie po `trim()`).
|
||||
- `pin(dock, text, id): DockButton[]`: dodaje na końcu `{id, label: defaultLabel(text), text: text.trim(), mode: "send"}`. Zwraca ten sam dock, gdy tekst jest pusty, już przypięty albo osiągnięto limit.
|
||||
- `unpin(dock, text)`, `remove(dock, id)`, `move(dock, id, step: -1 | 1)` (na krawędzi bez zmian), `rename(dock, id, label)` (pusty po `trim()` → `defaultLabel(text)`), `toggleMode(dock, id)`: każda zwraca nową tablicę i nie mutuje wejścia.
|
||||
- `dockAction(button, { hasAgent: boolean }): "send" | "insert" | "none"`
|
||||
- `dockMenu(dock, id): MenuItem[]`: komendy po kolei: `rename`, `mode` (etykieta „Tylko wstawiaj” przy `send`, „Wysyłaj od razu” przy `insert`), `left` (disabled na pierwszym), `right` (disabled na ostatnim), `remove` (`danger: true`).
|
||||
- `rowMenu({ tab: "history" | "favorites", favorite: boolean, pinned: boolean }): MenuItem[]`: `insert` „Wstaw”. Potem w zakładce `favorites` `pin` („Przypnij do docka” / „Odepnij z docka”). Na końcu `favorite` („Dodaj do ulubionych” / „Usuń z ulubionych”, `danger` przy usuwaniu).
|
||||
- `starMenu({ text: string, pinned: boolean }): MenuItem[]`: jedna pozycja `pin` („Przypnij bieżący tekst do docka” / „Odepnij bieżący tekst z docka”), `disabled`, gdy `text.trim()` jest pusty.
|
||||
- `storage.js`: `KEYS.dock = "herdr-composer.dock"`, `loadDock(store): DockButton[]` (przez `normalize`, bez fallbacku `ovis-composer.`), `saveDock(store, items): void` (zapisuje `normalize(items)`).
|
||||
|
||||
- [ ] **Step 1: Napisz testy, które padają** w `tests/dock.test.mjs`. Przypadki z wartościami:
|
||||
- `defaultLabel("/handoff") === "/handoff"`
|
||||
- `defaultLabel("npm test i raport po polsku") === "npm test i rapo…"` (15 + `…`)
|
||||
- `defaultLabel(" a\n b ") === "a b"`
|
||||
- `normalize("x")` daje `[]`
|
||||
- `normalize([{id:"1",text:"a",mode:"send",label:""}, {id:"2",text:" a ",mode:"send",label:"x"}, {id:"3",text:"b",mode:"zly"}])` → jeden wpis `{id:"1",label:"a",text:"a",mode:"send"}`
|
||||
- `normalize` z 35 poprawnymi wpisami → długość 30
|
||||
- `pin([], " /clear ", "9")` → `[{id:"9",label:"/clear",text:"/clear",mode:"send"}]`; `pin` tego samego tekstu drugi raz → bez zmian; `pin(d, " ", "x")` → bez zmian; `pin` przy 30 → bez zmian
|
||||
- `move(d, firstId, -1)` → bez zmian; `move(d, firstId, 1)` zamienia pierwszy z drugim; wejście nie jest zmutowane (`Object.isFrozen`-owa kopia albo porównanie z kopią)
|
||||
- `rename(d, id, " ")` → `label === defaultLabel(text)`; `toggleMode` dwa razy → `"send"`
|
||||
- `dockAction({mode:"insert"}, {hasAgent:true}) === "insert"`; `dockAction({mode:"send"}, {hasAgent:false}) === "none"`
|
||||
- `dockMenu`: komendy `["rename","mode","left","right","remove"]`; dla pierwszego `left.disabled === true`; etykiety trybu jak wyżej
|
||||
- `rowMenu({tab:"history",favorite:false,pinned:false})` → komendy `["insert","favorite"]`; `rowMenu({tab:"favorites",favorite:true,pinned:true})` → `["insert","pin","favorite"]` z etykietą „Odepnij z docka”
|
||||
- `starMenu({text:"",pinned:false})[0].disabled === true`
|
||||
|
||||
W `tests/storage.test.mjs`: `saveDock` → `loadDock` daje to samo; `loadDock` przy wartości pod `ovis-composer.dock` i braku nowej → `[]`; śmieci pod kluczem → `[]`.
|
||||
- [ ] **Step 2:** `npm test`: nowe testy padają (brak modułu lub funkcji).
|
||||
- [ ] **Step 3:** Zaimplementuj `dock.js` i zmiany w `storage.js` (dla odczytu wzoruj się na `readList`, ale bez `loadMigrating`).
|
||||
- [ ] **Step 4:** `npm test`: wszystko zielone.
|
||||
- [ ] **Step 5: Commit** `feat: dock model and storage (herdr-composer.dock)`
|
||||
|
||||
### Task 2: Dock w belce: rysowanie i klik
|
||||
|
||||
**Files:**
|
||||
- Modify: `herdr/herdr-composer/mods/herdr-composer/main.js` (`init`: `this.dock = loadDock(store)`; `renderCard`; nowe `renderDock`, `dockPress`)
|
||||
|
||||
**Interfaces — Consumes:** Task 1 (`loadDock`, `saveDock`, `dockAction`, `DockButton`), istniejące `syncOk`, `target`, `finish(agent, message, cx, mode)`, `overLimit`, `textarea.replace`, `syncFieldAfterReplace`, `notice`.
|
||||
|
||||
- [ ] **Step 1:** W `renderCard` wstaw za ☆ separator (1×18 px, `t.border`). Zamiast `div().flex_1()` wstaw `renderDock(t, active)`: `h_flex().flex_1().min_w(0).h(28).gap(6).overflow_x_scroll()` (`id("composer-dock")`). Pusty dock pokazuje podpowiedź w kolorze `t.dim`, rozmiar 12.
|
||||
- [ ] **Step 2:** Przycisk `id("dock-"+b.id)`, wysokość 28, `px(11)`, `rounded(8)`, tekst 12, `flex_none`, maks. szerokość 150 z ucięciem. `send`: `bg(t.chrome)`, `text_color(t.foreground)`. `insert`: brak tła, ramka 1 px `t.border` (przerywana, jeśli API pozwala; jeśli nie, pełna) i prefiks `✎ ` w `t.dim`. Gdy `!active`: `text_color(t.dim)`, bez `cursor_pointer` i bez akcji. Tooltip z pełnym `text`, jeśli `gpui-kit` ma `tooltip`; jeśli nie, pomiń.
|
||||
- [ ] **Step 3:** `dockPress(button, cx)`:
|
||||
- `insert`: `this.textarea.replace(button.text)`, `syncFieldAfterReplace()`, notice „Wstawiono w miejscu kursora — nic nie zostało wysłane.”
|
||||
- `send`: `syncOk` (przy błędzie ten sam komunikat co w `submit`, bez „Zostaje w szkicu”), potem `target()`, `overLimit(button.text)`, a na końcu `this.finish(agent, button.text.trim(), cx)`. Nie wolno wołać `clearField`, `submit` ani ruszać załączników.
|
||||
- [ ] **Step 4:** `npm test` zielone, `install.cmd`, `herdr-app check` i `herdr-app status` bez błędów. Testu w GUI wykonawca nie robi (Task 4, Opus).
|
||||
- [ ] **Step 5: Commit** `feat: composer dock in the bar (send / insert)`
|
||||
|
||||
### Task 3: Menu pod prawym klikiem (dock, ☆, wiersze panelu)
|
||||
|
||||
**Files:**
|
||||
- Modify: `main.js` (menu i obsługa komend), `panel.js` (secondary click woła `on.rowMenu(key, event, cx)` zamiast `on.toggle`)
|
||||
|
||||
**Interfaces — Consumes:** `dockMenu`, `rowMenu`, `starMenu`, `pin`, `unpin`, `remove`, `move`, `rename`, `toggleMode`, `isPinned`, `saveDock`, istniejące `toggleFavoriteText`, `panelPickKey`, `isFavorite`, `newId`.
|
||||
|
||||
- [ ] **Step 1: Jeden renderer menu** `renderContextMenu(t, items, onCommand)`: `v_flex`, min. szerokość 210, `bg(t.raised)`, ramka `t.border`, `rounded(8)`, `p(4)`. Pozycja `danger` w kolorze błędu z motywu, `disabled` przygaszona i bez akcji. Stan `this.contextMenu = { kind: "dock" | "row" | "star", id | key, items } | null`. Esc z fokusem w polu zamyka najpierw menu (dopisz w `runAction("escape")` przed panelem i przerwaniem agenta). Klik poza menu zamyka (`on_mouse_down_out`).
|
||||
- [ ] **Step 2: Kotwiczenie.** Przycisk docka i ☆: `Popover` z `.mouse_button("right")`, kontrolowany (`open(this.contextMenu?.kind===... && id===...)`, `on_open_change`). Wiersz panelu (lista wirtualna, `on_item_secondary_click`): menu jako `Popup` zakotwiczony do kontenera panelu (`anchor("top_right")`). Ruling: jeśli `Popover` nie zadziała z prawym przyciskiem w GUI, użyj `Popup` zakotwiczonego do całego docka, z tym samym rendererem.
|
||||
- [ ] **Step 3: Komendy.**
|
||||
- dock: `rename` ustawia `this.renaming = id` i rysuje przycisk jako mały `Input` (osobny stan input, szer. 110, wstępnie pełna nazwa). Enter wywołuje `rename` + `saveDock`. Esc i blur anulują. Kontekst `herdr-composer > Input` obejmuje też ten input, więc w `runAction` przy `this.renaming` klawisze `escape`, `up`, `down` i `tab` są obsługiwane jako edycja nazwy, a nie composera.
|
||||
- dock: `mode` wywołuje `toggleMode`, `left`/`right` wywołują `move`, `remove` wywołuje `remove`. Każda kończy się `saveDock` i `cx.notify()`.
|
||||
- wiersz: `insert` woła `panelPickKey`, `favorite` woła `toggleFavoriteText`, `pin` woła `pin(dock, text, this.newId())` albo `unpin`.
|
||||
- ☆: `pin`/`unpin` bieżącego `this.value`.
|
||||
- Lewy klik ☆ bez zmian.
|
||||
- [ ] **Step 4: `Ctrl+D` w panelu** dalej przełącza ulubione od razu (sprawdź, że `panelKey` tego nie zmienia).
|
||||
- [ ] **Step 5:** `npm test`, `install.cmd`, `herdr-app check` i `status` bez błędów.
|
||||
- [ ] **Step 6: Commit** `feat: right-click menus for dock, star and panel rows`
|
||||
|
||||
### Task 4 (Opus): weryfikacja w GUI, dokumentacja
|
||||
|
||||
- [ ] Test GUI (SendKeys i `herdr-app shot`, wykonuje Opus):
|
||||
- przypięcie z Ulubionych oraz z ☆;
|
||||
- klik `send` przy `idle`: dociera do agenta, a szkic zostaje;
|
||||
- klik przy `working`: trafia do kolejki;
|
||||
- tryb `insert`: tekst w miejscu kursora;
|
||||
- zmiana nazwy Enter/Esc;
|
||||
- przesuwanie i usuwanie;
|
||||
- przepełnienie (ponad 8 przycisków), przewijanie;
|
||||
- brak agenta: wyszarzone;
|
||||
- restart modu (`install.cmd`): dock przetrwał.
|
||||
- [ ] README: wiersz w tabeli Użycie („dock”) i akapit w „Dane” (`herdr-composer.dock`). RECIPE.md: punkt w „How it behaves”. `preview.png`: nowy zrzut z dockiem.
|
||||
- [ ] Commit `docs: composer dock in README, RECIPE and preview`
|
||||
@@ -0,0 +1,39 @@
|
||||
# herdr-composer — instalowalna paczka (projekt + plan)
|
||||
|
||||
> Zatwierdzone przez użytkownika 2026-11-19. Wykonawca: Ovis Fast. Review: Ovis Opus.
|
||||
|
||||
## Cel
|
||||
Prywatny mod (repo `http://git.mkali.pl/Factor/herdrMario.git`) instalowany jedną komendą — przez agenta (wzór herdr.dev: „Read ~/.config/herdr-app/AGENTS.md, then add this layout: …”) albo `install.cmd`. Nazwa `herdr-composer` (zamiast `ovis-composer`). Bez publikacji na GitHub/herdr.dev.
|
||||
|
||||
## Decyzje
|
||||
- Format paczki wg `~/.config/herdr-app/AGENTS.md` („Layouts and mods other people made”): folder `herdr/herdr-composer/` = `layouts/herdr-composer.json`, `mods/herdr-composer/*`, `keys.json`, `RECIPE.md`, `preview.png`.
|
||||
- Instalacja przez **kopię** (nie junction) → Herdr sam przeładowuje mod; aktualizacja = ponowne `install.cmd`.
|
||||
- Zmiana nazwy bez utraty danych: odczyt `herdr-composer.*`, a gdy brak — `ovis-composer.*` (i zapis pod nową nazwą).
|
||||
|
||||
## Zadanie A (Ovis Fast) — restrukturyzacja + zmiana nazwy + migracja
|
||||
1. `git mv mod/ovis-composer herdr/herdr-composer/mods/herdr-composer`; `git mv layouts/ovis-composer.json herdr/herdr-composer/layouts/herdr-composer.json` (w layoucie `content.mod` → `herdr-composer`). Usuń puste `mod/`, `layouts/`.
|
||||
2. W kodzie modu wszystkie identyfikatory `ovis-composer` → `herdr-composer`: `CONTEXT`/`key_context`, nazwy akcji `herdr-composer.*` (bind_keys + on_action), klucze `storage.KEYS` (`herdr-composer.history`, `.favorites`, `.usage`, `.userMin`, `.draft:<a>`, `.queue:<a>`), folder obrazów `data/herdr-composer/paste/`, `id()` elementów, komentarze/teksty. `.gitignore`: `herdr/herdr-composer/mods/herdr-composer/gpui-kit.d.ts`.
|
||||
3. Migracja w `storage.js` (czyste, testowane): każda funkcja `load*` czyta nowy klucz; gdy `null/undefined` — czyta klucz `ovis-composer.*` (ta sama końcówka) i, jeśli coś znalazła, zapisuje to pod nowym kluczem. Stare klucze zostają nietknięte. `cleanupPaste` sprząta oba foldery (`data/ovis-composer/paste` i nowy).
|
||||
4. `herdr/herdr-composer/keys.json`: `{"global": {"ctrl-shift-space": "herdr-composer.focus"}}`.
|
||||
5. Testy: importy z `../herdr/herdr-composer/mods/herdr-composer/<m>.js`; nowe testy migracji (nowy klucz wygrywa; fallback ze starego + zapis pod nowym; brak obu → domyślne; śmieci w starym kluczu → ignorowane jak dotąd).
|
||||
6. `grep -ri "ovis-composer"` w `herdr/` i `tests/` → tylko w kodzie migracji i w RECIPE (zdanie o pochodzeniu).
|
||||
|
||||
## Zadanie B (Ovis Fast) — instalator
|
||||
`install.cmd` w korzeniu repo (wywołuje `powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\install.ps1" %*`) i przepisany `scripts/install.ps1` (PowerShell 5):
|
||||
- `install` (domyślnie): jeśli repo jest klonem git i nie ma lokalnych zmian → `git pull --ff-only` (błąd = ostrzeżenie, kontynuacja). Kopiuje `herdr/herdr-composer/mods/herdr-composer` → `%USERPROFILE%\.config\herdr-app\mods\herdr-composer` (mirror: `robocopy /MIR`, kod wyjścia < 8 = OK; pomija `gpui-kit.d.ts`, `jsconfig.json`) i layout → `layouts\herdr-composer.json`. Scalenie `keys.json` paczki do `keys.json` użytkownika (kopia `keys.json.bak-herdr-composer` raz; nie nadpisuje istniejącego klawisza innego niż nasz — ostrzeżenie). Na końcu `herdr-app check …\mods\herdr-composer` i `herdr-app do layout.switch '{"name":"herdr-composer"}'`; brak `herdr-app` w PATH → ostrzeżenie, nie wyjątek.
|
||||
- **Sprzątanie poprzedniej wersji (`ovis-composer`):** jeśli `mods\ovis-composer` jest junction → `cmd /c rmdir` (tylko link); jeśli zwykły katalog → przenieś do `mods\ovis-composer.bak-<data>`. `layouts\ovis-composer.json` → przenieś do `.bak-<data>`. W `keys.json` usuń wpis wskazujący na `ovis-composer.focus`. Nigdy nie usuwaj plików repo.
|
||||
- `-Uninstall`: usuwa `mods\herdr-composer`, `layouts\herdr-composer.json`, nasz klawisz z `keys.json`, przełącza na `main`.
|
||||
- README: sekcja „Instalacja” — (1) przez agenta: `Read ~/.config/herdr-app/AGENTS.md, then add this layout: clone http://git.mkali.pl/Factor/herdrMario.git and use the folder herdr/herdr-composer`; (2) jedna komenda: `git clone http://git.mkali.pl/Factor/herdrMario.git "%USERPROFILE%\herdrMario" && "%USERPROFILE%\herdrMario\install.cmd"`; aktualizacja: ponownie `install.cmd`; odinstalowanie: `install.cmd -Uninstall`.
|
||||
- Usuń `-Reload` i junction z dokumentacji (nieaktualne).
|
||||
|
||||
## Zadanie C (Ovis Fast) — RECIPE.md + preview.png
|
||||
`herdr/herdr-composer/RECIPE.md` dokładnie wg struktury z AGENTS.md (Name + akapit + ``; What you see; How it behaves; Built from; Watch out). W **Built from/Watch out** jawnie: uruchamia `powershell` (`exec`: schowek, wybór pliku, rozmiary plików — ścieżki tylko jako Base64), `hc` (`send`, `put`, `get`, `interrupt`, `keys`), czyta pliki spoza swojego folderu (pliki użytkownika wskazane jako załączniki, `git ls-files` w folderze agenta); „+” i Ctrl+V obrazu tylko Windows; layout jest klonem `main` (wersja z `cloned_from`); UX inspirowany Ovis (devswha/ovis). `preview.png`: zrzut `herdr-app shot` okna z composerem (po instalacji, Zadanie D).
|
||||
|
||||
## Zadanie D (Ovis Opus) — instalacja na tej maszynie i weryfikacja
|
||||
`install.cmd` na tym komputerze → `herdr-app status` bez błędów, layout `herdr-composer`, historia/ulubione/drafty widoczne (migracja), `Ctrl+Shift+Space`, panel, test w GUI. `preview.png` ze zrzutu.
|
||||
|
||||
## Kryteria akceptacji
|
||||
- `npm test` zielone; `herdr-app check` modu OK.
|
||||
- Po `install.cmd` Herdr pokazuje composer w layoucie `herdr-composer`, historia sprzed zmiany nazwy jest widoczna.
|
||||
- Zmiana w repo + ponowne `install.cmd` → Herdr przeładowuje mod bez dodatkowych kroków.
|
||||
- `install.cmd -Uninstall` zostawia `~/.config/herdr-app` bez śladów `herdr-composer` (poza kopiami `.bak`).
|
||||
@@ -0,0 +1,184 @@
|
||||
# Profile agentów dla menu `/` — plan implementacji
|
||||
|
||||
> **Dla wykonawcy (Ovis Fast):** zadania wykonuj po kolei, każde osobnym commitem. Kroki mają checkboxy (`- [ ]`).
|
||||
|
||||
**Cel:** menu `/` podpowiada komendy dowolnego agenta. Wiedza o agencie pochodzi z profilu: domyślnego w kodzie albo z pliku `composer-agents.json` użytkownika. Do tego dochodzą komendy wysłane wcześniej do tego agenta, wzięte z historii.
|
||||
|
||||
**Architektura:**
|
||||
- Nowy czysty moduł `profiles.js`: domyślne profile, parsowanie i walidacja pliku, wybór profilu dla `agentName`.
|
||||
- `catalog.js` przestaje znać Claude Code: czyta źródła, które daje profil, a komendy z historii buduje osobną funkcją.
|
||||
- `main.js` w tle trzyma plik profili i cache źródeł `home` per `id` profilu, a pod pozycjami menu pokazuje wiersze informacyjne.
|
||||
|
||||
**Stack:** JS (ESM), GPUI z `gpui-kit`, testy `node --test` (`npm test`).
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-20-agent-profiles-design.md`. Przeczytaj cały plik przed startem.
|
||||
|
||||
## Ograniczenia globalne
|
||||
- Nie zmieniamy Herdr ani jego plików. Pracujemy tylko na gałęzi `feature/composer-dock`. Bez push.
|
||||
- Logika testowalna siedzi w czystych modułach (`profiles.js`, `catalog.js`; `exec` i `readText` wstrzyknięte). GPUI jest tylko w `main.js`.
|
||||
- Ścieżki do skryptów PowerShell trafiają wyłącznie przez `decode()` z `powershell.js` (Base64).
|
||||
- Menu `/` dla Claude Code (bez historii) daje **identyczną** listę jak przed zmianą: te same `key`, `group`, `insert`, `desc` i kolejność.
|
||||
- Plik: `[appHome(), "composer-agents.json"].join("\\")`. Brak pliku jest normalny i nie jest błędem.
|
||||
- TTL odświeżania pliku i źródeł `home`: 60 s (obecne `GLOBAL_TTL_MS`).
|
||||
- Teksty dla użytkownika dosłownie:
|
||||
- `GROUP_HISTORY = "Z historii"`;
|
||||
- nieznany agent: ``Nieznany agent `<nazwa>` – dodaj profil w ~/.config/herdr-app/composer-agents.json`` (gdzie `<nazwa>` to `agentName`);
|
||||
- problem z plikiem: `` `composer-agents.json`: <powód> ``.
|
||||
|
||||
## Review Focus
|
||||
1. `agentName` w innej wielkości liter niż `match` (np. `Kiro-CLI`): profil ma pasować. Test w Task 1.
|
||||
2. Plik z BOM, CRLF albo komentarzem-śmieciem: BOM jest usuwany, zły JSON daje domyślne profile i powód. Test w Task 1.
|
||||
3. Wpis historii zaczynający się ścieżką (`/c/Users/x`), samym `/` albo `/ cos` nie jest komendą. Test w Task 2.
|
||||
4. Dwa panele z różnymi agentami: menu codex nie pokazuje komend `~/.claude`, bo cache jest per `id`. Test cache w Task 3 (czysta funkcja).
|
||||
5. Profil z pliku nadpisujący `claude-code` bez `claude-plugins` nie pokazuje pluginów, a ścieżka `..` lub bezwzględna jest odrzucana. Test w Task 1.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: `profiles.js`, czyli domyślne profile, parsowanie i wybór
|
||||
|
||||
**Pliki:**
|
||||
- Utwórz: `herdr/herdr-composer/mods/herdr-composer/profiles.js`
|
||||
- Zmień: `herdr/herdr-composer/mods/herdr-composer/catalog.js` (przenieś `BUILTINS` i `AGENT_ALIASES` do `profiles.js`, w `catalog.js` zostaw `export { BUILTINS } from "./profiles.js"`)
|
||||
- Test: `tests/profiles.test.mjs`
|
||||
|
||||
**Interfejsy (produkuje):**
|
||||
- Typy (JSDoc):
|
||||
- `Source = {scope:"project"|"home", path:string, pattern:"*.md"|"*/SKILL.md", prefix:string}`, albo `{scope:"home", kind:"claude-plugins"}`;
|
||||
- `Profile = {id:string, match:string[], builtins:{key:string, desc:string}[], sources:Source[]}` (wszystko znormalizowane: `desc` domyślnie `""`, `prefix` domyślnie `"/"`).
|
||||
- `export const PROFILES_FILE = "composer-agents.json"`
|
||||
- `export const BUILTINS`: bez zmian treści.
|
||||
- `export const DEFAULT_PROFILES: Profile[]`:
|
||||
- `claude-code`: `match ["claude-code","claude"]`, builtins = `BUILTINS["claude-code"]`, sources w tej kolejności:
|
||||
1. project `.claude/commands` `*.md`;
|
||||
2. project `.claude/skills` `*/SKILL.md`;
|
||||
3. home `.claude/commands` `*.md`;
|
||||
4. home `.claude/skills` `*/SKILL.md`;
|
||||
5. `{scope:"home", kind:"claude-plugins"}`.
|
||||
- `codex`: `match ["codex"]`, builtins = `BUILTINS.codex`, `sources []`.
|
||||
- `export function parseProfiles(text: string|null|undefined): {profiles: Profile[], problem: string|null}`
|
||||
- `null`/`undefined` (brak pliku) daje `{profiles: [], problem: null}`.
|
||||
- Usuwa BOM. Zły JSON daje `{profiles: [], problem: "nieczytelny JSON"}`.
|
||||
- Brak `agents` albo `agents` nie jest tablicą: `problem: "brak listy agents"`.
|
||||
- Profil bez `id` (string) albo bez niepustego `match` (lista stringów) jest pomijany. Źródło z `path` bezwzględnym (`/x`, `C:/x`, `C:\x`, `\\x`) lub z segmentem `..`, nieznanym `scope` albo nieznanym `pattern` jest pomijane. Builtin bez `key` (string) jest pomijany.
|
||||
- Coś pominięto, a reszta działa: `problem: "pominięto <n> wpisów"`, gdzie `n` to liczba pominiętych profili, źródeł i builtinów razem.
|
||||
- `export function resolveProfile(userProfiles: Profile[], agent: string): Profile|null`: najpierw `userProfiles`, potem `DEFAULT_PROFILES`; pierwszy, którego `match` zawiera `agent` (bez rozróżniania wielkości liter, po `trim()`). `""` i `"default"` dają `null`, chyba że ktoś jawnie wpisał je w `match`.
|
||||
|
||||
- [ ] **Krok 1: testy (RED)** w `tests/profiles.test.mjs`:
|
||||
- `resolveProfile([], "claude")` i `resolveProfile([], "Claude-Code")` → `id === "claude-code"`; `resolveProfile([], "codex").id === "codex"`; `resolveProfile([], "kiro-cli") === null`; `resolveProfile([], "default") === null`.
|
||||
- Profil z pliku `{id:"claude-code", match:["claude-code"], builtins:[{key:"x"}]}` wygrywa z domyślnym: `builtins` to tylko `x`, a `sources` jest puste (brak `claude-plugins`).
|
||||
- `parseProfiles(null)` → `{profiles:[], problem:null}`.
|
||||
- `parseProfiles("\uFEFF{\"agents\":[{\"id\":\"kiro\",\"match\":[\"kiro-cli\"],\"sources\":[{\"scope\":\"home\",\"path\":\".kiro/prompts\",\"pattern\":\"*.md\",\"prefix\":\"@\"}]}]}\r\n")` → jeden profil, źródło z `prefix:"@"`, `problem:null`.
|
||||
- `parseProfiles("{nope")` → `problem:"nieczytelny JSON"`, `profiles:[]`.
|
||||
- `parseProfiles('{"agents":{}}')` → `problem:"brak listy agents"`.
|
||||
- Profil z dwoma źródłami `{path:"../x"}` i `{path:"C:/x"}` oraz jednym dobrym → zostaje 1 źródło, `problem:"pominięto 2 wpisów"`.
|
||||
- Profil bez `match` jest pominięty, drugi dobry zostaje.
|
||||
- `pattern:"**/*.md"` jest odrzucony.
|
||||
- `DEFAULT_PROFILES[0].builtins` ma te same klucze co `BUILTINS["claude-code"]`.
|
||||
- [ ] **Krok 2:** `npm test` daje FAIL (brak modułu).
|
||||
- [ ] **Krok 3:** zaimplementuj `profiles.js` i przenieś `BUILTINS` z re-eksportem w `catalog.js`.
|
||||
- [ ] **Krok 4:** `npm test` daje PASS, łącznie z dzisiejszymi 190 testami.
|
||||
- [ ] **Krok 5: commit** `feat: agent profiles describe each agent's commands`
|
||||
|
||||
---
|
||||
|
||||
### Task 2: `catalog.js` czyta źródła profilu i komendy z historii
|
||||
|
||||
**Pliki:**
|
||||
- Zmień: `herdr/herdr-composer/mods/herdr-composer/catalog.js`, `herdr/herdr-composer/mods/herdr-composer/suggest.js`
|
||||
- Test: `tests/catalog.test.mjs`
|
||||
|
||||
**Interfejsy:**
|
||||
- Konsumuje z Task 1: `Profile`, `Source`, `DEFAULT_PROFILES`, `resolveProfile`.
|
||||
- Produkuje:
|
||||
- `suggest.js`: `export const GROUP_HISTORY = "Z historii"`, w `GROUPS` po `GROUP_PLUGIN`, przed `GROUP_TERMINAL`.
|
||||
- `commands(cwd, exec, options)` z `options = {profile?: Profile|null, snippets?, global?: Item[], history?: Item[], onReadError?}`:
|
||||
- `profile` null lub brak: tylko `snippets` i `history`, bez `exec`;
|
||||
- w przeciwnym razie kolejność: builtins profilu, źródła `project` profilu (czytane przez `exec` w `cwd`), `global`, `snippets`, `history`;
|
||||
- deduplikacja po `key`: pierwszy wygrywa;
|
||||
- `insert` = `source.prefix + key + " "`.
|
||||
- Źródła `project` listuje **jedno** `exec` (sh, a PowerShell jako zapas, jak dziś `listProjectFiles`). Ścieżki i wzorce idą jako argumenty (sh) lub przez `decode()` (PS), nie są sklejane w skrypt. Nazwa skilla projektu: zawsze nazwa folderu, bez filtra `user-invocable` (jak dziś).
|
||||
- `globalCommands(home, exec, readText, options)` z `options = {sources: Source[], onReadError?}`:
|
||||
- czyta tylko źródła `scope:"home"` z `sources`; `kind:"claude-plugins"` daje dzisiejszą logikę pluginów (`~/.claude/settings.json` itd.);
|
||||
- źródło `home` `{path, pattern}` daje dzisiejszy spec `md` / `skills` dla `${home}/${path}`;
|
||||
- nazwy i filtr `user-invocable` jak dziś; `insert` z `prefix` źródła (plugin: `"/"`);
|
||||
- brak `sources` lub pusta lista: `[]` bez `exec`.
|
||||
- `export function historyCommands(history: HistoryEntry[], agent: string): Item[]`:
|
||||
- wpisy z `agentName` równym `agent` (bez wielkości liter, `trim`), od najnowszego `sentAt`;
|
||||
- pierwszy token `text.trimStart()` pasujący do `/^\/[A-Za-z0-9][\w:.-]*$/`;
|
||||
- `key` bez `/`, `desc: ""`, `group: GROUP_HISTORY`, `insert: "/"+key+" "`;
|
||||
- bez duplikatów.
|
||||
- `export function unknownAgentMessage(agent: string): string` oraz `export function profileProblemMessage(problem: string): string`: teksty z Ograniczeń globalnych.
|
||||
- Usuń `isClaudeCode` i `LIST_SH`/`LIST_PS` na sztywno. Test `isClaudeCode` zastępują testy `resolveProfile` z Task 1, więc usuwasz go.
|
||||
|
||||
- [ ] **Krok 1: test „CC bez zmian” PRZED zmianą kodu.** Na obecnym kodzie, na fałszywej maszynie z testów (`machine(...)`) z plikami:
|
||||
- projekt `.claude/commands/a.md`, `.claude/skills/s/SKILL.md` (z `name: inna`);
|
||||
- home `~/.claude/commands/handoff.md`;
|
||||
- jeden plugin.
|
||||
|
||||
Wywołaj `commands(cwd, exec, {agent:"claude-code", global: await globalCommands(...)})` i wpisz wynik (lista `{key, group, insert, desc}`) jako literał `EXPECTED_CC` w teście. Commit tylko testu: `test: pin the / menu of Claude Code before profiles`. `npm test` daje PASS.
|
||||
- [ ] **Krok 2: przepisz ten test na nowe API** (`profile: resolveProfile([], "claude-code")`, `globalCommands(..., {sources: profile.sources})`) z tym samym `EXPECTED_CC`. Dodaj testy (RED):
|
||||
- `commands` z `profile: null`, `history: [h]` daje `[h]` i `exec` nie zostaje wywołane;
|
||||
- profil `kiro` ze źródłem project `.kiro/prompts` `*.md` `prefix:"@"` daje `{key:"review", insert:"@review ", group:"Projekt"}`;
|
||||
- `globalCommands` z `sources: []` daje `[]`, bez `exec`;
|
||||
- `globalCommands` ze źródłem home `.kiro/prompts` daje grupę `Użytkownik`;
|
||||
- `historyCommands`: wpisy `"/clear"`, `" /superpowers:brainstorming x"`, `"/c/Users/x"`, `"/ cos"`, `"/"`, `"hej /clear"` oraz wpis innego agenta dają dokładnie `["superpowers:brainstorming","clear"]` (gdy `brainstorming` jest nowszy), w grupie `Z historii`;
|
||||
- `commands` z builtin `clear` i historią `clear` daje jedno `clear` z grupy `Wbudowane`;
|
||||
- `GROUPS` zawiera `"Z historii"` zaraz po `"Pluginy"`;
|
||||
- istniejące testy `globalCommands` dostają mechanicznie `{sources: DEFAULT_PROFILES[0].sources}`.
|
||||
- [ ] **Krok 3:** `npm test` daje FAIL na nowych testach.
|
||||
- [ ] **Krok 4:** zaimplementuj.
|
||||
- [ ] **Krok 5:** `npm test` daje PASS, z `EXPECTED_CC` bez zmian.
|
||||
- [ ] **Krok 6: commit** `feat: the / menu reads the sources of the agent's profile and its history`
|
||||
|
||||
---
|
||||
|
||||
### Task 3: `main.js`, czyli plik profili, cache per profil, wiersze informacyjne i README
|
||||
|
||||
**Pliki:**
|
||||
- Zmień: `herdr/herdr-composer/mods/herdr-composer/main.js` (`updateSuggestions` ~2213, `refreshGlobal` ~2228, `loadSuggestions` ~2275, `renderMenu` ~2824, stan w `init` ~199), `herdr/herdr-composer/mods/herdr-composer/catalog.js` (jedna czysta funkcja niżej), README moda (sekcja „Inni agenci”)
|
||||
- Test: `tests/catalog.test.mjs`
|
||||
|
||||
**Interfejsy:**
|
||||
- Konsumuje: `parseProfiles`, `resolveProfile`, `PROFILES_FILE` (Task 1); `commands`, `globalCommands`, `historyCommands`, `unknownAgentMessage`, `profileProblemMessage` (Task 2).
|
||||
- Produkuje w `catalog.js`: `export function menuNotes({profile, agent, profilesLoaded, problem}): string[]`:
|
||||
- `[profileProblemMessage(problem)]`, gdy `problem`;
|
||||
- plus `unknownAgentMessage(agent)`, gdy `!profile && profilesLoaded`;
|
||||
- kolejność: najpierw nieznany agent, potem problem.
|
||||
- Stan w `main.js`:
|
||||
- `this.userProfiles = []`, `this.profileProblem = null`, `this.profilesLoaded = false`;
|
||||
- `this.globalCommands = new Map()` (klucz `profile.id`, wartość `Item[]`) i `this.globalLoadedAt = new Map()`, zamiast dzisiejszych pojedynczych pól;
|
||||
- flaga `this.globalLoading` jak dziś.
|
||||
- `refreshGlobal(cx)`:
|
||||
1. gdy minęło 60 s od ostatniego odczytu pliku: `readTextFile([appHome(), PROFILES_FILE].join("\\"))`, potem `parseProfiles` i ustawienie trzech pól oraz `profilesLoaded = true`;
|
||||
2. `profile = resolveProfile(this.userProfiles, agentName(target))`; gdy profil ma źródła `home` i cache dla `profile.id` jest pusty lub starszy niż 60 s, `globalCommands(home(), exec, readTextFile, {sources: profile.sources, onReadError})` zapisuje wynik pod `profile.id`;
|
||||
3. po zakończeniu, gdy menu `/` jest otwarte, przeładuj menu tak jak dziś.
|
||||
|
||||
W `updateSuggestions` wołaj `refreshGlobal` dla **każdego** agenta przy `/` (usuń warunek `isClaudeCode`). `checking()` blokuje jak dziś.
|
||||
- `loadSuggestions`, gałąź `/`:
|
||||
- `profile = resolveProfile(this.userProfiles, agentName(agent))`;
|
||||
- `commands(cwd, exec, {profile, snippets: [], global: this.globalCommands.get(profile?.id) ?? [], history: catalog.historyCommands(storage.loadHistory(this.store), agentName(agent)), onReadError})`;
|
||||
- `this.menu.notes = catalog.menuNotes({...})`.
|
||||
- `renderMenu`: `notes` jako szare (`t.dim`, `text_size(11.5)`) wiersze **pod** pozycjami, w tej samej przewijanej liście. Nie da się ich wybrać, a indeksy pozycji i `scroll_to_item` się nie zmieniają. Komunikat „Żadna komenda nie pasuje” nie pojawia się, gdy pozycji nie ma, a są `notes` z nieznanym agentem.
|
||||
- README: sekcja „Inni agenci”:
|
||||
- klucz bierzesz z wiersza „Nieznany agent …”;
|
||||
- ścieżka pliku i format (pola z tabeli w specu);
|
||||
- że plik nadpisuje profil o tym samym `id` w całości;
|
||||
- przykład dla kiro z nagłówkiem „przykład niesprawdzony”.
|
||||
|
||||
- [ ] **Krok 1: testy (RED)** `menuNotes`:
|
||||
- `{profile:null, agent:"kiro-cli", profilesLoaded:true}` daje 1 wiersz zawierający `` `kiro-cli` ``;
|
||||
- to samo przy `profilesLoaded:false` daje `[]`;
|
||||
- profil plus `problem:"nieczytelny JSON"` daje `["`composer-agents.json`: nieczytelny JSON"]`;
|
||||
- `profile:null`, `problem` i `profilesLoaded:true` dają 2 wiersze, najpierw nieznany agent.
|
||||
- [ ] **Krok 2:** `npm test` daje FAIL.
|
||||
- [ ] **Krok 3:** zaimplementuj `menuNotes`, zmiany w `main.js` i README.
|
||||
- [ ] **Krok 4:** `npm test` daje PASS. `grep -n isClaudeCode herdr/herdr-composer/mods/herdr-composer/*.js` nic nie znajduje.
|
||||
- [ ] **Krok 5: commit** `feat: the composer reads agent profiles from composer-agents.json`
|
||||
|
||||
---
|
||||
|
||||
## Po wykonaniu (Ovis Opus, nie wykonawca)
|
||||
- Instalacja: `powershell -NoProfile -ExecutionPolicy Bypass -File scripts/install.ps1`, potem `herdr-app status` musi dać `"errors": []`.
|
||||
- GUI: menu `/` w CC wygląda tak jak przed zmianą.
|
||||
- Plik testowy `composer-agents.json` z profilem `codex` ze źródłem home `.claude/commands` daje `handoff` w menu codex w ciągu 60 s.
|
||||
- Uszkodzony plik daje wiersz z powodem. Po teście usuń plik.
|
||||
@@ -0,0 +1,29 @@
|
||||
# Potwierdzenie wysyłki — plan implementacji
|
||||
|
||||
**Spec:** `docs/superpowers/specs/2026-11-20-send-confirmation-design.md` (czytaj całość).
|
||||
**Gałąź:** `feature/send-confirmation`. Bez push.
|
||||
|
||||
## Ograniczenia globalne
|
||||
- Czasy dosłownie: `SENT_MS = 1500`, `NOTICE_MS = 3000` (stałe eksportowane z `view.js` lub `state.js`, gdzie pasuje).
|
||||
- Timery tylko przez `cx.timer.after` (jak `draftTimer`); poprzedni timer anulowany (`.cancel()`) przed nowym.
|
||||
- Logika testowalna w czystej funkcji; GPUI tylko w `main.js`.
|
||||
|
||||
## Review Focus
|
||||
1. Komunikat `info` A, po 2 s komunikat `problem` B: timer A nie może skasować B. Test w Task 1.
|
||||
2. Dwie wysyłki w odstępie 1 s: ✓ widoczne do 1,5 s po drugiej (timer odnowiony).
|
||||
3. Wysyłka nieudana (błąd `hc`): bez ✓, czerwony komunikat jak dziś.
|
||||
4. Wysyłka do kolejki (agent pracuje): komunikat o kolejce znika po 3 s, ✓ się nie pokazuje (nic nie poszło do terminala).
|
||||
|
||||
### Task 1: czysta logika (test)
|
||||
**Produkuje** w `view.js`: `export function noticeExpired(current, scheduled): boolean` — `true`, gdy `current` to ten sam obiekt co `scheduled` i `scheduled.level === "info"`.
|
||||
- [ ] Testy w `tests/view.test.mjs` (RED): ten sam obiekt `info` → `true`; inny obiekt o tym samym tekście → `false`; `problem`/`error` → `false`; `current === null` → `false`.
|
||||
- [ ] Implementacja, `npm test` PASS.
|
||||
|
||||
### Task 2: `main.js`
|
||||
- `notice(text, level, cx)`: zapamiętaj obiekt komunikatu; dla `"info"` ustaw (anulując poprzedni) `this.noticeTimer = cx.timer.after(NOTICE_MS, (cx) => { if (noticeExpired(this.state.notice, scheduled)) { this.state = reduce(this.state, { type: "notice", notice: null }); cx.notify(); } })`. Gdy `cx` brak (wywołania bez `cx`) — użyj `cx` dostępnego w miejscu wywołania: przejrzyj wszystkie `this.notice(` i dopisz `cx`, gdzie jest w zasięgu; gdzie go nie ma, komunikat zniknie przy najbliższym `notice`/akcji (zapisz listę takich miejsc w raporcie).
|
||||
- 4 × `this.notice("Wysłano do terminala.")` → `this.flashSent(cx)`: `this.sentUntil = Date.now() + SENT_MS`, timer `SENT_MS` → `cx.notify()` (odnowiony przy kolejnym wywołaniu); dodatkowo wyczyść bieżący komunikat `info` (stara informacja nie wisi).
|
||||
- Render: gdzie dziś wybierany jest `renderStop` / `renderSend`, najpierw: `Date.now() < this.sentUntil` → `renderSent(t)` (kółko 32 px, `rounded(999)`, `bg(t.done)`, „✓”, `text_size(13)`, `font_semibold()`, bez `on_click`).
|
||||
- Komentarz na górze `main.js` (linia ~23) i `delivery.js:16` o „Wysłano do terminala” zaktualizuj.
|
||||
- [ ] `npm test` PASS, `node --check main.js` OK.
|
||||
- [ ] README: jeśli wspomina „Wysłano do terminala”, popraw.
|
||||
- [ ] Commit (oba taski razem albo osobno): `feat: a green check confirms a send and info notices fade after 3 s` + `Co-Authored-By: Ovis Fast (Claude) <[email protected]>`.
|
||||
@@ -0,0 +1,39 @@
|
||||
# Composer Dock — projekt (krótki)
|
||||
|
||||
Data: 2026-11-19 · Makieta: `docs/superpowers/mockups/herdr-composer-dock.html` (zaakceptowana przez użytkownika)
|
||||
|
||||
## Cel i powód
|
||||
Jednym kliknięciem wysłać do agenta często używaną komendę (np. `/handoff`, `/clear`) albo wstawić szablon promptu. Przyciski ma ustawiać sam użytkownik, z poziomu composera, bez edycji plików.
|
||||
|
||||
## Zakres
|
||||
- Dock: rząd przycisków w belce composera między ☆ a chipem statusu, w miejscu obecnego `div().flex_1()` (`main.js`, `renderCard`). Za ☆ jest separator.
|
||||
- Przycisk = `{ id, label, text, mode }`, gdzie `mode`: `"send"` (domyślnie) lub `"insert"`.
|
||||
- `send`: ta sama droga co Enter (kolejka, gdy agent pracuje; odliczanie; `--force` przy `blocked`; strażnik tożsamości agenta). Tekst w polu pozostaje nietknięty.
|
||||
- `insert`: wstawia `text` w miejscu kursora (jak Enter w panelu Historii), nic nie wysyła.
|
||||
- Wygląd: `send` ma pełne tło, `insert` przerywaną ramkę i znak ✎.
|
||||
- Nazwa domyślna: `text` skrócony do najwyżej 16 znaków (15 + „…”), białe znaki zwinięte do jednej spacji. Pełny tekst pokazuje tooltip.
|
||||
- **Dodawanie:**
|
||||
1. w panelu Ulubione: prawy klik na wpis otwiera menu z opcjami Wstaw, Przypnij do docka / Odepnij z docka oraz Usuń z ulubionych;
|
||||
2. prawy klik na ☆ otwiera menu „Przypnij bieżący tekst do docka” (nieaktywne przy pustym polu).
|
||||
- Nowy przycisk trafia na koniec docka. Tekst już przypięty nie jest dodawany drugi raz; menu pokazuje wtedy „Odepnij”.
|
||||
- **Prawy klik na przycisk w docku:** Zmień nazwę (edycja w miejscu: Enter zapisuje, Esc lub utrata fokusu anuluje, pusta nazwa wraca do domyślnej), Tylko wstawiaj / Wysyłaj od razu, Przesuń w lewo, Przesuń w prawo, Usuń z docka.
|
||||
- **Pusty dock:** szara podpowiedź „Prawy klik w Ulubionych → Przypnij do docka”.
|
||||
- **Przepełnienie:** dock przewija się poziomo (`overflow_x_scroll`). Chip i Wyślij nie są ruchome.
|
||||
- **Brak agenta** (fokus na zwykłym terminalu): przyciski są wyszarzone i nieaktywne, tak jak 🕘/☆.
|
||||
- **Zapis:** `shared.json`, klucz `herdr-composer.dock`. Dock jest jeden, wspólny dla wszystkich agentów. Limit 30 przycisków. Uszkodzone wpisy są pomijane, tak jak w historii i ulubionych. Nie dotyczy migracji z `ovis-composer` (nowy klucz).
|
||||
|
||||
## Zmiana istniejącego zachowania
|
||||
Dziś prawy klik na wiersz w panelu Historia/Ulubione od razu przełącza ulubione. Po zmianie otwiera menu. `Ctrl+D` nadal przełącza od razu. W zakładce Historia menu ma Wstaw i Dodaj do ulubionych / Usuń z ulubionych.
|
||||
|
||||
## Podejścia (rozważone)
|
||||
- Konfiguracja: plik JSON / edycja w composerze / oba. **Wybrane: w composerze** (decyzja użytkownika).
|
||||
- Klik: zawsze wysyła / zawsze wstawia / tryb per przycisk. **Wybrane: per przycisk, domyślnie wysyła** (makieta zaakceptowana).
|
||||
|
||||
## Poza zakresem
|
||||
Ikony lub emoji jako przyciski, skróty klawiszowe do przycisków, przeciąganie myszą do zmiany kolejności, osobne docki per agent lub per projekt, import i eksport.
|
||||
|
||||
## Dla wykonawcy
|
||||
- Czysta logika (`dock.js`: dodaj, usuń, przesuń, zmień nazwę, przełącz tryb, `isPinned`, `defaultLabel`, `normalize` z limitem) z testami w `tests/dock.test.mjs`. Odczyt i zapis w `storage.js` (`KEYS.dock`, `loadDock`, `saveDock`).
|
||||
- Menu: `Popover` z `gpui-kit`, otwierany prawym przyciskiem (`MouseButton "right"`). Jeśli nie da się go użyć w wierszach panelu (`on_item_secondary_click`), dopuszczalny jest własny popup pozycjonowany w miejscu kliknięcia.
|
||||
- Akcja `send` korzysta z istniejącej ścieżki wysyłania (bez duplikowania logiki kolejki). Wymagany test, że tekst w polu i draft nie zmieniają się.
|
||||
- Wysokość bloku (auto-fit) nie może rosnąć przez dock: dock ma stałą wysokość 28 px.
|
||||
@@ -0,0 +1,122 @@
|
||||
# Profile agentów dla menu `/` — projekt
|
||||
|
||||
Data: 2026-11-20 · Gałąź: `feature/composer-dock` · Mod: `herdr/herdr-composer/mods/herdr-composer/`
|
||||
|
||||
## Cel i powód
|
||||
Menu `/` composera ma podpowiadać komendy każdego agenta, nie tylko Claude Code. Na tej maszynie są Claude Code i codex. Kiro-cli i Antigravity CLI działają na innych komputerach i nie da się ich tu uruchomić. Nie znamy więc ich kluczy `agentName()` ani ich komend i nie wolno ich zgadywać. Rozwiązanie musi działać bez tej wiedzy w kodzie. Użytkownik dopisuje ją w pliku na maszynie, na której agent działa, bez zmian w kodzie i bez reinstalacji moda.
|
||||
|
||||
## Dziś
|
||||
- `agentName(agent)` (`view.js:60`) zwraca `agent.app`, potem `program.key`, a w ostateczności `"default"`.
|
||||
- `catalog.js` ma na sztywno:
|
||||
- `BUILTINS["claude-code"]` (49 komend) i `BUILTINS.codex` (4 komendy);
|
||||
- alias `claude` → `claude-code`;
|
||||
- `isClaudeCode()`, które decyduje, czy czytać `.claude/commands`, `.claude/skills` projektu oraz `~/.claude` z pluginami (`globalCommands`).
|
||||
- Agent spoza tej listy dostaje w menu `/` tylko snippety, a te dziś są zawsze puste (`snippets: []` w `main.js`).
|
||||
- Historia (`storage.loadHistory`, do 500 wpisów, wspólna) zapisuje każdą wysłaną wiadomość z polem `agentName` = `agentName(agent)` (`main.js`, `recordSent`).
|
||||
|
||||
## Cele
|
||||
1. **Profil agenta** opisuje: jakie nazwy z `agentName()` do niego pasują, jakie ma wbudowane komendy i skąd czytać jego własne komendy (folder projektu i folder domowy).
|
||||
2. **Domyślne profile w kodzie** dla `claude-code` (z aliasem `claude`) i `codex`. Zachowują dzisiejsze działanie: te same komendy, grupy, kolejność i deduplikację.
|
||||
3. **Plik użytkownika** `~/.config/herdr-app/composer-agents.json` (obok `shared.json`) dodaje nowe profile albo nadpisuje domyślne.
|
||||
4. **Komendy z historii:** każde `/słowo` z początku wiadomości wysłanej wcześniej do agenta o tym samym `agentName` trafia do menu jako osobna grupa.
|
||||
5. **Nieznany agent:** kiedy żaden profil nie pasuje, menu pokazuje wiersz informacyjny z dokładnym kluczem, który trzeba wpisać w pliku.
|
||||
|
||||
## Układ maszyn
|
||||
Każdy komputer ma własną instalację herdr-app z tym modem, a agent działa lokalnie obok GUI (decyzja użytkownika). Plik profili, folder domowy i źródła są czytane lokalnie, bez `on: machine`. Agenci na zdalnych maszynach przez herdr-core są poza zakresem.
|
||||
|
||||
## Poza zakresem
|
||||
- Edytor profili w GUI.
|
||||
- Wpisywanie do kodu profili kiro-cli i Antigravity. Dostarczamy tylko przykład w README, wyraźnie oznaczony jako niesprawdzony.
|
||||
- Inny wyzwalacz menu niż `/`.
|
||||
- Zagnieżdżone skille (`~/.claude/skills/synced/`), czyli znany brak, który zostaje.
|
||||
- `clipboard.js` `IMAGE_APPS`.
|
||||
|
||||
## Anty-cele (porażka, nawet jeśli działa)
|
||||
- Jakakolwiek zmiana menu `/` dla Claude Code: inna lista, inne grupy, inna kolejność albo wolniejsze działanie.
|
||||
- Uszkodzony lub brakujący plik użytkownika psuje menu. Ma wtedy działać na domyślnych profilach.
|
||||
- Zgadywanie w kodzie kluczy lub komend agentów, których nie widzieliśmy.
|
||||
|
||||
## Podejścia (rozważone)
|
||||
- **Skąd brać komendy nieznanego agenta:** (1) profile w pliku, (2) nauka z użycia, (3) oba. **Wybrane: oba** (decyzja użytkownika).
|
||||
- **Gdzie trzymać profile:**
|
||||
- **A.** Domyślne w kodzie plus plik w home.
|
||||
- **B.** `shared()` z edytorem w GUI.
|
||||
- **C.** `agents.json` w folderze moda.
|
||||
- **Wybrane: A** (decyzja użytkownika). B oznacza dużo GUI do rzadkiej czynności. C nadpisuje `install.ps1` przy aktualizacji.
|
||||
- **Nauka z użycia:** nowy magazyn albo odczyt historii. **Wybrane: historia** (moja decyzja). Ma już `agentName`, więc nie trzeba nowego klucza ani nowego zapisu.
|
||||
|
||||
## Format pliku `composer-agents.json`
|
||||
```json
|
||||
{
|
||||
"agents": [
|
||||
{
|
||||
"id": "kiro",
|
||||
"match": ["kiro-cli", "kiro"],
|
||||
"builtins": [
|
||||
{ "key": "context", "desc": "Zarządza kontekstem." },
|
||||
{ "key": "model" }
|
||||
],
|
||||
"sources": [
|
||||
{ "scope": "project", "path": ".kiro/prompts", "pattern": "*.md" },
|
||||
{ "scope": "home", "path": ".kiro/prompts", "pattern": "*.md", "prefix": "@" }
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
- `id` (wymagany, string): nazwa profilu. Profil z pliku o tym samym `id` co domyślny **zastępuje go w całości**. Bez łączenia list, żeby zachowanie było przewidywalne.
|
||||
- `match` (wymagany, niepusta lista stringów): wartości `agentName()`, które pasują do profilu. Porównanie dokładne, bez rozróżniania wielkości liter. Pierwszy pasujący profil wygrywa, profile z pliku są sprawdzane przed domyślnymi.
|
||||
- `builtins` (opcjonalny): `{key, desc?}` trafiają do grupy `Wbudowane`.
|
||||
- `sources` (opcjonalny): lista źródeł.
|
||||
- `scope`: `"project"` (względem `cwd` panelu, czytane przez `exec` jak dziś `projectItems`) albo `"home"` (względem folderu domowego, czytane jak dziś `globalCommands`). Odpowiadają grupom `Projekt` i `Użytkownik`.
|
||||
- `path`: folder względny. Ścieżka bezwzględna i `..` są odrzucane.
|
||||
- `pattern`: `"*.md"` (nazwa komendy = nazwa pliku bez `.md`) albo `"*/SKILL.md"`. Inne wzorce są odrzucane. Nazwa skilla zależy od zakresu, tak jak dziś *(moja decyzja: CC bez zmian)*:
|
||||
- `home`: `name:` z frontmattera, a gdy go brak, nazwa folderu; pomija `user-invocable: false`;
|
||||
- `project`: zawsze nazwa folderu, bez filtra.
|
||||
- `prefix` (opcjonalny, domyślnie `"/"`): co wstawia wybór z menu (`insert: prefix + key + " "`). Przydaje się agentowi, który wywołuje prompty inaczej niż `/`.
|
||||
- Specjalne `{ "scope": "home", "kind": "claude-plugins" }` oznacza dzisiejszą logikę pluginów (`settings.json` → `enabledPlugins`, `installed_plugins.json`, `plugin.json`) i daje grupę `Pluginy`. Używa go domyślny profil `claude-code`. Inny profil może go użyć, ale nic poza tym nie robi.
|
||||
- Domyślny profil `claude-code` w kodzie wyrażony w tym formacie:
|
||||
- `match: ["claude-code", "claude"]`;
|
||||
- `builtins`: dzisiejsze 49;
|
||||
- `sources`: projekt `.claude/commands` `*.md`, projekt `.claude/skills` `*/SKILL.md`, home `.claude/commands` `*.md`, home `.claude/skills` `*/SKILL.md`, `claude-plugins`.
|
||||
- Domyślny `codex`: `match: ["codex"]`, dzisiejsze 4 builtins, bez źródeł.
|
||||
- `isClaudeCode()` znika z logiki katalogu. To, czy czytać `.claude`, wynika wyłącznie z profilu.
|
||||
|
||||
**Błędy w pliku.** Brak pliku jest normalny i oznacza same domyślne profile. Nieczytelny JSON albo zły kształt (`agents` nie jest listą) oznacza ignorowanie całego pliku. Pojedynczy zły profil lub źródło jest pomijany, reszta działa. Gdy plik został odrzucony w całości albo częściowo, menu `/` pokazuje u dołu jeden wiersz informacyjny: „`composer-agents.json`: <krótki powód>”.
|
||||
|
||||
## Komendy z historii
|
||||
- Źródło: `storage.loadHistory(store)`. Bierzemy wpisy, których `agentName` jest równe bieżącemu `agentName(agent)` (porównanie bez rozróżniania wielkości liter).
|
||||
- Z tekstu wpisu bierzemy pierwszy token, jeśli tekst po `trimStart()` zaczyna się od `/`, a token pasuje do `^/[A-Za-z0-9][\w:.-]*$`. Klucz to token bez `/`.
|
||||
- Grupa: nowa `GROUP_HISTORY = "Z historii"`, dopisana na końcu `GROUPS` w `suggest.js` (przed `Terminal`, jeśli ta grupa jest używana w tym menu, inaczej na końcu). Opis to pusty string. `insert: "/" + key + " "`.
|
||||
- Działa dla każdego agenta, także Claude Code.
|
||||
|
||||
## Kolejność i deduplikacja
|
||||
Źródła są łączone w tej kolejności: builtins, źródła `project` profilu, źródła `home` profilu (w tym pluginy), snippety, historia. Nazwa pojawia się raz: wygrywa pierwsze źródło, które ją ma, tak jak dziś. Dla Claude Code bez historii lista jest identyczna z dzisiejszą.
|
||||
|
||||
## Nieznany agent
|
||||
Żaden profil nie pasuje: menu pokazuje komendy z historii i snippety oraz jeden wiersz informacyjny „Nieznany agent `<agentName>` – dodaj profil w `~/.config/herdr-app/composer-agents.json`”. Wiersza nie da się wybrać (Enter/Tab go pomija, tak jak dzisiejsze komunikaty `NO_MATCH_MESSAGE` / `READ_ERROR_MESSAGE`). Agent o `agentName` = `"default"` też jest „nieznany”.
|
||||
|
||||
## Odświeżanie
|
||||
Ścieżka pliku pochodzi z `appHome()` modułu `herdr` (honoruje `$HERDR_APP_HOME`), nie jest wpisana na sztywno *(moja decyzja)*. Plik profili i źródła `home` są czytane w tle (dzisiejsze `refreshGlobal`) z tym samym TTL 60 s. Pierwsze `/` po starcie nie czeka na plik. Dopóki plik nie został wczytany ani razu, wiersz „Nieznany agent” się nie pokazuje. Po wczytaniu otwarte menu przeładowuje się tak jak dziś *(moja decyzja: bez spowolnienia CC i bez fałszywego komunikatu)*. Zmiana pliku pojawia się w menu w ciągu minuty, bez restartu. Cache źródeł `home` jest trzymany **per profil** (`id`), bo dwa terminale mogą mieć różnych agentów. Źródła `project` są czytane jak dziś, przy każdym otwarciu menu.
|
||||
|
||||
## Testy
|
||||
- Dzisiejsze testy `catalog.test.mjs` przechodzą bez zmian albo z mechaniczną zmianą wywołania.
|
||||
- Nowe przypadki:
|
||||
- wynik dla CC identyczny z wynikiem sprzed zmiany (lista kluczy, grup i `insert`);
|
||||
- plik nadpisuje profil domyślny;
|
||||
- plik dodaje profil z `prefix: "@"`;
|
||||
- uszkodzony JSON → domyślne profile i wiersz informacyjny;
|
||||
- zły profil pominięty, dobry działa;
|
||||
- ścieżka z `..` odrzucona;
|
||||
- komendy z historii (filtr agenta, regex, dedup z builtins);
|
||||
- nieznany agent → wiersz z kluczem.
|
||||
- GUI na tej maszynie: menu `/` dla CC wygląda tak jak przed zmianą. Plik testowy z profilem dla `codex` (albo z fałszywym `match` dla CC) pokazuje własne komendy w ciągu minuty.
|
||||
|
||||
## README
|
||||
Krótka sekcja „Inni agenci”:
|
||||
- skąd wziąć klucz (wiersz „Nieznany agent …” w menu);
|
||||
- format pliku;
|
||||
- przykład dla kiro, oznaczony jako niesprawdzony.
|
||||
|
||||
## Pozostawione wykonawcy
|
||||
Podział funkcji między `catalog.js` a ewentualny nowy `profiles.js`, nazwy funkcji i dokładny kształt cache w `main.js`. Byle `catalog.js` dalej działał w czystym Node z wstrzykniętymi `exec` i `readText`.
|
||||
@@ -0,0 +1,14 @@
|
||||
# Potwierdzenie wysyłki bez komunikatu — projekt (krótki)
|
||||
|
||||
Data: 2026-11-20 · Mod: `herdr/herdr-composer/mods/herdr-composer/`
|
||||
|
||||
## Cel i powód
|
||||
Komunikat „Wysłano do terminala.” pod kartą composera zabiera miejsce w pionie terminalowi i wisi, aż zastąpi go inny. Potwierdzenie ma być tam, gdzie patrzy użytkownik (przycisk wysyłki), a komunikaty informacyjne mają nie zajmować miejsca na stałe.
|
||||
|
||||
## Zakres
|
||||
- **✓ zamiast „Wysłano do terminala.”** Po udanej wysyłce (4 miejsca w `main.js`, dziś `this.notice("Wysłano do terminala.")`) przez **1,5 s** w miejscu przycisku wysyłki/Stop jest zielone kółko 32 px (`t.done`) z „✓” (kolor `t.solid_foreground` albo `t.background` — byle czytelny). Kliknięcie nic nie robi. Potem wraca `↵` albo Stop, zgodnie z bieżącym stanem. Druga wysyłka w trakcie odnawia 1,5 s. Komunikat „Wysłano do terminala.” znika całkowicie (nie jest ustawiany).
|
||||
- **Komunikaty `info` znikają po 3 s.** Każdy komunikat poziomu `"info"` jest czyszczony po **3 s** — chyba że w tym czasie pojawił się inny komunikat (timer czyści tylko ten, który ustawił). `"problem"` i `"error"` zostają jak dziś (do zastąpienia).
|
||||
- Bez zmian: toasty błędów, kolejka, chip statusu, Esc.
|
||||
|
||||
## Podejścia
|
||||
Znikający komunikat / usunięcie komunikatu / ✓ na przycisku. **Wybrane: ✓ na przycisku** (decyzja użytkownika) plus znikanie pozostałych `info` po 3 s (decyzja użytkownika). Mój wybór: ✓ ma pierwszeństwo przed Stop przez 1,5 s (inaczej byłby niewidoczny, bo po wysyłce agent od razu „pracuje”); Stop w tym czasie zastępuje `Esc`.
|
||||
@@ -0,0 +1,33 @@
|
||||
# Herdr Unified Prompt Experience — raport końcowy (Ovis Opus)
|
||||
|
||||
Data: 2026-11-19 · Gałąź: `feature/unified-prompt` · Status: **PARTIALLY_APPROVED** (aktualizacja 2026-11-19: błąd nr 1 naprawiony w e6afb3e, composer przy dolnej krawędzi w 568db3d, blok dopasowany do treści w 406f00f)
|
||||
|
||||
## Zrealizowane (z dowodem)
|
||||
|
||||
| Funkcja | Dowód |
|
||||
|---|---|
|
||||
| Globalny composer w layoucie `ovis-composer`, jedna instancja, bez rekompilacji | `herdr-app status` → `errors: []`, zrzuty |
|
||||
| Fokus tam, gdzie klik; `Ctrl+Shift+Space`; skróty tylko w `ovis-composer > Input` | GUI (Opus + użytkownik): Esc w oknie nazwy działa |
|
||||
| Autouzupełnianie `/` `@` ze strzałkami | GUI: ↓↓ → `model` |
|
||||
| Trwałe drafty per agent + kontrola tożsamości terminala (`created_ms`) | testy jednostkowe |
|
||||
| Kolejka: odliczanie 3 s + Anuluj, Stop wstrzymuje, Ponów/Edytuj/Usuń, brak podwójnej wysyłki | testy jednostkowe, review |
|
||||
| Historia + Ulubione (panel, wyszukiwanie z podświetleniem, wstawianie w kursor) | GUI: wpis `19.11 11:59 · herdrMario · Ovis Fast`, „kolor” podświetlone |
|
||||
| Jeden potok załączników: Ctrl+V obrazu, Drag & Drop, „+” (PowerShell), limit 32 MiB fail-closed, Base64 do PowerShell | GUI: kafelek + miniatura |
|
||||
| Obraz rzeczywiście dociera do agenta | GUI end-to-end: Claude Code przeczytał PNG i odpowiedział „Pomarańczowy.” |
|
||||
| Testy | `npm test`: 143/143 |
|
||||
|
||||
## Niezależny review
|
||||
Każde zadanie: review spec + jakość, rundy poprawek, re-review. Review całej gałęzi (Opus): „With fixes” → jedna fala poprawek (9/9 zaadresowane).
|
||||
|
||||
## Otwarte (świadomie nienaprawione)
|
||||
1. ~~**Important:** odpowiedź do agenta `blocked`, gdy w kolejce są wpisy, trafia do kolejki zamiast iść od razu z `--force` (regresja z ostatniej fali). Poprawka jednoliniowa w `finish()`: `busy = draining || (mode !== "now" && status !== "blocked" && queueBlocksDirectSend(...))`. Obejście: Ctrl+Enter.~~ **Naprawione (e6afb3e), test `directSendBlocked`.**
|
||||
2. Nie sprawdzone w GUI: odpowiedź na pytanie agenta w stanie `blocked`, Drag & Drop, dialog „+”, przełączanie agentów w trakcie pisania.
|
||||
3. Drobne (lista w ledgerze): `addFiles` cicho porzuca pliki po zmianie agenta; `install.ps1` przerywa, gdy brak `herdr-app` w PATH. (Blok composera dopasowuje się do treści — naprawione w 406f00f.)
|
||||
|
||||
## Rekompilacja
|
||||
Nie była potrzebna. Zmiany poza repo: junction `mods\ovis-composer`, `layouts\ovis-composer.json`, wpis `ctrl-shift-space` w `keys.json` (kopie `.bak-20261119`). Wycofanie: `scripts\install.ps1 -Uninstall`.
|
||||
|
||||
## Ryzyka utrzymania
|
||||
- Herdr nie przeładowuje moda po zmianach za junction → `install.ps1 -Reload`.
|
||||
- Aktualizacja Herdr może zmienić API modów → `herdr-app check` po aktualizacji.
|
||||
- Ukrycie pola wpisywania w TUI agenta niemożliwe bez rekompilacji (decyzja A).
|
||||
@@ -0,0 +1,201 @@
|
||||
# herdr-composer
|
||||
|
||||
A message bar under the terminal. The person types to the focused agent in one
|
||||
field that is theirs: the text survives switching agents and restarting Herdr, a
|
||||
message sent while the agent works waits for its turn and goes out on its own, files
|
||||
and images are dropped, picked or pasted in, and everything sent can be found again
|
||||
(and starred) in a History | Favourites panel. The terminal underneath only shows.
|
||||
|
||||

|
||||
|
||||
It is a layout (a clone of `main`, Herdr 0.1.16) plus one mod. It descends from the
|
||||
`ovis-composer` mod of this repo; the UX is inspired by Ovis (devswha/ovis).
|
||||
|
||||
## What you see
|
||||
|
||||
The window is the `main` layout with one block added. Left to right, top to bottom:
|
||||
|
||||
- **Sidebar**, 268 px, `chrome` background: brand row (46 px), the Spaces list and the
|
||||
Agents list (equal weight, 90 px minimum), the footer (69 px).
|
||||
- **Work column** (resizable): tabs (42 px), then the body (8 px padding, 8 px gap): the
|
||||
terminal pane of the active tab and, on the right, a 368 px panel (280-900 px) with
|
||||
Files and Changes; then **the composer block**; then the status bar (28 px).
|
||||
- **The composer block** starts at 150 px layout height (120-520) and is as tall as its
|
||||
content (see Watch out); its content sits at the bottom edge, 8 px padding, 6 px gap.
|
||||
Top to bottom, only what applies is drawn:
|
||||
1. the suggestion menu (rounded 10, `popover` background, a list 118 px high, groups
|
||||
in 10 px `dim` type, one row per command or file);
|
||||
2. the queue: one row per waiting message (a 7 px colored dot, the text, a state
|
||||
label, buttons);
|
||||
3. the question about an image for a program that may not take it;
|
||||
4. a notice line (11.5 px; `dim`, or `blocked` red for problems);
|
||||
5. **the card** (rounded 12, 1 px `border`, `raised` background): attachment tiles
|
||||
(44 px high: 36 px thumbnail or extension, name, size or reason, "Ponów", x), the
|
||||
field (`background`, rounded 8, 13 px, 1 to 10 rows), and a row of controls: three
|
||||
28 px round buttons `+`, a clock, a star; a 1x18 px divider; **the dock** (flexible,
|
||||
28 px high, scrolls sideways: one 28 px button per saved text, rounded 8, 12 px; a
|
||||
send button on `chrome`, an insert button with a 1 px dashed `border` and a `✎`
|
||||
prefix; empty: "Prawy klik w Ulubionych → Przypnij do docka" in `dim`); the agent pill (rounded 12:
|
||||
a 7 px status dot, the tab's name, the status word, a paperclip and the count when
|
||||
files are attached); and a 32 px round button, a white arrow to send, or a white
|
||||
square (Stop) when the field is empty and the agent works;
|
||||
6. the strip: `space · folder · branch` left (11 px, `dim`), `N / 20000` right
|
||||
(red `Limit 20000 znaków · N za dużo` when over).
|
||||
- **The panel** (Ctrl+R or the clock) covers the whole block (6 px inset, rounded 12,
|
||||
`popover` background): the header (tabs "Historia N" and "Ulubione N", a 30 px search
|
||||
field with a magnifier, a 28 px close x), the list (rows 56 px: the text in two lines
|
||||
with the match lit, a line `DD.MM HH:MM · space · tab`, a star), the footer with the keys.
|
||||
While it is open a block lower than 320 px is made 360 px tall and goes back when it closes.
|
||||
- **The preview** of an image (click a thumbnail): a dark scrim over the block, the image,
|
||||
`name · size · Esc zamyka`.
|
||||
|
||||
Polish is the language of every text of the mod.
|
||||
|
||||
## How it behaves
|
||||
|
||||
**Status of the agent** (pill dot and word): working "pracuje", blocked "czeka na Ciebie",
|
||||
done "skończył", idle "gotowy" (the dot takes the theme color of the status).
|
||||
|
||||
**Focus follows the click.** The composer never takes the keyboard on its own: the field
|
||||
has it after a click on it or `ctrl-shift-space`; a click in a terminal gives the keys to
|
||||
that terminal. A focus on a terminal that is not an agent: the field is replaced by
|
||||
"Ten terminal nie jest agentem. Wybierz agenta z listy, aby pisać." and the draft is kept.
|
||||
|
||||
**Keys in the field:** Enter sends (the message is trimmed; empty is ignored), Shift+Enter
|
||||
a new line, Ctrl+Enter sends now whatever the status, Alt+Enter queues it held
|
||||
("Wstrzymana — wyślij ręcznie"), Ctrl+R opens the panel, Esc closes the menu or the
|
||||
panel and otherwise, with an empty field and a working agent, stops the agent
|
||||
(`hc interrupt`; the queue is held and nothing goes out on its own). Up/Down/Tab move
|
||||
and accept in the suggestion menu; without a menu Up/Down move the cursor between lines.
|
||||
|
||||
**Sending.** Idle or done: out at once (a green check on the send button for 1.5 s). Blocked: out at once with
|
||||
`--force` (an answer), ahead of the queue. Working: into the queue ("Następna tura"). When
|
||||
the turn ends (working or blocked, then idle or done) the first queued message counts
|
||||
down "Wysyłam za 3 s" (button "Anuluj" holds it) and goes out; the next waits for the
|
||||
next turn. One message per turn. A message that goes while another is queued or counting
|
||||
waits at the end of the queue. Queue rows: "Wyślij teraz" (held), "Ponów" (an unconfirmed
|
||||
one), "Edytuj" (back into the field at the caret), "Usuń". After a restart a message that
|
||||
was on the wire is "Nie potwierdzono" and is never sent again on its own.
|
||||
|
||||
**Drafts.** Per agent (the key is the address, `t2`), written 500 ms after the last change
|
||||
and at once when the agent changes; text, caret, attachments. The identity of the terminal
|
||||
(`created_ms` from `hc get`) is stored with it: when the address now belongs to another
|
||||
terminal the draft comes back with "Szkic z poprzedniej sesji agenta" and the whole queue
|
||||
is held.
|
||||
|
||||
**Suggestions.** `/` at the start of a line: the built-in commands of the agent
|
||||
(`claude-code`, `codex`, ...), the project's `.claude/commands/*.md` and
|
||||
`.claude/skills/*/SKILL.md`, ranked by use; `@`: the project's files (`git ls-files`).
|
||||
|
||||
**Attachments.** One pipeline for a drop, the `+` button (a file dialog) and Ctrl+V (an
|
||||
image or copied files; text pastes as text): checked (32 MiB a file, 100 a message, no
|
||||
folders), a tile "dodawanie...", `hc put <agent> <file>`, then ready and `@path` goes
|
||||
into the text - the path the agent sees, in quotes when it has a space. Pasted images are
|
||||
saved in `data/herdr-composer/paste/` (removed after 7 days). An image for a program
|
||||
other than `claude-code`, `codex`, `gemini`, `opencode` asks first ("Anuluj" / "Wyślij mimo to").
|
||||
|
||||
**History and favourites.** Every message that `hc send` accepted is stored (500, newest
|
||||
first, any space or agent). In the panel: type to search (case-insensitive, Polish letters
|
||||
too), Up/Down, Enter inserts at the caret the field had when the panel opened and sends
|
||||
nothing, Tab switches tab, Ctrl+D stars a row at once, a right click opens a menu (Wstaw,
|
||||
Dodaj do ulubionych / Usuń z ulubionych; in Favourites also Przypnij do docka / Odepnij
|
||||
z docka), Esc or the x closes. The star next to the field stars the text in it (100
|
||||
favourites); a right click on it pins the text to the dock.
|
||||
|
||||
**Dock.** A row of buttons in the bar, one dock for every agent (30 at most). A click on a
|
||||
send button sends its text the way Enter does (queue, countdown, `--force` when blocked)
|
||||
and leaves the field, the draft and the files alone; an insert button puts its text at
|
||||
the caret. A right click on a button: Zmień nazwę (in place: Enter keeps, Esc drops; an
|
||||
empty name falls back to the first 15 characters + "…"), Tylko wstawiaj / Wysyłaj od
|
||||
razu, Przesuń w lewo / w prawo, Usuń z docka. Without an agent the buttons are dimmed.
|
||||
|
||||
## Built from
|
||||
|
||||
**Layout** `layouts/herdr-composer.json`, a clone of `main` (`cloned_from` 0.1.16), `canvas`
|
||||
background, no title bar, 1 px `border` dividers. Tree: `root` (row) > `sidebar` (column,
|
||||
268 px, 44-480, `chrome`; `brand` workspace-chrome 46 px, `sidebar-lists` with `spaces` and
|
||||
`agents`, `sidebar-footer` workspace-chrome `{footer: true}` 69 px) and `work` (column,
|
||||
`resizable: true`; `tabs` 42 px, `work-body` row with `main` and `panel` (368 px, 280-900;
|
||||
a stack of `files` and `changes`), `composer`, `status` workspace-status 28 px). The block
|
||||
`composer`: `content: {mod: "herdr-composer"}`, `size: {px: 150}`, `min: 120`, `max: 520`,
|
||||
a `focus` border in `accent`.
|
||||
|
||||
**Mod** `mods/herdr-composer/` (`mod.json`: `place: none`, `focusable: true`): `main.js` (the
|
||||
view), `state.js` (drafts, attachments, queue; pure), `delivery.js` (sending, the gate,
|
||||
countdown rules), `storage.js` (the shared store, migration from `ovis-composer.*`),
|
||||
`history.js`, `attachments.js`, `clipboard.js`, `suggest.js`, `catalog.js`, `profiles.js` (agent profiles), `keys.js`,
|
||||
`dock.js` (the dock and its menus; pure), `view.js` (helpers), `panel.js` (the panel and the preview). The pure modules import nothing
|
||||
from Herdr and are tested with Node (`npm test`).
|
||||
|
||||
**Herdr API:** `agents`, `panes`, `focused`, `theme`, `settings` (`zoom`), `appHome`,
|
||||
`shared`/`setShared` (the store: `herdr-composer.history`, `.favorites`, `.usage`,
|
||||
`.userMin`, `.dock`, `.draft:<address>`, `.queue:<address>`), `notify` (toast, only for a failed
|
||||
send or `hc` call), `nextCommand`, `run("layout.resize", {id: "composer", px})`,
|
||||
`cx.bind_keys` in the context `herdr-composer > Input` (up, down, tab, ctrl-r,
|
||||
ctrl-enter, alt-enter, escape), `fs/promises` (the paste folder), gpui-kit and gpui-base
|
||||
(`v_flex`, `h_flex`, `Textarea`, `Input`, `v_virtual_list`, `Scrollbar`, `image`,
|
||||
`on_size_change`, `on_drop`, the `paste_other` event of the textarea).
|
||||
|
||||
**`keys.json`:** `global` `ctrl-shift-space` -> `herdr-composer.focus`.
|
||||
|
||||
**Programs it runs - say this before installing:**
|
||||
- `powershell -NoProfile -STA -Command ...` (`exec`): reads the clipboard (files, an
|
||||
image saved as PNG), shows the file dialog, measures the files dropped or picked. Every
|
||||
path goes in as Base64 of UTF-8, never as text of the script.
|
||||
- `hc` (herdr-core): `hc send --json [--force] <terminal> -- <text>`, `hc put <terminal>
|
||||
<file> --json`, `hc get <terminal> --json`, `hc interrupt <terminal> --json`.
|
||||
- `git ls-files` and, for the `/` menu, `sh` or `powershell` reading
|
||||
`.claude/commands/*.md` and `.claude/skills/*/SKILL.md` in the agent's folder.
|
||||
|
||||
**Files outside its own folder:** the files the person drops, picks or copies (to attach
|
||||
them), the agent's project folder (the lists above), `data/herdr-composer/paste/`.
|
||||
It makes no network request.
|
||||
|
||||
**Art:** none; the glyphs `+`, a clock, a star, `x`, a magnifier, a paperclip are text.
|
||||
|
||||
## Watch out
|
||||
|
||||
- `hc send` reads a message that starts with `-` as an option unless the text is after
|
||||
`--`. Always send `["send", "--json", terminal, "--", text]`.
|
||||
- `--force` only for the person's own Enter to a blocked agent, never from the queue.
|
||||
- The block reports its size in logical pixels (layout px times `settings().zoom`);
|
||||
`layout.resize` wants layout px. Divide by the zoom or the block grows by the zoom factor.
|
||||
- The block's height: the content's, floored at the height the person dragged the border
|
||||
to (`herdr-composer.userMin`), 120-520, resized after 120 ms and only for a difference
|
||||
over 4 px; the panel pauses it.
|
||||
- Row handlers cannot live inside a `v_virtual_list` renderer: a row click uses
|
||||
`on_item_click`; the star in a panel row is found by where `on_mouse_down` on the list landed (STAR_ZONE, right edge). Ctrl+D or a right click toggle it too.
|
||||
- `image()` draws only files inside the app's folder (give it the path relative to
|
||||
`appHome()`): thumbnails exist for pasted images; an image from elsewhere gets a tile
|
||||
with its extension and no preview.
|
||||
- The textarea binds the arrows and Tab and eats them; the composer binds the same keys
|
||||
itself in `herdr-composer > Input`. An open panel takes them first, whoever has the keyboard.
|
||||
- Whether Ctrl+Z undoes an insert from the panel is not verified; the notice does not promise it.
|
||||
- A mod copy is loaded once: after an update Herdr must see changed files (`install.cmd`
|
||||
copies them, so it reloads the mod).
|
||||
- Windows only: the clipboard, the `+` dialog and the file sizes use PowerShell.
|
||||
- Limits: 20 000 characters a message, 32 MiB a file, 100 files a message, history 500,
|
||||
favourites 100, the dock 30 buttons, the menu shows 20 rows.
|
||||
- The layout is a clone: it keeps the look of `main` as of 0.1.16 and does not follow later
|
||||
changes of `main`.
|
||||
- Data kept under `ovis-composer.*` by the earlier name is read when the new key is empty
|
||||
and written under `herdr-composer.*`; the old keys stay.
|
||||
|
||||
## Done when
|
||||
|
||||
- `herdr-app check mods/herdr-composer` passes and `herdr-app status` shows no errors with
|
||||
the layout `herdr-composer` shown.
|
||||
- Typing in the field, switching to another agent and back, restarting Herdr: the text and
|
||||
the caret are back for each agent.
|
||||
- Enter to an idle agent sends; to a working one queues, and after the turn a 3-second
|
||||
countdown with "Anuluj" precedes the send; Stop empties nothing but holds the queue.
|
||||
- Enter to a blocked agent sends at once.
|
||||
- A message starting with `- ` or `--help` is delivered as text.
|
||||
- Ctrl+V of a screenshot gives a tile and an `@path`; the agent can read the image.
|
||||
- Ctrl+R opens the panel with the sent messages; search lights the match; Enter inserts at
|
||||
the caret and sends nothing; Esc closes it and the block returns to its height.
|
||||
- Ctrl+Shift+Space focuses the field; clicking a terminal gives that terminal the keys.
|
||||
- A right click on a Favourites row pins it to the dock; a click on the button sends it
|
||||
and leaves the draft; a right click on the button renames, moves, switches the mode and
|
||||
removes it; the dock survives a reload.
|
||||
- `npm test` passes.
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"global": {
|
||||
"ctrl-shift-space": "herdr-composer.focus"
|
||||
}
|
||||
}
|
||||
@@ -160,7 +160,7 @@
|
||||
"id": "composer",
|
||||
"type": "block",
|
||||
"size": {
|
||||
"px": 260
|
||||
"px": 150
|
||||
},
|
||||
"min": 120,
|
||||
"max": 520,
|
||||
@@ -171,7 +171,7 @@
|
||||
}
|
||||
},
|
||||
"content": {
|
||||
"mod": "ovis-composer"
|
||||
"mod": "herdr-composer"
|
||||
}
|
||||
},
|
||||
{
|
||||
File renamed without changes.
@@ -0,0 +1,627 @@
|
||||
// catalog.js - where the composer's suggestions come from.
|
||||
//
|
||||
// The workspace is reached only through the injected `exec` (the mod's
|
||||
// `herdr.exec`), so this module runs in plain Node (tests/suggest.test.mjs)
|
||||
// with a fake runner. It has no clock and no storage of its own: the view
|
||||
// reads the person's snippets and passes them in, and it schedules the retry
|
||||
// and the debounce with the numbers exported here.
|
||||
//
|
||||
// Sources for `/`: the profile of the agent (profiles.js) says which are
|
||||
// read - its built-in commands, the folders of the project and of the home
|
||||
// folder with its own commands, the plugins - and the person's snippets and
|
||||
// the commands sent to this agent before (the history) come on top. An agent
|
||||
// with no profile gets only the snippets and the history, and nothing is
|
||||
// read for it. One source for `@`: the files git tracks in the pane's folder.
|
||||
//
|
||||
// A read that fails is not an empty list: the failure is reported through
|
||||
// `onReadError` and the menu keeps what it knows. A caller with no handler
|
||||
// gets the failure itself - nobody may mistake a broken catalog for one
|
||||
// with nothing to show. An empty list without a failure means the catalog
|
||||
// was read and nothing fit.
|
||||
|
||||
import {
|
||||
GROUP_BUILTIN,
|
||||
GROUP_PROJECT,
|
||||
GROUP_USER,
|
||||
GROUP_PLUGIN,
|
||||
GROUP_HISTORY,
|
||||
rank,
|
||||
} from "./suggest.js";
|
||||
import { decode } from "./powershell.js";
|
||||
|
||||
/**
|
||||
* @typedef {import("./suggest.js").Item} Item
|
||||
*
|
||||
* @typedef {object} ExecResult
|
||||
* @property {number} code
|
||||
* @property {string} stdout
|
||||
* @property {string} stderr
|
||||
*
|
||||
* @typedef {(command:string, args?:string[], options?:{cwd?:string}) => Promise<ExecResult>} Exec
|
||||
*/
|
||||
|
||||
/** How long the composer waits before it asks the workspace again. */
|
||||
export const DEBOUNCE_MS = 150;
|
||||
|
||||
/** The waits between the tries after a read failed: 2 s, 5 s, 15 s, 30 s. */
|
||||
export const RETRY_DELAYS = [2000, 5000, 15000, 30000];
|
||||
|
||||
/** The catalog could not be read - the person may keep typing. */
|
||||
export const READ_ERROR_MESSAGE =
|
||||
"Nie udało się wczytać podpowiedzi. Pisz dalej, spróbujemy ponownie.";
|
||||
|
||||
/** The catalog was read and nothing fit the needle. */
|
||||
export const NO_MATCH_MESSAGE = "Żadna komenda nie pasuje. Zmień słowo albo pisz dalej.";
|
||||
|
||||
/** The same, for the files of an `@`. */
|
||||
export const NO_FILE_MATCH_MESSAGE = "Żaden plik nie pasuje. Zmień słowo albo pisz dalej.";
|
||||
|
||||
export { BUILTINS } from "./profiles.js";
|
||||
|
||||
/** How many files the `@` menu shows at most. */
|
||||
const FILE_LIMIT = 20;
|
||||
|
||||
/** One command: a `/` and a name that holds no space and no path separator. */
|
||||
const HISTORY_COMMAND = /^\/[A-Za-z0-9][\w:.-]*$/;
|
||||
|
||||
/** The message of a pane whose agent has no profile. */
|
||||
export function unknownAgentMessage(agent) {
|
||||
return `Nieznany agent \`${agent}\` – dodaj profil w ~/.config/herdr-app/composer-agents.json`;
|
||||
}
|
||||
|
||||
/** The message about a `composer-agents.json` that could not be read whole. */
|
||||
export function profileProblemMessage(problem) {
|
||||
return `\`composer-agents.json\`: ${problem}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The grey rows under the items of the `/` menu: the agent has no profile
|
||||
* (once the file of the profiles was read - before that we do not know yet)
|
||||
* and the file of the profiles could not be read whole. They cannot be picked.
|
||||
*
|
||||
* @param {{profile:object|null, agent:string, profilesLoaded:boolean, problem:string|null}} state
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function menuNotes({ profile, agent, profilesLoaded, problem }) {
|
||||
const notes = [];
|
||||
if (!profile && profilesLoaded) notes.push(unknownAgentMessage(agent));
|
||||
if (problem) notes.push(profileProblemMessage(problem));
|
||||
return notes;
|
||||
}
|
||||
|
||||
/**
|
||||
* The listing with a POSIX shell, for the project and for the home folder:
|
||||
* the arguments come in threes - the index of the spec, its kind (`file`,
|
||||
* `md` or `skills`) and its path - and every file found is written as
|
||||
* `index<TAB>path`.
|
||||
*/
|
||||
const LIST_SH =
|
||||
'while [ $# -ge 3 ]; do i=$1; k=$2; p=$3; shift 3; case "$k" in ' +
|
||||
'file) [ -f "$p" ] && printf \'%s\\t%s\\n\' "$i" "$p";; ' +
|
||||
'md) for f in "$p"/*.md; do [ -f "$f" ] && printf \'%s\\t%s\\n\' "$i" "$f"; done;; ' +
|
||||
'skills) for f in "$p"/*/SKILL.md; do [ -f "$f" ] && printf \'%s\\t%s\\n\' "$i" "$f"; done;; ' +
|
||||
"esac; done; exit 0";
|
||||
|
||||
/** Reading one file with a POSIX shell. */
|
||||
const READ_SH = 'cat -- "$1"';
|
||||
|
||||
/**
|
||||
* How long to wait before the next try after a read failed. The last wait
|
||||
* repeats: the composer keeps trying every 30 s until the catalog is read.
|
||||
*
|
||||
* @param {number} attempt - 0 for the first wait
|
||||
* @returns {number} milliseconds
|
||||
*/
|
||||
export function retryDelay(attempt) {
|
||||
const index = Number.isFinite(attempt) ? Math.max(0, Math.floor(attempt)) : 0;
|
||||
return RETRY_DELAYS[Math.min(index, RETRY_DELAYS.length - 1)];
|
||||
}
|
||||
|
||||
/**
|
||||
* The commands the `/` menu offers, in this order: the built-ins of the
|
||||
* profile, the project sources of the profile (read with `exec` in `cwd`),
|
||||
* the global ones (`options.global`, read by `globalCommands`), the snippets
|
||||
* and the history (`historyCommands`). A name is offered once: the first
|
||||
* source that has it wins. Without a profile only the snippets and the
|
||||
* history are offered, and nothing is read (no `exec`).
|
||||
*
|
||||
* A source that cannot be read does not take the others with it: the menu
|
||||
* shows what is known and the failure goes to `onReadError`, so the caller
|
||||
* can tell a catalog it could not read from one with nothing to show.
|
||||
* Without a handler the call rejects - the failure is never swallowed.
|
||||
*
|
||||
* @param {string} cwd - the folder of the pane
|
||||
* @param {Exec} exec
|
||||
* @param {{profile?:object|null, snippets?:object[], global?:Item[], history?:Item[], onReadError?:(error:Error) => void}} [options]
|
||||
* @returns {Promise<Item[]>}
|
||||
*/
|
||||
export async function commands(cwd, exec, options = {}) {
|
||||
const profile = options.profile ?? null;
|
||||
const snippets = snippetItems(options.snippets);
|
||||
const history = Array.isArray(options.history) ? options.history : [];
|
||||
|
||||
// An agent we know nothing about: nothing to read.
|
||||
if (!profile) return dedupe([...snippets, ...history]);
|
||||
|
||||
const builtins = builtinItems(profile);
|
||||
|
||||
let project = [];
|
||||
try {
|
||||
project = await projectItems(cwd, exec, profile.sources);
|
||||
} catch (err) {
|
||||
// Nobody to tell: the caller gets the failure instead of a list that
|
||||
// looks empty - an empty list would say "nothing fits" and the caller
|
||||
// would never try again.
|
||||
if (options.onReadError) options.onReadError(err);
|
||||
else throw err;
|
||||
}
|
||||
|
||||
const global = Array.isArray(options.global) ? options.global : [];
|
||||
|
||||
return dedupe([...builtins, ...project, ...global, ...snippets, ...history]);
|
||||
}
|
||||
|
||||
/** A name is offered once: the first source that has it wins. */
|
||||
function dedupe(items) {
|
||||
const seen = new Set();
|
||||
const out = [];
|
||||
for (const item of items) {
|
||||
if (seen.has(item.key)) continue;
|
||||
seen.add(item.key);
|
||||
out.push(item);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The commands that were sent to this agent before: the first word of every
|
||||
* message of the history that starts with a `/` and is a command name (not a
|
||||
* path such as /c/Users/x). The newest come first.
|
||||
*
|
||||
* @param {{text?:string, agentName?:string, sentAt?:number}[]} history
|
||||
* @param {string} agent - `agentName()` of the pane
|
||||
* @returns {Item[]}
|
||||
*/
|
||||
export function historyCommands(history, agent) {
|
||||
const name = String(agent ?? "").trim().toLowerCase();
|
||||
if (!Array.isArray(history)) return [];
|
||||
|
||||
const entries = history
|
||||
.filter((entry) => String(entry?.agentName ?? "").trim().toLowerCase() === name)
|
||||
.sort((a, b) => (Number(b.sentAt) || 0) - (Number(a.sentAt) || 0));
|
||||
|
||||
const seen = new Set();
|
||||
const items = [];
|
||||
for (const entry of entries) {
|
||||
const token = String(entry.text ?? "").trimStart().split(/\s/, 1)[0];
|
||||
if (!HISTORY_COMMAND.test(token)) continue;
|
||||
const key = token.slice(1);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
items.push({ key, desc: "", group: GROUP_HISTORY, insert: `/${key} ` });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* The commands that live in the person's `~/.claude`: their own commands and
|
||||
* skills, and those of the plugins that `settings.json` switches on.
|
||||
*
|
||||
* Reads the two JSON files and the `plugin.json` of every enabled plugin
|
||||
* with `readText` (a missing or broken file is an empty source), lists the
|
||||
* files in one `exec`, reads each of them with `readText`. A listing that
|
||||
* fails goes to `onReadError` - without a handler the call rejects.
|
||||
*
|
||||
* @param {string} home - the person's home folder
|
||||
* @param {Exec} exec
|
||||
* @param {(path:string) => Promise<string|null>} readText
|
||||
* @param {{sources?:object[], onReadError?:(error:Error) => void}} [options]
|
||||
* `sources`: the sources of the profile; only the ones of the `home` scope
|
||||
* are read, and none of them means nothing is read
|
||||
* @returns {Promise<Item[]>}
|
||||
*/
|
||||
export async function globalCommands(home, exec, readText, options = {}) {
|
||||
const root = slashes(home).replace(/\/+$/, "");
|
||||
const claude = `${root}/.claude`;
|
||||
const sources = (Array.isArray(options.sources) ? options.sources : []).filter(
|
||||
(source) => source?.scope === "home",
|
||||
);
|
||||
|
||||
/** @type {{kind:"file"|"md"|"skills", path:string, plugin:string|null, prefix:string}[]} */
|
||||
const specs = [];
|
||||
|
||||
for (const source of sources) {
|
||||
if (source.kind === "claude-plugins") {
|
||||
const settings = await readJson(readText, `${claude}/settings.json`);
|
||||
const installed = await readJson(readText, `${claude}/plugins/installed_plugins.json`);
|
||||
const enabled =
|
||||
settings && typeof settings.enabledPlugins === "object" ? settings.enabledPlugins : {};
|
||||
|
||||
for (const [id, on] of Object.entries(enabled ?? {})) {
|
||||
if (on !== true) continue;
|
||||
const entries = installed?.plugins?.[id];
|
||||
const installPath = Array.isArray(entries) ? entries[0]?.installPath : null;
|
||||
if (typeof installPath !== "string" || installPath === "") continue;
|
||||
|
||||
const base = slashes(installPath).replace(/\/+$/, "");
|
||||
const name = id.split("@")[0];
|
||||
const manifest = await readJson(readText, `${base}/.claude-plugin/plugin.json`);
|
||||
specs.push(...pluginSpecs(base, name, manifest).map((spec) => ({ ...spec, prefix: "/" })));
|
||||
}
|
||||
} else {
|
||||
specs.push({
|
||||
kind: source.pattern === "*/SKILL.md" ? "skills" : "md",
|
||||
path: `${root}/${source.path}`,
|
||||
plugin: null,
|
||||
prefix: source.prefix ?? "/",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Nothing to look at: no `exec` either.
|
||||
if (specs.length === 0) return [];
|
||||
|
||||
let listed = [];
|
||||
try {
|
||||
listed = (await listFiles(exec, specs)).found;
|
||||
} catch (err) {
|
||||
if (options.onReadError) options.onReadError(err);
|
||||
else throw err;
|
||||
return [];
|
||||
}
|
||||
|
||||
const items = [];
|
||||
for (const { index, path } of listed) {
|
||||
const spec = specs[index];
|
||||
if (!spec) continue;
|
||||
const text = await readText(path);
|
||||
if (text === null || text === undefined) continue;
|
||||
|
||||
const { fields } = frontmatter(String(text));
|
||||
if (fields["user-invocable"] === "false") continue;
|
||||
|
||||
const own = commandName(path);
|
||||
const isSkill = path.toLowerCase().endsWith("/skill.md");
|
||||
const name = isSkill && fields.name ? fields.name : own;
|
||||
if (!name) continue;
|
||||
|
||||
const key = spec.plugin ? `${spec.plugin}:${name}` : name;
|
||||
items.push({
|
||||
key,
|
||||
desc: describe(text),
|
||||
group: spec.plugin ? GROUP_PLUGIN : GROUP_USER,
|
||||
insert: `${spec.prefix}${key} `,
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** Backslashes of a Windows path become slashes. */
|
||||
function slashes(path) {
|
||||
return String(path).replace(/\\/g, "/");
|
||||
}
|
||||
|
||||
/** A JSON file, or `null` when it is missing or broken. */
|
||||
async function readJson(readText, path) {
|
||||
try {
|
||||
const text = await readText(path);
|
||||
if (text === null || text === undefined) return null;
|
||||
return JSON.parse(String(text).replace(/^\uFEFF/, ""));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a plugin keeps its commands. `skills` and `commands` of its
|
||||
* `plugin.json` may be a list of paths (a skill's folder or a `.md` file), a
|
||||
* folder to look through, or missing (the default folders).
|
||||
*/
|
||||
function pluginSpecs(base, plugin, manifest) {
|
||||
const join = (rel) => `${base}/${String(rel).replace(/^\.\//, "").replace(/\/+$/, "")}`;
|
||||
const out = [];
|
||||
|
||||
const skills = manifest?.skills;
|
||||
if (skills === undefined || skills === null) {
|
||||
out.push({ kind: "skills", path: join("skills"), plugin });
|
||||
} else if (typeof skills === "string") {
|
||||
out.push({ kind: "skills", path: join(skills), plugin });
|
||||
} else if (Array.isArray(skills)) {
|
||||
for (const rel of skills) {
|
||||
if (typeof rel !== "string") continue;
|
||||
const path = join(rel);
|
||||
out.push({ kind: "file", path: /\.md$/i.test(path) ? path : `${path}/SKILL.md`, plugin });
|
||||
}
|
||||
}
|
||||
|
||||
const cmds = manifest?.commands;
|
||||
if (cmds === undefined || cmds === null) {
|
||||
out.push({ kind: "md", path: join("commands"), plugin });
|
||||
} else if (typeof cmds === "string") {
|
||||
const path = join(cmds);
|
||||
out.push({ kind: /\.md$/i.test(path) ? "file" : "md", path, plugin });
|
||||
} else if (Array.isArray(cmds)) {
|
||||
for (const rel of cmds) {
|
||||
if (typeof rel !== "string") continue;
|
||||
const path = join(rel);
|
||||
out.push({ kind: /\.md$/i.test(path) ? "file" : "md", path, plugin });
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The files the `@` menu offers: the ones git tracks in the pane's folder.
|
||||
*
|
||||
* The best matches come first and only then are they cut to twenty - a file
|
||||
* that fits is never hidden behind twenty names that do not. Without a
|
||||
* handler the call rejects when git fails.
|
||||
*
|
||||
* @param {string} cwd - the folder of the pane
|
||||
* @param {Exec} exec
|
||||
* @param {{needle?:string, limit?:number, onReadError?:(error:Error) => void}} [options]
|
||||
* @returns {Promise<Item[]>}
|
||||
*/
|
||||
export async function files(cwd, exec, options = {}) {
|
||||
const needle = String(options.needle ?? "").toLowerCase();
|
||||
const limit = Number.isFinite(options.limit) ? options.limit : FILE_LIMIT;
|
||||
|
||||
let paths = [];
|
||||
try {
|
||||
paths = await gitFiles(cwd, exec);
|
||||
} catch (err) {
|
||||
// Nobody to tell: the caller gets the failure instead of an empty list
|
||||
// that would say "nothing fits".
|
||||
if (options.onReadError) options.onReadError(err);
|
||||
else throw err;
|
||||
}
|
||||
|
||||
const items = paths.map((path) => ({ key: path, desc: "", insert: `@${path} ` }));
|
||||
return rank(items, needle, { atLineStart: true }).slice(0, limit);
|
||||
}
|
||||
|
||||
/** The built-in commands of a profile. */
|
||||
function builtinItems(profile) {
|
||||
return (profile.builtins ?? []).map((item) => ({
|
||||
key: item.key,
|
||||
desc: item.desc ?? "",
|
||||
group: GROUP_BUILTIN,
|
||||
insert: `/${item.key} `,
|
||||
}));
|
||||
}
|
||||
|
||||
/** The commands the project has, as the project sources of the profile say. */
|
||||
async function projectItems(cwd, exec, sources) {
|
||||
const specs = (Array.isArray(sources) ? sources : [])
|
||||
.filter((source) => source?.scope === "project" && !source.kind)
|
||||
.map((source) => ({
|
||||
kind: source.pattern === "*/SKILL.md" ? "skills" : "md",
|
||||
path: source.path,
|
||||
prefix: source.prefix ?? "/",
|
||||
}));
|
||||
// Nothing to look at: no `exec` either.
|
||||
if (specs.length === 0) return [];
|
||||
|
||||
const { shell, found } = await listFiles(exec, specs, { cwd, shellFirst: true, relative: true });
|
||||
|
||||
const items = [];
|
||||
for (const { index, path } of found) {
|
||||
const spec = specs[index];
|
||||
if (!spec) continue;
|
||||
const name = commandName(path);
|
||||
if (!name) continue;
|
||||
const text = await readFile(cwd, exec, path, shell);
|
||||
if (text === null) continue;
|
||||
items.push({
|
||||
key: name,
|
||||
desc: describe(text),
|
||||
group: GROUP_PROJECT,
|
||||
insert: `${spec.prefix}${name} `,
|
||||
});
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** The person's own snippets, as the view read them from the storage. */
|
||||
function snippetItems(snippets) {
|
||||
if (!Array.isArray(snippets)) return [];
|
||||
|
||||
const items = [];
|
||||
for (const snippet of snippets) {
|
||||
const key = String(snippet?.key ?? snippet?.name ?? "").trim();
|
||||
if (!key) continue;
|
||||
const item = {
|
||||
key,
|
||||
desc: String(snippet?.desc ?? snippet?.description ?? ""),
|
||||
group: GROUP_USER,
|
||||
insert: `/${key} `,
|
||||
};
|
||||
if (Number.isFinite(snippet?.uses)) item.uses = snippet.uses;
|
||||
items.push(item);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* The files of the specs, listed by one `exec`. For the home folder it is
|
||||
* PowerShell first (the machine this mod is made for) and a POSIX shell after
|
||||
* it; for the project (`options.shellFirst`) a POSIX shell first - it is what
|
||||
* a Linux or macOS machine has - and PowerShell after it. Neither is there:
|
||||
* the listing could not be read. The paths of the specs reach PowerShell
|
||||
* only as Base64 of a JSON text (`decode`). With `options.relative` the
|
||||
* paths found are relative to `options.cwd`, as the specs are.
|
||||
*
|
||||
* @returns {Promise<{shell:"sh"|"powershell", found:{index:number, path:string}[]}>}
|
||||
*/
|
||||
async function listFiles(exec, specs, options = {}) {
|
||||
const relative = options.relative === true;
|
||||
const psScript =
|
||||
"$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " +
|
||||
`$specs = ConvertFrom-Json (${decode(JSON.stringify(specs.map((spec, i) => ({ i, k: spec.kind, p: spec.path, r: relative }))))}); ` +
|
||||
"foreach ($s in $specs) { $p = $s.p; " +
|
||||
"if ($s.k -eq 'file') { if (Test-Path -LiteralPath $p -PathType Leaf) { \"$($s.i)`t$p\" } } " +
|
||||
"elseif (Test-Path -LiteralPath $p -PathType Container) { " +
|
||||
"if ($s.k -eq 'md') { Get-ChildItem -LiteralPath $p -Filter '*.md' -File | ForEach-Object { " +
|
||||
"$o = if ($s.r) { \"$p/$($_.Name)\" } else { $_.FullName }; \"$($s.i)`t$o\" } } " +
|
||||
"else { Get-ChildItem -LiteralPath $p -Directory | ForEach-Object { $f = Join-Path $_.FullName 'SKILL.md'; " +
|
||||
"if (Test-Path -LiteralPath $f -PathType Leaf) { " +
|
||||
"$o = if ($s.r) { \"$p/$($_.Name)/SKILL.md\" } else { $f }; \"$($s.i)`t$o\" } } } } }";
|
||||
|
||||
const shArgs = ["-c", LIST_SH, "catalog"];
|
||||
specs.forEach((spec, i) => shArgs.push(String(i), spec.kind, spec.path));
|
||||
|
||||
const tries = [
|
||||
["powershell", ["-NoProfile", "-Command", psScript]],
|
||||
["sh", shArgs],
|
||||
];
|
||||
if (options.shellFirst) tries.reverse();
|
||||
|
||||
for (const [command, args] of tries) {
|
||||
let result;
|
||||
try {
|
||||
result = await exec(command, args, options.cwd === undefined ? {} : { cwd: options.cwd });
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (!result || result.code !== 0) continue;
|
||||
|
||||
const found = [];
|
||||
for (const line of String(result.stdout ?? "").split("\n")) {
|
||||
const match = /^(\d+)\t(.+)$/.exec(line.replace(/\r$/, ""));
|
||||
if (match) found.push({ index: Number(match[1]), path: slashes(match[2]).trim() });
|
||||
}
|
||||
return { shell: command, found };
|
||||
}
|
||||
throw new Error(
|
||||
relative ? "nie udało się wczytać katalogu projektu" : "nie udało się wczytać katalogu globalnego",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* One file of the project. The file may be gone between the listing and the
|
||||
* read - then it is left out of the menu, not a reason to fail the catalog.
|
||||
*/
|
||||
async function readFile(cwd, exec, path, kind) {
|
||||
const shells = kind === "sh" ? ["sh", "powershell"] : ["powershell", "sh"];
|
||||
|
||||
for (const shell of shells) {
|
||||
const text = await tryRead(exec, shell, path, cwd);
|
||||
if (text !== null) return text;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** One read, or `null` when the file is not there or cannot be read. */
|
||||
async function tryRead(exec, shell, path, cwd) {
|
||||
const args =
|
||||
shell === "sh"
|
||||
? ["-c", READ_SH, "catalog", path]
|
||||
: ["-NoProfile", "-Command", readScript(path)];
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await exec(shell, args, { cwd });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!result || result.code !== 0) return null;
|
||||
return String(result.stdout ?? "");
|
||||
}
|
||||
|
||||
/**
|
||||
* The PowerShell that reads one file.
|
||||
*
|
||||
* The path comes from a project that may have been cloned from anywhere, and
|
||||
* PowerShell reads U+2018..U+201B as quotes too: the path is never in the
|
||||
* script as text, only as Base64 that the script decodes (`powershell.js`).
|
||||
*
|
||||
* @param {string} path
|
||||
* @returns {string}
|
||||
*/
|
||||
export function readScript(path) {
|
||||
return (
|
||||
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " +
|
||||
// A file that is gone writes nothing and says nothing - the command
|
||||
// would be a ghost. Without the encoding, Windows PowerShell reads a file
|
||||
// without a BOM as the system's own code page, and the text comes out
|
||||
// garbled.
|
||||
`$path = ${decode(path)}; ` +
|
||||
"if (-not (Test-Path -LiteralPath $path)) { exit 1 }; " +
|
||||
"Get-Content -Raw -Encoding utf8 -ErrorAction Stop -LiteralPath $path"
|
||||
);
|
||||
}
|
||||
|
||||
/** The name of the command a file holds: the file's name, or a skill's folder. */
|
||||
function commandName(path) {
|
||||
const parts = path.split("/");
|
||||
const file = parts[parts.length - 1] ?? "";
|
||||
if (file.toLowerCase() === "skill.md") return parts[parts.length - 2] ?? "";
|
||||
return file.replace(/\.md$/i, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* What the menu says about a command: the description of the front matter if
|
||||
* there is one, else the first line that says something.
|
||||
*/
|
||||
function describe(markdown) {
|
||||
const { fields, body } = frontmatter(String(markdown ?? ""));
|
||||
if (fields.description) return clip(fields.description);
|
||||
|
||||
const line = body
|
||||
.split("\n")
|
||||
.map((part) => part.trim())
|
||||
.find((part) => part !== "" && !part.startsWith("#"));
|
||||
return clip(line ?? "");
|
||||
}
|
||||
|
||||
/** The front matter of a markdown file, if it has one. */
|
||||
function frontmatter(text) {
|
||||
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
|
||||
if (!match) return { fields: {}, body: text };
|
||||
|
||||
const fields = {};
|
||||
for (const line of match[1].split(/\r?\n/)) {
|
||||
const field = /^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/.exec(line);
|
||||
if (!field) continue;
|
||||
fields[field[1].toLowerCase()] = field[2].trim().replace(/^["']|["']$/g, "");
|
||||
}
|
||||
return { fields, body: text.slice(match[0].length) };
|
||||
}
|
||||
|
||||
/** One line of text, no longer than the menu has room for. */
|
||||
function clip(text) {
|
||||
const flat = String(text).replace(/\s+/g, " ").trim();
|
||||
if (flat.length <= 160) return flat;
|
||||
return `${flat.slice(0, 160).replace(/\s\S*$/, "")}…`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The files git tracks in the folder. `-z` keeps the names as they are - git
|
||||
* would otherwise write a name with a non-ASCII character in it quoted and
|
||||
* escaped.
|
||||
*/
|
||||
async function gitFiles(cwd, exec) {
|
||||
let result;
|
||||
try {
|
||||
result = await exec("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], {
|
||||
cwd,
|
||||
});
|
||||
} catch (err) {
|
||||
throw new Error(`nie udało się wczytać plików: ${err?.message ?? String(err)}`);
|
||||
}
|
||||
|
||||
if (!result || result.code !== 0) {
|
||||
const stderr = String(result?.stderr ?? "");
|
||||
// A folder that is not a repository has no files to offer - that is an
|
||||
// empty list, not a catalog that could not be read.
|
||||
if (result?.code === 128 && /repo/i.test(stderr)) return [];
|
||||
throw new Error(
|
||||
`nie udało się wczytać plików: ${stderr.trim() || `git zakończone kodem ${result?.code}`}`,
|
||||
);
|
||||
}
|
||||
|
||||
return String(result.stdout ?? "")
|
||||
.split("\0")
|
||||
.map((path) => path.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
+2
-52
@@ -18,6 +18,8 @@
|
||||
// An empty or missing <bytes> means the size could not be read: the caller
|
||||
// does not let such a file through (fail closed).
|
||||
|
||||
import { decode } from "./powershell.js";
|
||||
|
||||
/** How long a pasted image stays in the paste folder. */
|
||||
export const PASTE_MAX_AGE_MS = 7 * 864e5;
|
||||
|
||||
@@ -254,55 +256,3 @@ function toBytes(text) {
|
||||
const value = Number(text);
|
||||
return Number.isFinite(value) && value >= 0 ? value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* PowerShell that yields `text` - without the text itself being in the
|
||||
* script.
|
||||
*
|
||||
* A path or a name comes from the outside, and PowerShell reads more than the
|
||||
* ASCII apostrophe as a quote (U+2018, U+2019, U+201A, U+201B too), so no
|
||||
* quoting is safe enough. The text goes in as Base64 of its UTF-8 bytes - an
|
||||
* alphabet with no quote, no `$`, no space - and is decoded by PowerShell.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {string}
|
||||
*/
|
||||
function decode(text) {
|
||||
return `[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64(utf8(text))}'))`;
|
||||
}
|
||||
|
||||
/** The UTF-8 bytes of a text (a lone surrogate becomes U+FFFD). */
|
||||
function utf8(text) {
|
||||
const bytes = [];
|
||||
for (const char of String(text)) {
|
||||
let code = char.codePointAt(0);
|
||||
if (code >= 0xd800 && code <= 0xdfff) code = 0xfffd;
|
||||
if (code < 0x80) {
|
||||
bytes.push(code);
|
||||
} else if (code < 0x800) {
|
||||
bytes.push(0xc0 | (code >> 6), 0x80 | (code & 63));
|
||||
} else if (code < 0x10000) {
|
||||
bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
|
||||
} else {
|
||||
bytes.push(0xf0 | (code >> 18), 0x80 | ((code >> 12) & 63), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
/** Base64 of bytes (no Buffer, no btoa: the mods do not have to have them). */
|
||||
function base64(bytes) {
|
||||
let out = "";
|
||||
for (let i = 0; i < bytes.length; i += 3) {
|
||||
const a = bytes[i];
|
||||
const b = bytes[i + 1];
|
||||
const c = bytes[i + 2];
|
||||
out += BASE64[a >> 2];
|
||||
out += BASE64[((a & 3) << 4) | ((b ?? 0) >> 4)];
|
||||
out += b === undefined ? "=" : BASE64[((b & 15) << 2) | ((c ?? 0) >> 6)];
|
||||
out += c === undefined ? "=" : BASE64[c & 63];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
+1
-1
@@ -13,7 +13,7 @@
|
||||
// for a plain shell with no agent, and also when it fails. Neither the exit
|
||||
// code nor those fields say whether the agent got the message. Therefore:
|
||||
// - ok:true means "the text was pasted and Enter pressed", NOT "the agent
|
||||
// received it" - the UI says "Wysłano do terminala";
|
||||
// received it" - the UI shows a green check on the send button;
|
||||
// - the only failure is a non-zero exit code (its stderr becomes the notice);
|
||||
// - every `--json` call checks the payload for an "error" field, because `hc`
|
||||
// exits 0 even on error (measured: `hc wait t3 --json` for a missing
|
||||
@@ -0,0 +1,292 @@
|
||||
// dock.js - the model of the dock: the buttons next to the composer that send
|
||||
// or insert a text kept by the person.
|
||||
//
|
||||
// Pure: no gpui-kit, gpui-base or herdr imports. Every function returns a new
|
||||
// list and leaves its input alone. storage.js keeps the list under
|
||||
// `herdr-composer.dock` and runs it through `normalize`.
|
||||
|
||||
/**
|
||||
* @typedef {object} DockButton
|
||||
* @property {string} id
|
||||
* @property {string} label
|
||||
* @property {string} text
|
||||
* @property {"send"|"insert"} mode
|
||||
*
|
||||
* @typedef {object} MenuItem
|
||||
* @property {string} command
|
||||
* @property {string} label
|
||||
* @property {boolean} [disabled]
|
||||
* @property {boolean} [danger]
|
||||
*/
|
||||
|
||||
/** How many buttons the dock holds. */
|
||||
export const DOCK_LIMIT = 30;
|
||||
|
||||
/** The longest default label: 15 characters and an ellipsis. */
|
||||
export const LABEL_MAX = 16;
|
||||
|
||||
const MODES = new Set(["send", "insert"]);
|
||||
|
||||
/**
|
||||
* The label a button gets when the person gave none: the text with white
|
||||
* space folded into single spaces, cut to LABEL_MAX characters.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {string}
|
||||
*/
|
||||
export function defaultLabel(text) {
|
||||
const folded = String(text).replace(/\s+/g, " ").trim();
|
||||
const chars = Array.from(folded);
|
||||
return chars.length > LABEL_MAX ? `${chars.slice(0, LABEL_MAX - 1).join("")}…` : folded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep what is a button: `id` and `text` not empty, a known `mode`. An empty
|
||||
* label becomes the default one. A text that is already there (compared after
|
||||
* `trim()`) is dropped - the first wins - and the list is cut to DOCK_LIMIT.
|
||||
*
|
||||
* @param {unknown} raw
|
||||
* @returns {DockButton[]}
|
||||
*/
|
||||
export function normalize(raw) {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
|
||||
/** @type {DockButton[]} */
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
const ids = new Set();
|
||||
for (const item of raw) {
|
||||
if (out.length >= DOCK_LIMIT) break;
|
||||
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
|
||||
const { id, label, text, mode } = /** @type {Record<string, unknown>} */ (item);
|
||||
if (typeof id !== "string" || id === "") continue;
|
||||
if (typeof text !== "string" || text.trim() === "") continue;
|
||||
if (typeof mode !== "string" || !MODES.has(mode)) continue;
|
||||
const key = text.trim();
|
||||
if (seen.has(key) || ids.has(id)) continue;
|
||||
seen.add(key);
|
||||
ids.add(id);
|
||||
out.push({
|
||||
id,
|
||||
label: typeof label === "string" && label.trim() !== "" ? label.trim() : defaultLabel(text),
|
||||
text,
|
||||
mode: /** @type {"send"|"insert"} */ (mode),
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {DockButton[]} dock
|
||||
* @param {string} text
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isPinned(dock, text) {
|
||||
const key = String(text).trim();
|
||||
return dock.some((button) => button.text.trim() === key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a button at the end. The same dock comes back when the text is empty,
|
||||
* already pinned, or the dock is full.
|
||||
*
|
||||
* @param {DockButton[]} dock
|
||||
* @param {string} text
|
||||
* @param {string} id
|
||||
* @returns {DockButton[]}
|
||||
*/
|
||||
export function pin(dock, text, id) {
|
||||
const clean = String(text).trim();
|
||||
if (clean === "" || isPinned(dock, clean) || dock.length >= DOCK_LIMIT) return dock;
|
||||
return [...dock, { id, label: defaultLabel(clean), text: clean, mode: "send" }];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {DockButton[]} dock
|
||||
* @param {string} text
|
||||
* @returns {DockButton[]}
|
||||
*/
|
||||
export function unpin(dock, text) {
|
||||
const key = String(text).trim();
|
||||
return dock.filter((button) => button.text.trim() !== key);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {DockButton[]} dock
|
||||
* @param {string} id
|
||||
* @returns {DockButton[]}
|
||||
*/
|
||||
export function remove(dock, id) {
|
||||
return dock.filter((button) => button.id !== id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a button one place; at the edge nothing changes.
|
||||
*
|
||||
* @param {DockButton[]} dock
|
||||
* @param {string} id
|
||||
* @param {-1|1} step
|
||||
* @returns {DockButton[]}
|
||||
*/
|
||||
export function move(dock, id, step) {
|
||||
const from = dock.findIndex((button) => button.id === id);
|
||||
const to = from + step;
|
||||
if (from < 0 || to < 0 || to >= dock.length) return [...dock];
|
||||
const out = [...dock];
|
||||
[out[from], out[to]] = [out[to], out[from]];
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* An empty name (after `trim()`) gives the default label back.
|
||||
*
|
||||
* @param {DockButton[]} dock
|
||||
* @param {string} id
|
||||
* @param {string} label
|
||||
* @returns {DockButton[]}
|
||||
*/
|
||||
export function rename(dock, id, label) {
|
||||
const clean = String(label).trim();
|
||||
return dock.map((button) =>
|
||||
button.id === id ? { ...button, label: clean === "" ? defaultLabel(button.text) : clean } : button,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {DockButton[]} dock
|
||||
* @param {string} id
|
||||
* @returns {DockButton[]}
|
||||
*/
|
||||
export function toggleMode(dock, id) {
|
||||
return dock.map((button) =>
|
||||
button.id === id ? { ...button, mode: button.mode === "send" ? "insert" : "send" } : button,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a click on a button does. Sending needs an agent; inserting does not.
|
||||
*
|
||||
* @param {{mode: "send"|"insert"}} button
|
||||
* @param {{hasAgent: boolean}} context
|
||||
* @returns {"send"|"insert"|"none"}
|
||||
*/
|
||||
export function dockAction(button, { hasAgent }) {
|
||||
if (button.mode === "insert") return "insert";
|
||||
return hasAgent ? "send" : "none";
|
||||
}
|
||||
|
||||
/**
|
||||
* The right-click menu of a button.
|
||||
*
|
||||
* @param {DockButton[]} dock
|
||||
* @param {string} id
|
||||
* @returns {MenuItem[]}
|
||||
*/
|
||||
export function dockMenu(dock, id) {
|
||||
const index = dock.findIndex((button) => button.id === id);
|
||||
const button = dock[index];
|
||||
return [
|
||||
{ command: "rename", label: "Zmień nazwę" },
|
||||
{ command: "mode", label: button && button.mode === "insert" ? "Wysyłaj od razu" : "Tylko wstawiaj" },
|
||||
{ command: "left", label: "Przesuń w lewo", disabled: index <= 0 },
|
||||
{ command: "right", label: "Przesuń w prawo", disabled: index < 0 || index >= dock.length - 1 },
|
||||
{ command: "remove", label: "Usuń z docka", danger: true },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The right-click menu of a row of the history or the favourites.
|
||||
*
|
||||
* @param {{tab: "history"|"favorites", favorite: boolean, pinned: boolean}} row
|
||||
* @returns {MenuItem[]}
|
||||
*/
|
||||
export function rowMenu({ tab, favorite, pinned }) {
|
||||
/** @type {MenuItem[]} */
|
||||
const items = [{ command: "insert", label: "Wstaw" }];
|
||||
if (tab === "favorites") {
|
||||
items.push({ command: "pin", label: pinned ? "Odepnij z docka" : "Przypnij do docka" });
|
||||
}
|
||||
items.push(
|
||||
favorite
|
||||
? { command: "favorite", label: "Usuń z ulubionych", danger: true }
|
||||
: { command: "favorite", label: "Dodaj do ulubionych" },
|
||||
);
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* The right-click menu of the star: pin the text that is in the field.
|
||||
*
|
||||
* @param {{text: string, pinned: boolean}} state
|
||||
* @returns {MenuItem[]}
|
||||
*/
|
||||
export function starMenu({ text, pinned }) {
|
||||
return [
|
||||
{
|
||||
command: "pin",
|
||||
label: pinned ? "Odepnij bieżący tekst z docka" : "Przypnij bieżący tekst do docka",
|
||||
disabled: String(text).trim() === "",
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The menu that is open after a `Popover` said it opened or closed.
|
||||
*
|
||||
* Opening always opens that menu (the one before it, if any, is replaced).
|
||||
* Closing only closes the menu it is about: a late "closed" of a menu that
|
||||
* another one has replaced must leave the new one open.
|
||||
*
|
||||
* @param {{kind: string, id: string}|null} current
|
||||
* @param {{kind: string, id: string, open: boolean}} change
|
||||
* @returns {{kind: string, id: string}|null}
|
||||
*/
|
||||
export function menuTransition(current, { kind, id, open }) {
|
||||
if (open) return { kind, id };
|
||||
return current && current.kind === kind && current.id === id ? null : current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply one change to the dock as it is stored now. The dock is shared by
|
||||
* every copy of the composer, so a copy never writes back the list it holds:
|
||||
* it reads the stored one, applies the operation to it and writes the result.
|
||||
*
|
||||
* @param {unknown} stored
|
||||
* @param {(dock: DockButton[]) => DockButton[]} operation
|
||||
* @returns {DockButton[]}
|
||||
*/
|
||||
export function applyDock(stored, operation) {
|
||||
return normalize(operation(normalize(stored)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a button made by hand (the "+" form): the text, a name (empty gives the
|
||||
* default label) and a mode. The same dock comes back when the text is empty,
|
||||
* already pinned, or the dock is full.
|
||||
*
|
||||
* @param {DockButton[]} dock
|
||||
* @param {{id: string, text: string, label?: string, mode?: string}} button
|
||||
* @returns {DockButton[]}
|
||||
*/
|
||||
export function add(dock, { id, text, label, mode }) {
|
||||
const clean = String(text).trim();
|
||||
if (clean === "" || isPinned(dock, clean) || dock.length >= DOCK_LIMIT) return dock;
|
||||
const name = String(label ?? "").trim();
|
||||
return [
|
||||
...dock,
|
||||
{ id, label: name === "" ? defaultLabel(clean) : name, text: clean, mode: mode === "insert" ? "insert" : "send" },
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* True while `now` is less than `ms` after `at`: the click that closed
|
||||
* something is still the same click.
|
||||
*
|
||||
* @param {number} now
|
||||
* @param {number} at
|
||||
* @param {number} ms
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function withinGuard(now, at, ms) {
|
||||
return now - at < ms;
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File diff suppressed because it is too large.
Load diff
File renamed without changes.
@@ -9,18 +9,32 @@
|
||||
// Limit of the list: rows of a `v_virtual_list` cannot carry their own click
|
||||
// handlers (the host refuses a handler inside the item renderer) - one
|
||||
// `on_item_click` serves the whole list and names the row by its key. So a row
|
||||
// click inserts the text; the star of a row is a sign, not a button (the
|
||||
// favourites are toggled with Ctrl+D or a right click - `on_item_secondary_click`).
|
||||
// click inserts the text. The star of a row is not an element with a handler
|
||||
// either: `on_mouse_down` on the list says where the press landed, and a press
|
||||
// in the STAR_ZONE at the right edge makes the click toggle the favourite
|
||||
// (main.js). Ctrl+D and the right-click menu do the same.
|
||||
|
||||
import { div, image } from "gpui-kit";
|
||||
import { v_flex, h_flex, Input, Scrollbar, v_virtual_list } from "gpui-base";
|
||||
import { segments, entryMeta } from "./history.js";
|
||||
|
||||
/** The height of one row - the list is virtual, so every row has the same. */
|
||||
export const ROW_HEIGHT = 56;
|
||||
/**
|
||||
* The height of one row - the list is virtual, so every row has the same.
|
||||
*
|
||||
* 7 px of padding above and below, the two lines of text (TEXT_HEIGHT), 2 px
|
||||
* and the line of meta (about 18 px): a row that is lower lets the second
|
||||
* line of the text run into the meta.
|
||||
*/
|
||||
export const ROW_HEIGHT = 76;
|
||||
|
||||
/** The text lines of a row (the rest is cut). */
|
||||
const TEXT_HEIGHT = 34;
|
||||
/**
|
||||
* The right edge of a row that counts as its star: 10 px of padding, the
|
||||
* 24 px star and a little room (a click lands next to a small target).
|
||||
*/
|
||||
export const STAR_ZONE = 48;
|
||||
|
||||
/** Two lines of the text of a row, at about 20 px a line (the rest is cut). */
|
||||
const TEXT_HEIGHT = 40;
|
||||
|
||||
/**
|
||||
* The panel.
|
||||
@@ -32,6 +46,8 @@ const TEXT_HEIGHT = 34;
|
||||
* query: string,
|
||||
* index: number,
|
||||
* input: object,
|
||||
* searchFocused: boolean,
|
||||
* fieldBackground: string,
|
||||
* scroll: object,
|
||||
* isFavorite: (text:string) => boolean,
|
||||
* }} view
|
||||
@@ -39,8 +55,10 @@ const TEXT_HEIGHT = 34;
|
||||
* key: (event:any, cx:any) => void,
|
||||
* tab: (tab:string, cx:any) => void,
|
||||
* pick: (key:string, cx:any) => void,
|
||||
* toggle: (key:string, cx:any) => void,
|
||||
* rowMenu: (key:string, cx:any) => void,
|
||||
* press: (event:any) => void,
|
||||
* clear: (cx:any) => void,
|
||||
* close: (cx:any) => void,
|
||||
* }} on
|
||||
*/
|
||||
export function renderPanel(t, view, on) {
|
||||
@@ -48,7 +66,7 @@ export function renderPanel(t, view, on) {
|
||||
|
||||
return v_flex()
|
||||
.id("composer-panel")
|
||||
.key_context("ovis-composer-panel")
|
||||
.key_context("herdr-composer-panel")
|
||||
.on_key_down((event, cx) => on.key(event, cx))
|
||||
.size_full()
|
||||
.rounded(12)
|
||||
@@ -83,12 +101,21 @@ function renderTop(t, view, on) {
|
||||
.children([
|
||||
renderTab(t, "history", `Historia ${counts.history}`, view.tab === "history", on),
|
||||
renderTab(t, "favorites", `Ulubione ${counts.favorites}`, view.tab === "favorites", on),
|
||||
// The search field: a darker recess with a border that lights up while
|
||||
// the field has the keyboard (the `.hsearch` of the mockup).
|
||||
h_flex()
|
||||
.id("composer-panel-search")
|
||||
.flex_1()
|
||||
.min_w(0)
|
||||
.h(30)
|
||||
.px(10)
|
||||
.items_center()
|
||||
.gap(6)
|
||||
.rounded(8)
|
||||
.bg(view.fieldBackground)
|
||||
.border_1()
|
||||
.border_color(view.searchFocused ? t.accent : t.input)
|
||||
.child(div().flex_none().text_size(13).text_color(t.dim).child("⌕"))
|
||||
.child(Input.new(view.input).flex_1().min_w(0).text_size(12.5))
|
||||
.when(view.query !== "", (el) =>
|
||||
el.child(
|
||||
@@ -103,6 +130,21 @@ function renderTop(t, view, on) {
|
||||
.child("✕"),
|
||||
),
|
||||
),
|
||||
// Close the panel - the same road as Esc.
|
||||
div()
|
||||
.id("composer-panel-close")
|
||||
.size(28)
|
||||
.flex_none()
|
||||
.flex()
|
||||
.items_center()
|
||||
.justify_center()
|
||||
.rounded(6)
|
||||
.text_size(13)
|
||||
.text_color(t.dim)
|
||||
.cursor_pointer()
|
||||
.hover((s) => s.bg(t.hover).text_color(t.foreground))
|
||||
.on_click((event, cx) => on.close(cx))
|
||||
.child("✕"),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -131,6 +173,7 @@ function renderList(t, view, on) {
|
||||
return v_flex()
|
||||
.size_full()
|
||||
.relative()
|
||||
.on_mouse_down("left", (event, cx) => on.press(event))
|
||||
.child(
|
||||
v_virtual_list(
|
||||
"composer-panel-list",
|
||||
@@ -142,7 +185,7 @@ function renderList(t, view, on) {
|
||||
.track_scroll(view.scroll)
|
||||
.size_full()
|
||||
.on_item_click((key, cx) => on.pick(key, cx))
|
||||
.on_item_secondary_click((key, event, cx) => on.toggle(key, cx)),
|
||||
.on_item_secondary_click((key, event, cx) => on.rowMenu(key, cx)),
|
||||
)
|
||||
.child(Scrollbar.vertical("composer-panel-list").absolute().inset_0());
|
||||
}
|
||||
@@ -284,7 +327,7 @@ export function renderPreview(t, preview, handle, on) {
|
||||
return v_flex()
|
||||
.id("composer-preview")
|
||||
.track_focus(handle)
|
||||
.key_context("ovis-composer-preview")
|
||||
.key_context("herdr-composer-preview")
|
||||
.on_key_down((event, cx) => {
|
||||
if (String(event.key).toLowerCase() === "escape") {
|
||||
on.close(cx);
|
||||
@@ -0,0 +1,59 @@
|
||||
// powershell.js - how text from the outside gets into a PowerShell script.
|
||||
//
|
||||
// Pure: no gpui-kit, no gpui-base, no herdr. Every script the mod hands to
|
||||
// `exec("powershell", ["-Command", script])` (clipboard.js, catalog.js) builds
|
||||
// what it needs from a path or a name that is NOT the mod's own - a file the
|
||||
// person dropped, a file in a cloned project - through `decode`, and never by
|
||||
// putting that text between quotes.
|
||||
|
||||
/**
|
||||
* PowerShell that yields `text` - without the text itself being in the
|
||||
* script.
|
||||
*
|
||||
* A path or a name comes from the outside, and PowerShell reads more than the
|
||||
* ASCII apostrophe as a quote (U+2018, U+2019, U+201A, U+201B too), so no
|
||||
* quoting is safe enough. The text goes in as Base64 of its UTF-8 bytes - an
|
||||
* alphabet with no quote, no `$`, no space - and is decoded by PowerShell.
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns {string} a PowerShell expression
|
||||
*/
|
||||
export function decode(text) {
|
||||
return `[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64(utf8(text))}'))`;
|
||||
}
|
||||
|
||||
/** The UTF-8 bytes of a text (a lone surrogate becomes U+FFFD). */
|
||||
function utf8(text) {
|
||||
const bytes = [];
|
||||
for (const char of String(text)) {
|
||||
let code = char.codePointAt(0);
|
||||
if (code >= 0xd800 && code <= 0xdfff) code = 0xfffd;
|
||||
if (code < 0x80) {
|
||||
bytes.push(code);
|
||||
} else if (code < 0x800) {
|
||||
bytes.push(0xc0 | (code >> 6), 0x80 | (code & 63));
|
||||
} else if (code < 0x10000) {
|
||||
bytes.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
|
||||
} else {
|
||||
bytes.push(0xf0 | (code >> 18), 0x80 | ((code >> 12) & 63), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63));
|
||||
}
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
|
||||
/** Base64 of bytes (no Buffer, no btoa: the mods do not have to have them). */
|
||||
function base64(bytes) {
|
||||
let out = "";
|
||||
for (let i = 0; i < bytes.length; i += 3) {
|
||||
const a = bytes[i];
|
||||
const b = bytes[i + 1];
|
||||
const c = bytes[i + 2];
|
||||
out += BASE64[a >> 2];
|
||||
out += BASE64[((a & 3) << 4) | ((b ?? 0) >> 4)];
|
||||
out += b === undefined ? "=" : BASE64[((b & 15) << 2) | ((c ?? 0) >> 6)];
|
||||
out += c === undefined ? "=" : BASE64[c & 63];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// profiles.js - what the composer knows about each agent.
|
||||
//
|
||||
// Pure: no GPUI, no herdr, no IO. A profile says which `agentName()` values
|
||||
// belong to an agent, its built-in commands and where its own commands live
|
||||
// (a folder of the project and a folder of the person's home). The defaults
|
||||
// are here; the person adds or replaces profiles in `composer-agents.json`.
|
||||
// A profile of the file with the id of a default one replaces it whole.
|
||||
//
|
||||
// Source = {scope:"project"|"home", path, pattern:"*.md"|"*/SKILL.md", prefix}
|
||||
// | {scope:"home", kind:"claude-plugins"}
|
||||
// Profile = {id, match:string[], builtins:{key, desc}[], sources:Source[]}
|
||||
|
||||
/** The file the person's profiles live in, in the app's home folder. */
|
||||
export const PROFILES_FILE = "composer-agents.json";
|
||||
|
||||
/**
|
||||
* The built-in commands of the agents. The list is kept by hand, in the
|
||||
* alphabetical order: when a new version of Claude Code brings a command,
|
||||
* add it here.
|
||||
*/
|
||||
export const BUILTINS = {
|
||||
"claude-code": [
|
||||
{ key: "add-dir", desc: "Dodaje katalog roboczy." },
|
||||
{ key: "agents", desc: "Zarządza subagentami." },
|
||||
{ key: "bashes", desc: "Pokazuje zadania w tle." },
|
||||
{ key: "bug", desc: "Zgłasza błąd Claude Code." },
|
||||
{ key: "clear", desc: "Czyści historię rozmowy." },
|
||||
{ key: "code-review", desc: "Przegląd zmian pod kątem błędów." },
|
||||
{ key: "compact", desc: "Zwija historię do podsumowania." },
|
||||
{ key: "config", desc: "Otwiera ustawienia." },
|
||||
{ key: "context", desc: "Pokazuje zużycie kontekstu." },
|
||||
{ key: "cost", desc: "Pokazuje koszt i zużycie tokenów." },
|
||||
{ key: "doctor", desc: "Sprawdza instalację Claude Code." },
|
||||
{ key: "exit", desc: "Kończy sesję." },
|
||||
{ key: "export", desc: "Eksportuje rozmowę." },
|
||||
{ key: "fast", desc: "Przełącza tryb szybki." },
|
||||
{ key: "feedback", desc: "Wysyła opinię o Claude Code." },
|
||||
{ key: "fewer-permission-prompts", desc: "Dodaje bezpieczne komendy do listy dozwolonych." },
|
||||
{ key: "help", desc: "Pomoc." },
|
||||
{ key: "hooks", desc: "Zarządza hookami." },
|
||||
{ key: "ide", desc: "Łączy z IDE." },
|
||||
{ key: "init", desc: "Tworzy CLAUDE.md dla projektu." },
|
||||
{ key: "install-github-app", desc: "Instaluje aplikację GitHub." },
|
||||
{ key: "keybindings", desc: "Ustawia skróty klawiszowe." },
|
||||
{ key: "login", desc: "Logowanie." },
|
||||
{ key: "logout", desc: "Wylogowanie." },
|
||||
{ key: "loop", desc: "Uruchamia polecenie cyklicznie." },
|
||||
{ key: "mcp", desc: "Zarządza serwerami MCP." },
|
||||
{ key: "memory", desc: "Edytuje pliki pamięci." },
|
||||
{ key: "model", desc: "Wybiera model." },
|
||||
{ key: "output-style", desc: "Ustawia styl odpowiedzi." },
|
||||
{ key: "permissions", desc: "Ustawia uprawnienia narzędzi." },
|
||||
{ key: "plugin", desc: "Zarządza pluginami." },
|
||||
{ key: "pr-comments", desc: "Pokazuje komentarze PR." },
|
||||
{ key: "privacy-settings", desc: "Ustawienia prywatności." },
|
||||
{ key: "release-notes", desc: "Pokazuje informacje o wydaniu." },
|
||||
{ key: "resume", desc: "Wznawia wcześniejszą sesję." },
|
||||
{ key: "review", desc: "Przegląd pull requesta." },
|
||||
{ key: "rewind", desc: "Cofa rozmowę lub kod." },
|
||||
{ key: "schedule", desc: "Planuje zadania w chmurze." },
|
||||
{ key: "security-review", desc: "Przegląd bezpieczeństwa zmian." },
|
||||
{ key: "simplify", desc: "Upraszcza zmieniony kod." },
|
||||
{ key: "status", desc: "Pokazuje stan sesji." },
|
||||
{ key: "statusline", desc: "Ustawia linię statusu." },
|
||||
{ key: "terminal-setup", desc: "Konfiguruje terminal." },
|
||||
{ key: "todos", desc: "Pokazuje listę zadań." },
|
||||
{ key: "upgrade", desc: "Zmienia plan." },
|
||||
{ key: "usage", desc: "Pokazuje limity użycia." },
|
||||
{ key: "vim", desc: "Przełącza tryb vim." },
|
||||
{ key: "workflows", desc: "Pokazuje przebieg workflow." },
|
||||
],
|
||||
codex: [
|
||||
{ key: "model", desc: "Wybiera model." },
|
||||
{ key: "approvals", desc: "Ustawia sposób zatwierdzania poleceń." },
|
||||
{ key: "new", desc: "Zaczyna nową sesję." },
|
||||
{ key: "resume", desc: "Wznawia wcześniejszą sesję." },
|
||||
],
|
||||
};
|
||||
|
||||
const CC_SOURCES = [
|
||||
{ scope: "project", path: ".claude/commands", pattern: "*.md", prefix: "/" },
|
||||
{ scope: "project", path: ".claude/skills", pattern: "*/SKILL.md", prefix: "/" },
|
||||
{ scope: "home", path: ".claude/commands", pattern: "*.md", prefix: "/" },
|
||||
{ scope: "home", path: ".claude/skills", pattern: "*/SKILL.md", prefix: "/" },
|
||||
{ scope: "home", kind: "claude-plugins" },
|
||||
];
|
||||
|
||||
/** The profiles the composer brings. */
|
||||
export const DEFAULT_PROFILES = [
|
||||
{
|
||||
id: "claude-code",
|
||||
match: ["claude-code", "claude"],
|
||||
builtins: BUILTINS["claude-code"],
|
||||
sources: CC_SOURCES,
|
||||
},
|
||||
{ id: "codex", match: ["codex"], builtins: BUILTINS.codex, sources: [] },
|
||||
];
|
||||
|
||||
const PATTERNS = new Set(["*.md", "*/SKILL.md"]);
|
||||
|
||||
/** A relative path with no `..` segment: absolute forms are not allowed. */
|
||||
function safePath(path) {
|
||||
if (typeof path !== "string" || path.trim() === "") return false;
|
||||
if (/^[\\/]/.test(path) || /^[A-Za-z]:/.test(path)) return false;
|
||||
return !path.split(/[\\/]/).includes("..");
|
||||
}
|
||||
|
||||
/** One source, normalised, or `null` when it is not valid. */
|
||||
function parseSource(raw) {
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
if (raw.scope === "home" && raw.kind === "claude-plugins") {
|
||||
return { scope: "home", kind: "claude-plugins" };
|
||||
}
|
||||
if (raw.scope !== "project" && raw.scope !== "home") return null;
|
||||
if (!safePath(raw.path) || !PATTERNS.has(raw.pattern)) return null;
|
||||
const prefix = typeof raw.prefix === "string" ? raw.prefix : "/";
|
||||
const path = raw.path.replace(/\\/g, "/").replace(/\/+$/, "");
|
||||
return { scope: raw.scope, path, pattern: raw.pattern, prefix };
|
||||
}
|
||||
|
||||
/**
|
||||
* The profiles of the person's file.
|
||||
*
|
||||
* @param {string|null|undefined} text - the file, `null` when it is missing
|
||||
* @returns {{profiles: object[], problem: string|null}}
|
||||
*/
|
||||
export function parseProfiles(text) {
|
||||
if (text === null || text === undefined) return { profiles: [], problem: null };
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(String(text).replace(/^\uFEFF/, ""));
|
||||
} catch {
|
||||
return { profiles: [], problem: "nieczytelny JSON" };
|
||||
}
|
||||
if (!data || !Array.isArray(data.agents)) return { profiles: [], problem: "brak listy agents" };
|
||||
|
||||
let skipped = 0;
|
||||
const profiles = [];
|
||||
for (const raw of data.agents) {
|
||||
const match = Array.isArray(raw?.match) ? raw.match : null;
|
||||
if (
|
||||
!raw ||
|
||||
typeof raw.id !== "string" ||
|
||||
raw.id.trim() === "" ||
|
||||
!match ||
|
||||
match.length === 0 ||
|
||||
!match.every((m) => typeof m === "string")
|
||||
) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
|
||||
const builtins = [];
|
||||
for (const b of Array.isArray(raw.builtins) ? raw.builtins : []) {
|
||||
if (!b || typeof b.key !== "string" || b.key === "") {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
builtins.push({ key: b.key, desc: typeof b.desc === "string" ? b.desc : "" });
|
||||
}
|
||||
|
||||
const sources = [];
|
||||
for (const s of Array.isArray(raw.sources) ? raw.sources : []) {
|
||||
const source = parseSource(s);
|
||||
if (source) sources.push(source);
|
||||
else skipped++;
|
||||
}
|
||||
profiles.push({ id: raw.id, match: match.map((m) => m.trim()), builtins, sources });
|
||||
}
|
||||
return { profiles, problem: skipped > 0 ? `pominięto ${skipped} wpisów` : null };
|
||||
}
|
||||
|
||||
/**
|
||||
* The profile of an agent: the person's first, then the defaults. `""` and
|
||||
* `"default"` match nothing unless a profile lists them.
|
||||
*
|
||||
* @param {object[]} userProfiles
|
||||
* @param {string} agent - `agentName()` of the pane
|
||||
* @returns {object|null}
|
||||
*/
|
||||
export function resolveProfile(userProfiles, agent) {
|
||||
const name = String(agent ?? "").trim().toLowerCase();
|
||||
for (const profile of [...(userProfiles ?? []), ...DEFAULT_PROFILES]) {
|
||||
if (profile.match.some((m) => String(m).trim().toLowerCase() === name)) return profile;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -4,9 +4,9 @@
|
||||
// never mutates the one it was given, so the model can be tested in plain Node
|
||||
// (tests/state.test.mjs) and reasoned about without a running app.
|
||||
//
|
||||
// Drafts, attachments and the queue are keyed by agent name ("claude-code",
|
||||
// "codex"): each belongs to the agent it was written for, and switching agents
|
||||
// must not lose any of them.
|
||||
// Drafts, attachments and the queue are keyed by the address of the agent
|
||||
// (`AgentInfo.address`, e.g. "t2"): each belongs to the agent it was written
|
||||
// for, and switching agents must not lose any of them.
|
||||
|
||||
import { onRestart } from "./delivery.js";
|
||||
|
||||
+121
-10
@@ -47,6 +47,8 @@
|
||||
* @property {string} text
|
||||
* @property {number} createdAt
|
||||
*
|
||||
* @typedef {import("./dock.js").DockButton} DockButton
|
||||
*
|
||||
* @typedef {object} QueueEntry
|
||||
* @property {string} id
|
||||
* @property {string} text
|
||||
@@ -56,18 +58,33 @@
|
||||
* @property {string} [reason]
|
||||
*/
|
||||
|
||||
import { normalize as normalizeDock } from "./dock.js";
|
||||
|
||||
/** The states a queue entry may be in (the ones state.js knows). */
|
||||
const QUEUE_STATES = new Set(["queued", "countdown", "sending", "held", "uncertain"]);
|
||||
|
||||
/**
|
||||
* The composer used to be called `ovis-composer`, and what it kept lives under
|
||||
* keys with that prefix. Every `load*` reads the new key first; when there is
|
||||
* none it reads the old one and - if there is something worth keeping - writes
|
||||
* it under the new key. The old keys are never touched.
|
||||
*/
|
||||
const PREFIX = "herdr-composer.";
|
||||
export const LEGACY_PREFIX = "ovis-composer.";
|
||||
|
||||
/** The keys the composer writes into the shared store. */
|
||||
export const KEYS = {
|
||||
history: "ovis-composer.history",
|
||||
favorites: "ovis-composer.favorites",
|
||||
usage: "ovis-composer.usage",
|
||||
/** The queue is per agent: `ovis-composer.queue:<agent>`. */
|
||||
queue: "ovis-composer.queue",
|
||||
/** The draft is per agent: `ovis-composer.draft:<agent>`. */
|
||||
draft: "ovis-composer.draft",
|
||||
history: "herdr-composer.history",
|
||||
favorites: "herdr-composer.favorites",
|
||||
usage: "herdr-composer.usage",
|
||||
/** The height (layout px) the person dragged the composer to; 0 or none: not set. */
|
||||
userMin: "herdr-composer.userMin",
|
||||
/** The queue is per agent: `herdr-composer.queue:<agent>`. */
|
||||
queue: "herdr-composer.queue",
|
||||
/** The draft is per agent: `herdr-composer.draft:<agent>`. */
|
||||
draft: "herdr-composer.draft",
|
||||
/** The buttons of the dock (dock.js). New in herdr-composer: no legacy key. */
|
||||
dock: "herdr-composer.dock",
|
||||
};
|
||||
|
||||
/** How many entries the history keeps. */
|
||||
@@ -128,6 +145,26 @@ export function saveFavorites(store, items) {
|
||||
writeList(store, KEYS.favorites, items, FAVORITES_LIMIT, isFavoriteEntry, toFavoriteEntry);
|
||||
}
|
||||
|
||||
/**
|
||||
* The buttons of the dock. Only what is a button comes back (dock.js
|
||||
* `normalize`). The dock is new, so there is no `ovis-composer.dock` to read.
|
||||
*
|
||||
* @param {Store} store
|
||||
* @returns {DockButton[]}
|
||||
*/
|
||||
export function loadDock(store) {
|
||||
return normalizeDock(read(store, KEYS.dock));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Store} store
|
||||
* @param {DockButton[]} items
|
||||
* @returns {void}
|
||||
*/
|
||||
export function saveDock(store, items) {
|
||||
write(store, KEYS.dock, normalizeDock(items));
|
||||
}
|
||||
|
||||
/**
|
||||
* The queue of one agent - the messages that wait for their turn.
|
||||
*
|
||||
@@ -191,7 +228,7 @@ export function draftKey(agent) {
|
||||
*/
|
||||
export function loadDraft(store, agent) {
|
||||
if (typeof agent !== "string" || agent === "") return null;
|
||||
return toDraft(read(store, draftKey(agent)));
|
||||
return loadMigrating(store, draftKey(agent), toDraft, (draft) => draft !== null);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -247,6 +284,32 @@ function toDraft(value) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The height the person dragged the composer block to (layout px). 0 is "not
|
||||
* set"; anything that is not a positive number is not a height.
|
||||
*
|
||||
* @param {Store} store
|
||||
* @returns {number}
|
||||
*/
|
||||
export function loadUserMin(store) {
|
||||
return loadMigrating(
|
||||
store,
|
||||
KEYS.userMin,
|
||||
(value) => (typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0),
|
||||
(px) => px > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Store} store
|
||||
* @param {number} px - 0 clears it; what is not a number is not written
|
||||
* @returns {void}
|
||||
*/
|
||||
export function saveUserMin(store, px) {
|
||||
if (typeof px !== "number" || !Number.isFinite(px) || px < 0) return;
|
||||
write(store, KEYS.userMin, Math.round(px));
|
||||
}
|
||||
|
||||
/**
|
||||
* How often each command was used - the numbers the ranking of the
|
||||
* suggestions breaks its ties with (`suggest.rank` reads `item.uses`).
|
||||
@@ -259,7 +322,10 @@ function toDraft(value) {
|
||||
* @returns {Record<string, number>}
|
||||
*/
|
||||
export function loadUsage(store) {
|
||||
const raw = read(store, KEYS.usage);
|
||||
return loadMigrating(
|
||||
store,
|
||||
KEYS.usage,
|
||||
(raw) => {
|
||||
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {};
|
||||
|
||||
const counts = {};
|
||||
@@ -267,6 +333,9 @@ export function loadUsage(store) {
|
||||
if (typeof value === "number" && Number.isFinite(value) && value >= 0) counts[key] = value;
|
||||
}
|
||||
return counts;
|
||||
},
|
||||
(counts) => Object.keys(counts).length > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -302,10 +371,52 @@ export function saveUsage(store, counts) {
|
||||
* @returns {any[]}
|
||||
*/
|
||||
function readList(store, key, limit, isValid, shape) {
|
||||
const found = toList(read(store, key), isValid);
|
||||
return loadMigrating(
|
||||
store,
|
||||
key,
|
||||
(raw) => {
|
||||
const found = toList(raw, isValid);
|
||||
if (!found) return [];
|
||||
const list = shape ? found.map(shape) : found;
|
||||
return limit > 0 ? list.slice(-limit) : list;
|
||||
},
|
||||
(list) => list.length > 0,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a value under its key; when the key was never written, under the key
|
||||
* the composer had before it was renamed (`ovis-composer.*`).
|
||||
*
|
||||
* What is found under the old key is parsed like anything else (rubbish gives
|
||||
* the default), and only when the result is worth keeping the old value is
|
||||
* written under the new key. A store that cannot be written to does not break
|
||||
* the read. The old key stays as it was.
|
||||
*
|
||||
* @template T
|
||||
* @param {Store} store
|
||||
* @param {string} key - the new key (`herdr-composer.*`)
|
||||
* @param {(raw:unknown) => T} parse - the value as the composer uses it; `null` gives the default
|
||||
* @param {(parsed:T) => boolean} worthKeeping
|
||||
* @returns {T}
|
||||
*/
|
||||
function loadMigrating(store, key, parse, worthKeeping) {
|
||||
const current = read(store, key);
|
||||
if (current !== null && current !== undefined) return parse(current);
|
||||
if (!key.startsWith(PREFIX)) return parse(null);
|
||||
|
||||
const old = read(store, LEGACY_PREFIX + key.slice(PREFIX.length));
|
||||
if (old === null || old === undefined) return parse(null);
|
||||
|
||||
const parsed = parse(old);
|
||||
if (worthKeeping(parsed)) {
|
||||
try {
|
||||
write(store, key, old);
|
||||
} catch {
|
||||
// The data is read; it is written under the new key next time.
|
||||
}
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -14,7 +14,7 @@
|
||||
* @typedef {object} Item
|
||||
* @property {string} key - the name the needle is matched against
|
||||
* @property {string} desc - one line about the item
|
||||
* @property {string} [group] - Wbudowane | Projekt | Użytkownik | Terminal
|
||||
* @property {string} [group] - Wbudowane | Projekt | Użytkownik | Pluginy | Z historii | Terminal
|
||||
* @property {string} insert - the text put into the field ("/review ")
|
||||
* @property {number} [uses] - how often the person picked the item
|
||||
*/
|
||||
@@ -25,11 +25,22 @@ export const GROUP_BUILTIN = "Wbudowane";
|
||||
export const GROUP_PROJECT = "Projekt";
|
||||
/** The person's own saved snippets. */
|
||||
export const GROUP_USER = "Użytkownik";
|
||||
/** The commands of the plugins that are switched on. */
|
||||
export const GROUP_PLUGIN = "Pluginy";
|
||||
/** The commands that were sent to this agent before. */
|
||||
export const GROUP_HISTORY = "Z historii";
|
||||
/** The commands the terminal itself understands. */
|
||||
export const GROUP_TERMINAL = "Terminal";
|
||||
|
||||
/** The groups, in the order the menu shows them. */
|
||||
export const GROUPS = [GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, GROUP_TERMINAL];
|
||||
export const GROUPS = [
|
||||
GROUP_BUILTIN,
|
||||
GROUP_PROJECT,
|
||||
GROUP_USER,
|
||||
GROUP_PLUGIN,
|
||||
GROUP_HISTORY,
|
||||
GROUP_TERMINAL,
|
||||
];
|
||||
|
||||
/** A name may start a word after one of these. */
|
||||
const BOUNDARY = new Set([":", "-", "_", ".", "/"]);
|
||||
@@ -8,7 +8,7 @@
|
||||
// belongs to an agent (the draft, the queue, the attachments) is keyed by the
|
||||
// agent's address, so two Claude Code agents never share a draft.
|
||||
|
||||
import { drain, gateAfter } from "./delivery.js";
|
||||
import { drain, gateAfter, queueBlocksDirectSend } from "./delivery.js";
|
||||
import { LIMITS } from "./attachments.js";
|
||||
|
||||
/**
|
||||
@@ -495,3 +495,137 @@ export function canAutoSend(ready, key) {
|
||||
export function stillSameAgent({ before, after, target }) {
|
||||
return before !== "" && before === after && before === target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Must a message that could go out now wait behind what is already in flight
|
||||
* or in the queue?
|
||||
*
|
||||
* - a message on the wire always goes first (`draining`);
|
||||
* - Ctrl+Enter (`mode "now"`) is the person's own order and does not wait;
|
||||
* - an answer to an agent that is `blocked` does not wait either: the queue
|
||||
* does not start while the agent waits for the person, so queueing the
|
||||
* answer would leave the agent waiting for ever - it goes ahead (with
|
||||
* `--force`) and the queue stays as it is;
|
||||
* - otherwise it waits when a message is queued or counting down.
|
||||
*
|
||||
* @param {{draining:boolean, mode:string, status:string, queue:object[]|undefined}} input
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function directSendBlocked({ draining, mode, status, queue }) {
|
||||
if (draining) return true;
|
||||
if (mode === "now" || status === "blocked") return false;
|
||||
return queueBlocksDirectSend(queue);
|
||||
}
|
||||
|
||||
// --- the height of the composer block ----------------------------------------
|
||||
//
|
||||
// The block is as tall as its content (menu, queue, notices, card, strip),
|
||||
// unless the person dragged its border: then that height is the floor.
|
||||
|
||||
/**
|
||||
* The height the block should have, in the pixels of the layout.
|
||||
*
|
||||
* What the content measures is in logical pixels (layout px times the zoom of
|
||||
* the app), plus the padding of the root; the floor is what the person dragged
|
||||
* the block to (`userMin`, 0 for none); the result stays inside the range the
|
||||
* layout allows.
|
||||
*
|
||||
* @param {{contentHeight:number, padding:number, zoom:number, userMin:number, min:number, max:number}} input
|
||||
* @returns {number}
|
||||
*/
|
||||
export function blockTargetPx({ contentHeight, padding, zoom, userMin, min, max }) {
|
||||
const factor = Number.isFinite(zoom) && zoom > 0 ? zoom : 1;
|
||||
const need = Math.ceil((contentHeight + padding) / factor);
|
||||
const wanted = Math.max(need, Number.isFinite(userMin) ? userMin : 0);
|
||||
return Math.round(Math.min(max, Math.max(min, wanted)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Is the difference worth a `layout.resize`? Under 5 px it is not: typing and
|
||||
* the growing of the field must not make the block twitch.
|
||||
*
|
||||
* @param {number|null|undefined} current
|
||||
* @param {number|null|undefined} target
|
||||
* @param {number} [threshold]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function shouldResize(current, target, threshold = 4) {
|
||||
if (!Number.isFinite(current) || !Number.isFinite(target)) return false;
|
||||
return Math.abs(current - target) > threshold;
|
||||
}
|
||||
|
||||
/**
|
||||
* Is a reported height the person's drag?
|
||||
*
|
||||
* The composer keeps the height it ordered last (`orderedPx`); a height it did
|
||||
* not order is somebody dragging the border. Before anything was ordered the
|
||||
* first height is the layout's own, not a drag.
|
||||
*
|
||||
* @param {{reportedPx:number, orderedPx:number|null, tolerance?:number}} input
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isManualResize({ reportedPx, orderedPx, tolerance = 3 }) {
|
||||
if (!Number.isFinite(reportedPx) || !Number.isFinite(orderedPx)) return false;
|
||||
return Math.abs(reportedPx - orderedPx) > tolerance;
|
||||
}
|
||||
|
||||
// --- colors from the theme -----------------------------------------------------
|
||||
|
||||
/**
|
||||
* How light a color is (0 dark .. 1 light), from `#rgb`, `#rrggbb` or
|
||||
* `#rrggbbaa`; nothing for what is not such a color.
|
||||
*
|
||||
* @param {unknown} color
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function luminance(color) {
|
||||
if (typeof color !== "string") return null;
|
||||
let hex = color.trim();
|
||||
if (!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(hex)) return null;
|
||||
hex = hex.slice(1);
|
||||
if (hex.length === 3) hex = hex.replace(/./g, "$&$&");
|
||||
const channel = (at) => parseInt(hex.slice(at, at + 2), 16) / 255;
|
||||
return 0.2126 * channel(0) + 0.7152 * channel(2) + 0.0722 * channel(4);
|
||||
}
|
||||
|
||||
/**
|
||||
* The background of an input field set into a panel: the darkest color the
|
||||
* theme names among the usual surfaces, so the field reads as a recess in the
|
||||
* panel whatever the theme. A theme with none to offer leaves the panel's own.
|
||||
*
|
||||
* @param {Record<string,string>} theme - `theme()`
|
||||
* @param {string} panelBackground - the background of the panel
|
||||
* @returns {string}
|
||||
*/
|
||||
export function fieldBackground(theme, panelBackground) {
|
||||
let best = null;
|
||||
let bestLight = Infinity;
|
||||
for (const key of ["background", "canvas", "pane", "surface", "chrome"]) {
|
||||
const light = luminance(theme?.[key]);
|
||||
if (light !== null && light < bestLight) {
|
||||
best = theme[key];
|
||||
bestLight = light;
|
||||
}
|
||||
}
|
||||
return best ?? panelBackground;
|
||||
}
|
||||
|
||||
/** How long the green check stays on the send button after a send, ms. */
|
||||
export const SENT_MS = 1500;
|
||||
|
||||
/** How long an `info` notice stays under the card, ms. */
|
||||
export const NOTICE_MS = 3000;
|
||||
|
||||
/**
|
||||
* Is it time to clear the notice? Only the very notice the timer was set for,
|
||||
* and only an `info` one: another notice that came in the meantime (even with
|
||||
* the same text) is none of this timer's business, and a `problem` or an
|
||||
* `error` stays until something replaces it.
|
||||
*
|
||||
* @param {{level?:string}|null} current - the notice of the state now
|
||||
* @param {{level?:string}} scheduled - the notice the timer was set for
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function noticeExpired(current, scheduled) {
|
||||
return current !== null && current === scheduled && scheduled.level === "info";
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 928 KiB |
@@ -0,0 +1,5 @@
|
||||
@echo off
|
||||
rem Installs (or updates) the herdr-composer package. Run it again to update;
|
||||
rem "install.cmd -Uninstall" removes it. See README.md.
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0scripts\install.ps1" %*
|
||||
exit /b %ERRORLEVEL%
|
||||
@@ -1,367 +0,0 @@
|
||||
// catalog.js - where the composer's suggestions come from.
|
||||
//
|
||||
// The workspace is reached only through the injected `exec` (the mod's
|
||||
// `herdr.exec`), so this module runs in plain Node (tests/suggest.test.mjs)
|
||||
// with a fake runner. It has no clock and no storage of its own: the view
|
||||
// reads the person's snippets and passes them in, and it schedules the retry
|
||||
// and the debounce with the numbers exported here.
|
||||
//
|
||||
// Three sources for `/` (the design's §5.3): the built-in commands of the
|
||||
// agent, the project's own `.claude/commands/*.md` and
|
||||
// `.claude/skills/*/SKILL.md`, and the person's saved snippets. One source
|
||||
// for `@`: the files git tracks in the pane's folder.
|
||||
//
|
||||
// A read that fails is not an empty list: the failure is reported through
|
||||
// `onReadError` and the menu keeps what it knows. A caller with no handler
|
||||
// gets the failure itself - nobody may mistake a broken catalog for one
|
||||
// with nothing to show. An empty list without a failure means the catalog
|
||||
// was read and nothing fit.
|
||||
|
||||
import { GROUP_BUILTIN, GROUP_PROJECT, GROUP_USER, rank } from "./suggest.js";
|
||||
|
||||
/**
|
||||
* @typedef {import("./suggest.js").Item} Item
|
||||
*
|
||||
* @typedef {object} ExecResult
|
||||
* @property {number} code
|
||||
* @property {string} stdout
|
||||
* @property {string} stderr
|
||||
*
|
||||
* @typedef {(command:string, args?:string[], options?:{cwd?:string}) => Promise<ExecResult>} Exec
|
||||
*/
|
||||
|
||||
/** How long the composer waits before it asks the workspace again. */
|
||||
export const DEBOUNCE_MS = 150;
|
||||
|
||||
/** The waits between the tries after a read failed: 2 s, 5 s, 15 s, 30 s. */
|
||||
export const RETRY_DELAYS = [2000, 5000, 15000, 30000];
|
||||
|
||||
/** The catalog could not be read - the person may keep typing. */
|
||||
export const READ_ERROR_MESSAGE =
|
||||
"Nie udało się wczytać podpowiedzi. Pisz dalej, spróbujemy ponownie.";
|
||||
|
||||
/** The catalog was read and nothing fit the needle. */
|
||||
export const NO_MATCH_MESSAGE = "Żadna komenda nie pasuje. Zmień słowo albo pisz dalej.";
|
||||
|
||||
/** The same, for the files of an `@`. */
|
||||
export const NO_FILE_MATCH_MESSAGE = "Żaden plik nie pasuje. Zmień słowo albo pisz dalej.";
|
||||
|
||||
/** The built-in commands of the agents, the small list the design names. */
|
||||
export const BUILTINS = {
|
||||
"claude-code": [
|
||||
{ key: "clear", desc: "Czyści historię rozmowy." },
|
||||
{ key: "compact", desc: "Ścisza historię do podsumowania." },
|
||||
{ key: "model", desc: "Wybiera model." },
|
||||
{ key: "permissions", desc: "Ustawia uprawnienia narzędzi." },
|
||||
{ key: "config", desc: "Otwiera ustawienia." },
|
||||
{ key: "resume", desc: "Wznawia wcześniejszą sesję." },
|
||||
],
|
||||
codex: [
|
||||
{ key: "model", desc: "Wybiera model." },
|
||||
{ key: "approvals", desc: "Ustawia sposób zatwierdzania poleceń." },
|
||||
{ key: "new", desc: "Zaczyna nową sesję." },
|
||||
{ key: "resume", desc: "Wznawia wcześniejszą sesję." },
|
||||
],
|
||||
};
|
||||
|
||||
/** The same agent under the name the program's table gives it. */
|
||||
const AGENT_ALIASES = { claude: "claude-code" };
|
||||
|
||||
/** How many files the `@` menu shows at most. */
|
||||
const FILE_LIMIT = 20;
|
||||
|
||||
/** The project's command files, as a shell finds them. */
|
||||
const LIST_SH =
|
||||
'for f in .claude/commands/*.md .claude/skills/*/SKILL.md; do [ -f "$f" ] && printf \'%s\\n\' "$f"; done; exit 0';
|
||||
|
||||
/** The same in PowerShell, for a machine without a POSIX shell. */
|
||||
const LIST_PS =
|
||||
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " +
|
||||
"@(Get-ChildItem -Path '.claude/commands/*.md','.claude/skills/*/SKILL.md' -File -ErrorAction SilentlyContinue) " +
|
||||
"| ForEach-Object { Resolve-Path -Relative -LiteralPath $_.FullName }";
|
||||
|
||||
/** Reading one file with a POSIX shell. */
|
||||
const READ_SH = 'cat -- "$1"';
|
||||
|
||||
/**
|
||||
* How long to wait before the next try after a read failed. The last wait
|
||||
* repeats: the composer keeps trying every 30 s until the catalog is read.
|
||||
*
|
||||
* @param {number} attempt - 0 for the first wait
|
||||
* @returns {number} milliseconds
|
||||
*/
|
||||
export function retryDelay(attempt) {
|
||||
const index = Number.isFinite(attempt) ? Math.max(0, Math.floor(attempt)) : 0;
|
||||
return RETRY_DELAYS[Math.min(index, RETRY_DELAYS.length - 1)];
|
||||
}
|
||||
|
||||
/**
|
||||
* The commands the `/` menu offers: the agent's built-ins, the project's own
|
||||
* and the person's snippets.
|
||||
*
|
||||
* A source that cannot be read does not take the others with it: the menu
|
||||
* shows what is known and the failure goes to `onReadError`, so the caller
|
||||
* can tell a catalog it could not read from one with nothing to show.
|
||||
* Without a handler the call rejects - the failure is never swallowed.
|
||||
*
|
||||
* @param {string} cwd - the folder of the pane
|
||||
* @param {Exec} exec
|
||||
* @param {{agent?:string, snippets?:object[], onReadError?:(error:Error) => void}} [options]
|
||||
* @returns {Promise<Item[]>}
|
||||
*/
|
||||
export async function commands(cwd, exec, options = {}) {
|
||||
const builtins = builtinItems(options.agent);
|
||||
const snippets = snippetItems(options.snippets);
|
||||
|
||||
let project = [];
|
||||
try {
|
||||
project = await projectItems(cwd, exec);
|
||||
} catch (err) {
|
||||
// Nobody to tell: the caller gets the failure instead of a list that
|
||||
// looks empty - an empty list would say "nothing fits" and the caller
|
||||
// would never try again.
|
||||
if (options.onReadError) options.onReadError(err);
|
||||
else throw err;
|
||||
}
|
||||
|
||||
return [...builtins, ...project, ...snippets];
|
||||
}
|
||||
|
||||
/**
|
||||
* The files the `@` menu offers: the ones git tracks in the pane's folder.
|
||||
*
|
||||
* The best matches come first and only then are they cut to twenty - a file
|
||||
* that fits is never hidden behind twenty names that do not. Without a
|
||||
* handler the call rejects when git fails.
|
||||
*
|
||||
* @param {string} cwd - the folder of the pane
|
||||
* @param {Exec} exec
|
||||
* @param {{needle?:string, limit?:number, onReadError?:(error:Error) => void}} [options]
|
||||
* @returns {Promise<Item[]>}
|
||||
*/
|
||||
export async function files(cwd, exec, options = {}) {
|
||||
const needle = String(options.needle ?? "").toLowerCase();
|
||||
const limit = Number.isFinite(options.limit) ? options.limit : FILE_LIMIT;
|
||||
|
||||
let paths = [];
|
||||
try {
|
||||
paths = await gitFiles(cwd, exec);
|
||||
} catch (err) {
|
||||
// Nobody to tell: the caller gets the failure instead of an empty list
|
||||
// that would say "nothing fits".
|
||||
if (options.onReadError) options.onReadError(err);
|
||||
else throw err;
|
||||
}
|
||||
|
||||
const items = paths.map((path) => ({ key: path, desc: "", insert: `@${path} ` }));
|
||||
return rank(items, needle, { atLineStart: true }).slice(0, limit);
|
||||
}
|
||||
|
||||
/** The built-in commands of one agent - an agent we do not know has none. */
|
||||
function builtinItems(agent) {
|
||||
const name = String(agent ?? "");
|
||||
const list = BUILTINS[name] ?? BUILTINS[AGENT_ALIASES[name]];
|
||||
if (!list) return [];
|
||||
return list.map((item) => ({
|
||||
key: item.key,
|
||||
desc: item.desc,
|
||||
group: GROUP_BUILTIN,
|
||||
insert: `/${item.key} `,
|
||||
}));
|
||||
}
|
||||
|
||||
/** The commands the project has: its command files and its skills. */
|
||||
async function projectItems(cwd, exec) {
|
||||
const { kind, paths } = await listProjectFiles(cwd, exec);
|
||||
|
||||
const items = [];
|
||||
for (const path of paths) {
|
||||
const name = commandName(path);
|
||||
if (!name) continue;
|
||||
const text = await readFile(cwd, exec, path, kind);
|
||||
if (text === null) continue;
|
||||
items.push({ key: name, desc: describe(text), group: GROUP_PROJECT, insert: `/${name} ` });
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/** The person's own snippets, as the view read them from the storage. */
|
||||
function snippetItems(snippets) {
|
||||
if (!Array.isArray(snippets)) return [];
|
||||
|
||||
const items = [];
|
||||
for (const snippet of snippets) {
|
||||
const key = String(snippet?.key ?? snippet?.name ?? "").trim();
|
||||
if (!key) continue;
|
||||
const item = {
|
||||
key,
|
||||
desc: String(snippet?.desc ?? snippet?.description ?? ""),
|
||||
group: GROUP_USER,
|
||||
insert: `/${key} `,
|
||||
};
|
||||
if (Number.isFinite(snippet?.uses)) item.uses = snippet.uses;
|
||||
items.push(item);
|
||||
}
|
||||
return items;
|
||||
}
|
||||
|
||||
/**
|
||||
* The project's command files. A POSIX shell is asked first - it is what a
|
||||
* Linux or macOS machine has - and PowerShell after it, for a Windows machine
|
||||
* without one. Neither is there: the catalog could not be read.
|
||||
*/
|
||||
async function listProjectFiles(cwd, exec) {
|
||||
const viaShell = await tryList(exec, "sh", ["-c", LIST_SH, "catalog"], cwd, false);
|
||||
if (viaShell) return { kind: "sh", paths: viaShell };
|
||||
|
||||
const viaPowerShell = await tryList(
|
||||
exec,
|
||||
"powershell",
|
||||
["-NoProfile", "-Command", LIST_PS],
|
||||
cwd,
|
||||
true,
|
||||
);
|
||||
if (viaPowerShell) return { kind: "powershell", paths: viaPowerShell };
|
||||
|
||||
throw new Error("nie udało się wczytać katalogu projektu");
|
||||
}
|
||||
|
||||
/** One listing, or `null` when the program is not there or it failed. */
|
||||
async function tryList(exec, command, args, cwd, windowsPaths) {
|
||||
let result;
|
||||
try {
|
||||
result = await exec(command, args, { cwd });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!result || result.code !== 0) return null;
|
||||
|
||||
return String(result.stdout ?? "")
|
||||
.split("\n")
|
||||
.map((line) => {
|
||||
const path = line.trim();
|
||||
// PowerShell writes the separators of its own platform.
|
||||
return windowsPaths ? path.replace(/\\/g, "/") : path;
|
||||
})
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* One file of the project. The file may be gone between the listing and the
|
||||
* read - then it is left out of the menu, not a reason to fail the catalog.
|
||||
*/
|
||||
async function readFile(cwd, exec, path, kind) {
|
||||
const shells = kind === "sh" ? ["sh", "powershell"] : ["powershell", "sh"];
|
||||
|
||||
for (const shell of shells) {
|
||||
const text = await tryRead(exec, shell, path, cwd);
|
||||
if (text !== null) return text;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** One read, or `null` when the file is not there or cannot be read. */
|
||||
async function tryRead(exec, shell, path, cwd) {
|
||||
const args =
|
||||
shell === "sh"
|
||||
? ["-c", READ_SH, "catalog", path]
|
||||
: ["-NoProfile", "-Command", readScript(path)];
|
||||
|
||||
let result;
|
||||
try {
|
||||
result = await exec(shell, args, { cwd });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!result || result.code !== 0) return null;
|
||||
return String(result.stdout ?? "");
|
||||
}
|
||||
|
||||
/** The PowerShell that reads one file; the path goes in as a literal. */
|
||||
function readScript(path) {
|
||||
const literal = path.replace(/'/g, "''");
|
||||
return (
|
||||
"[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); " +
|
||||
// A file that is gone writes nothing and says nothing - the command
|
||||
// would be a ghost. Without the encoding, Windows PowerShell reads a file
|
||||
// without a BOM as the system's own code page, and the text comes out
|
||||
// garbled.
|
||||
`if (-not (Test-Path -LiteralPath '${literal}')) { exit 1 }; ` +
|
||||
`Get-Content -Raw -Encoding utf8 -ErrorAction Stop -LiteralPath '${literal}'`
|
||||
);
|
||||
}
|
||||
|
||||
/** The name of the command a file holds: the file's name, or a skill's folder. */
|
||||
function commandName(path) {
|
||||
const parts = path.split("/");
|
||||
const file = parts[parts.length - 1] ?? "";
|
||||
if (file.toLowerCase() === "skill.md") return parts[parts.length - 2] ?? "";
|
||||
return file.replace(/\.md$/i, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* What the menu says about a command: the description of the front matter if
|
||||
* there is one, else the first line that says something.
|
||||
*/
|
||||
function describe(markdown) {
|
||||
const { fields, body } = frontmatter(String(markdown ?? ""));
|
||||
if (fields.description) return clip(fields.description);
|
||||
|
||||
const line = body
|
||||
.split("\n")
|
||||
.map((part) => part.trim())
|
||||
.find((part) => part !== "" && !part.startsWith("#"));
|
||||
return clip(line ?? "");
|
||||
}
|
||||
|
||||
/** The front matter of a markdown file, if it has one. */
|
||||
function frontmatter(text) {
|
||||
const match = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(text);
|
||||
if (!match) return { fields: {}, body: text };
|
||||
|
||||
const fields = {};
|
||||
for (const line of match[1].split(/\r?\n/)) {
|
||||
const field = /^([A-Za-z][A-Za-z0-9_-]*):\s*(.*)$/.exec(line);
|
||||
if (!field) continue;
|
||||
fields[field[1].toLowerCase()] = field[2].trim().replace(/^["']|["']$/g, "");
|
||||
}
|
||||
return { fields, body: text.slice(match[0].length) };
|
||||
}
|
||||
|
||||
/** One line of text, no longer than the menu has room for. */
|
||||
function clip(text) {
|
||||
const flat = String(text).replace(/\s+/g, " ").trim();
|
||||
if (flat.length <= 160) return flat;
|
||||
return `${flat.slice(0, 160).replace(/\s\S*$/, "")}…`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The files git tracks in the folder. `-z` keeps the names as they are - git
|
||||
* would otherwise write a name with a non-ASCII character in it quoted and
|
||||
* escaped.
|
||||
*/
|
||||
async function gitFiles(cwd, exec) {
|
||||
let result;
|
||||
try {
|
||||
result = await exec("git", ["ls-files", "--cached", "--others", "--exclude-standard", "-z"], {
|
||||
cwd,
|
||||
});
|
||||
} catch (err) {
|
||||
throw new Error(`nie udało się wczytać plików: ${err?.message ?? String(err)}`);
|
||||
}
|
||||
|
||||
if (!result || result.code !== 0) {
|
||||
const stderr = String(result?.stderr ?? "");
|
||||
// A folder that is not a repository has no files to offer - that is an
|
||||
// empty list, not a catalog that could not be read.
|
||||
if (result?.code === 128 && /repo/i.test(stderr)) return [];
|
||||
throw new Error(
|
||||
`nie udało się wczytać plików: ${stderr.trim() || `git zakończone kodem ${result?.code}`}`,
|
||||
);
|
||||
}
|
||||
|
||||
return String(result.stdout ?? "")
|
||||
.split("\0")
|
||||
.map((path) => path.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
+324
-106
@@ -1,32 +1,63 @@
|
||||
# install.ps1 - link the repo's ovis-composer mod into the Herdr config.
|
||||
# install.ps1 - install the herdr-composer package into the Herdr config.
|
||||
#
|
||||
# .\scripts\install.ps1 install (idempotent)
|
||||
# .\scripts\install.ps1 -Uninstall remove the junction, restore backups
|
||||
# .\scripts\install.ps1 -Reload recreate the junction so Herdr loads the mod again
|
||||
# install.cmd install or update (the same command both times)
|
||||
# install.cmd -Uninstall remove it again
|
||||
#
|
||||
# Herdr does NOT see changes behind the junction on its own: after editing
|
||||
# mod\ovis-composer run -Reload (the junction is removed and made again, and
|
||||
# Herdr reloads the mod).
|
||||
# What install does (Windows PowerShell 5):
|
||||
# 1. git pull --ff-only when this folder is a git clone without local changes
|
||||
# (a failure is a warning - the install goes on with what is here);
|
||||
# 2. COPIES herdr\herdr-composer\mods\herdr-composer to
|
||||
# ~\.config\herdr-app\mods\herdr-composer (a mirror, so Herdr sees the new
|
||||
# files and reloads the mod by itself) and the layout to
|
||||
# ~\.config\herdr-app\layouts\herdr-composer.json (an existing layout that
|
||||
# differs is saved first; an identical one is left alone);
|
||||
# 3. merges the keys of the package (keys.json) into the person's keys.json
|
||||
# (the file is rewritten - the formatting changes, the meaning does not -
|
||||
# and a copy is saved first; a key the person already binds to something
|
||||
# else is left alone, with a warning);
|
||||
# 4. clears away the earlier version (ovis-composer): a junction is only
|
||||
# unlinked, a directory or a layout file is moved out, its key is taken
|
||||
# out of keys.json - files of this repo are never deleted;
|
||||
# 5. herdr-app check on the mod; the layout is switched to herdr-composer on
|
||||
# the first install, or when the earlier ovis-composer was the shown one -
|
||||
# otherwise the person is told how to switch (ctrl-shift-l). No herdr-app
|
||||
# on the PATH is a warning, not an error.
|
||||
#
|
||||
# Works on Windows PowerShell 5.
|
||||
# EVERY copy this script makes goes to
|
||||
# ~\.config\herdr-app\backups\herdr-composer\<yyyyMMdd-HHmmss>\
|
||||
# and never next to the originals: Herdr loads whatever it finds in mods\ and
|
||||
# layouts\, so a backup left there would be loaded as a mod or a layout.
|
||||
#
|
||||
# The person's data (history, favourites, drafts, the queue) is not touched:
|
||||
# the mod reads what the earlier version kept (storage.js).
|
||||
|
||||
[CmdletBinding()]
|
||||
param([switch]$Uninstall, [switch]$Reload)
|
||||
param([switch]$Uninstall)
|
||||
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$Stamp = '20261119'
|
||||
$Name = 'herdr-composer'
|
||||
$OldName = 'ovis-composer'
|
||||
|
||||
$Repo = Split-Path -Parent $PSScriptRoot
|
||||
$HerdrDir = Join-Path $env:USERPROFILE '.config\herdr-app'
|
||||
$Package = Join-Path $Repo 'herdr\herdr-composer'
|
||||
$ModSrc = Join-Path $Package "mods\$Name"
|
||||
$LayoutSrc = Join-Path $Package "layouts\$Name.json"
|
||||
$KeysSrc = Join-Path $Package 'keys.json'
|
||||
|
||||
$HerdrDir = if ($env:HERDR_APP_HOME) { $env:HERDR_APP_HOME } else { Join-Path $env:USERPROFILE '.config\herdr-app' }
|
||||
$ModsDir = Join-Path $HerdrDir 'mods'
|
||||
$Junction = Join-Path $ModsDir 'ovis-composer'
|
||||
$ModBackup = "$Junction.bak-$Stamp"
|
||||
$ModSource = Join-Path $Repo 'mod\ovis-composer'
|
||||
$LayoutSrc = Join-Path $Repo 'layouts\ovis-composer.json'
|
||||
$LayoutDst = Join-Path $HerdrDir 'layouts\ovis-composer.json'
|
||||
$LayoutBak = "$LayoutDst.bak-$Stamp"
|
||||
$LayoutsDir = Join-Path $HerdrDir 'layouts'
|
||||
$ModDst = Join-Path $ModsDir $Name
|
||||
$LayoutDst = Join-Path $LayoutsDir "$Name.json"
|
||||
$KeysFile = Join-Path $HerdrDir 'keys.json'
|
||||
$KeysBak = "$KeysFile.bak-$Stamp"
|
||||
|
||||
# One folder per run; made when the first copy is saved.
|
||||
$BackupDir = Join-Path $HerdrDir "backups\$Name\$(Get-Date -Format 'yyyyMMdd-HHmmss')"
|
||||
$script:KeysSaved = $false
|
||||
|
||||
$OurAction = "$Name.focus"
|
||||
$OldAction = "$OldName.focus"
|
||||
|
||||
function Test-Junction([string]$Path) {
|
||||
if (-not (Test-Path -LiteralPath $Path)) { return $false }
|
||||
@@ -34,121 +65,308 @@ function Test-Junction([string]$Path) {
|
||||
return [bool]($item.Attributes -band [IO.FileAttributes]::ReparsePoint)
|
||||
}
|
||||
|
||||
function Remove-Junction([string]$Path) {
|
||||
# rmdir on a junction removes only the link, never the target's contents.
|
||||
function Remove-Junction([string]$Path) {
|
||||
cmd /c rmdir "`"$Path`"" | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw "rmdir failed for $Path" }
|
||||
}
|
||||
|
||||
# Merge "ctrl-shift-space": "ovis-composer.focus" into keys.json "global",
|
||||
# leaving every other entry alone. Backs the file up once; idempotent.
|
||||
function Install-KeyEntry {
|
||||
$chord = 'ctrl-shift-space'
|
||||
$action = 'ovis-composer.focus'
|
||||
if (-not (Test-Path -LiteralPath $KeysFile)) {
|
||||
$obj = [pscustomobject]@{ global = [pscustomobject]@{ $chord = $action } }
|
||||
} else {
|
||||
$raw = [IO.File]::ReadAllText($KeysFile)
|
||||
$obj = $raw | ConvertFrom-Json
|
||||
if ($obj -isnot [pscustomobject]) { throw "keys.json is not a JSON object - resolve by hand." }
|
||||
if (-not $obj.PSObject.Properties['global']) {
|
||||
$obj | Add-Member -NotePropertyName 'global' -NotePropertyValue ([pscustomobject]@{})
|
||||
# The path in the backup folder for an item with this name (never an existing one).
|
||||
function Get-BackupPath([string]$ItemName) {
|
||||
New-Item -ItemType Directory -Force -Path $BackupDir | Out-Null
|
||||
$candidate = Join-Path $BackupDir $ItemName
|
||||
$n = 1
|
||||
while (Test-Path -LiteralPath $candidate) {
|
||||
$candidate = Join-Path $BackupDir "$ItemName-$n"
|
||||
$n++
|
||||
}
|
||||
$global = $obj.global
|
||||
if ($global.PSObject.Properties[$chord] -and $global.$chord -eq $action) {
|
||||
Write-Host "keys.json already has $chord"
|
||||
return $candidate
|
||||
}
|
||||
|
||||
# Moves a file or directory out of mods\ / layouts\ into the backup folder.
|
||||
function Move-ToBackup([string]$Path) {
|
||||
$target = Get-BackupPath (Split-Path -Leaf $Path)
|
||||
Move-Item -LiteralPath $Path -Destination $target
|
||||
return $target
|
||||
}
|
||||
|
||||
# Nothing this script deletes or overwrites may be inside the repo.
|
||||
function Assert-OutsideRepo([string]$Path) {
|
||||
$full = [IO.Path]::GetFullPath($Path).TrimEnd([char]92)
|
||||
$repo = [IO.Path]::GetFullPath($Repo).TrimEnd([char]92)
|
||||
if ($full -ieq $repo -or $full.StartsWith($repo + '\', [StringComparison]::OrdinalIgnoreCase)) {
|
||||
throw "$Path is inside the repo - refusing to touch it."
|
||||
}
|
||||
}
|
||||
|
||||
function Test-HerdrApp { return [bool](Get-Command 'herdr-app' -ErrorAction SilentlyContinue) }
|
||||
|
||||
# Runs herdr-app and waits for it.
|
||||
#
|
||||
# herdr-app.exe is a program of the GUI subsystem: PowerShell does not wait for
|
||||
# it and does not set $LASTEXITCODE (whatever the last console program left
|
||||
# there stays - 1 after robocopy means "copied"). So it is started with
|
||||
# Start-Process, waited for, and its exit code and output are read from the
|
||||
# process and from two temporary files.
|
||||
#
|
||||
# Returns ExitCode, Output (stdout) and Error (stderr).
|
||||
function Invoke-HerdrApp([string[]]$Arguments) {
|
||||
$exe = (Get-Command 'herdr-app' -ErrorAction Stop).Source
|
||||
$outFile = [IO.Path]::GetTempFileName()
|
||||
$errFile = [IO.Path]::GetTempFileName()
|
||||
try {
|
||||
$quoted = @($Arguments | ForEach-Object {
|
||||
if ($_ -match '[\s"]') { '"' + ($_ -replace '"', '\"') + '"' } else { $_ }
|
||||
})
|
||||
$process = Start-Process -FilePath $exe -ArgumentList $quoted -NoNewWindow -PassThru `
|
||||
-RedirectStandardOutput $outFile -RedirectStandardError $errFile
|
||||
# Holding the handle keeps ExitCode readable after the process ended.
|
||||
$null = $process.Handle
|
||||
$process.WaitForExit()
|
||||
return [pscustomobject]@{
|
||||
ExitCode = $process.ExitCode
|
||||
Output = [IO.File]::ReadAllText($outFile)
|
||||
Error = [IO.File]::ReadAllText($errFile)
|
||||
}
|
||||
} finally {
|
||||
Remove-Item -LiteralPath $outFile, $errFile -Force -ErrorAction SilentlyContinue
|
||||
}
|
||||
}
|
||||
|
||||
# Prints what herdr-app said (stdout, then stderr).
|
||||
function Write-HerdrOutput($Result) {
|
||||
foreach ($text in @($Result.Output, $Result.Error)) {
|
||||
if ($text -and $text.Trim() -ne '') { Write-Host ($text.TrimEnd()) }
|
||||
}
|
||||
}
|
||||
|
||||
# The name of the layout the window shows now, or nothing when it cannot be told.
|
||||
function Get-ActiveLayout {
|
||||
if (-not (Test-HerdrApp)) { return $null }
|
||||
try {
|
||||
$result = Invoke-HerdrApp @('status')
|
||||
if ($result.ExitCode -ne 0) { return $null }
|
||||
return [string]($result.Output | ConvertFrom-Json).layout
|
||||
} catch {
|
||||
return $null
|
||||
}
|
||||
}
|
||||
|
||||
function Switch-Layout([string]$LayoutName) {
|
||||
if (-not (Test-HerdrApp)) {
|
||||
Write-Warning "herdr-app is not on the PATH - switch the layout to '$LayoutName' by hand (ctrl-shift-l)."
|
||||
return
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $KeysBak)) {
|
||||
Copy-Item -LiteralPath $KeysFile -Destination $KeysBak
|
||||
Write-Host "Backed up keys.json to $KeysBak"
|
||||
# `--name <x>`, not a JSON argument: quotes inside an argument do not survive.
|
||||
$result = Invoke-HerdrApp @('do', 'layout.switch', '--name', $LayoutName)
|
||||
Write-HerdrOutput $result
|
||||
if ($result.ExitCode -ne 0) {
|
||||
Write-Warning "layout.switch to '$LayoutName' failed (exit $($result.ExitCode)) - switch it by hand (ctrl-shift-l)."
|
||||
}
|
||||
$global | Add-Member -NotePropertyName $chord -NotePropertyValue $action -Force
|
||||
}
|
||||
$json = $obj | ConvertTo-Json -Depth 32
|
||||
[IO.File]::WriteAllText($KeysFile, $json, (New-Object Text.UTF8Encoding($false)))
|
||||
Write-Host "keys.json: $chord -> $action"
|
||||
}
|
||||
|
||||
if ($Reload) {
|
||||
if (-not (Test-Junction $Junction)) { throw "$Junction is not a junction - run install.ps1 first." }
|
||||
Remove-Junction $Junction
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $ModSource 'main.js'))) {
|
||||
throw 'Repo files vanished after removing the junction - aborting.'
|
||||
# --- keys.json ----------------------------------------------------------------
|
||||
|
||||
function Read-Json([string]$Path) {
|
||||
$raw = [IO.File]::ReadAllText($Path)
|
||||
if ($raw.Trim() -eq '') { return [pscustomobject]@{} }
|
||||
$obj = $raw | ConvertFrom-Json
|
||||
if ($obj -isnot [pscustomobject]) { throw "$Path is not a JSON object - resolve by hand." }
|
||||
return $obj
|
||||
}
|
||||
cmd /c mklink /J "`"$Junction`"" "`"$ModSource`"" | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'mklink /J failed' }
|
||||
Write-Host "Junction recreated: $Junction -> $ModSource (Herdr loads the mod again)"
|
||||
exit 0
|
||||
|
||||
function Write-Json($Object, [string]$Path) {
|
||||
$json = $Object | ConvertTo-Json -Depth 32
|
||||
[IO.File]::WriteAllText($Path, $json, (New-Object Text.UTF8Encoding($false)))
|
||||
}
|
||||
|
||||
# A copy of keys.json, once per run, before it is rewritten.
|
||||
function Save-KeysCopy {
|
||||
if ($script:KeysSaved -or -not (Test-Path -LiteralPath $KeysFile)) { return }
|
||||
$target = Get-BackupPath 'keys.json'
|
||||
Copy-Item -LiteralPath $KeysFile -Destination $target
|
||||
$script:KeysSaved = $true
|
||||
Write-Host "Saved a copy of keys.json: $target"
|
||||
}
|
||||
|
||||
# Takes out every key (in every section) that is bound to one of $Actions.
|
||||
# Returns how many it removed.
|
||||
function Remove-KeyActions($Keys, [string[]]$Actions) {
|
||||
$removed = 0
|
||||
foreach ($section in @($Keys.PSObject.Properties)) {
|
||||
if ($section.Value -isnot [pscustomobject]) { continue }
|
||||
foreach ($key in @($section.Value.PSObject.Properties)) {
|
||||
if ($Actions -contains [string]$key.Value) {
|
||||
$section.Value.PSObject.Properties.Remove($key.Name)
|
||||
$removed++
|
||||
}
|
||||
}
|
||||
}
|
||||
return $removed
|
||||
}
|
||||
|
||||
# Merges the keys of the package into the person's: adds what is missing, keeps
|
||||
# what is there, warns about a key the person binds to something else.
|
||||
function Update-Keys {
|
||||
if (-not (Test-Path -LiteralPath $KeysSrc)) { return }
|
||||
$package = Read-Json $KeysSrc
|
||||
|
||||
if (-not (Test-Path -LiteralPath $KeysFile)) {
|
||||
Write-Json $package $KeysFile
|
||||
Write-Host "keys.json created from the package"
|
||||
return
|
||||
}
|
||||
|
||||
$mine = Read-Json $KeysFile
|
||||
$changed = $false
|
||||
|
||||
# The key of the earlier version points at an action that no longer exists.
|
||||
if ((Remove-KeyActions $mine @($OldAction)) -gt 0) {
|
||||
Save-KeysCopy
|
||||
$changed = $true
|
||||
Write-Host "keys.json: removed the key of $OldName"
|
||||
}
|
||||
|
||||
foreach ($section in $package.PSObject.Properties) {
|
||||
if (-not $mine.PSObject.Properties[$section.Name]) {
|
||||
Save-KeysCopy
|
||||
$mine | Add-Member -NotePropertyName $section.Name -NotePropertyValue ([pscustomobject]@{})
|
||||
$changed = $true
|
||||
}
|
||||
$target = $mine.($section.Name)
|
||||
foreach ($key in $section.Value.PSObject.Properties) {
|
||||
$existing = $target.PSObject.Properties[$key.Name]
|
||||
if ($existing) {
|
||||
if ([string]$existing.Value -ne [string]$key.Value) {
|
||||
Write-Warning "keys.json: '$($key.Name)' is already bound to '$($existing.Value)' - left as it is (the package wants '$($key.Value)')."
|
||||
}
|
||||
continue
|
||||
}
|
||||
Save-KeysCopy
|
||||
$target | Add-Member -NotePropertyName $key.Name -NotePropertyValue $key.Value
|
||||
$changed = $true
|
||||
Write-Host "keys.json: $($key.Name) -> $($key.Value)"
|
||||
}
|
||||
}
|
||||
|
||||
if ($changed) { Write-Json $mine $KeysFile } else { Write-Host "keys.json already has the keys" }
|
||||
}
|
||||
|
||||
function Remove-OurKeys {
|
||||
if (-not (Test-Path -LiteralPath $KeysFile)) { return }
|
||||
$mine = Read-Json $KeysFile
|
||||
if ((Remove-KeyActions $mine @($OurAction, $OldAction)) -gt 0) {
|
||||
Save-KeysCopy
|
||||
Write-Json $mine $KeysFile
|
||||
Write-Host "keys.json: removed the keys of $Name"
|
||||
}
|
||||
}
|
||||
|
||||
# --- uninstall ----------------------------------------------------------------
|
||||
|
||||
if ($Uninstall) {
|
||||
if (Test-Junction $Junction) {
|
||||
Remove-Junction $Junction
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $ModSource 'main.js'))) {
|
||||
throw 'Repo files vanished after removing the junction - aborting.'
|
||||
Assert-OutsideRepo $ModDst
|
||||
if (Test-Junction $ModDst) {
|
||||
Remove-Junction $ModDst
|
||||
Write-Host "Removed junction $ModDst"
|
||||
} elseif (Test-Path -LiteralPath $ModDst) {
|
||||
Remove-Item -LiteralPath $ModDst -Recurse -Force
|
||||
Write-Host "Removed $ModDst"
|
||||
}
|
||||
Write-Host "Removed junction $Junction"
|
||||
if (Test-Path -LiteralPath $LayoutDst) {
|
||||
Remove-Item -LiteralPath $LayoutDst -Force
|
||||
Write-Host "Removed $LayoutDst"
|
||||
}
|
||||
if ((Test-Path -LiteralPath $ModBackup) -and -not (Test-Path -LiteralPath $Junction)) {
|
||||
Move-Item -LiteralPath $ModBackup -Destination $Junction
|
||||
Write-Host "Restored $Junction"
|
||||
}
|
||||
if (Test-Path -LiteralPath $LayoutBak) {
|
||||
Copy-Item -LiteralPath $LayoutBak -Destination $LayoutDst -Force
|
||||
Write-Host "Restored layout"
|
||||
}
|
||||
if (Test-Path -LiteralPath $KeysBak) {
|
||||
Copy-Item -LiteralPath $KeysBak -Destination $KeysFile -Force
|
||||
Write-Host "Restored keys.json"
|
||||
}
|
||||
herdr-app do layout.switch '{"name":"main"}'
|
||||
if ($LASTEXITCODE -ne 0) { Write-Warning "layout.switch to main failed (exit $LASTEXITCODE) - switch the layout by hand." }
|
||||
Remove-OurKeys
|
||||
Switch-Layout 'main'
|
||||
exit 0
|
||||
}
|
||||
|
||||
# 1. Mod directory -> junction to the repo.
|
||||
$relink = $false
|
||||
if (Test-Junction $Junction) {
|
||||
$target = (Get-Item -LiteralPath $Junction -Force).Target
|
||||
if ($target -is [array]) { $target = $target[0] }
|
||||
if ($target -and ([IO.Path]::GetFullPath($target).TrimEnd([char]92) -ieq [IO.Path]::GetFullPath($ModSource).TrimEnd([char]92))) {
|
||||
Write-Host "Junction already in place: $Junction"
|
||||
# --- install ------------------------------------------------------------------
|
||||
|
||||
if (-not (Test-Path -LiteralPath (Join-Path $ModSrc 'main.js'))) { throw "Package not found: $ModSrc" }
|
||||
if (-not (Test-Path -LiteralPath $HerdrDir)) { throw "Herdr config not found: $HerdrDir (is Herdr installed and started once?)" }
|
||||
Assert-OutsideRepo $ModDst
|
||||
Assert-OutsideRepo $LayoutDst
|
||||
|
||||
# What decides whether the layout is switched at the end - read before anything changes.
|
||||
$firstInstall = -not (Test-Path -LiteralPath $LayoutDst)
|
||||
$activeLayout = Get-ActiveLayout
|
||||
|
||||
# 1. Update the repo when it is a clean clone.
|
||||
if ((Test-Path -LiteralPath (Join-Path $Repo '.git')) -and (Get-Command git -ErrorAction SilentlyContinue)) {
|
||||
try {
|
||||
$dirty = & git -C $Repo status --porcelain
|
||||
if ($dirty) {
|
||||
Write-Warning 'Local changes in the repo - not updating it (git pull skipped).'
|
||||
} else {
|
||||
Write-Host "Junction points at '$target' - recreating it for $ModSource"
|
||||
Remove-Junction $Junction
|
||||
$relink = $true
|
||||
& git -C $Repo pull --ff-only
|
||||
if ($LASTEXITCODE -ne 0) { Write-Warning "git pull --ff-only failed (exit $LASTEXITCODE) - installing what is here." }
|
||||
}
|
||||
} else { $relink = $true }
|
||||
if ($relink) {
|
||||
if (Test-Path -LiteralPath $Junction) {
|
||||
if (Test-Path -LiteralPath $ModBackup) { throw "$ModBackup already exists - resolve by hand." }
|
||||
Move-Item -LiteralPath $Junction -Destination $ModBackup
|
||||
Write-Host "Backed up to $ModBackup"
|
||||
} catch {
|
||||
Write-Warning "git pull failed: $($_.Exception.Message) - installing what is here."
|
||||
}
|
||||
cmd /c mklink /J "`"$Junction`"" "`"$ModSource`"" | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { throw 'mklink /J failed' }
|
||||
Write-Host "Junction: $Junction -> $ModSource"
|
||||
}
|
||||
|
||||
# gpui-kit.d.ts is git-ignored; keep a copy next to the sources for the editor.
|
||||
$kitDst = Join-Path $ModSource 'gpui-kit.d.ts'
|
||||
$kitSrc = if (Test-Path -LiteralPath (Join-Path $ModBackup 'gpui-kit.d.ts')) { Join-Path $ModBackup 'gpui-kit.d.ts' } else { Join-Path $HerdrDir 'gpui-kit.d.ts' }
|
||||
if (-not (Test-Path -LiteralPath $kitDst) -and (Test-Path -LiteralPath $kitSrc)) {
|
||||
Copy-Item -LiteralPath $kitSrc -Destination $kitDst
|
||||
# 2. The earlier version (ovis-composer) goes out of the way.
|
||||
$OldMod = Join-Path $ModsDir $OldName
|
||||
if (Test-Junction $OldMod) {
|
||||
Remove-Junction $OldMod
|
||||
Write-Host "Removed the junction of the earlier version: $OldMod"
|
||||
} elseif (Test-Path -LiteralPath $OldMod) {
|
||||
$saved = Move-ToBackup $OldMod
|
||||
Write-Host "Moved the earlier version to $saved"
|
||||
}
|
||||
$OldLayout = Join-Path $LayoutsDir "$OldName.json"
|
||||
if (Test-Path -LiteralPath $OldLayout) {
|
||||
$saved = Move-ToBackup $OldLayout
|
||||
Write-Host "Moved the earlier layout to $saved"
|
||||
}
|
||||
|
||||
# 2. Layout (back up the existing file once).
|
||||
if ((Test-Path -LiteralPath $LayoutDst) -and -not (Test-Path -LiteralPath $LayoutBak)) {
|
||||
Copy-Item -LiteralPath $LayoutDst -Destination $LayoutBak
|
||||
Write-Host "Backed up layout to $LayoutBak"
|
||||
}
|
||||
# 3. The mod: a mirror copy. gpui-kit.d.ts and jsconfig.json are the editor's,
|
||||
# written by Herdr next to the mod - they are not part of the copy and are not
|
||||
# purged from the destination.
|
||||
New-Item -ItemType Directory -Force -Path $ModsDir | Out-Null
|
||||
if (Test-Junction $ModDst) { Remove-Junction $ModDst }
|
||||
robocopy $ModSrc $ModDst /MIR /XF gpui-kit.d.ts jsconfig.json /NFL /NDL /NJH /NJS /NP | Out-Null
|
||||
$robocopyExit = $LASTEXITCODE
|
||||
# 0-7 are all "fine" for robocopy (1 = files were copied); nothing below may
|
||||
# read this code as if it were the result of its own command.
|
||||
$global:LASTEXITCODE = 0
|
||||
if ($robocopyExit -ge 8) { throw "robocopy failed (exit $robocopyExit)" }
|
||||
Write-Host "Mod copied: $ModDst"
|
||||
|
||||
# 4. The layout: an existing one that differs is saved first, an identical one stays.
|
||||
New-Item -ItemType Directory -Force -Path $LayoutsDir | Out-Null
|
||||
if (Test-Path -LiteralPath $LayoutDst) {
|
||||
$same = (Get-FileHash -LiteralPath $LayoutSrc -Algorithm SHA256).Hash -eq (Get-FileHash -LiteralPath $LayoutDst -Algorithm SHA256).Hash
|
||||
if ($same) {
|
||||
Write-Host "Layout is up to date: $LayoutDst"
|
||||
} else {
|
||||
$saved = Move-ToBackup $LayoutDst
|
||||
Write-Host "Saved the layout that was there: $saved"
|
||||
Copy-Item -LiteralPath $LayoutSrc -Destination $LayoutDst -Force
|
||||
Write-Host "Layout copied"
|
||||
Write-Host "Layout copied: $LayoutDst"
|
||||
}
|
||||
} else {
|
||||
Copy-Item -LiteralPath $LayoutSrc -Destination $LayoutDst -Force
|
||||
Write-Host "Layout copied: $LayoutDst"
|
||||
}
|
||||
|
||||
# 3. Key binding (Task 2).
|
||||
Install-KeyEntry
|
||||
# 5. Keys.
|
||||
Update-Keys
|
||||
|
||||
# 4. Show the layout.
|
||||
herdr-app do layout.switch '{"name":"ovis-composer"}'
|
||||
if ($LASTEXITCODE -ne 0) { Write-Warning "layout.switch to ovis-composer failed (exit $LASTEXITCODE) - switch the layout by hand." }
|
||||
# 6. Check the mod; switch the layout only where the person has not chosen another one.
|
||||
if (Test-HerdrApp) {
|
||||
$check = Invoke-HerdrApp @('check', $ModDst)
|
||||
Write-HerdrOutput $check
|
||||
if ($check.ExitCode -ne 0) { Write-Warning "herdr-app check reported a problem (exit $($check.ExitCode))." }
|
||||
} else {
|
||||
Write-Warning 'herdr-app is not on the PATH - the mod was not checked.'
|
||||
}
|
||||
if ($firstInstall -or $activeLayout -eq $OldName) {
|
||||
Switch-Layout $Name
|
||||
} elseif ($activeLayout -ne $Name) {
|
||||
# ASCII only in this file (Windows PowerShell 5 reads it in the ANSI code page): the Polish letters are built.
|
||||
Write-Host "Prze$([char]0x0142)$([char]0x0105)cz layout: ctrl-shift-l (layout '$Name')"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { LIMITS, validate, validateMany, mention, removeMention } from "../mod/ovis-composer/attachments.js";
|
||||
import { LIMITS, validate, validateMany, mention, removeMention } from "../herdr/herdr-composer/mods/herdr-composer/attachments.js";
|
||||
|
||||
test("validate rejects over 32 MiB", () => {
|
||||
const r = validate({ bytes: 33 * 2 ** 20 });
|
||||
@@ -59,7 +59,7 @@ test("removeMention takes the quoted form and the bare form out", () => {
|
||||
assert.equal(removeMention('see @"/a b/c.png"x now', "/a b/c.png"), 'see @"/a b/c.png"x now');
|
||||
});
|
||||
|
||||
import { formatBytes } from "../mod/ovis-composer/attachments.js";
|
||||
import { formatBytes } from "../herdr/herdr-composer/mods/herdr-composer/attachments.js";
|
||||
|
||||
test("formatBytes", () => {
|
||||
assert.equal(formatBytes(0), "0 B");
|
||||
@@ -71,12 +71,12 @@ test("formatBytes", () => {
|
||||
assert.equal(formatBytes(NaN), "");
|
||||
});
|
||||
|
||||
import { relativeTo } from "../mod/ovis-composer/attachments.js";
|
||||
import { relativeTo } from "../herdr/herdr-composer/mods/herdr-composer/attachments.js";
|
||||
|
||||
test("relativeTo: a file inside the folder, forward slashes, any case", () => {
|
||||
assert.equal(
|
||||
relativeTo("C:\\Users\\Factor\\.config\\herdr-app", "C:\\Users\\Factor\\.config\\herdr-app\\data\\ovis-composer\\paste\\paste-1.png"),
|
||||
"data/ovis-composer/paste/paste-1.png",
|
||||
relativeTo("C:\\Users\\Factor\\.config\\herdr-app", "C:\\Users\\Factor\\.config\\herdr-app\\data\\herdr-composer\\paste\\paste-1.png"),
|
||||
"data/herdr-composer/paste/paste-1.png",
|
||||
);
|
||||
assert.equal(relativeTo("c:/users/factor/.config/herdr-app/", "C:\\Users\\Factor\\.config\\herdr-app\\a b\\ę.png"), "a b/ę.png");
|
||||
});
|
||||
|
||||
@@ -0,0 +1,458 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
BUILTINS,
|
||||
commands,
|
||||
globalCommands,
|
||||
historyCommands,
|
||||
menuNotes,
|
||||
} from "../herdr/herdr-composer/mods/herdr-composer/catalog.js";
|
||||
import {
|
||||
DEFAULT_PROFILES,
|
||||
resolveProfile,
|
||||
} from "../herdr/herdr-composer/mods/herdr-composer/profiles.js";
|
||||
import {
|
||||
GROUPS,
|
||||
GROUP_HISTORY,
|
||||
GROUP_USER,
|
||||
GROUP_PLUGIN,
|
||||
} from "../herdr/herdr-composer/mods/herdr-composer/suggest.js";
|
||||
|
||||
const HOME = "C:/Users/Test";
|
||||
const CC_PROFILE = DEFAULT_PROFILES[0];
|
||||
const CC = CC_PROFILE.sources;
|
||||
|
||||
/**
|
||||
* A fake machine: `files` maps a path to its text. `exec` answers the POSIX
|
||||
* listing of catalog.js (powershell is "not installed"), `readText` reads.
|
||||
*/
|
||||
function machine(files, { listError = false } = {}) {
|
||||
const exec = async (command, args) => {
|
||||
if (command !== "sh") throw new Error("not found");
|
||||
if (listError) return { code: 2, stdout: "", stderr: "boom" };
|
||||
const rest = args.slice(3);
|
||||
const lines = [];
|
||||
for (let i = 0; i + 2 < rest.length; i += 3) {
|
||||
const [index, kind, path] = rest.slice(i, i + 3);
|
||||
for (const file of Object.keys(files)) {
|
||||
const name = file.slice(file.lastIndexOf("/") + 1);
|
||||
const dir = file.slice(0, file.lastIndexOf("/"));
|
||||
if (kind === "file" && file === path) lines.push(`${index}\t${file}`);
|
||||
if (kind === "md" && dir === path && name.endsWith(".md")) lines.push(`${index}\t${file}`);
|
||||
if (kind === "skills" && name === "SKILL.md" && dir.slice(0, dir.lastIndexOf("/")) === path)
|
||||
lines.push(`${index}\t${file}`);
|
||||
}
|
||||
}
|
||||
return { code: 0, stdout: lines.join("\n"), stderr: "" };
|
||||
};
|
||||
const readText = async (path) => files[path] ?? null;
|
||||
return { exec, readText };
|
||||
}
|
||||
|
||||
const skill = (name, extra = "") => `---\nname: ${name}\ndescription: Opis ${name}\n${extra}---\nTreść\n`;
|
||||
|
||||
function plugins(enabled, installed) {
|
||||
return {
|
||||
[`${HOME}/.claude/settings.json`]: JSON.stringify({ enabledPlugins: enabled }),
|
||||
[`${HOME}/.claude/plugins/installed_plugins.json`]: JSON.stringify({
|
||||
version: 2,
|
||||
plugins: Object.fromEntries(
|
||||
Object.entries(installed).map(([id, path]) => [id, [{ installPath: path }]]),
|
||||
),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One fake machine for the project (relative paths, `cwd` given) and the
|
||||
* person's home (absolute paths). It answers the POSIX scripts of catalog.js:
|
||||
* the old fixed project listing, and the listing by (index, kind, path)
|
||||
* triples; PowerShell is "not installed".
|
||||
*/
|
||||
function ccMachine(files) {
|
||||
const inner = machine(files);
|
||||
const match = (index, kind, path) => {
|
||||
const lines = [];
|
||||
for (const file of Object.keys(files)) {
|
||||
const name = file.slice(file.lastIndexOf("/") + 1);
|
||||
const dir = file.slice(0, file.lastIndexOf("/"));
|
||||
if (kind === "file" && file === path) lines.push(`${index}\t${file}`);
|
||||
if (kind === "md" && dir === path && name.endsWith(".md")) lines.push(`${index}\t${file}`);
|
||||
if (kind === "skills" && name === "SKILL.md" && dir.slice(0, dir.lastIndexOf("/")) === path)
|
||||
lines.push(`${index}\t${file}`);
|
||||
}
|
||||
return lines;
|
||||
};
|
||||
const exec = async (command, args, options = {}) => {
|
||||
if (command !== "sh") throw new Error("not found");
|
||||
const rest = args.slice(3);
|
||||
// the new listing of a profile's project sources: the same triples
|
||||
if (options.cwd && rest.length > 0 && rest.length % 3 === 0 && /^\d+$/.test(rest[0])) {
|
||||
const lines = [];
|
||||
for (let i = 0; i < rest.length; i += 3) lines.push(...match(rest[i], rest[i + 1], rest[i + 2]));
|
||||
return { code: 0, stdout: lines.join("\n"), stderr: "" };
|
||||
}
|
||||
// the old fixed listing of the project
|
||||
if (options.cwd && rest.length === 0) {
|
||||
const stdout = Object.keys(files)
|
||||
.filter((f) => /^\.claude\/(commands\/[^/]+\.md|skills\/[^/]+\/SKILL\.md)$/.test(f))
|
||||
.join("\n");
|
||||
return { code: 0, stdout, stderr: "" };
|
||||
}
|
||||
// a read of one file
|
||||
if (rest.length === 1) {
|
||||
const text = files[rest[0]];
|
||||
return text === undefined ? { code: 1, stdout: "", stderr: "" } : { code: 0, stdout: text, stderr: "" };
|
||||
}
|
||||
return inner.exec(command, args, options);
|
||||
};
|
||||
return { exec, readText: inner.readText };
|
||||
}
|
||||
|
||||
const CC_FILES = {
|
||||
".claude/commands/a.md": "---\ndescription: Komenda a\n---\nTreść\n",
|
||||
".claude/skills/s/SKILL.md": skill("inna"),
|
||||
[`${HOME}/.claude/commands/handoff.md`]: "---\ndescription: Przekazanie\n---\nTreść\n",
|
||||
...plugins({ "sp@official": true }, { "sp@official": "C:\\p\\sp" }),
|
||||
"C:/p/sp/skills/brainstorming/SKILL.md": skill("brainstorming"),
|
||||
};
|
||||
|
||||
const ccRow = (item) => ({ key: item.key, group: item.group, insert: item.insert, desc: item.desc });
|
||||
|
||||
test("GROUPS has Pluginy right after Użytkownik", () => {
|
||||
assert.equal(GROUPS[GROUPS.indexOf(GROUP_USER) + 1], "Pluginy");
|
||||
assert.equal(GROUP_PLUGIN, "Pluginy");
|
||||
});
|
||||
|
||||
test("claude-code builtins: the full list, unique keys", () => {
|
||||
const keys = BUILTINS["claude-code"].map((item) => item.key);
|
||||
for (const key of ["context", "help", "mcp", "rewind", "clear"]) assert.ok(keys.includes(key), key);
|
||||
assert.equal(new Set(keys).size, keys.length);
|
||||
assert.deepEqual(keys, [...keys].sort());
|
||||
});
|
||||
|
||||
test("globalCommands: an enabled plugin gives plugin:name (default skills dir)", async () => {
|
||||
const dir = "C:/p/superpowers/7.0.2";
|
||||
const { exec, readText } = machine({
|
||||
...plugins({ "superpowers@official": true }, { "superpowers@official": "C:\\p\\superpowers\\7.0.2" }),
|
||||
[`${dir}/skills/brainstorming/SKILL.md`]: skill("brainstorming"),
|
||||
});
|
||||
const items = await globalCommands(HOME, exec, readText, { sources: CC });
|
||||
assert.equal(items.length, 1);
|
||||
assert.equal(items[0].key, "superpowers:brainstorming");
|
||||
assert.equal(items[0].group, GROUP_PLUGIN);
|
||||
assert.equal(items[0].insert, "/superpowers:brainstorming ");
|
||||
assert.equal(items[0].desc, "Opis brainstorming");
|
||||
});
|
||||
|
||||
test("globalCommands: disabled or unlisted plugin gives nothing", async () => {
|
||||
const dir = "C:/p/a/1";
|
||||
const { exec, readText } = machine({
|
||||
...plugins({ "a@m": false }, { "a@m": dir, "b@m": "C:/p/b/1" }),
|
||||
[`${dir}/skills/x/SKILL.md`]: skill("x"),
|
||||
["C:/p/b/1/skills/y/SKILL.md"]: skill("y"),
|
||||
});
|
||||
assert.deepEqual(await globalCommands(HOME, exec, readText, { sources: CC }), []);
|
||||
});
|
||||
|
||||
test("globalCommands: plugin.json skills array takes only the named dirs", async () => {
|
||||
const dir = "C:/p/mp/1";
|
||||
const { exec, readText } = machine({
|
||||
...plugins({ "mp@m": true }, { "mp@m": dir }),
|
||||
[`${dir}/.claude-plugin/plugin.json`]: JSON.stringify({ skills: ["./skills/eng/tdd"] }),
|
||||
[`${dir}/skills/eng/tdd/SKILL.md`]: skill("tdd"),
|
||||
[`${dir}/skills/eng/other/SKILL.md`]: skill("other"),
|
||||
[`${dir}/skills/direct/SKILL.md`]: skill("direct"),
|
||||
});
|
||||
const keys = (await globalCommands(HOME, exec, readText, { sources: CC })).map((item) => item.key);
|
||||
assert.deepEqual(keys, ["mp:tdd"]);
|
||||
});
|
||||
|
||||
test("globalCommands: plugin commands dir and user-invocable false", async () => {
|
||||
const dir = "C:/p/c/1";
|
||||
const { exec, readText } = machine({
|
||||
...plugins({ "c@m": true }, { "c@m": dir }),
|
||||
[`${dir}/commands/ship.md`]: "---\ndescription: Wysyła\n---\n",
|
||||
[`${dir}/skills/hidden/SKILL.md`]: skill("hidden", "user-invocable: false\n"),
|
||||
[`${dir}/skills/shown/SKILL.md`]: skill("shown"),
|
||||
});
|
||||
const keys = (await globalCommands(HOME, exec, readText, { sources: CC })).map((item) => item.key).sort();
|
||||
assert.deepEqual(keys, ["c:ship", "c:shown"]);
|
||||
});
|
||||
|
||||
test("globalCommands: name: in the front matter wins over the folder name", async () => {
|
||||
const { exec, readText } = machine({
|
||||
[`${HOME}/.claude/skills/folder/SKILL.md`]: skill("real-name"),
|
||||
});
|
||||
const items = await globalCommands(HOME, exec, readText, { sources: CC });
|
||||
assert.deepEqual(items.map((item) => item.key), ["real-name"]);
|
||||
});
|
||||
|
||||
test("globalCommands: a user command gives handoff in Użytkownik", async () => {
|
||||
const { exec, readText } = machine({
|
||||
[`${HOME}/.claude/commands/handoff.md`]: "---\ndescription: Przekazanie\n---\n",
|
||||
});
|
||||
const items = await globalCommands(HOME, exec, readText, { sources: CC });
|
||||
assert.equal(items.length, 1);
|
||||
assert.equal(items[0].key, "handoff");
|
||||
assert.equal(items[0].group, GROUP_USER);
|
||||
assert.equal(items[0].insert, "/handoff ");
|
||||
});
|
||||
|
||||
test("globalCommands: no settings.json, broken json: user items only, no throw", async () => {
|
||||
const none = machine({ [`${HOME}/.claude/commands/a.md`]: "x" });
|
||||
assert.deepEqual((await globalCommands(HOME, none.exec, none.readText, { sources: CC })).map((i) => i.key), ["a"]);
|
||||
|
||||
const broken = machine({
|
||||
[`${HOME}/.claude/settings.json`]: "{nope",
|
||||
[`${HOME}/.claude/plugins/installed_plugins.json`]: "[[",
|
||||
[`${HOME}/.claude/commands/a.md`]: "x",
|
||||
});
|
||||
assert.deepEqual((await globalCommands(HOME, broken.exec, broken.readText, { sources: CC })).map((i) => i.key), ["a"]);
|
||||
});
|
||||
|
||||
test("globalCommands: a listing failure goes to onReadError, or throws", async () => {
|
||||
const { exec, readText } = machine({}, { listError: true });
|
||||
const errors = [];
|
||||
const items = await globalCommands(HOME, exec, readText, { sources: CC, onReadError: (err) => errors.push(err) });
|
||||
assert.deepEqual(items, []);
|
||||
assert.equal(errors.length, 1);
|
||||
await assert.rejects(() => globalCommands(HOME, exec, readText, { sources: CC }));
|
||||
});
|
||||
|
||||
test("paths with spaces and Polish letters are not put in the PowerShell script as text", async () => {
|
||||
const home = "D:/Użytkownik Zażółć/x";
|
||||
let script = "";
|
||||
const exec = async (command, args) => {
|
||||
if (command === "powershell") {
|
||||
script = args[args.length - 1];
|
||||
return { code: 0, stdout: "", stderr: "" };
|
||||
}
|
||||
throw new Error("no");
|
||||
};
|
||||
await globalCommands(home, exec, async () => null, { sources: CC });
|
||||
assert.ok(script.length > 0);
|
||||
assert.ok(!script.includes("Zażółć"));
|
||||
});
|
||||
|
||||
test("commands: options.global joins after the project, first key wins", async () => {
|
||||
const exec = async () => ({ code: 0, stdout: "", stderr: "" });
|
||||
const global = [
|
||||
{ key: "clear", desc: "dup", group: GROUP_USER, insert: "/clear " },
|
||||
{ key: "handoff", desc: "h", group: GROUP_USER, insert: "/handoff " },
|
||||
];
|
||||
const items = await commands("/x", exec, { profile: CC_PROFILE, global });
|
||||
assert.equal(items.filter((item) => item.key === "clear").length, 1);
|
||||
assert.equal(
|
||||
items.find((item) => item.key === "clear").desc,
|
||||
BUILTINS["claude-code"].find((item) => item.key === "clear").desc,
|
||||
);
|
||||
assert.ok(items.some((item) => item.key === "handoff"));
|
||||
});
|
||||
|
||||
test("commands: codex gets its builtins and snippets - no project sources, no exec", async () => {
|
||||
let calls = 0;
|
||||
const exec = async () => {
|
||||
calls += 1;
|
||||
return { code: 0, stdout: "", stderr: "" };
|
||||
};
|
||||
const items = await commands("/x", exec, {
|
||||
profile: resolveProfile([], "codex"),
|
||||
snippets: [{ key: "mine", desc: "s" }],
|
||||
});
|
||||
assert.equal(calls, 0);
|
||||
const keys = items.map((item) => item.key);
|
||||
assert.deepEqual(keys, [...BUILTINS.codex.map((item) => item.key), "mine"]);
|
||||
});
|
||||
|
||||
test("commands: claude-code still reads the project and takes the global ones", async () => {
|
||||
const { exec } = ccMachine({ ".claude/commands/p.md": "x" });
|
||||
const global = [{ key: "handoff", desc: "h", group: GROUP_USER, insert: "/handoff " }];
|
||||
const items = await commands("/x", exec, { profile: resolveProfile([], "claude"), global });
|
||||
const keys = items.map((item) => item.key);
|
||||
assert.ok(keys.includes("handoff"));
|
||||
assert.ok(keys.includes("clear"));
|
||||
});
|
||||
|
||||
const EXPECTED_CC = [
|
||||
{"key":"add-dir","group":"Wbudowane","insert":"/add-dir ","desc":"Dodaje katalog roboczy."},
|
||||
{"key":"agents","group":"Wbudowane","insert":"/agents ","desc":"Zarządza subagentami."},
|
||||
{"key":"bashes","group":"Wbudowane","insert":"/bashes ","desc":"Pokazuje zadania w tle."},
|
||||
{"key":"bug","group":"Wbudowane","insert":"/bug ","desc":"Zgłasza błąd Claude Code."},
|
||||
{"key":"clear","group":"Wbudowane","insert":"/clear ","desc":"Czyści historię rozmowy."},
|
||||
{"key":"code-review","group":"Wbudowane","insert":"/code-review ","desc":"Przegląd zmian pod kątem błędów."},
|
||||
{"key":"compact","group":"Wbudowane","insert":"/compact ","desc":"Zwija historię do podsumowania."},
|
||||
{"key":"config","group":"Wbudowane","insert":"/config ","desc":"Otwiera ustawienia."},
|
||||
{"key":"context","group":"Wbudowane","insert":"/context ","desc":"Pokazuje zużycie kontekstu."},
|
||||
{"key":"cost","group":"Wbudowane","insert":"/cost ","desc":"Pokazuje koszt i zużycie tokenów."},
|
||||
{"key":"doctor","group":"Wbudowane","insert":"/doctor ","desc":"Sprawdza instalację Claude Code."},
|
||||
{"key":"exit","group":"Wbudowane","insert":"/exit ","desc":"Kończy sesję."},
|
||||
{"key":"export","group":"Wbudowane","insert":"/export ","desc":"Eksportuje rozmowę."},
|
||||
{"key":"fast","group":"Wbudowane","insert":"/fast ","desc":"Przełącza tryb szybki."},
|
||||
{"key":"feedback","group":"Wbudowane","insert":"/feedback ","desc":"Wysyła opinię o Claude Code."},
|
||||
{"key":"fewer-permission-prompts","group":"Wbudowane","insert":"/fewer-permission-prompts ","desc":"Dodaje bezpieczne komendy do listy dozwolonych."},
|
||||
{"key":"help","group":"Wbudowane","insert":"/help ","desc":"Pomoc."},
|
||||
{"key":"hooks","group":"Wbudowane","insert":"/hooks ","desc":"Zarządza hookami."},
|
||||
{"key":"ide","group":"Wbudowane","insert":"/ide ","desc":"Łączy z IDE."},
|
||||
{"key":"init","group":"Wbudowane","insert":"/init ","desc":"Tworzy CLAUDE.md dla projektu."},
|
||||
{"key":"install-github-app","group":"Wbudowane","insert":"/install-github-app ","desc":"Instaluje aplikację GitHub."},
|
||||
{"key":"keybindings","group":"Wbudowane","insert":"/keybindings ","desc":"Ustawia skróty klawiszowe."},
|
||||
{"key":"login","group":"Wbudowane","insert":"/login ","desc":"Logowanie."},
|
||||
{"key":"logout","group":"Wbudowane","insert":"/logout ","desc":"Wylogowanie."},
|
||||
{"key":"loop","group":"Wbudowane","insert":"/loop ","desc":"Uruchamia polecenie cyklicznie."},
|
||||
{"key":"mcp","group":"Wbudowane","insert":"/mcp ","desc":"Zarządza serwerami MCP."},
|
||||
{"key":"memory","group":"Wbudowane","insert":"/memory ","desc":"Edytuje pliki pamięci."},
|
||||
{"key":"model","group":"Wbudowane","insert":"/model ","desc":"Wybiera model."},
|
||||
{"key":"output-style","group":"Wbudowane","insert":"/output-style ","desc":"Ustawia styl odpowiedzi."},
|
||||
{"key":"permissions","group":"Wbudowane","insert":"/permissions ","desc":"Ustawia uprawnienia narzędzi."},
|
||||
{"key":"plugin","group":"Wbudowane","insert":"/plugin ","desc":"Zarządza pluginami."},
|
||||
{"key":"pr-comments","group":"Wbudowane","insert":"/pr-comments ","desc":"Pokazuje komentarze PR."},
|
||||
{"key":"privacy-settings","group":"Wbudowane","insert":"/privacy-settings ","desc":"Ustawienia prywatności."},
|
||||
{"key":"release-notes","group":"Wbudowane","insert":"/release-notes ","desc":"Pokazuje informacje o wydaniu."},
|
||||
{"key":"resume","group":"Wbudowane","insert":"/resume ","desc":"Wznawia wcześniejszą sesję."},
|
||||
{"key":"review","group":"Wbudowane","insert":"/review ","desc":"Przegląd pull requesta."},
|
||||
{"key":"rewind","group":"Wbudowane","insert":"/rewind ","desc":"Cofa rozmowę lub kod."},
|
||||
{"key":"schedule","group":"Wbudowane","insert":"/schedule ","desc":"Planuje zadania w chmurze."},
|
||||
{"key":"security-review","group":"Wbudowane","insert":"/security-review ","desc":"Przegląd bezpieczeństwa zmian."},
|
||||
{"key":"simplify","group":"Wbudowane","insert":"/simplify ","desc":"Upraszcza zmieniony kod."},
|
||||
{"key":"status","group":"Wbudowane","insert":"/status ","desc":"Pokazuje stan sesji."},
|
||||
{"key":"statusline","group":"Wbudowane","insert":"/statusline ","desc":"Ustawia linię statusu."},
|
||||
{"key":"terminal-setup","group":"Wbudowane","insert":"/terminal-setup ","desc":"Konfiguruje terminal."},
|
||||
{"key":"todos","group":"Wbudowane","insert":"/todos ","desc":"Pokazuje listę zadań."},
|
||||
{"key":"upgrade","group":"Wbudowane","insert":"/upgrade ","desc":"Zmienia plan."},
|
||||
{"key":"usage","group":"Wbudowane","insert":"/usage ","desc":"Pokazuje limity użycia."},
|
||||
{"key":"vim","group":"Wbudowane","insert":"/vim ","desc":"Przełącza tryb vim."},
|
||||
{"key":"workflows","group":"Wbudowane","insert":"/workflows ","desc":"Pokazuje przebieg workflow."},
|
||||
{"key":"a","group":"Projekt","insert":"/a ","desc":"Komenda a"},
|
||||
{"key":"s","group":"Projekt","insert":"/s ","desc":"Opis inna"},
|
||||
{"key":"handoff","group":"Użytkownik","insert":"/handoff ","desc":"Przekazanie"},
|
||||
{"key":"sp:brainstorming","group":"Pluginy","insert":"/sp:brainstorming ","desc":"Opis brainstorming"},
|
||||
];
|
||||
|
||||
test("the / menu of Claude Code stays as it was", async () => {
|
||||
const { exec, readText } = ccMachine(CC_FILES);
|
||||
const global = await globalCommands(HOME, exec, readText, { sources: CC });
|
||||
const items = await commands("/proj", exec, { profile: resolveProfile([], "claude-code"), global });
|
||||
assert.deepEqual(items.map(ccRow), EXPECTED_CC);
|
||||
});
|
||||
|
||||
test("commands: no profile gives only the history and the snippets, and no exec", async () => {
|
||||
let calls = 0;
|
||||
const exec = async () => {
|
||||
calls += 1;
|
||||
return { code: 0, stdout: "", stderr: "" };
|
||||
};
|
||||
const h = { key: "clear", desc: "", group: GROUP_HISTORY, insert: "/clear " };
|
||||
assert.deepEqual(await commands("/x", exec, { profile: null, history: [h] }), [h]);
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
|
||||
test("commands: a profile project source with a prefix", async () => {
|
||||
const profile = {
|
||||
id: "kiro",
|
||||
match: ["kiro-cli"],
|
||||
builtins: [],
|
||||
sources: [{ scope: "project", path: ".kiro/prompts", pattern: "*.md", prefix: "@" }],
|
||||
};
|
||||
const { exec } = ccMachine({ ".kiro/prompts/review.md": "---\ndescription: R\n---\n" });
|
||||
const items = await commands("/x", exec, { profile });
|
||||
assert.deepEqual(items, [
|
||||
{ key: "review", desc: "R", group: "Projekt", insert: "@review " },
|
||||
]);
|
||||
});
|
||||
|
||||
test("commands: a project source path never reaches the shell as a script", async () => {
|
||||
const seen = [];
|
||||
const exec = async (command, args) => {
|
||||
seen.push([command, args]);
|
||||
return { code: 0, stdout: "", stderr: "" };
|
||||
};
|
||||
const profile = {
|
||||
id: "x",
|
||||
match: ["x"],
|
||||
builtins: [],
|
||||
sources: [{ scope: "project", path: ".a b/Zażółć", pattern: "*.md", prefix: "/" }],
|
||||
};
|
||||
await commands("/x", exec, { profile });
|
||||
assert.equal(seen.length, 1);
|
||||
assert.ok(!seen[0][1][1].includes("Zażółć"));
|
||||
assert.ok(seen[0][1].includes(".a b/Zażółć"));
|
||||
});
|
||||
|
||||
test("globalCommands: no sources gives [] and no exec", async () => {
|
||||
let calls = 0;
|
||||
const exec = async () => {
|
||||
calls += 1;
|
||||
return { code: 0, stdout: "", stderr: "" };
|
||||
};
|
||||
assert.deepEqual(await globalCommands(HOME, exec, async () => null, { sources: [] }), []);
|
||||
assert.deepEqual(await globalCommands(HOME, exec, async () => null), []);
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
|
||||
test("globalCommands: a home source gives the Użytkownik group with its prefix", async () => {
|
||||
const { exec, readText } = machine({ [`${HOME}/.kiro/prompts/plan.md`]: "---\ndescription: P\n---\n" });
|
||||
const sources = [{ scope: "home", path: ".kiro/prompts", pattern: "*.md", prefix: "@" }];
|
||||
const items = await globalCommands(HOME, exec, readText, { sources });
|
||||
assert.deepEqual(items, [{ key: "plan", desc: "P", group: GROUP_USER, insert: "@plan " }]);
|
||||
});
|
||||
|
||||
test("globalCommands: a project source is not read from home", async () => {
|
||||
const { exec, readText } = machine({ [`${HOME}/.kiro/prompts/plan.md`]: "x" });
|
||||
const sources = [{ scope: "project", path: ".kiro/prompts", pattern: "*.md", prefix: "/" }];
|
||||
assert.deepEqual(await globalCommands(HOME, exec, readText, { sources }), []);
|
||||
});
|
||||
|
||||
test("historyCommands: commands of this agent, newest first, no paths", () => {
|
||||
const e = (text, sentAt, agentName = "claude-code") => ({ text, sentAt, agentName });
|
||||
const history = [
|
||||
e("/clear", 1),
|
||||
e(" /superpowers:brainstorming x", 5),
|
||||
e("/c/Users/x", 6),
|
||||
e("/ cos", 7),
|
||||
e("/", 8),
|
||||
e("hej /clear", 9),
|
||||
e("/other", 10, "codex"),
|
||||
];
|
||||
const items = historyCommands(history, "Claude-Code");
|
||||
assert.deepEqual(items.map((i) => i.key), ["superpowers:brainstorming", "clear"]);
|
||||
assert.ok(items.every((i) => i.group === "Z historii" && i.desc === ""));
|
||||
assert.equal(items[0].insert, "/superpowers:brainstorming ");
|
||||
});
|
||||
|
||||
test("commands: a history command that is a builtin shows once, as Wbudowane", async () => {
|
||||
const exec = async () => ({ code: 0, stdout: "", stderr: "" });
|
||||
const items = await commands("/x", exec, {
|
||||
profile: resolveProfile([], "codex"),
|
||||
history: historyCommands([{ text: "/model", sentAt: 1, agentName: "codex" }], "codex"),
|
||||
});
|
||||
const model = items.filter((i) => i.key === "model");
|
||||
assert.equal(model.length, 1);
|
||||
assert.equal(model[0].group, "Wbudowane");
|
||||
});
|
||||
|
||||
test("GROUPS has Z historii right after Pluginy", () => {
|
||||
assert.equal(GROUPS[GROUPS.indexOf("Pluginy") + 1], "Z historii");
|
||||
});
|
||||
|
||||
test("menuNotes: an unknown agent names the key, but only once the file was read", () => {
|
||||
const loaded = menuNotes({ profile: null, agent: "kiro-cli", profilesLoaded: true, problem: null });
|
||||
assert.equal(loaded.length, 1);
|
||||
assert.ok(loaded[0].includes("`kiro-cli`"));
|
||||
assert.ok(loaded[0].includes("composer-agents.json"));
|
||||
assert.deepEqual(menuNotes({ profile: null, agent: "kiro-cli", profilesLoaded: false, problem: null }), []);
|
||||
});
|
||||
|
||||
test("menuNotes: a problem with the file is one row", () => {
|
||||
assert.deepEqual(
|
||||
menuNotes({ profile: CC_PROFILE, agent: "claude", profilesLoaded: true, problem: "nieczytelny JSON" }),
|
||||
["`composer-agents.json`: nieczytelny JSON"],
|
||||
);
|
||||
});
|
||||
|
||||
test("menuNotes: unknown agent first, then the problem", () => {
|
||||
const notes = menuNotes({ profile: null, agent: "kiro-cli", profilesLoaded: true, problem: "brak listy agents" });
|
||||
assert.equal(notes.length, 2);
|
||||
assert.ok(notes[0].startsWith("Nieznany agent"));
|
||||
assert.equal(notes[1], "`composer-agents.json`: brak listy agents");
|
||||
});
|
||||
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
|
||||
import {
|
||||
clipboardScript, parseClipboardResult, pickerScript, parsePickerResult,
|
||||
sizeScript, parseSizeResult, staleFiles, supportsImages,
|
||||
} from "../mod/ovis-composer/clipboard.js";
|
||||
} from "../herdr/herdr-composer/mods/herdr-composer/clipboard.js";
|
||||
|
||||
const ok = (stdout) => ({ code: 0, stdout, stderr: "" });
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { decide, gateAfter, onRestart, shouldDrain, shouldStartCountdown, drain } from "../mod/ovis-composer/delivery.js";
|
||||
import { decide, gateAfter, onRestart, shouldDrain, shouldStartCountdown, drain } from "../herdr/herdr-composer/mods/herdr-composer/delivery.js";
|
||||
|
||||
test("decide idle/done -> send", () => {
|
||||
assert.equal(decide("idle").kind, "send");
|
||||
@@ -56,7 +56,7 @@ test("onRestart: countdown -> held without left, sending -> uncertain", () => {
|
||||
});
|
||||
|
||||
test("drain sends an entry whose countdown ran out", async () => {
|
||||
const { createState, reduce } = await import("../mod/ovis-composer/state.js");
|
||||
const { createState, reduce } = await import("../herdr/herdr-composer/mods/herdr-composer/state.js");
|
||||
let s = reduce(createState(), { type: "queue", agent: "t2", item: { id: "1", text: "a", createdAt: 1 } });
|
||||
s = reduce(s, { type: "countdown_start", agent: "t2", id: "1" });
|
||||
const calls = [];
|
||||
@@ -106,7 +106,7 @@ test("shouldStartCountdown tolerates a non-array queue", () => {
|
||||
assert.equal(shouldStartCountdown(sc({ queue: null })), false);
|
||||
});
|
||||
|
||||
import { queueBlocksDirectSend } from "../mod/ovis-composer/delivery.js";
|
||||
import { queueBlocksDirectSend } from "../herdr/herdr-composer/mods/herdr-composer/delivery.js";
|
||||
|
||||
test("queueBlocksDirectSend: a message that waits (queued or counting down) goes first", () => {
|
||||
assert.equal(queueBlocksDirectSend([{ state: "queued" }]), true);
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
DOCK_LIMIT, LABEL_MAX, defaultLabel, normalize, isPinned, pin, unpin, remove, move,
|
||||
rename, toggleMode, dockAction, dockMenu, rowMenu, starMenu, menuTransition, applyDock, add, withinGuard,
|
||||
} from "../herdr/herdr-composer/mods/herdr-composer/dock.js";
|
||||
|
||||
const btn = (id, text, extra = {}) => ({ id, label: text, text, mode: "send", ...extra });
|
||||
const three = () => [btn("1", "a"), btn("2", "b"), btn("3", "c")];
|
||||
|
||||
test("limits", () => {
|
||||
assert.equal(DOCK_LIMIT, 30);
|
||||
assert.equal(LABEL_MAX, 16);
|
||||
});
|
||||
|
||||
test("defaultLabel", () => {
|
||||
assert.equal(defaultLabel("/handoff"), "/handoff");
|
||||
assert.equal(defaultLabel("npm test i raport po polsku"), "npm test i rapo…");
|
||||
assert.equal(defaultLabel(" a\n b "), "a b");
|
||||
});
|
||||
|
||||
test("normalize: rubbish, bad modes, duplicates, label", () => {
|
||||
assert.deepEqual(normalize("x"), []);
|
||||
assert.deepEqual(normalize(null), []);
|
||||
const out = normalize([
|
||||
{ id: "1", text: "a", mode: "send", label: "" },
|
||||
{ id: "2", text: " a ", mode: "send", label: "x" },
|
||||
{ id: "3", text: "b", mode: "zly" },
|
||||
]);
|
||||
assert.deepEqual(out, [{ id: "1", label: "a", text: "a", mode: "send" }]);
|
||||
});
|
||||
|
||||
test("normalize: limit 30", () => {
|
||||
const raw = Array.from({ length: 35 }, (_, i) => ({ id: `i${i}`, text: `t${i}`, mode: "send", label: "l" }));
|
||||
assert.equal(normalize(raw).length, 30);
|
||||
});
|
||||
|
||||
test("pin", () => {
|
||||
const d = pin([], " /clear ", "9");
|
||||
assert.deepEqual(d, [{ id: "9", label: "/clear", text: "/clear", mode: "send" }]);
|
||||
assert.equal(pin(d, "/clear", "10"), d);
|
||||
assert.equal(pin(d, " ", "x"), d);
|
||||
const full = Array.from({ length: 30 }, (_, i) => btn(`i${i}`, `t${i}`));
|
||||
assert.equal(pin(full, "new", "n"), full);
|
||||
assert.equal(isPinned(d, " /clear "), true);
|
||||
assert.equal(isPinned(d, "other"), false);
|
||||
});
|
||||
|
||||
test("unpin and remove", () => {
|
||||
const d = three();
|
||||
assert.deepEqual(unpin(d, " b ").map((b) => b.id), ["1", "3"]);
|
||||
assert.deepEqual(remove(d, "1").map((b) => b.id), ["2", "3"]);
|
||||
assert.equal(d.length, 3);
|
||||
});
|
||||
|
||||
test("move: edge no change, swap, no mutation", () => {
|
||||
const d = three();
|
||||
const copy = JSON.parse(JSON.stringify(d));
|
||||
assert.deepEqual(move(d, "1", -1).map((b) => b.id), ["1", "2", "3"]);
|
||||
assert.deepEqual(move(d, "3", 1).map((b) => b.id), ["1", "2", "3"]);
|
||||
assert.deepEqual(move(d, "1", 1).map((b) => b.id), ["2", "1", "3"]);
|
||||
assert.deepEqual(d, copy);
|
||||
});
|
||||
|
||||
test("rename and toggleMode", () => {
|
||||
const d = three();
|
||||
assert.equal(rename(d, "1", " ")[0].label, defaultLabel("a"));
|
||||
assert.equal(rename(d, "1", " Moje ")[0].label, "Moje");
|
||||
assert.equal(d[0].label, "a");
|
||||
const once = toggleMode(d, "1");
|
||||
assert.equal(once[0].mode, "insert");
|
||||
assert.equal(toggleMode(once, "1")[0].mode, "send");
|
||||
assert.equal(d[0].mode, "send");
|
||||
});
|
||||
|
||||
test("dockAction", () => {
|
||||
assert.equal(dockAction({ mode: "insert" }, { hasAgent: true }), "insert");
|
||||
assert.equal(dockAction({ mode: "send" }, { hasAgent: true }), "send");
|
||||
assert.equal(dockAction({ mode: "send" }, { hasAgent: false }), "none");
|
||||
});
|
||||
|
||||
test("dockMenu", () => {
|
||||
const d = three();
|
||||
const m = dockMenu(d, "1");
|
||||
assert.deepEqual(m.map((i) => i.command), ["rename", "mode", "left", "right", "remove"]);
|
||||
assert.equal(m[0].label, "Zmień nazwę");
|
||||
assert.equal(m[1].label, "Tylko wstawiaj");
|
||||
assert.equal(m[2].label, "Przesuń w lewo");
|
||||
assert.equal(m[2].disabled, true);
|
||||
assert.notEqual(m[3].disabled, true);
|
||||
assert.equal(m[4].label, "Usuń z docka");
|
||||
assert.equal(m[4].danger, true);
|
||||
const last = dockMenu(d, "3");
|
||||
assert.equal(last[3].disabled, true);
|
||||
const ins = dockMenu(toggleMode(d, "2"), "2");
|
||||
assert.equal(ins[1].label, "Wysyłaj od razu");
|
||||
});
|
||||
|
||||
test("rowMenu", () => {
|
||||
const h = rowMenu({ tab: "history", favorite: false, pinned: false });
|
||||
assert.deepEqual(h.map((i) => i.command), ["insert", "favorite"]);
|
||||
assert.equal(h[0].label, "Wstaw");
|
||||
assert.equal(h[1].label, "Dodaj do ulubionych");
|
||||
const f = rowMenu({ tab: "favorites", favorite: true, pinned: true });
|
||||
assert.deepEqual(f.map((i) => i.command), ["insert", "pin", "favorite"]);
|
||||
assert.equal(f[1].label, "Odepnij z docka");
|
||||
assert.equal(f[2].label, "Usuń z ulubionych");
|
||||
assert.equal(f[2].danger, true);
|
||||
const g = rowMenu({ tab: "favorites", favorite: true, pinned: false });
|
||||
assert.equal(g[1].label, "Przypnij do docka");
|
||||
});
|
||||
|
||||
test("starMenu", () => {
|
||||
assert.equal(starMenu({ text: "", pinned: false })[0].disabled, true);
|
||||
assert.equal(starMenu({ text: " ", pinned: false })[0].disabled, true);
|
||||
const on = starMenu({ text: "x", pinned: false });
|
||||
assert.equal(on[0].command, "pin");
|
||||
assert.equal(on[0].label, "Przypnij bieżący tekst do docka");
|
||||
assert.notEqual(on[0].disabled, true);
|
||||
assert.equal(starMenu({ text: "x", pinned: true })[0].label, "Odepnij bieżący tekst z docka");
|
||||
});
|
||||
|
||||
test("normalize: duplicate ids dropped (first wins), labels trimmed", () => {
|
||||
const out = normalize([
|
||||
{ id: "1", text: "a", mode: "send", label: " Moje " },
|
||||
{ id: "1", text: "b", mode: "send", label: "x" },
|
||||
{ id: "2", text: "c", mode: "send", label: " " },
|
||||
]);
|
||||
assert.deepEqual(out, [
|
||||
{ id: "1", label: "Moje", text: "a", mode: "send" },
|
||||
{ id: "2", label: "c", text: "c", mode: "send" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("menuTransition: open replaces, close only closes its own menu", () => {
|
||||
const A = { kind: "dock", id: "A" };
|
||||
const B = { kind: "dock", id: "B" };
|
||||
assert.deepEqual(menuTransition(null, { ...A, open: true }), A);
|
||||
// open A, a command (menu closed), open B -> B is open
|
||||
let state = menuTransition(null, { ...A, open: true });
|
||||
state = null;
|
||||
assert.deepEqual(menuTransition(state, { ...B, open: true }), B);
|
||||
// open A, then open B, then the late close of A -> B stays
|
||||
state = menuTransition(A, { ...B, open: true });
|
||||
assert.deepEqual(menuTransition(state, { ...A, open: false }), B);
|
||||
// close of the open one closes; a close with nothing open stays null
|
||||
assert.equal(menuTransition(B, { ...B, open: false }), null);
|
||||
assert.equal(menuTransition(null, { ...A, open: false }), null);
|
||||
// same id, other kind is another menu
|
||||
assert.deepEqual(menuTransition(B, { kind: "star", id: "B", open: false }), B);
|
||||
});
|
||||
|
||||
test("applyDock: works on the stored list, so another copy's change survives", () => {
|
||||
const stored = [btn("1", "a"), btn("2", "from-copy-A")];
|
||||
// copy B held only ["a"]; it pins "b" - the result keeps A's pin
|
||||
const out = applyDock(stored, (d) => pin(d, "b", "3"));
|
||||
assert.deepEqual(out.map((b) => b.id), ["1", "2", "3"]);
|
||||
assert.deepEqual(applyDock("rubbish", (d) => pin(d, "x", "9")).map((b) => b.id), ["9"]);
|
||||
assert.deepEqual(applyDock(stored, (d) => remove(d, "1")).map((b) => b.id), ["2"]);
|
||||
});
|
||||
|
||||
test("add: label, mode, empty text, duplicate, limit", () => {
|
||||
const a = add([], { id: "1", text: " /handoff ", label: "", mode: "send" });
|
||||
assert.deepEqual(a, [{ id: "1", label: "/handoff", text: "/handoff", mode: "send" }]);
|
||||
const b = add(a, { id: "2", text: "npm test", label: " Testy ", mode: "insert" });
|
||||
assert.deepEqual(b[1], { id: "2", label: "Testy", text: "npm test", mode: "insert" });
|
||||
assert.equal(add(b, { id: "3", text: " ", label: "x", mode: "send" }), b);
|
||||
assert.equal(add(b, { id: "3", text: "npm test", label: "x", mode: "send" }), b);
|
||||
const full = Array.from({ length: DOCK_LIMIT }, (_, i) => btn(`f${i}`, `t${i}`));
|
||||
assert.equal(add(full, { id: "n", text: "new", label: "", mode: "send" }), full);
|
||||
assert.equal(add([], { id: "1", text: "x", label: "", mode: "bogus" })[0].mode, "send");
|
||||
});
|
||||
|
||||
test("withinGuard: only just after the moment", () => {
|
||||
assert.equal(withinGuard(1100, 1000, 250), true);
|
||||
assert.equal(withinGuard(1250, 1000, 250), false);
|
||||
assert.equal(withinGuard(5000, 0, 250), false);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { record, search, toggleFavorite, isFavorite } from "../mod/ovis-composer/history.js";
|
||||
import { loadHistory, saveHistory, loadFavorites, saveFavorites, KEYS } from "../mod/ovis-composer/storage.js";
|
||||
import { record, search, toggleFavorite, isFavorite } from "../herdr/herdr-composer/mods/herdr-composer/history.js";
|
||||
import { loadHistory, saveHistory, loadFavorites, saveFavorites, KEYS } from "../herdr/herdr-composer/mods/herdr-composer/storage.js";
|
||||
|
||||
const memStore = () => {
|
||||
const m = new Map();
|
||||
@@ -107,7 +107,7 @@ test("storage: old favourites (at) load as createdAt", () => {
|
||||
assert.equal(loadFavorites(store)[0].createdAt, 4);
|
||||
});
|
||||
|
||||
import { segments, formatMoment, entryMeta, panelState, moveIndex, otherTab } from "../mod/ovis-composer/history.js";
|
||||
import { segments, formatMoment, entryMeta, panelState, moveIndex, otherTab } from "../herdr/herdr-composer/mods/herdr-composer/history.js";
|
||||
|
||||
test("segments splits a text on the ranges", () => {
|
||||
assert.deepEqual(segments("uruchom testy", [[8, 12]]), [
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { keyIntent } from "../mod/ovis-composer/keys.js";
|
||||
import { keyIntent } from "../herdr/herdr-composer/mods/herdr-composer/keys.js";
|
||||
|
||||
const ev = (key, mods = {}) => ({ key, shift: false, ctrl: false, alt: false, composing: false, ...mods });
|
||||
const ctx = (o = {}) => ({ hasKeyboard: true, menuOpen: false, panelOpen: false, empty: false, status: null, ...o });
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { decode } from "../herdr/herdr-composer/mods/herdr-composer/powershell.js";
|
||||
import { readScript } from "../herdr/herdr-composer/mods/herdr-composer/catalog.js";
|
||||
|
||||
const NASTY = [
|
||||
".claude/commands/it\u2019s.md",
|
||||
".claude/commands/it\u2018s.md",
|
||||
".claude/commands/a\u201Ab\u201Bc.md",
|
||||
".claude/commands/o'brien.md",
|
||||
".claude/commands/$env:USERNAME.md",
|
||||
'.claude/commands/"; calc #.md',
|
||||
".claude/skills/zażółć gęślą/SKILL.md",
|
||||
];
|
||||
|
||||
const b64s = (script) =>
|
||||
[...script.matchAll(/FromBase64String\('([A-Za-z0-9+/=]*)'\)/g)].map((m) => Buffer.from(m[1], "base64").toString("utf8"));
|
||||
|
||||
test("decode: PowerShell that yields the text, with the text itself nowhere in it", () => {
|
||||
for (const text of NASTY) {
|
||||
const expr = decode(text);
|
||||
assert.deepEqual(b64s(expr), [text]);
|
||||
assert.equal(expr.includes(text), false);
|
||||
assert.match(expr, /^\[System\.Text\.Encoding\]::UTF8\.GetString\(\[System\.Convert\]::FromBase64String\('[A-Za-z0-9+/=]*'\)\)$/);
|
||||
}
|
||||
});
|
||||
|
||||
test("decode: every length of tail, emoji, newline, empty", () => {
|
||||
for (const text of ["", "a", "ab", "abc", "abcd", "ęą", "😀x", "a\nb"]) {
|
||||
assert.deepEqual(b64s(decode(text)), [text]);
|
||||
}
|
||||
});
|
||||
|
||||
test("catalog readScript: the path of a project file is only ever Base64", () => {
|
||||
for (const path of NASTY) {
|
||||
const script = readScript(path);
|
||||
assert.deepEqual(b64s(script), [path]);
|
||||
for (const raw of ["\u2019", "\u2018", "\u201A", "\u201B", "$env:USERNAME", "calc", "o'brien", "zażółć"]) {
|
||||
if (path.includes(raw)) assert.equal(script.includes(raw), false, `${raw} in the script`);
|
||||
}
|
||||
// the script still reads the file
|
||||
assert.ok(script.includes("Get-Content"));
|
||||
assert.ok(script.includes("-LiteralPath"));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
BUILTINS,
|
||||
DEFAULT_PROFILES,
|
||||
PROFILES_FILE,
|
||||
parseProfiles,
|
||||
resolveProfile,
|
||||
} from "../herdr/herdr-composer/mods/herdr-composer/profiles.js";
|
||||
|
||||
test("PROFILES_FILE is composer-agents.json", () => {
|
||||
assert.equal(PROFILES_FILE, "composer-agents.json");
|
||||
});
|
||||
|
||||
test("resolveProfile: defaults, case-insensitive, unknown and default are null", () => {
|
||||
assert.equal(resolveProfile([], "claude").id, "claude-code");
|
||||
assert.equal(resolveProfile([], "Claude-Code").id, "claude-code");
|
||||
assert.equal(resolveProfile([], "codex").id, "codex");
|
||||
assert.equal(resolveProfile([], "kiro-cli"), null);
|
||||
assert.equal(resolveProfile([], "default"), null);
|
||||
assert.equal(resolveProfile([], ""), null);
|
||||
});
|
||||
|
||||
test("resolveProfile: match is case-insensitive for a user profile", () => {
|
||||
const { profiles } = parseProfiles('{"agents":[{"id":"kiro","match":["kiro-cli"]}]}');
|
||||
assert.equal(resolveProfile(profiles, "Kiro-CLI").id, "kiro");
|
||||
assert.equal(resolveProfile(profiles, " kiro-cli ").id, "kiro");
|
||||
});
|
||||
|
||||
test("resolveProfile: a user profile with the same id replaces the default whole", () => {
|
||||
const { profiles } = parseProfiles(
|
||||
'{"agents":[{"id":"claude-code","match":["claude-code"],"builtins":[{"key":"x"}]}]}',
|
||||
);
|
||||
const profile = resolveProfile(profiles, "claude-code");
|
||||
assert.deepEqual(profile.builtins, [{ key: "x", desc: "" }]);
|
||||
assert.deepEqual(profile.sources, []);
|
||||
});
|
||||
|
||||
test("parseProfiles: no file is normal", () => {
|
||||
assert.deepEqual(parseProfiles(null), { profiles: [], problem: null });
|
||||
assert.deepEqual(parseProfiles(undefined), { profiles: [], problem: null });
|
||||
});
|
||||
|
||||
test("parseProfiles: BOM and CRLF are fine, prefix kept", () => {
|
||||
const text =
|
||||
'\uFEFF{"agents":[{"id":"kiro","match":["kiro-cli"],"sources":[{"scope":"home","path":".kiro/prompts","pattern":"*.md","prefix":"@"}]}]}\r\n';
|
||||
const { profiles, problem } = parseProfiles(text);
|
||||
assert.equal(problem, null);
|
||||
assert.equal(profiles.length, 1);
|
||||
assert.deepEqual(profiles[0].sources, [
|
||||
{ scope: "home", path: ".kiro/prompts", pattern: "*.md", prefix: "@" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("parseProfiles: broken JSON", () => {
|
||||
assert.deepEqual(parseProfiles("{nope"), { profiles: [], problem: "nieczytelny JSON" });
|
||||
});
|
||||
|
||||
test("parseProfiles: agents is not a list", () => {
|
||||
assert.deepEqual(parseProfiles('{"agents":{}}'), { profiles: [], problem: "brak listy agents" });
|
||||
assert.deepEqual(parseProfiles("{}"), { profiles: [], problem: "brak listy agents" });
|
||||
});
|
||||
|
||||
test("parseProfiles: bad sources are dropped, the good one stays", () => {
|
||||
const text = JSON.stringify({
|
||||
agents: [
|
||||
{
|
||||
id: "a",
|
||||
match: ["a"],
|
||||
sources: [
|
||||
{ scope: "project", path: "../x", pattern: "*.md" },
|
||||
{ scope: "home", path: "C:/x", pattern: "*.md" },
|
||||
{ scope: "project", path: ".a/cmds", pattern: "*.md" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const { profiles, problem } = parseProfiles(text);
|
||||
assert.equal(profiles[0].sources.length, 1);
|
||||
assert.equal(profiles[0].sources[0].prefix, "/");
|
||||
assert.equal(problem, "pominięto 2 wpisów");
|
||||
});
|
||||
|
||||
test("parseProfiles: absolute and traversal path forms are rejected", () => {
|
||||
for (const path of ["/x", "C:/x", "C:\\x", "\\\\x", "a/../b", "a\\..\\b", ".."]) {
|
||||
const text = JSON.stringify({
|
||||
agents: [{ id: "a", match: ["a"], sources: [{ scope: "home", path, pattern: "*.md" }] }],
|
||||
});
|
||||
assert.deepEqual(parseProfiles(text).profiles[0].sources, [], path);
|
||||
}
|
||||
});
|
||||
|
||||
test("parseProfiles: a profile without match is dropped, the next stays", () => {
|
||||
const text = JSON.stringify({ agents: [{ id: "bad" }, { id: "ok", match: ["ok"] }] });
|
||||
const { profiles, problem } = parseProfiles(text);
|
||||
assert.deepEqual(profiles.map((p) => p.id), ["ok"]);
|
||||
assert.equal(problem, "pominięto 1 wpisów");
|
||||
});
|
||||
|
||||
test("parseProfiles: unknown pattern, scope and keyless builtin are dropped", () => {
|
||||
const text = JSON.stringify({
|
||||
agents: [
|
||||
{
|
||||
id: "a",
|
||||
match: ["a"],
|
||||
builtins: [{ key: "ok", desc: "d" }, { desc: "no key" }],
|
||||
sources: [
|
||||
{ scope: "home", path: "p", pattern: "**/*.md" },
|
||||
{ scope: "nowhere", path: "p", pattern: "*.md" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const { profiles, problem } = parseProfiles(text);
|
||||
assert.deepEqual(profiles[0].builtins, [{ key: "ok", desc: "d" }]);
|
||||
assert.deepEqual(profiles[0].sources, []);
|
||||
assert.equal(problem, "pominięto 3 wpisów");
|
||||
});
|
||||
|
||||
test("parseProfiles: claude-plugins source is kept for home only", () => {
|
||||
const text = JSON.stringify({
|
||||
agents: [{ id: "a", match: ["a"], sources: [{ scope: "home", kind: "claude-plugins" }] }],
|
||||
});
|
||||
assert.deepEqual(parseProfiles(text).profiles[0].sources, [{ scope: "home", kind: "claude-plugins" }]);
|
||||
});
|
||||
|
||||
test("DEFAULT_PROFILES: claude-code keeps the builtins and the five sources", () => {
|
||||
const cc = DEFAULT_PROFILES[0];
|
||||
assert.equal(cc.id, "claude-code");
|
||||
assert.deepEqual(cc.match, ["claude-code", "claude"]);
|
||||
assert.deepEqual(
|
||||
cc.builtins.map((b) => b.key),
|
||||
BUILTINS["claude-code"].map((b) => b.key),
|
||||
);
|
||||
assert.deepEqual(cc.sources, [
|
||||
{ scope: "project", path: ".claude/commands", pattern: "*.md", prefix: "/" },
|
||||
{ scope: "project", path: ".claude/skills", pattern: "*/SKILL.md", prefix: "/" },
|
||||
{ scope: "home", path: ".claude/commands", pattern: "*.md", prefix: "/" },
|
||||
{ scope: "home", path: ".claude/skills", pattern: "*/SKILL.md", prefix: "/" },
|
||||
{ scope: "home", kind: "claude-plugins" },
|
||||
]);
|
||||
const codex = DEFAULT_PROFILES[1];
|
||||
assert.equal(codex.id, "codex");
|
||||
assert.deepEqual(codex.sources, []);
|
||||
assert.equal(codex.builtins.length, 4);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { sendArgs, parseSendArgs, sendNow } from "../mod/ovis-composer/delivery.js";
|
||||
import { sendArgs, parseSendArgs, sendNow } from "../herdr/herdr-composer/mods/herdr-composer/delivery.js";
|
||||
|
||||
const ok = { code: 0, stdout: "{}", stderr: "" };
|
||||
|
||||
@@ -49,8 +49,8 @@ test("--force is only there when asked for, and before the `--`", async () => {
|
||||
});
|
||||
|
||||
test("the queue never forces: drain sends without --force", async () => {
|
||||
const { createState, reduce } = await import("../mod/ovis-composer/state.js");
|
||||
const { drain } = await import("../mod/ovis-composer/delivery.js");
|
||||
const { createState, reduce } = await import("../herdr/herdr-composer/mods/herdr-composer/state.js");
|
||||
const { drain } = await import("../herdr/herdr-composer/mods/herdr-composer/delivery.js");
|
||||
const state = reduce(createState(), { type: "queue", agent: "t2", item: { id: "1", text: "q", createdAt: 1 } });
|
||||
const calls = [];
|
||||
const result = await drain(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createState, reduce, isSending } from "../mod/ovis-composer/state.js";
|
||||
import { createState, reduce, isSending } from "../herdr/herdr-composer/mods/herdr-composer/state.js";
|
||||
|
||||
test("createState starts empty", () => {
|
||||
const s = createState();
|
||||
|
||||
+136
-8
@@ -2,8 +2,8 @@ import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
HISTORY_LIMIT, queueKey, loadHistory, saveHistory, loadQueue, saveQueue, loadUsage, saveUsage,
|
||||
KEYS, draftKey, loadDraft, saveDraft,
|
||||
} from "../mod/ovis-composer/storage.js";
|
||||
KEYS, draftKey, loadDraft, saveDraft, loadDock, saveDock,
|
||||
} from "../herdr/herdr-composer/mods/herdr-composer/storage.js";
|
||||
|
||||
const memStore = () => {
|
||||
const m = new Map();
|
||||
@@ -23,12 +23,12 @@ test("saveHistory truncates to 500, keeping the newest", () => {
|
||||
|
||||
test("history drops invalid entries on load", () => {
|
||||
const store = memStore();
|
||||
store.set("ovis-composer.history", [{ id: "a", text: "x", at: 1 }, { id: "b" }, null]);
|
||||
store.set("herdr-composer.history", [{ id: "a", text: "x", at: 1 }, { id: "b" }, null]);
|
||||
assert.equal(loadHistory(store).length, 1);
|
||||
});
|
||||
|
||||
test("queueKey is per agent", () => {
|
||||
assert.equal(queueKey("a1"), "ovis-composer.queue:a1");
|
||||
assert.equal(queueKey("a1"), "herdr-composer.queue:a1");
|
||||
});
|
||||
|
||||
test("queue roundtrip; keeps sending state as written", () => {
|
||||
@@ -42,7 +42,7 @@ test("queue roundtrip; keeps sending state as written", () => {
|
||||
test("saveQueue ignores empty agent", () => {
|
||||
const store = memStore();
|
||||
saveQueue(store, "", [{ id: "1", text: "t", state: "queued", createdAt: 1 }]);
|
||||
assert.equal(store.get("ovis-composer.queue:"), undefined);
|
||||
assert.equal(store.get("herdr-composer.queue:"), undefined);
|
||||
});
|
||||
|
||||
test("usage keeps only non-negative finite numbers", () => {
|
||||
@@ -64,8 +64,8 @@ const draft = (over = {}) => ({
|
||||
});
|
||||
|
||||
test("draftKey is per agent", () => {
|
||||
assert.equal(KEYS.draft, "ovis-composer.draft");
|
||||
assert.equal(draftKey("t2"), "ovis-composer.draft:t2");
|
||||
assert.equal(KEYS.draft, "herdr-composer.draft");
|
||||
assert.equal(draftKey("t2"), "herdr-composer.draft:t2");
|
||||
});
|
||||
|
||||
test("draft roundtrip", () => {
|
||||
@@ -97,7 +97,7 @@ test("saveDraft ignores rubbish and empty agent", () => {
|
||||
saveDraft(store, "t2", "x");
|
||||
saveDraft(store, "", draft());
|
||||
assert.equal(loadDraft(store, "t2").text, "hello");
|
||||
assert.equal(store.get("ovis-composer.draft:"), undefined);
|
||||
assert.equal(store.get("herdr-composer.draft:"), undefined);
|
||||
});
|
||||
|
||||
test("empty draft overwrites the old one", () => {
|
||||
@@ -132,3 +132,131 @@ test("queue roundtrip keeps a countdown entry (restart turns it into held)", ()
|
||||
saveQueue(store, "a", q);
|
||||
assert.deepEqual(loadQueue(store, "a"), q);
|
||||
});
|
||||
|
||||
import { loadUserMin, saveUserMin } from "../herdr/herdr-composer/mods/herdr-composer/storage.js";
|
||||
|
||||
test("userMin: the height the person dragged the composer to; 0 is none", () => {
|
||||
const store = memStore();
|
||||
assert.equal(loadUserMin(store), 0);
|
||||
saveUserMin(store, 300);
|
||||
assert.equal(loadUserMin(store), 300);
|
||||
saveUserMin(store, 0);
|
||||
assert.equal(loadUserMin(store), 0);
|
||||
store.set("herdr-composer.userMin", "x");
|
||||
assert.equal(loadUserMin(store), 0);
|
||||
store.set("herdr-composer.userMin", -5);
|
||||
assert.equal(loadUserMin(store), 0);
|
||||
saveUserMin(store, NaN);
|
||||
assert.equal(store.get("herdr-composer.userMin"), -5);
|
||||
});
|
||||
|
||||
// --- the rename ovis-composer -> herdr-composer: nothing the person kept is lost
|
||||
|
||||
import { LEGACY_PREFIX, loadFavorites } from "../herdr/herdr-composer/mods/herdr-composer/storage.js";
|
||||
|
||||
const OLD = "ovis-composer.";
|
||||
const NEW = "herdr-composer.";
|
||||
|
||||
test("migration: the legacy prefix", () => {
|
||||
assert.equal(LEGACY_PREFIX, "ovis-composer.");
|
||||
assert.equal(KEYS.history, "herdr-composer.history");
|
||||
assert.equal(queueKey("t2"), "herdr-composer.queue:t2");
|
||||
assert.equal(draftKey("t2"), "herdr-composer.draft:t2");
|
||||
});
|
||||
|
||||
test("migration: the new key wins over the old one", () => {
|
||||
const store = memStore();
|
||||
store.set(OLD + "history", [{ id: "old", text: "old", at: 1 }]);
|
||||
store.set(NEW + "history", [{ id: "new", text: "new", sentAt: 2 }]);
|
||||
assert.deepEqual(loadHistory(store).map((e) => e.id), ["new"]);
|
||||
});
|
||||
|
||||
test("migration: history from the old key is read and written under the new one; the old stays", () => {
|
||||
const store = memStore();
|
||||
const old = [{ id: "old", text: "old", at: 1 }];
|
||||
store.set(OLD + "history", old);
|
||||
assert.deepEqual(loadHistory(store).map((e) => e.id), ["old"]);
|
||||
assert.deepEqual(store.get(NEW + "history"), old);
|
||||
assert.deepEqual(store.get(OLD + "history"), old);
|
||||
});
|
||||
|
||||
test("migration: favourites, usage, queue, draft and userMin come across the same way", () => {
|
||||
const store = memStore();
|
||||
store.set(OLD + "favorites", [{ id: "f", text: "x", at: 4 }]);
|
||||
store.set(OLD + "usage", { review: 2 });
|
||||
store.set(OLD + "queue:t2", [{ id: "1", text: "t", state: "held", createdAt: 5 }]);
|
||||
store.set(OLD + "draft:t2", { text: "szkic", caret: 2, attachments: [], identity: { created_ms: 9, app: null }, savedAt: 1 });
|
||||
store.set(OLD + "userMin", 300);
|
||||
|
||||
assert.equal(loadFavorites(store)[0].createdAt, 4);
|
||||
assert.deepEqual(loadUsage(store), { review: 2 });
|
||||
assert.equal(loadQueue(store, "t2")[0].state, "held");
|
||||
assert.equal(loadDraft(store, "t2").text, "szkic");
|
||||
assert.equal(loadUserMin(store), 300);
|
||||
|
||||
for (const key of ["favorites", "usage", "queue:t2", "draft:t2", "userMin"]) {
|
||||
assert.notEqual(store.get(NEW + key), undefined, key);
|
||||
assert.notEqual(store.get(OLD + key), undefined, key);
|
||||
}
|
||||
});
|
||||
|
||||
test("migration: neither key -> the defaults, and nothing is written", () => {
|
||||
const store = memStore();
|
||||
assert.deepEqual(loadHistory(store), []);
|
||||
assert.deepEqual(loadFavorites(store), []);
|
||||
assert.deepEqual(loadUsage(store), {});
|
||||
assert.deepEqual(loadQueue(store, "t2"), []);
|
||||
assert.equal(loadDraft(store, "t2"), null);
|
||||
assert.equal(loadUserMin(store), 0);
|
||||
assert.equal(store.get(NEW + "history"), undefined);
|
||||
assert.equal(store.get(NEW + "draft:t2"), undefined);
|
||||
});
|
||||
|
||||
test("migration: rubbish in the old key is ignored as before, and not copied", () => {
|
||||
const store = memStore();
|
||||
store.set(OLD + "history", "x");
|
||||
store.set(OLD + "favorites", [{ nope: 1 }]);
|
||||
store.set(OLD + "queue:t2", [{ id: "1" }]);
|
||||
store.set(OLD + "draft:t2", [1, 2]);
|
||||
store.set(OLD + "usage", { a: -1, b: "x" });
|
||||
store.set(OLD + "userMin", -3);
|
||||
assert.deepEqual(loadHistory(store), []);
|
||||
assert.deepEqual(loadFavorites(store), []);
|
||||
assert.deepEqual(loadQueue(store, "t2"), []);
|
||||
assert.equal(loadDraft(store, "t2"), null);
|
||||
assert.deepEqual(loadUsage(store), {});
|
||||
assert.equal(loadUserMin(store), 0);
|
||||
for (const key of ["history", "favorites", "queue:t2", "draft:t2", "usage", "userMin"]) {
|
||||
assert.equal(store.get(NEW + key), undefined, key);
|
||||
}
|
||||
});
|
||||
|
||||
test("migration: a store that cannot be written to still reads the old data", () => {
|
||||
const raw = new Map([[OLD + "history", [{ id: "old", text: "old", at: 1 }]]]);
|
||||
const store = { get: (k) => raw.get(k), set: () => { throw new Error("read-only"); } };
|
||||
assert.deepEqual(loadHistory(store).map((e) => e.id), ["old"]);
|
||||
});
|
||||
|
||||
test("dock roundtrip under herdr-composer.dock", () => {
|
||||
const store = memStore();
|
||||
const d = [{ id: "1", label: "a", text: "a", mode: "send" }, { id: "2", label: "b", text: "b", mode: "insert" }];
|
||||
saveDock(store, d);
|
||||
assert.equal(KEYS.dock, "herdr-composer.dock");
|
||||
assert.deepEqual(store.get("herdr-composer.dock"), d);
|
||||
assert.deepEqual(loadDock(store), d);
|
||||
});
|
||||
|
||||
test("dock does not read the legacy key", () => {
|
||||
const store = memStore();
|
||||
store.set("ovis-composer.dock", [{ id: "1", label: "a", text: "a", mode: "send" }]);
|
||||
assert.deepEqual(loadDock(store), []);
|
||||
assert.equal(store.get("herdr-composer.dock"), undefined);
|
||||
});
|
||||
|
||||
test("dock rubbish loads as empty", () => {
|
||||
const store = memStore();
|
||||
store.set("herdr-composer.dock", "smieci");
|
||||
assert.deepEqual(loadDock(store), []);
|
||||
store.set("herdr-composer.dock", { a: 1 });
|
||||
assert.deepEqual(loadDock(store), []);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { detect, startsLine, rank, merge, GROUPS } from "../mod/ovis-composer/suggest.js";
|
||||
import { detect, startsLine, rank, merge, GROUPS } from "../herdr/herdr-composer/mods/herdr-composer/suggest.js";
|
||||
|
||||
test("detect finds a slash command at caret", () => {
|
||||
assert.deepEqual(detect("ala /re", 7), { trigger: "/", needle: "re", start: 4 });
|
||||
|
||||
+110
-4
@@ -2,8 +2,8 @@ import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
targetAgent, agentKey, agentName, agentStatus, createGate, gatePasses, openGate, closeGate,
|
||||
isPlainEnter, statusText, queueLabel, applySuggestion, insertedNewline,
|
||||
} from "../mod/ovis-composer/view.js";
|
||||
isPlainEnter, statusText, queueLabel, applySuggestion, insertedNewline, noticeExpired,
|
||||
} from "../herdr/herdr-composer/mods/herdr-composer/view.js";
|
||||
|
||||
const agents = [{ address: "t1", app: "claude-code" }, { address: "a2" }];
|
||||
|
||||
@@ -55,7 +55,7 @@ test("insertedNewline finds the index", () => {
|
||||
});
|
||||
|
||||
test("canAutoSend waits for the draft/identity check of the agent", async () => {
|
||||
const { canAutoSend } = await import("../mod/ovis-composer/view.js");
|
||||
const { canAutoSend } = await import("../herdr/herdr-composer/mods/herdr-composer/view.js");
|
||||
assert.equal(canAutoSend(new Set(), "t2"), false);
|
||||
assert.equal(canAutoSend(new Set(["t2"]), "t2"), true);
|
||||
assert.equal(canAutoSend(new Set(["t3"]), "t2"), false);
|
||||
@@ -70,7 +70,7 @@ test("queueLabel for every state", () => {
|
||||
assert.equal(queueLabel({ state: "countdown", left: 2 }), "Wysyłam za 2 s");
|
||||
});
|
||||
|
||||
import { stillSameAgent } from "../mod/ovis-composer/view.js";
|
||||
import { stillSameAgent } from "../herdr/herdr-composer/mods/herdr-composer/view.js";
|
||||
|
||||
test("stillSameAgent: only when the field and the focus are on one agent", () => {
|
||||
assert.equal(stillSameAgent({ before: "t2", after: "t2", target: "t2" }), true);
|
||||
@@ -81,3 +81,109 @@ test("stillSameAgent: only when the field and the focus are on one agent", () =>
|
||||
assert.equal(stillSameAgent({ before: "", after: "", target: "" }), false);
|
||||
assert.equal(stillSameAgent({ before: "", after: "t2", target: "t2" }), false);
|
||||
});
|
||||
|
||||
import { directSendBlocked } from "../herdr/herdr-composer/mods/herdr-composer/view.js";
|
||||
|
||||
test("directSendBlocked: who must wait behind the queue", () => {
|
||||
const queue = [{ state: "queued" }];
|
||||
// an answer to a blocked agent goes ahead of the queue
|
||||
assert.equal(directSendBlocked({ draining: false, mode: "auto", status: "blocked", queue }), false);
|
||||
// an idle agent with a queue: the new message waits at the end
|
||||
assert.equal(directSendBlocked({ draining: false, mode: "auto", status: "idle", queue }), true);
|
||||
assert.equal(directSendBlocked({ draining: false, mode: "auto", status: "done", queue }), true);
|
||||
// Ctrl+Enter is the person's own order
|
||||
assert.equal(directSendBlocked({ draining: false, mode: "now", status: "idle", queue }), false);
|
||||
// a message on the wire always goes first
|
||||
assert.equal(directSendBlocked({ draining: true, mode: "now", status: "blocked", queue: [] }), true);
|
||||
assert.equal(directSendBlocked({ draining: true, mode: "auto", status: "idle", queue }), true);
|
||||
// nothing waits
|
||||
assert.equal(directSendBlocked({ draining: false, mode: "auto", status: "idle", queue: [] }), false);
|
||||
assert.equal(directSendBlocked({ draining: false, mode: "auto", status: "idle", queue: [{ state: "held" }] }), false);
|
||||
});
|
||||
|
||||
import { blockTargetPx, shouldResize, isManualResize } from "../herdr/herdr-composer/mods/herdr-composer/view.js";
|
||||
|
||||
const fit = (over = {}) => ({ contentHeight: 100, padding: 16, zoom: 1.2, userMin: 0, min: 120, max: 520, ...over });
|
||||
|
||||
test("blockTargetPx: the content (plus padding) in layout px, clamped to the layout's range", () => {
|
||||
// (100 + 16) / 1.2 = 96.7 -> 97, under the minimum of 120
|
||||
assert.equal(blockTargetPx(fit()), 120);
|
||||
// (300 + 16) / 1.2 = 263.3 -> 264
|
||||
assert.equal(blockTargetPx(fit({ contentHeight: 300 })), 264);
|
||||
assert.equal(blockTargetPx(fit({ contentHeight: 5000 })), 520);
|
||||
assert.equal(blockTargetPx(fit({ contentHeight: 300, zoom: 1 })), 316);
|
||||
});
|
||||
|
||||
test("blockTargetPx: the height the person dragged to is kept, and content that needs more wins", () => {
|
||||
assert.equal(blockTargetPx(fit({ contentHeight: 100, userMin: 300 })), 300);
|
||||
assert.equal(blockTargetPx(fit({ contentHeight: 500, userMin: 300 })), 430);
|
||||
assert.equal(blockTargetPx(fit({ contentHeight: 100, userMin: 9999 })), 520);
|
||||
assert.equal(blockTargetPx(fit({ contentHeight: 100, userMin: 0 })), 120);
|
||||
});
|
||||
|
||||
test("blockTargetPx: a zoom that is not a number counts as 1", () => {
|
||||
assert.equal(blockTargetPx(fit({ contentHeight: 300, zoom: 0 })), 316);
|
||||
assert.equal(blockTargetPx(fit({ contentHeight: 300, zoom: NaN })), 316);
|
||||
});
|
||||
|
||||
test("shouldResize: only for a difference over 4 px", () => {
|
||||
assert.equal(shouldResize(150, 154), false);
|
||||
assert.equal(shouldResize(150, 155), true);
|
||||
assert.equal(shouldResize(150, 145), true);
|
||||
assert.equal(shouldResize(150, 146), false);
|
||||
assert.equal(shouldResize(null, 150), false);
|
||||
assert.equal(shouldResize(150, undefined), false);
|
||||
});
|
||||
|
||||
test("isManualResize: a height nobody ordered is the person's drag", () => {
|
||||
assert.equal(isManualResize({ reportedPx: 200, orderedPx: 200 }), false);
|
||||
assert.equal(isManualResize({ reportedPx: 202, orderedPx: 200 }), false);
|
||||
assert.equal(isManualResize({ reportedPx: 260, orderedPx: 200 }), true);
|
||||
assert.equal(isManualResize({ reportedPx: 100, orderedPx: 200 }), true);
|
||||
// nothing was ordered yet: the first size is the layout's, not a drag
|
||||
assert.equal(isManualResize({ reportedPx: 150, orderedPx: null }), false);
|
||||
assert.equal(isManualResize({ reportedPx: NaN, orderedPx: 200 }), false);
|
||||
});
|
||||
|
||||
import { luminance, fieldBackground } from "../herdr/herdr-composer/mods/herdr-composer/view.js";
|
||||
|
||||
test("luminance: black is darker than grey is darker than white; alpha and rubbish are tolerated", () => {
|
||||
assert.ok(luminance("#000000") < luminance("#808080"));
|
||||
assert.ok(luminance("#808080") < luminance("#ffffff"));
|
||||
assert.equal(luminance("#000000ff"), luminance("#000000"));
|
||||
assert.equal(luminance("#fff"), luminance("#ffffff"));
|
||||
assert.equal(luminance("red"), null);
|
||||
assert.equal(luminance(undefined), null);
|
||||
});
|
||||
|
||||
test("fieldBackground: the darkest color the theme has, darker than the panel", () => {
|
||||
const theme = { popover: "#2a2c31", background: "#101114", canvas: "#16171a", raised: "#202226", chrome: "#1b1c20" };
|
||||
assert.equal(fieldBackground(theme, theme.popover), "#101114");
|
||||
// a theme where the background is lighter than another color: that one wins
|
||||
assert.equal(fieldBackground({ ...theme, background: "#3a3c41", canvas: "#0c0d0f" }, theme.popover), "#0c0d0f");
|
||||
// nothing valid: the panel's own color
|
||||
assert.equal(fieldBackground({}, "#2a2c31"), "#2a2c31");
|
||||
assert.equal(fieldBackground({ background: "nope" }, "#2a2c31"), "#2a2c31");
|
||||
});
|
||||
|
||||
test("noticeExpired: the same info notice expires", () => {
|
||||
const info = { text: "a", level: "info" };
|
||||
assert.equal(noticeExpired(info, info), true);
|
||||
});
|
||||
|
||||
test("noticeExpired: another notice with the same text is not touched", () => {
|
||||
const scheduled = { text: "a", level: "info" };
|
||||
assert.equal(noticeExpired({ text: "a", level: "info" }, scheduled), false);
|
||||
});
|
||||
|
||||
test("noticeExpired: a problem or an error stays, and so does an info that was replaced by one", () => {
|
||||
const problem = { text: "b", level: "problem" };
|
||||
const error = { text: "c", level: "error" };
|
||||
assert.equal(noticeExpired(problem, problem), false);
|
||||
assert.equal(noticeExpired(error, error), false);
|
||||
assert.equal(noticeExpired(problem, { text: "a", level: "info" }), false);
|
||||
});
|
||||
|
||||
test("noticeExpired: no current notice is nothing to clear", () => {
|
||||
assert.equal(noticeExpired(null, { text: "a", level: "info" }), false);
|
||||
});
|
||||
Reference in new issue
Block a user