bots-garden/sidekickspublic Fork
⑂ f1d3e7d
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/sidekicks.git
git clone ssh://git@rickub.com/bots-garden/sidekicks.git

Host key fingerprint (ed25519): SHA256:iycHnxEyq0Q7uyVpB7JlznP0G7JrTPXLYRcAU5CSLhc — verify it before your first connect.

Download ZIP

#51 Décharger le modèle d'un agent : depuis le panneau Log (l'agent choisi ou tous), la liste Agents et la vue de l'agent

/unload est envoyé dans une session à part (aucune trace dans les conversations),
la réponse va dans le Log. AgentService.Unload / UnloadAll, tests Go et frontend,
docs EN + FR.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
k33g committed 2026-11-09T19:55:18+01:00 Browse files
f1d3e7d parent: b854072
modified .memory/history.md +1 -0
@@ -217,3 +217,4 @@
217217 - #72/#73: `terminalSessions.svelte.ts` keeps terminals (xterm screen in its own element, reparented by TerminalView) outside AgentView; sub-tabs, +/×, 8 max per agent, counts on the tab and ⌨ n in the Agents panel; AgentView remembers the last tab per agent.
218218 - Verified in the app under Xvfb (Linux): colouring, selection, drag and drop (HTML5 DnD works in WebKitGTK with slow xdotool moves), F2, menu, Move to…, delete to trash, terminal running while away, 3 terminals, close, exit/restart, no shell left after quit. Trap: the sandbox's `tty` prints no newline (not an app bug). `make verify` green. Not checked on macOS.
219219 - Also filed #75–#80 (collective memory REST API, MCP mode question, MCP gateway, plugins, acting outside, prompt injection), no milestone.
220+- **2026-11-09 — #51 unload a model from the Log panel** (owner: "/unload already works; from the Log panel, unload the selected model or all of them"): convention kept — an agent that announces the `unload` slash command can unload its model. `channels.Manager.Unload` sends `/unload` in a throwaway session (no trace in conversations; refuses no-command / answering agents), `AgentService.Unload` also refuses a stopped agent and writes the answer to the agent log (`unload: …`), `UnloadAll` returns `{unloaded, skipped}` without starting stopped agents. UI: ⏏ Unload the model + ⏏ Unload all in the Log panel (result line), ⏏ on the agent row and in the agent view header; the frontend decides visibility from `appState.commands` (no `canUnload` in `List()`, it would be lost on agent:state events). Verified under Xvfb with two fake ACP agents (Python, scratchpad). Docs EN/FR: memory-pressure how-to, memory explanation, AgentService reference.
@@ -217,3 +217,4 @@
217 - #72/#73: `terminalSessions.svelte.ts` keeps terminals (xterm screen in its own element, reparented by TerminalView) outside AgentView; sub-tabs, +/×, 8 max per agent, counts on the tab and ⌨ n in the Agents panel; AgentView remembers the last tab per agent.217 - #72/#73: `terminalSessions.svelte.ts` keeps terminals (xterm screen in its own element, reparented by TerminalView) outside AgentView; sub-tabs, +/×, 8 max per agent, counts on the tab and ⌨ n in the Agents panel; AgentView remembers the last tab per agent.
218 - Verified in the app under Xvfb (Linux): colouring, selection, drag and drop (HTML5 DnD works in WebKitGTK with slow xdotool moves), F2, menu, Move to…, delete to trash, terminal running while away, 3 terminals, close, exit/restart, no shell left after quit. Trap: the sandbox's `tty` prints no newline (not an app bug). `make verify` green. Not checked on macOS.218 - Verified in the app under Xvfb (Linux): colouring, selection, drag and drop (HTML5 DnD works in WebKitGTK with slow xdotool moves), F2, menu, Move to…, delete to trash, terminal running while away, 3 terminals, close, exit/restart, no shell left after quit. Trap: the sandbox's `tty` prints no newline (not an app bug). `make verify` green. Not checked on macOS.
219 - Also filed #75–#80 (collective memory REST API, MCP mode question, MCP gateway, plugins, acting outside, prompt injection), no milestone.219 - Also filed #75–#80 (collective memory REST API, MCP mode question, MCP gateway, plugins, acting outside, prompt injection), no milestone.
220+- **2026-11-09 — #51 unload a model from the Log panel** (owner: "/unload already works; from the Log panel, unload the selected model or all of them"): convention kept — an agent that announces the `unload` slash command can unload its model. `channels.Manager.Unload` sends `/unload` in a throwaway session (no trace in conversations; refuses no-command / answering agents), `AgentService.Unload` also refuses a stopped agent and writes the answer to the agent log (`unload: …`), `UnloadAll` returns `{unloaded, skipped}` without starting stopped agents. UI: ⏏ Unload the model + ⏏ Unload all in the Log panel (result line), ⏏ on the agent row and in the agent view header; the frontend decides visibility from `appState.commands` (no `canUnload` in `List()`, it would be lost on agent:state events). Verified under Xvfb with two fake ACP agents (Python, scratchpad). Docs EN/FR: memory-pressure how-to, memory explanation, AgentService reference.
modified .tickets/issues/0051-ajouter-un-bouton-pour-decharger-le-modele-de-la.yaml +41 -7
@@ -1,12 +1,12 @@
11 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
22 id: 51
33 title: Ajouter un bouton pour décharger le modèle de la mémoire (quand l'agent le permet)
4-state: open
4+state: closed
55 author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-10-31T07:10:06.981Z
9-updatedAt: 2026-11-09T18:48:12.000Z
9+updatedAt: 2026-11-09T18:55:08.000Z
1010 labels:
1111 - kind::feature
1212 - area::acp
@@ -64,44 +64,54 @@ body: |
6464 tasks:
6565 - id: 1
6666 title: "Unload(agent) : session dédiée, envoi de /unload, refus si arrêté, occupé ou sans la commande"
67- state: open
67+ state: closed
6868 priority: medium
6969 author:
7070 name: k33g
7171 email: ph.charriere@gmail.com
7272 createdAt: 2026-11-01T06:48:09.000Z
73+ updatedAt: 2026-11-09T18:55:08.000Z
74+ closedAt: 2026-11-09T18:55:08.000Z
7375 - id: 2
7476 title: "AgentService.Unload et canUnload dans List(), bindings"
75- state: open
77+ state: closed
7678 priority: medium
7779 author:
7880 name: k33g
7981 email: ph.charriere@gmail.com
8082 createdAt: 2026-11-01T06:48:09.000Z
83+ updatedAt: 2026-11-09T18:55:08.000Z
84+ closedAt: 2026-11-09T18:55:08.000Z
8185 - id: 3
8286 title: "Interface : bouton ⏏ dans la liste Agents et la vue de l'agent"
83- state: open
87+ state: closed
8488 priority: medium
8589 author:
8690 name: k33g
8791 email: ph.charriere@gmail.com
8892 createdAt: 2026-11-01T06:48:09.000Z
93+ updatedAt: 2026-11-09T18:55:08.000Z
94+ closedAt: 2026-11-09T18:55:08.000Z
8995 - id: 4
9096 title: Tests et documentation EN + FR
91- state: open
97+ state: closed
9298 priority: low
9399 author:
94100 name: k33g
95101 email: ph.charriere@gmail.com
96102 createdAt: 2026-11-01T06:48:09.000Z
103+ updatedAt: 2026-11-09T18:55:08.000Z
104+ closedAt: 2026-11-09T18:55:08.000Z
97105 - id: 5
98106 title: "Panneau Log : ⏏ décharger le modèle de l'agent sélectionné, et ⏏ Tout décharger"
99- state: open
107+ state: closed
100108 priority: medium
101109 author:
102110 name: k33g
103111 email: ph.charriere@gmail.com
104112 createdAt: 2026-11-09T18:48:12.000Z
113+ updatedAt: 2026-11-09T18:55:08.000Z
114+ closedAt: 2026-11-09T18:55:08.000Z
105115 comments:
106116 - id: 1
107117 author:
@@ -113,3 +123,27 @@ comments:
113123 le panneau **Log**, décharger le modèle de l'agent sélectionné, ou tous les modèles.
114124 Les deux questions « À trancher » sont donc tranchées : oui pour le bouton dans le Log, oui pour
115125 « Tout décharger ».
126+ - id: 2
127+ author:
128+ name: k33g
129+ email: ph.charriere@gmail.com
130+ createdAt: 2026-11-09T18:55:08.000Z
131+ body: |
132+ Implémenté.
133+
134+ - `channels.Manager.Unload(agent)` : refuse un agent sans commande `unload` (`ErrCannotUnload`)
135+ ou qui répond (`ErrAgentAnswering`), sinon ouvre une session à part, y envoie `/unload` et
136+ renvoie la réponse. Les commandes annoncées dans cette session sont gardées comme d'habitude.
137+ - `AgentService.Unload(name)` : refuse aussi un agent arrêté (`ErrNotRunning`) ; la réponse de
138+ l'agent va dans son **Log** (`unload: …`). `AgentService.UnloadAll()` renvoie
139+ `{unloaded, skipped}` ; les agents arrêtés ne sont pas démarrés.
140+ - Écart avec la tâche 2 : pas de `canUnload` dans `List()`. L'interface connaît déjà les commandes
141+ de chaque agent (`appState.commands`, tenu à jour par `commands:changed`) ; un champ dans
142+ `List()` aurait été perdu à chaque événement `agent:state`.
143+ - Interface : **⏏ Décharger le modèle** et **⏏ Tout décharger** dans le panneau Log, à côté de la
144+ pression mémoire, avec une ligne de résultat ; ⏏ sur la ligne de l'agent (liste Agents) et
145+ dans l'en-tête de sa vue. Grisé tant que l'agent n'est pas prêt ; erreurs traduites.
146+ - Tests : Go (channels + app, avec un faux agent qui annonce ou non `unload`), frontend
147+ (`unload.test.ts`). Vérifié dans l'application avec deux faux agents ACP.
148+ - Docs EN + FR : guide « Surveiller la pression mémoire », explication « Mémoire et modèles
149+ locaux » (la convention `unload`), référence `AgentService`.
@@ -1,12 +1,12 @@
1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.1 # Managed by IssueSpec. Hand edits are welcome; keep the schema valid.
2 id: 512 id: 51
3 title: Ajouter un bouton pour décharger le modèle de la mémoire (quand l'agent le permet)3 title: Ajouter un bouton pour décharger le modèle de la mémoire (quand l'agent le permet)
4-state: open4+state: closed
5 author:5 author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-10-31T07:10:06.981Z8 createdAt: 2026-10-31T07:10:06.981Z
9-updatedAt: 2026-11-09T18:48:12.000Z9+updatedAt: 2026-11-09T18:55:08.000Z
10 labels:10 labels:
11 - kind::feature11 - kind::feature
12 - area::acp12 - area::acp
@@ -64,44 +64,54 @@ body: |
64 tasks:64 tasks:
65 - id: 165 - id: 1
66 title: "Unload(agent) : session dédiée, envoi de /unload, refus si arrêté, occupé ou sans la commande"66 title: "Unload(agent) : session dédiée, envoi de /unload, refus si arrêté, occupé ou sans la commande"
67- state: open67+ state: closed
68 priority: medium68 priority: medium
69 author:69 author:
70 name: k33g70 name: k33g
71 email: ph.charriere@gmail.com71 email: ph.charriere@gmail.com
72 createdAt: 2026-11-01T06:48:09.000Z72 createdAt: 2026-11-01T06:48:09.000Z
73+ updatedAt: 2026-11-09T18:55:08.000Z
74+ closedAt: 2026-11-09T18:55:08.000Z
73 - id: 275 - id: 2
74 title: "AgentService.Unload et canUnload dans List(), bindings"76 title: "AgentService.Unload et canUnload dans List(), bindings"
75- state: open77+ state: closed
76 priority: medium78 priority: medium
77 author:79 author:
78 name: k33g80 name: k33g
79 email: ph.charriere@gmail.com81 email: ph.charriere@gmail.com
80 createdAt: 2026-11-01T06:48:09.000Z82 createdAt: 2026-11-01T06:48:09.000Z
83+ updatedAt: 2026-11-09T18:55:08.000Z
84+ closedAt: 2026-11-09T18:55:08.000Z
81 - id: 385 - id: 3
82 title: "Interface : bouton ⏏ dans la liste Agents et la vue de l'agent"86 title: "Interface : bouton ⏏ dans la liste Agents et la vue de l'agent"
83- state: open87+ state: closed
84 priority: medium88 priority: medium
85 author:89 author:
86 name: k33g90 name: k33g
87 email: ph.charriere@gmail.com91 email: ph.charriere@gmail.com
88 createdAt: 2026-11-01T06:48:09.000Z92 createdAt: 2026-11-01T06:48:09.000Z
93+ updatedAt: 2026-11-09T18:55:08.000Z
94+ closedAt: 2026-11-09T18:55:08.000Z
89 - id: 495 - id: 4
90 title: Tests et documentation EN + FR96 title: Tests et documentation EN + FR
91- state: open97+ state: closed
92 priority: low98 priority: low
93 author:99 author:
94 name: k33g100 name: k33g
95 email: ph.charriere@gmail.com101 email: ph.charriere@gmail.com
96 createdAt: 2026-11-01T06:48:09.000Z102 createdAt: 2026-11-01T06:48:09.000Z
103+ updatedAt: 2026-11-09T18:55:08.000Z
104+ closedAt: 2026-11-09T18:55:08.000Z
97 - id: 5105 - id: 5
98 title: "Panneau Log : ⏏ décharger le modèle de l'agent sélectionné, et ⏏ Tout décharger"106 title: "Panneau Log : ⏏ décharger le modèle de l'agent sélectionné, et ⏏ Tout décharger"
99- state: open107+ state: closed
100 priority: medium108 priority: medium
101 author:109 author:
102 name: k33g110 name: k33g
103 email: ph.charriere@gmail.com111 email: ph.charriere@gmail.com
104 createdAt: 2026-11-09T18:48:12.000Z112 createdAt: 2026-11-09T18:48:12.000Z
113+ updatedAt: 2026-11-09T18:55:08.000Z
114+ closedAt: 2026-11-09T18:55:08.000Z
105 comments:115 comments:
106 - id: 1116 - id: 1
107 author:117 author:
@@ -113,3 +123,27 @@ comments:
113 le panneau **Log**, décharger le modèle de l'agent sélectionné, ou tous les modèles.123 le panneau **Log**, décharger le modèle de l'agent sélectionné, ou tous les modèles.
114 Les deux questions « À trancher » sont donc tranchées : oui pour le bouton dans le Log, oui pour124 Les deux questions « À trancher » sont donc tranchées : oui pour le bouton dans le Log, oui pour
115 « Tout décharger ».125 « Tout décharger ».
126+ - id: 2
127+ author:
128+ name: k33g
129+ email: ph.charriere@gmail.com
130+ createdAt: 2026-11-09T18:55:08.000Z
131+ body: |
132+ Implémenté.
133+
134+ - `channels.Manager.Unload(agent)` : refuse un agent sans commande `unload` (`ErrCannotUnload`)
135+ ou qui répond (`ErrAgentAnswering`), sinon ouvre une session à part, y envoie `/unload` et
136+ renvoie la réponse. Les commandes annoncées dans cette session sont gardées comme d'habitude.
137+ - `AgentService.Unload(name)` : refuse aussi un agent arrêté (`ErrNotRunning`) ; la réponse de
138+ l'agent va dans son **Log** (`unload: …`). `AgentService.UnloadAll()` renvoie
139+ `{unloaded, skipped}` ; les agents arrêtés ne sont pas démarrés.
140+ - Écart avec la tâche 2 : pas de `canUnload` dans `List()`. L'interface connaît déjà les commandes
141+ de chaque agent (`appState.commands`, tenu à jour par `commands:changed`) ; un champ dans
142+ `List()` aurait été perdu à chaque événement `agent:state`.
143+ - Interface : **⏏ Décharger le modèle** et **⏏ Tout décharger** dans le panneau Log, à côté de la
144+ pression mémoire, avec une ligne de résultat ; ⏏ sur la ligne de l'agent (liste Agents) et
145+ dans l'en-tête de sa vue. Grisé tant que l'agent n'est pas prêt ; erreurs traduites.
146+ - Tests : Go (channels + app, avec un faux agent qui annonce ou non `unload`), frontend
147+ (`unload.test.ts`). Vérifié dans l'application avec deux faux agents ACP.
148+ - Docs EN + FR : guide « Surveiller la pression mémoire », explication « Mémoire et modèles
149+ locaux » (la convention `unload`), référence `AgentService`.
modified docs/en/explanation/memory-and-local-models.md +9 -2
@@ -21,10 +21,17 @@ The same reasoning applies to the people who will use Sidekicks on their laptops
2121
2222 The price of stopping idle agents is memory of another kind: mm cannot reload a session, so an agent restarted after a pause no longer remembers the beginning of the conversation. Sidekicks says so in the conversation (milestone M2) and will give the agent the context back with channels (issue #25).
2323
24-## Rejected alternatives
24+## Unloading a model on request
25+
26+Stopping an agent frees its model, but also its sessions. When the memory pressure rises (see [How to watch the memory pressure](../how-to/watch-the-memory-pressure.md)), the user can instead have an agent **unload its model** and keep running (issue #51): the model is loaded again with the next message.
27+
28+Sidekicks does not talk to the model server: it does not know which model an agent uses, nor where it is served. The agent knows, so the agent does it. ACP has no standard method for that, hence a convention: **an agent that announces a slash command named `unload` can unload its model**. mm announces it right after `session/new`, and checks that the model is loaded before unloading it (it never loads a model to unload it).
29+
30+Sidekicks sends `/unload` in a session of its own, opened for it and forgotten afterwards, so that nothing appears in the conversations; the agent's answer goes to its log. It does so only while the agent runs and answers nothing: a stopped agent has nothing loaded (`afterStop` is the place to unload on stop), and an agent that is answering would load its model again at once. If ACP or mm offer an extension method one day, it can replace the command without changing the interface.
31+
2532
2633 - **Starting every configured agent at launch**: simple, and unusable with four local models.
27-- **Letting each agent unload its own model**: mm can (`/unload`), but only Sidekicks knows whether another agent still needs the same model.
34+- **Letting each agent unload its own model on its own**: mm can (`/unload`), but only Sidekicks knows whether another agent still needs the same model. Unloading stays a choice of the user (above).
2835
2936 ## How it relates to the rest
3037
@@ -21,10 +21,17 @@ The same reasoning applies to the people who will use Sidekicks on their laptops
21 21
22 The price of stopping idle agents is memory of another kind: mm cannot reload a session, so an agent restarted after a pause no longer remembers the beginning of the conversation. Sidekicks says so in the conversation (milestone M2) and will give the agent the context back with channels (issue #25).22 The price of stopping idle agents is memory of another kind: mm cannot reload a session, so an agent restarted after a pause no longer remembers the beginning of the conversation. Sidekicks says so in the conversation (milestone M2) and will give the agent the context back with channels (issue #25).
23 23
24-## Rejected alternatives24+## Unloading a model on request
25+
26+Stopping an agent frees its model, but also its sessions. When the memory pressure rises (see [How to watch the memory pressure](../how-to/watch-the-memory-pressure.md)), the user can instead have an agent **unload its model** and keep running (issue #51): the model is loaded again with the next message.
27+
28+Sidekicks does not talk to the model server: it does not know which model an agent uses, nor where it is served. The agent knows, so the agent does it. ACP has no standard method for that, hence a convention: **an agent that announces a slash command named `unload` can unload its model**. mm announces it right after `session/new`, and checks that the model is loaded before unloading it (it never loads a model to unload it).
29+
30+Sidekicks sends `/unload` in a session of its own, opened for it and forgotten afterwards, so that nothing appears in the conversations; the agent's answer goes to its log. It does so only while the agent runs and answers nothing: a stopped agent has nothing loaded (`afterStop` is the place to unload on stop), and an agent that is answering would load its model again at once. If ACP or mm offer an extension method one day, it can replace the command without changing the interface.
31+
25 32
26 - **Starting every configured agent at launch**: simple, and unusable with four local models.33 - **Starting every configured agent at launch**: simple, and unusable with four local models.
27-- **Letting each agent unload its own model**: mm can (`/unload`), but only Sidekicks knows whether another agent still needs the same model.34+- **Letting each agent unload its own model on its own**: mm can (`/unload`), but only Sidekicks knows whether another agent still needs the same model. Unloading stays a choice of the user (above).
28 35
29 ## How it relates to the rest36 ## How it relates to the rest
30 37
modified docs/en/how-to/watch-the-memory-pressure.md +7 -1
@@ -9,6 +9,8 @@ Local models and agents take a lot of memory. When the computer runs short of it
99
1010 Hover over the level for a reminder of what to do. The line is refreshed every 5 seconds while the panel is open.
1111 3. When the level is **high** or **critical**, free memory:
12+ - unload the model of the agent whose log is shown: **⏏ Unload the model**, next to the agent's name in the panel. The agent keeps running; its model is loaded again with its next message. What the agent answers is written in its log (`unload: …`). The button is there only for an agent that offers the `/unload` command (mm does), and it can be used only while the agent is running and not answering;
13+ - or unload every model at once: **⏏ Unload all**. Each running agent that can is asked; a line under the bar names the agents unloaded and the ones left alone (answering, or without `/unload`). Stopped agents are not started for it;
1214 - stop an agent you do not need: **■** next to it in the **Agents** panel;
1315 - close the applications you do not use.
1416
@@ -17,8 +19,12 @@ Local models and agents take a lot of memory. When the computer runs short of it
1719 - **On macOS**, the level is the one the system gives, the same as the *Memory Pressure* graph of Activity Monitor. The memory used is counted as Activity Monitor does: app memory, wired memory and compressed memory. The memory "cached" by macOS is not counted: it is given back as soon as an application needs it.
1820 - **On Windows** (and Linux), the level is worked out from the memory still available: **high** under 20 %, **critical** under 10 %.
1921 - If the memory cannot be measured, the line is not shown.
22+- Unloading a model frees its memory within a few seconds, when the model server applies it. Typing `/unload` in a conversation with the agent has the same effect, but leaves the command and its answer in the conversation.
23+
24+**⏏** is also in the agent's row of the **Agents** panel (on hover) and in the header of the agent's view.
2025
2126 ## See also
2227
23-- [Reference: services called by the interface](../reference/agents-and-events.md#services-called-by-the-interface) (`SystemService.Memory`)
28+- [Reference: services called by the interface](../reference/agents-and-events.md#services-called-by-the-interface) (`SystemService.Memory`, `AgentService.Unload`, `AgentService.UnloadAll`)
29+- [Explanation: memory and local models](../explanation/memory-and-local-models.md#unloading-a-model-on-request)
2430 - [Work with an agent's files and terminal](work-with-an-agents-files.md)
@@ -9,6 +9,8 @@ Local models and agents take a lot of memory. When the computer runs short of it
9 9
10 Hover over the level for a reminder of what to do. The line is refreshed every 5 seconds while the panel is open.10 Hover over the level for a reminder of what to do. The line is refreshed every 5 seconds while the panel is open.
11 3. When the level is **high** or **critical**, free memory:11 3. When the level is **high** or **critical**, free memory:
12+ - unload the model of the agent whose log is shown: **⏏ Unload the model**, next to the agent's name in the panel. The agent keeps running; its model is loaded again with its next message. What the agent answers is written in its log (`unload: …`). The button is there only for an agent that offers the `/unload` command (mm does), and it can be used only while the agent is running and not answering;
13+ - or unload every model at once: **⏏ Unload all**. Each running agent that can is asked; a line under the bar names the agents unloaded and the ones left alone (answering, or without `/unload`). Stopped agents are not started for it;
12 - stop an agent you do not need: **■** next to it in the **Agents** panel;14 - stop an agent you do not need: **■** next to it in the **Agents** panel;
13 - close the applications you do not use.15 - close the applications you do not use.
14 16
@@ -17,8 +19,12 @@ Local models and agents take a lot of memory. When the computer runs short of it
17 - **On macOS**, the level is the one the system gives, the same as the *Memory Pressure* graph of Activity Monitor. The memory used is counted as Activity Monitor does: app memory, wired memory and compressed memory. The memory "cached" by macOS is not counted: it is given back as soon as an application needs it.19 - **On macOS**, the level is the one the system gives, the same as the *Memory Pressure* graph of Activity Monitor. The memory used is counted as Activity Monitor does: app memory, wired memory and compressed memory. The memory "cached" by macOS is not counted: it is given back as soon as an application needs it.
18 - **On Windows** (and Linux), the level is worked out from the memory still available: **high** under 20 %, **critical** under 10 %.20 - **On Windows** (and Linux), the level is worked out from the memory still available: **high** under 20 %, **critical** under 10 %.
19 - If the memory cannot be measured, the line is not shown.21 - If the memory cannot be measured, the line is not shown.
22+- Unloading a model frees its memory within a few seconds, when the model server applies it. Typing `/unload` in a conversation with the agent has the same effect, but leaves the command and its answer in the conversation.
23+
24+**⏏** is also in the agent's row of the **Agents** panel (on hover) and in the header of the agent's view.
20 25
21 ## See also26 ## See also
22 27
23-- [Reference: services called by the interface](../reference/agents-and-events.md#services-called-by-the-interface) (`SystemService.Memory`)28+- [Reference: services called by the interface](../reference/agents-and-events.md#services-called-by-the-interface) (`SystemService.Memory`, `AgentService.Unload`, `AgentService.UnloadAll`)
29+- [Explanation: memory and local models](../explanation/memory-and-local-models.md#unloading-a-model-on-request)
24 - [Work with an agent's files and terminal](work-with-an-agents-files.md)30 - [Work with an agent's files and terminal](work-with-an-agents-files.md)
modified docs/en/reference/agents-and-events.md +2 -0
@@ -49,6 +49,8 @@ The Go names and types are in `internal/events`; the TypeScript constants and ty
4949 | `AgentService` | `List()` | Every agent with `name, title, icon, description, state, error, outdated, runtime, canStopSandbox, canRemoveSandbox`, in configuration order. |
5050 | | `Start(name)`, `Stop(name)`, `Restart(name)` | As in the transitions above; an error is returned to the interface. A start first recreates a missing sandbox when `runtime.lifecycle.create` is set. |
5151 | | `StopSandbox(name)`, `RemoveSandbox(name)` | Stops the agent, then runs `runtime.lifecycle.stop` or `remove` (container or sandbox); the output goes to the agent's log. |
52+| | `Unload(name)` | Has a running, idle agent that announced the `unload` command unload its model (issue #51): `/unload` is sent in a session of its own, which no conversation shows; the answer goes to the agent's log as `unload: …` lines. Errors: unknown agent, `the agent is not running…`, `the agent is answering…`, `this agent cannot unload its model…`. |
53+| | `UnloadAll()` | `Unload` for every running agent: returns `{unloaded[], skipped[]}` (agent names); stopped agents are left out. |
5254 | | `Logs(name)` | The last 200 stderr lines of the agent. |
5355 | `ConfigService` | `Current()` | `path, source, created, valid, problems[], warnings[], theme, language, historyProblem`. |
5456 | `SystemService` | `Memory()` | `level` (`normal`, `warning`, `critical`), `used` and `total` in bytes; all empty (`total` 0) where the memory cannot be measured. macOS: the level of `kern.memorystatus_vm_pressure_level`, used = app + wired + compressed memory (`vm_stat`), as in Activity Monitor. Linux and Windows: worked out from the available memory, `warning` under 20 %, `critical` under 10 %. The Log panel calls it every 5 seconds while it is open (issue #61). |
@@ -49,6 +49,8 @@ The Go names and types are in `internal/events`; the TypeScript constants and ty
49 | `AgentService` | `List()` | Every agent with `name, title, icon, description, state, error, outdated, runtime, canStopSandbox, canRemoveSandbox`, in configuration order. |49 | `AgentService` | `List()` | Every agent with `name, title, icon, description, state, error, outdated, runtime, canStopSandbox, canRemoveSandbox`, in configuration order. |
50 | | `Start(name)`, `Stop(name)`, `Restart(name)` | As in the transitions above; an error is returned to the interface. A start first recreates a missing sandbox when `runtime.lifecycle.create` is set. |50 | | `Start(name)`, `Stop(name)`, `Restart(name)` | As in the transitions above; an error is returned to the interface. A start first recreates a missing sandbox when `runtime.lifecycle.create` is set. |
51 | | `StopSandbox(name)`, `RemoveSandbox(name)` | Stops the agent, then runs `runtime.lifecycle.stop` or `remove` (container or sandbox); the output goes to the agent's log. |51 | | `StopSandbox(name)`, `RemoveSandbox(name)` | Stops the agent, then runs `runtime.lifecycle.stop` or `remove` (container or sandbox); the output goes to the agent's log. |
52+| | `Unload(name)` | Has a running, idle agent that announced the `unload` command unload its model (issue #51): `/unload` is sent in a session of its own, which no conversation shows; the answer goes to the agent's log as `unload: …` lines. Errors: unknown agent, `the agent is not running…`, `the agent is answering…`, `this agent cannot unload its model…`. |
53+| | `UnloadAll()` | `Unload` for every running agent: returns `{unloaded[], skipped[]}` (agent names); stopped agents are left out. |
52 | | `Logs(name)` | The last 200 stderr lines of the agent. |54 | | `Logs(name)` | The last 200 stderr lines of the agent. |
53 | `ConfigService` | `Current()` | `path, source, created, valid, problems[], warnings[], theme, language, historyProblem`. |55 | `ConfigService` | `Current()` | `path, source, created, valid, problems[], warnings[], theme, language, historyProblem`. |
54 | `SystemService` | `Memory()` | `level` (`normal`, `warning`, `critical`), `used` and `total` in bytes; all empty (`total` 0) where the memory cannot be measured. macOS: the level of `kern.memorystatus_vm_pressure_level`, used = app + wired + compressed memory (`vm_stat`), as in Activity Monitor. Linux and Windows: worked out from the available memory, `warning` under 20 %, `critical` under 10 %. The Log panel calls it every 5 seconds while it is open (issue #61). |56 | `SystemService` | `Memory()` | `level` (`normal`, `warning`, `critical`), `used` and `total` in bytes; all empty (`total` 0) where the memory cannot be measured. macOS: the level of `kern.memorystatus_vm_pressure_level`, used = app + wired + compressed memory (`vm_stat`), as in Activity Monitor. Linux and Windows: worked out from the available memory, `warning` under 20 %, `critical` under 10 %. The Log panel calls it every 5 seconds while it is open (issue #61). |
modified docs/fr/explanation/memoire-et-modeles-locaux.md +9 -2
@@ -21,10 +21,17 @@ Le même raisonnement s'applique aux personnes qui utiliseront Sidekicks sur leu
2121
2222 Le prix de l'arrêt des agents inactifs est une mémoire d'un autre genre : mm ne sait pas recharger une session, donc un agent redémarré après une pause ne se souvient plus du début de la conversation. Sidekicks le dit dans la conversation (milestone M2) et redonnera le contexte à l'agent avec les channels (issue #25).
2323
24-## Alternatives écartées
24+## Décharger un modèle à la demande
25+
26+Arrêter un agent libère son modèle, mais aussi ses sessions. Quand la pression mémoire monte (voir [Surveiller la pression mémoire](../how-to/surveiller-la-pression-memoire.md)), l'utilisateur peut plutôt demander à un agent de **décharger son modèle** sans s'arrêter (ticket #51) : le modèle est rechargé au message suivant.
27+
28+Sidekicks ne parle pas au serveur de modèles : il ne sait pas quel modèle un agent utilise, ni où il est servi. L'agent le sait, c'est donc lui qui le fait. ACP n'a pas de méthode standard pour ça, d'où une convention : **un agent qui annonce une commande slash nommée `unload` sait décharger son modèle**. mm l'annonce juste après `session/new`, et vérifie que le modèle est chargé avant de le décharger (il ne charge jamais un modèle pour le décharger).
29+
30+Sidekicks envoie `/unload` dans une session à part, ouverte pour l'occasion puis oubliée, pour que rien n'apparaisse dans les conversations ; la réponse de l'agent va dans son journal. Il ne le fait que quand l'agent tourne et ne répond à rien : un agent arrêté n'a rien de chargé (`afterStop` sert à décharger à l'arrêt), et un agent en train de répondre rechargerait aussitôt son modèle. Si ACP ou mm proposent un jour une méthode d'extension, elle pourra remplacer la commande sans changer l'interface.
31+
2532
2633 - **Démarrer tous les agents configurés au lancement** : simple, et inutilisable avec quatre modèles locaux.
27-- **Laisser chaque agent décharger son propre modèle** : mm le sait faire (`/unload`), mais seul Sidekicks sait si un autre agent a encore besoin du même modèle.
34+- **Laisser chaque agent décharger son propre modèle de lui-même** : mm le sait faire (`/unload`), mais seul Sidekicks sait si un autre agent a encore besoin du même modèle. Décharger reste un choix de l'utilisateur (ci-dessus).
2835
2936 ## Lien avec le reste
3037
@@ -21,10 +21,17 @@ Le même raisonnement s'applique aux personnes qui utiliseront Sidekicks sur leu
21 21
22 Le prix de l'arrêt des agents inactifs est une mémoire d'un autre genre : mm ne sait pas recharger une session, donc un agent redémarré après une pause ne se souvient plus du début de la conversation. Sidekicks le dit dans la conversation (milestone M2) et redonnera le contexte à l'agent avec les channels (issue #25).22 Le prix de l'arrêt des agents inactifs est une mémoire d'un autre genre : mm ne sait pas recharger une session, donc un agent redémarré après une pause ne se souvient plus du début de la conversation. Sidekicks le dit dans la conversation (milestone M2) et redonnera le contexte à l'agent avec les channels (issue #25).
23 23
24-## Alternatives écartées24+## Décharger un modèle à la demande
25+
26+Arrêter un agent libère son modèle, mais aussi ses sessions. Quand la pression mémoire monte (voir [Surveiller la pression mémoire](../how-to/surveiller-la-pression-memoire.md)), l'utilisateur peut plutôt demander à un agent de **décharger son modèle** sans s'arrêter (ticket #51) : le modèle est rechargé au message suivant.
27+
28+Sidekicks ne parle pas au serveur de modèles : il ne sait pas quel modèle un agent utilise, ni où il est servi. L'agent le sait, c'est donc lui qui le fait. ACP n'a pas de méthode standard pour ça, d'où une convention : **un agent qui annonce une commande slash nommée `unload` sait décharger son modèle**. mm l'annonce juste après `session/new`, et vérifie que le modèle est chargé avant de le décharger (il ne charge jamais un modèle pour le décharger).
29+
30+Sidekicks envoie `/unload` dans une session à part, ouverte pour l'occasion puis oubliée, pour que rien n'apparaisse dans les conversations ; la réponse de l'agent va dans son journal. Il ne le fait que quand l'agent tourne et ne répond à rien : un agent arrêté n'a rien de chargé (`afterStop` sert à décharger à l'arrêt), et un agent en train de répondre rechargerait aussitôt son modèle. Si ACP ou mm proposent un jour une méthode d'extension, elle pourra remplacer la commande sans changer l'interface.
31+
25 32
26 - **Démarrer tous les agents configurés au lancement** : simple, et inutilisable avec quatre modèles locaux.33 - **Démarrer tous les agents configurés au lancement** : simple, et inutilisable avec quatre modèles locaux.
27-- **Laisser chaque agent décharger son propre modèle** : mm le sait faire (`/unload`), mais seul Sidekicks sait si un autre agent a encore besoin du même modèle.34+- **Laisser chaque agent décharger son propre modèle de lui-même** : mm le sait faire (`/unload`), mais seul Sidekicks sait si un autre agent a encore besoin du même modèle. Décharger reste un choix de l'utilisateur (ci-dessus).
28 35
29 ## Lien avec le reste36 ## Lien avec le reste
30 37
modified docs/fr/how-to/surveiller-la-pression-memoire.md +7 -1
@@ -9,6 +9,8 @@ Les modèles locaux et les agents prennent beaucoup de mémoire. Quand l'ordinat
99
1010 Survolez le niveau pour un rappel de ce qu'il faut faire. La ligne est mise à jour toutes les 5 secondes tant que le panneau est ouvert.
1111 3. Quand le niveau est **élevée** ou **critique**, libérez de la mémoire :
12+ - déchargez le modèle de l'agent dont le journal est affiché : **⏏ Décharger le modèle**, à côté du nom de l'agent dans le panneau. L'agent continue de tourner ; son modèle est rechargé à son prochain message. Ce que l'agent répond est écrit dans son journal (`unload: …`). Le bouton n'est là que pour un agent qui propose la commande `/unload` (c'est le cas de mm), et ne sert que quand l'agent tourne et ne répond pas ;
13+ - ou déchargez tous les modèles d'un coup : **⏏ Tout décharger**. Chaque agent en marche qui le sait faire est sollicité ; une ligne sous la barre nomme les agents déchargés et ceux laissés de côté (en train de répondre, ou sans `/unload`). Les agents arrêtés ne sont pas démarrés pour ça ;
1214 - arrêtez un agent dont vous n'avez pas besoin : **■** à côté de lui dans le panneau **Agents** ;
1315 - fermez les applications dont vous ne vous servez pas.
1416
@@ -17,8 +19,12 @@ Les modèles locaux et les agents prennent beaucoup de mémoire. Quand l'ordinat
1719 - **Sous macOS**, le niveau est celui que donne le système, le même que le graphique *Pression de la mémoire* de Moniteur d'activité. La mémoire utilisée est comptée comme dans Moniteur d'activité : mémoire des apps, mémoire résidente et mémoire compressée. La mémoire « en cache » de macOS n'est pas comptée : elle est rendue dès qu'une application en a besoin.
1820 - **Sous Windows** (et Linux), le niveau est déduit de la mémoire encore disponible : **élevée** sous 20 %, **critique** sous 10 %.
1921 - Si la mémoire ne peut pas être mesurée, la ligne n'est pas affichée.
22+- Décharger un modèle libère sa mémoire en quelques secondes, quand le serveur de modèles l'applique. Taper `/unload` dans une conversation avec l'agent a le même effet, mais laisse la commande et sa réponse dans la conversation.
23+
24+**⏏** est aussi sur la ligne de l'agent dans le panneau **Agents** (au survol) et dans l'en-tête de la vue de l'agent.
2025
2126 ## Voir aussi
2227
23-- [Référence : services appelés par l'interface](../reference/agents-et-evenements.md#services-appelés-par-linterface) (`SystemService.Memory`)
28+- [Référence : services appelés par l'interface](../reference/agents-et-evenements.md#services-appelés-par-linterface) (`SystemService.Memory`, `AgentService.Unload`, `AgentService.UnloadAll`)
29+- [Explication : mémoire et modèles locaux](../explanation/memoire-et-modeles-locaux.md#décharger-un-modèle-à-la-demande)
2430 - [Travailler avec les fichiers et le terminal d'un agent](fichiers-et-terminal-d-un-agent.md)
@@ -9,6 +9,8 @@ Les modèles locaux et les agents prennent beaucoup de mémoire. Quand l'ordinat
9 9
10 Survolez le niveau pour un rappel de ce qu'il faut faire. La ligne est mise à jour toutes les 5 secondes tant que le panneau est ouvert.10 Survolez le niveau pour un rappel de ce qu'il faut faire. La ligne est mise à jour toutes les 5 secondes tant que le panneau est ouvert.
11 3. Quand le niveau est **élevée** ou **critique**, libérez de la mémoire :11 3. Quand le niveau est **élevée** ou **critique**, libérez de la mémoire :
12+ - déchargez le modèle de l'agent dont le journal est affiché : **⏏ Décharger le modèle**, à côté du nom de l'agent dans le panneau. L'agent continue de tourner ; son modèle est rechargé à son prochain message. Ce que l'agent répond est écrit dans son journal (`unload: …`). Le bouton n'est là que pour un agent qui propose la commande `/unload` (c'est le cas de mm), et ne sert que quand l'agent tourne et ne répond pas ;
13+ - ou déchargez tous les modèles d'un coup : **⏏ Tout décharger**. Chaque agent en marche qui le sait faire est sollicité ; une ligne sous la barre nomme les agents déchargés et ceux laissés de côté (en train de répondre, ou sans `/unload`). Les agents arrêtés ne sont pas démarrés pour ça ;
12 - arrêtez un agent dont vous n'avez pas besoin : **■** à côté de lui dans le panneau **Agents** ;14 - arrêtez un agent dont vous n'avez pas besoin : **■** à côté de lui dans le panneau **Agents** ;
13 - fermez les applications dont vous ne vous servez pas.15 - fermez les applications dont vous ne vous servez pas.
14 16
@@ -17,8 +19,12 @@ Les modèles locaux et les agents prennent beaucoup de mémoire. Quand l'ordinat
17 - **Sous macOS**, le niveau est celui que donne le système, le même que le graphique *Pression de la mémoire* de Moniteur d'activité. La mémoire utilisée est comptée comme dans Moniteur d'activité : mémoire des apps, mémoire résidente et mémoire compressée. La mémoire « en cache » de macOS n'est pas comptée : elle est rendue dès qu'une application en a besoin.19 - **Sous macOS**, le niveau est celui que donne le système, le même que le graphique *Pression de la mémoire* de Moniteur d'activité. La mémoire utilisée est comptée comme dans Moniteur d'activité : mémoire des apps, mémoire résidente et mémoire compressée. La mémoire « en cache » de macOS n'est pas comptée : elle est rendue dès qu'une application en a besoin.
18 - **Sous Windows** (et Linux), le niveau est déduit de la mémoire encore disponible : **élevée** sous 20 %, **critique** sous 10 %.20 - **Sous Windows** (et Linux), le niveau est déduit de la mémoire encore disponible : **élevée** sous 20 %, **critique** sous 10 %.
19 - Si la mémoire ne peut pas être mesurée, la ligne n'est pas affichée.21 - Si la mémoire ne peut pas être mesurée, la ligne n'est pas affichée.
22+- Décharger un modèle libère sa mémoire en quelques secondes, quand le serveur de modèles l'applique. Taper `/unload` dans une conversation avec l'agent a le même effet, mais laisse la commande et sa réponse dans la conversation.
23+
24+**⏏** est aussi sur la ligne de l'agent dans le panneau **Agents** (au survol) et dans l'en-tête de la vue de l'agent.
20 25
21 ## Voir aussi26 ## Voir aussi
22 27
23-- [Référence : services appelés par l'interface](../reference/agents-et-evenements.md#services-appelés-par-linterface) (`SystemService.Memory`)28+- [Référence : services appelés par l'interface](../reference/agents-et-evenements.md#services-appelés-par-linterface) (`SystemService.Memory`, `AgentService.Unload`, `AgentService.UnloadAll`)
29+- [Explication : mémoire et modèles locaux](../explanation/memoire-et-modeles-locaux.md#décharger-un-modèle-à-la-demande)
24 - [Travailler avec les fichiers et le terminal d'un agent](fichiers-et-terminal-d-un-agent.md)30 - [Travailler avec les fichiers et le terminal d'un agent](fichiers-et-terminal-d-un-agent.md)
modified docs/fr/reference/agents-et-evenements.md +2 -0
@@ -49,6 +49,8 @@ Les noms et types Go sont dans `internal/events` ; les constantes et types TypeS
4949 | `AgentService` | `List()` | Tous les agents avec `name, title, icon, description, state, error, outdated, runtime, canStopSandbox, canRemoveSandbox`, dans l'ordre de la configuration. |
5050 | | `Start(name)`, `Stop(name)`, `Restart(name)` | Comme dans les transitions ci-dessus ; une erreur est renvoyée à l'interface. Un démarrage recrée d'abord une sandbox absente si `runtime.lifecycle.create` est défini. |
5151 | | `StopSandbox(name)`, `RemoveSandbox(name)` | Arrête l'agent, puis lance `runtime.lifecycle.stop` ou `remove` (conteneur ou sandbox) ; la sortie va dans le journal de l'agent. |
52+| | `Unload(name)` | Demande à un agent en marche et inactif, qui a annoncé la commande `unload`, de décharger son modèle (ticket #51) : `/unload` est envoyé dans une session à part, qu'aucune conversation ne montre ; la réponse va dans le journal de l'agent, en lignes `unload: …`. Erreurs : agent inconnu, `the agent is not running…`, `the agent is answering…`, `this agent cannot unload its model…`. |
53+| | `UnloadAll()` | `Unload` pour chaque agent en marche : renvoie `{unloaded[], skipped[]}` (noms d'agents) ; les agents arrêtés sont laissés de côté. |
5254 | | `Logs(name)` | Les 200 dernières lignes stderr de l'agent. |
5355 | `ConfigService` | `Current()` | `path, source, created, valid, problems[], warnings[], theme, language, historyProblem`. |
5456 | `SystemService` | `Memory()` | `level` (`normal`, `warning`, `critical`), `used` et `total` en octets ; tout vide (`total` à 0) là où la mémoire ne peut pas être mesurée. macOS : le niveau de `kern.memorystatus_vm_pressure_level`, utilisée = mémoire des apps + résidente + compressée (`vm_stat`), comme dans Moniteur d'activité. Linux et Windows : déduit de la mémoire disponible, `warning` sous 20 %, `critical` sous 10 %. Le panneau Log l'appelle toutes les 5 secondes tant qu'il est ouvert (issue #61). |
@@ -49,6 +49,8 @@ Les noms et types Go sont dans `internal/events` ; les constantes et types TypeS
49 | `AgentService` | `List()` | Tous les agents avec `name, title, icon, description, state, error, outdated, runtime, canStopSandbox, canRemoveSandbox`, dans l'ordre de la configuration. |49 | `AgentService` | `List()` | Tous les agents avec `name, title, icon, description, state, error, outdated, runtime, canStopSandbox, canRemoveSandbox`, dans l'ordre de la configuration. |
50 | | `Start(name)`, `Stop(name)`, `Restart(name)` | Comme dans les transitions ci-dessus ; une erreur est renvoyée à l'interface. Un démarrage recrée d'abord une sandbox absente si `runtime.lifecycle.create` est défini. |50 | | `Start(name)`, `Stop(name)`, `Restart(name)` | Comme dans les transitions ci-dessus ; une erreur est renvoyée à l'interface. Un démarrage recrée d'abord une sandbox absente si `runtime.lifecycle.create` est défini. |
51 | | `StopSandbox(name)`, `RemoveSandbox(name)` | Arrête l'agent, puis lance `runtime.lifecycle.stop` ou `remove` (conteneur ou sandbox) ; la sortie va dans le journal de l'agent. |51 | | `StopSandbox(name)`, `RemoveSandbox(name)` | Arrête l'agent, puis lance `runtime.lifecycle.stop` ou `remove` (conteneur ou sandbox) ; la sortie va dans le journal de l'agent. |
52+| | `Unload(name)` | Demande à un agent en marche et inactif, qui a annoncé la commande `unload`, de décharger son modèle (ticket #51) : `/unload` est envoyé dans une session à part, qu'aucune conversation ne montre ; la réponse va dans le journal de l'agent, en lignes `unload: …`. Erreurs : agent inconnu, `the agent is not running…`, `the agent is answering…`, `this agent cannot unload its model…`. |
53+| | `UnloadAll()` | `Unload` pour chaque agent en marche : renvoie `{unloaded[], skipped[]}` (noms d'agents) ; les agents arrêtés sont laissés de côté. |
52 | | `Logs(name)` | Les 200 dernières lignes stderr de l'agent. |54 | | `Logs(name)` | Les 200 dernières lignes stderr de l'agent. |
53 | `ConfigService` | `Current()` | `path, source, created, valid, problems[], warnings[], theme, language, historyProblem`. |55 | `ConfigService` | `Current()` | `path, source, created, valid, problems[], warnings[], theme, language, historyProblem`. |
54 | `SystemService` | `Memory()` | `level` (`normal`, `warning`, `critical`), `used` et `total` en octets ; tout vide (`total` à 0) là où la mémoire ne peut pas être mesurée. macOS : le niveau de `kern.memorystatus_vm_pressure_level`, utilisée = mémoire des apps + résidente + compressée (`vm_stat`), comme dans Moniteur d'activité. Linux et Windows : déduit de la mémoire disponible, `warning` sous 20 %, `critical` sous 10 %. Le panneau Log l'appelle toutes les 5 secondes tant qu'il est ouvert (issue #61). |56 | `SystemService` | `Memory()` | `level` (`normal`, `warning`, `critical`), `used` et `total` en octets ; tout vide (`total` à 0) là où la mémoire ne peut pas être mesurée. macOS : le niveau de `kern.memorystatus_vm_pressure_level`, utilisée = mémoire des apps + résidente + compressée (`vm_stat`), comme dans Moniteur d'activité. Linux et Windows : déduit de la mémoire disponible, `warning` sous 20 %, `critical` sous 10 %. Le panneau Log l'appelle toutes les 5 secondes tant qu'il est ouvert (issue #61). |
modified frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/app/agentservice.ts +23 -0
@@ -15,6 +15,10 @@ import { Call as $Call, CancellablePromise as $CancellablePromise } from "@wails
1515 // @ts-ignore: Unused imports
1616 import * as agents$0 from "../agents/models.js";
1717
18+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
19+// @ts-ignore: Unused imports
20+import * as $models from "./models.js";
21+
1822 /**
1923 * List returns every agent of the configuration with its state.
2024 */
@@ -67,3 +71,22 @@ export function Stop(name: string): $CancellablePromise<void> {
6771 export function StopSandbox(name: string): $CancellablePromise<void> {
6872 return $Call.ByID(923009821, name);
6973 }
74+
75+/**
76+ * Unload has the agent unload its model from memory, without stopping it
77+ * (issue #51), when it offers the /unload command. Nothing appears in the
78+ * conversations: what the agent answers goes to its log. The model is loaded
79+ * again with the next message.
80+ */
81+export function Unload(name: string): $CancellablePromise<void> {
82+ return $Call.ByID(3375635717, name);
83+}
84+
85+/**
86+ * UnloadAll has every running agent that offers /unload unload its model.
87+ * Stopped agents are not counted; running agents that are answering or
88+ * cannot unload are skipped.
89+ */
90+export function UnloadAll(): $CancellablePromise<$models.UnloadResult> {
91+ return $Call.ByID(3399716516);
92+}
@@ -15,6 +15,10 @@ import { Call as $Call, CancellablePromise as $CancellablePromise } from "@wails
15 // @ts-ignore: Unused imports15 // @ts-ignore: Unused imports
16 import * as agents$0 from "../agents/models.js";16 import * as agents$0 from "../agents/models.js";
17 17
18+// eslint-disable-next-line @typescript-eslint/ban-ts-comment
19+// @ts-ignore: Unused imports
20+import * as $models from "./models.js";
21+
18 /**22 /**
19 * List returns every agent of the configuration with its state.23 * List returns every agent of the configuration with its state.
20 */24 */
@@ -67,3 +71,22 @@ export function Stop(name: string): $CancellablePromise<void> {
67 export function StopSandbox(name: string): $CancellablePromise<void> {71 export function StopSandbox(name: string): $CancellablePromise<void> {
68 return $Call.ByID(923009821, name);72 return $Call.ByID(923009821, name);
69 }73 }
74+
75+/**
76+ * Unload has the agent unload its model from memory, without stopping it
77+ * (issue #51), when it offers the /unload command. Nothing appears in the
78+ * conversations: what the agent answers goes to its log. The model is loaded
79+ * again with the next message.
80+ */
81+export function Unload(name: string): $CancellablePromise<void> {
82+ return $Call.ByID(3375635717, name);
83+}
84+
85+/**
86+ * UnloadAll has every running agent that offers /unload unload its model.
87+ * Stopped agents are not counted; running agents that are answering or
88+ * cannot unload are skipped.
89+ */
90+export function UnloadAll(): $CancellablePromise<$models.UnloadResult> {
91+ return $Call.ByID(3399716516);
92+}
modified frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/app/index.ts +1 -0
@@ -27,5 +27,6 @@ export type {
2727 ResetResult,
2828 SandboxEnv,
2929 SaveResult,
30+ UnloadResult,
3031 WorkspaceInfo
3132 } from "./models.js";
@@ -27,5 +27,6 @@ export type {
27 ResetResult,27 ResetResult,
28 SandboxEnv,28 SandboxEnv,
29 SaveResult,29 SaveResult,
30+ UnloadResult,
30 WorkspaceInfo31 WorkspaceInfo
31 } from "./models.js";32 } from "./models.js";
modified frontend/bindings/git.rickub.com/bots-garden/sidekicks/internal/app/models.ts +9 -0
@@ -175,6 +175,15 @@ export interface SaveResult {
175175 "conflict": boolean;
176176 }
177177
178+/**
179+ * UnloadResult says which agents unloaded their model, and which running
180+ * agents were left alone: answering, unable to unload, or failing.
181+ */
182+export interface UnloadResult {
183+ "unloaded": string[] | null;
184+ "skipped": string[] | null;
185+}
186+
178187 /**
179188 * WorkspaceInfo tells where an agent's folder is, or why it cannot be shown.
180189 */
@@ -175,6 +175,15 @@ export interface SaveResult {
175 "conflict": boolean;175 "conflict": boolean;
176 }176 }
177 177
178+/**
179+ * UnloadResult says which agents unloaded their model, and which running
180+ * agents were left alone: answering, unable to unload, or failing.
181+ */
182+export interface UnloadResult {
183+ "unloaded": string[] | null;
184+ "skipped": string[] | null;
185+}
186+
178 /**187 /**
179 * WorkspaceInfo tells where an agent's folder is, or why it cannot be shown.188 * WorkspaceInfo tells where an agent's folder is, or why it cannot be shown.
180 */189 */
modified frontend/src/lib/agent/AgentView.svelte +6 -1
@@ -11,7 +11,7 @@
1111 import { onMount } from 'svelte'
1212 import { AgentService, WorkspaceService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
1313 import { hasMessage, t, type MessageKey } from '../i18n/index.svelte'
14- import { act, appState, openDirect } from '../state.svelte'
14+ import { act, appState, loadCommands, openDirect } from '../state.svelte'
1515 import ActionError from '../chat/ActionError.svelte'
1616 import AgentAvatar from './AgentAvatar.svelte'
1717 import AgentLog from './AgentLog.svelte'
@@ -20,6 +20,7 @@
2020 import ErrorText from '../chat/ErrorText.svelte'
2121 import { activeTerminal, closeTerminal, newTerminal, runningTerminals, terminalsOf } from '../terminalSessions.svelte'
2222 import { maxTerminalsPerAgent } from '../terminals'
23+ import { canUnload, unloadReady } from '../unload'
2324
2425 let { agent: name }: { agent: string } = $props()
2526
@@ -61,6 +62,7 @@
6162 }
6263
6364 onMount(async () => {
65+ void loadCommands(name)
6466 const info = await WorkspaceService.Info(name)
6567 location = info?.location ?? ''
6668 revealable = info?.revealable ?? false
@@ -84,6 +86,9 @@
8486 {#if agent.state === 'stopped' || agent.state === 'error'}
8587 <button onclick={() => act(() => AgentService.Start(name))}>{t('workspace.start')}</button>
8688 {:else}
89+ {#if canUnload(appState.commands[name])}
90+ <button disabled={!unloadReady(agent.state)} onclick={() => act(() => AgentService.Unload(name))} title={t('unload.oneHelp', { agent: agent.title })}>{t('unload.one')}</button>
91+ {/if}
8792 <button onclick={() => act(() => AgentService.Restart(name))}>{t('workspace.restart')}</button>
8893 <button class="stop" onclick={() => act(() => AgentService.Stop(name))}>{t('workspace.stop')}</button>
8994 {/if}
@@ -11,7 +11,7 @@
11 import { onMount } from 'svelte'11 import { onMount } from 'svelte'
12 import { AgentService, WorkspaceService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'12 import { AgentService, WorkspaceService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
13 import { hasMessage, t, type MessageKey } from '../i18n/index.svelte'13 import { hasMessage, t, type MessageKey } from '../i18n/index.svelte'
14- import { act, appState, openDirect } from '../state.svelte'14+ import { act, appState, loadCommands, openDirect } from '../state.svelte'
15 import ActionError from '../chat/ActionError.svelte'15 import ActionError from '../chat/ActionError.svelte'
16 import AgentAvatar from './AgentAvatar.svelte'16 import AgentAvatar from './AgentAvatar.svelte'
17 import AgentLog from './AgentLog.svelte'17 import AgentLog from './AgentLog.svelte'
@@ -20,6 +20,7 @@
20 import ErrorText from '../chat/ErrorText.svelte'20 import ErrorText from '../chat/ErrorText.svelte'
21 import { activeTerminal, closeTerminal, newTerminal, runningTerminals, terminalsOf } from '../terminalSessions.svelte'21 import { activeTerminal, closeTerminal, newTerminal, runningTerminals, terminalsOf } from '../terminalSessions.svelte'
22 import { maxTerminalsPerAgent } from '../terminals'22 import { maxTerminalsPerAgent } from '../terminals'
23+ import { canUnload, unloadReady } from '../unload'
23 24
24 let { agent: name }: { agent: string } = $props()25 let { agent: name }: { agent: string } = $props()
25 26
@@ -61,6 +62,7 @@
61 }62 }
62 63
63 onMount(async () => {64 onMount(async () => {
65+ void loadCommands(name)
64 const info = await WorkspaceService.Info(name)66 const info = await WorkspaceService.Info(name)
65 location = info?.location ?? ''67 location = info?.location ?? ''
66 revealable = info?.revealable ?? false68 revealable = info?.revealable ?? false
@@ -84,6 +86,9 @@
84 {#if agent.state === 'stopped' || agent.state === 'error'}86 {#if agent.state === 'stopped' || agent.state === 'error'}
85 <button onclick={() => act(() => AgentService.Start(name))}>{t('workspace.start')}</button>87 <button onclick={() => act(() => AgentService.Start(name))}>{t('workspace.start')}</button>
86 {:else}88 {:else}
89+ {#if canUnload(appState.commands[name])}
90+ <button disabled={!unloadReady(agent.state)} onclick={() => act(() => AgentService.Unload(name))} title={t('unload.oneHelp', { agent: agent.title })}>{t('unload.one')}</button>
91+ {/if}
87 <button onclick={() => act(() => AgentService.Restart(name))}>{t('workspace.restart')}</button>92 <button onclick={() => act(() => AgentService.Restart(name))}>{t('workspace.restart')}</button>
88 <button class="stop" onclick={() => act(() => AgentService.Stop(name))}>{t('workspace.stop')}</button>93 <button class="stop" onclick={() => act(() => AgentService.Stop(name))}>{t('workspace.stop')}</button>
89 {/if}94 {/if}
modified frontend/src/lib/errors.ts +3 -0
@@ -36,6 +36,9 @@ const rules: Rule[] = [
3636 { pattern: /unknown agent:?\s*(\S*)/, key: 'error.unknownAgent', groups: ['agent'] },
3737 { pattern: /the history was written by a newer Sidekicks/, key: 'error.newerHistory' },
3838 { pattern: /an agent is answering in this channel/, key: 'error.channelBusy' },
39+ { pattern: /the agent is answering: wait for the end of its answer to unload/, key: 'error.agentAnswering' },
40+ { pattern: /the agent is not running: it has no model to unload/, key: 'error.notRunning' },
41+ { pattern: /cannot unload its model: it offers no \/unload command/, key: 'error.cannotUnload' },
3942 ]
4043
4144 /**
@@ -36,6 +36,9 @@ const rules: Rule[] = [
36 { pattern: /unknown agent:?\s*(\S*)/, key: 'error.unknownAgent', groups: ['agent'] },36 { pattern: /unknown agent:?\s*(\S*)/, key: 'error.unknownAgent', groups: ['agent'] },
37 { pattern: /the history was written by a newer Sidekicks/, key: 'error.newerHistory' },37 { pattern: /the history was written by a newer Sidekicks/, key: 'error.newerHistory' },
38 { pattern: /an agent is answering in this channel/, key: 'error.channelBusy' },38 { pattern: /an agent is answering in this channel/, key: 'error.channelBusy' },
39+ { pattern: /the agent is answering: wait for the end of its answer to unload/, key: 'error.agentAnswering' },
40+ { pattern: /the agent is not running: it has no model to unload/, key: 'error.notRunning' },
41+ { pattern: /cannot unload its model: it offers no \/unload command/, key: 'error.cannotUnload' },
39 ]42 ]
40 43
41 /**44 /**
modified frontend/src/lib/i18n/messages.ts +22 -0
@@ -43,6 +43,14 @@ export const en = {
4343 // log
4444 'logs.of': 'Log of',
4545 'logs.empty': 'Nothing yet: the log fills up when the agent starts.',
46+ 'unload.one': '⏏ Unload the model',
47+ 'unload.oneHelp': "Frees the memory {agent}'s model takes, without stopping it: the model is loaded again with its next message.",
48+ 'unload.agent': "Unload {agent}'s model",
49+ 'unload.all': '⏏ Unload all',
50+ 'unload.allHelp': 'Frees the memory of the models of every running agent that can do it.',
51+ 'unload.done': 'Model unloaded: {agents}.',
52+ 'unload.skipped': 'Left alone (answering or cannot unload): {agents}.',
53+ 'unload.none': 'No running agent to unload.',
4654 'memory.pressure': 'Memory pressure:',
4755 'memory.level.normal': 'normal',
4856 'memory.level.warning': 'high',
@@ -161,6 +169,9 @@ export const en = {
161169 'error.unknownAgent': 'The agent "{agent}" is no longer in the configuration.',
162170 'error.newerHistory': 'The history was written by a newer Sidekicks. Update Sidekicks to read it.',
163171 'error.channelBusy': 'An agent is answering here: stop it (■) or wait for the end of its answer, then clear the history.',
172+ 'error.agentAnswering': 'The agent is answering: wait for the end of its answer, then unload its model.',
173+ 'error.notRunning': 'The agent is not running: its model is not loaded by it.',
174+ 'error.cannotUnload': 'This agent cannot unload its model: it offers no /unload command.',
164175 'code.copy': 'Copy',
165176 'code.copied': 'Copied ✓',
166177 'message.copy': 'Copy the answer',
@@ -427,6 +438,14 @@ export const fr: Record<MessageKey, string> = {
427438
428439 'logs.of': 'Journal de',
429440 'logs.empty': "Rien pour l'instant : le journal se remplit quand l'agent démarre.",
441+ 'unload.one': '⏏ Décharger le modèle',
442+ 'unload.oneHelp': "Libère la mémoire prise par le modèle de {agent}, sans l'arrêter : le modèle est rechargé à son prochain message.",
443+ 'unload.agent': 'Décharger le modèle de {agent}',
444+ 'unload.all': '⏏ Tout décharger',
445+ 'unload.allHelp': 'Libère la mémoire des modèles de tous les agents qui tournent et savent le faire.',
446+ 'unload.done': 'Modèle déchargé : {agents}.',
447+ 'unload.skipped': 'Laissés de côté (en train de répondre ou sans /unload) : {agents}.',
448+ 'unload.none': 'Aucun agent en marche à décharger.',
430449 'memory.pressure': 'Pression mémoire :',
431450 'memory.level.normal': 'normale',
432451 'memory.level.warning': 'élevée',
@@ -538,6 +557,9 @@ export const fr: Record<MessageKey, string> = {
538557 'error.unknownAgent': "L'agent « {agent} » n'est plus dans la configuration.",
539558 'error.newerHistory': "L'historique a été écrit par un Sidekicks plus récent. Mettez Sidekicks à jour pour le lire.",
540559 'error.channelBusy': "Un agent répond ici : arrêtez-le (■) ou attendez la fin de sa réponse, puis videz l'historique.",
560+ 'error.agentAnswering': "L'agent est en train de répondre : attendez la fin de sa réponse, puis déchargez son modèle.",
561+ 'error.notRunning': "L'agent ne tourne pas : il n'a pas de modèle chargé.",
562+ 'error.cannotUnload': 'Cet agent ne sait pas décharger son modèle : il ne propose pas de commande /unload.',
541563 'code.copy': 'Copier',
542564 'code.copied': 'Copié ✓',
543565 'message.copy': 'Copier la réponse',
@@ -43,6 +43,14 @@ export const en = {
43 // log43 // log
44 'logs.of': 'Log of',44 'logs.of': 'Log of',
45 'logs.empty': 'Nothing yet: the log fills up when the agent starts.',45 'logs.empty': 'Nothing yet: the log fills up when the agent starts.',
46+ 'unload.one': '⏏ Unload the model',
47+ 'unload.oneHelp': "Frees the memory {agent}'s model takes, without stopping it: the model is loaded again with its next message.",
48+ 'unload.agent': "Unload {agent}'s model",
49+ 'unload.all': '⏏ Unload all',
50+ 'unload.allHelp': 'Frees the memory of the models of every running agent that can do it.',
51+ 'unload.done': 'Model unloaded: {agents}.',
52+ 'unload.skipped': 'Left alone (answering or cannot unload): {agents}.',
53+ 'unload.none': 'No running agent to unload.',
46 'memory.pressure': 'Memory pressure:',54 'memory.pressure': 'Memory pressure:',
47 'memory.level.normal': 'normal',55 'memory.level.normal': 'normal',
48 'memory.level.warning': 'high',56 'memory.level.warning': 'high',
@@ -161,6 +169,9 @@ export const en = {
161 'error.unknownAgent': 'The agent "{agent}" is no longer in the configuration.',169 'error.unknownAgent': 'The agent "{agent}" is no longer in the configuration.',
162 'error.newerHistory': 'The history was written by a newer Sidekicks. Update Sidekicks to read it.',170 'error.newerHistory': 'The history was written by a newer Sidekicks. Update Sidekicks to read it.',
163 'error.channelBusy': 'An agent is answering here: stop it (■) or wait for the end of its answer, then clear the history.',171 'error.channelBusy': 'An agent is answering here: stop it (■) or wait for the end of its answer, then clear the history.',
172+ 'error.agentAnswering': 'The agent is answering: wait for the end of its answer, then unload its model.',
173+ 'error.notRunning': 'The agent is not running: its model is not loaded by it.',
174+ 'error.cannotUnload': 'This agent cannot unload its model: it offers no /unload command.',
164 'code.copy': 'Copy',175 'code.copy': 'Copy',
165 'code.copied': 'Copied ✓',176 'code.copied': 'Copied ✓',
166 'message.copy': 'Copy the answer',177 'message.copy': 'Copy the answer',
@@ -427,6 +438,14 @@ export const fr: Record<MessageKey, string> = {
427 438
428 'logs.of': 'Journal de',439 'logs.of': 'Journal de',
429 'logs.empty': "Rien pour l'instant : le journal se remplit quand l'agent démarre.",440 'logs.empty': "Rien pour l'instant : le journal se remplit quand l'agent démarre.",
441+ 'unload.one': '⏏ Décharger le modèle',
442+ 'unload.oneHelp': "Libère la mémoire prise par le modèle de {agent}, sans l'arrêter : le modèle est rechargé à son prochain message.",
443+ 'unload.agent': 'Décharger le modèle de {agent}',
444+ 'unload.all': '⏏ Tout décharger',
445+ 'unload.allHelp': 'Libère la mémoire des modèles de tous les agents qui tournent et savent le faire.',
446+ 'unload.done': 'Modèle déchargé : {agents}.',
447+ 'unload.skipped': 'Laissés de côté (en train de répondre ou sans /unload) : {agents}.',
448+ 'unload.none': 'Aucun agent en marche à décharger.',
430 'memory.pressure': 'Pression mémoire :',449 'memory.pressure': 'Pression mémoire :',
431 'memory.level.normal': 'normale',450 'memory.level.normal': 'normale',
432 'memory.level.warning': 'élevée',451 'memory.level.warning': 'élevée',
@@ -538,6 +557,9 @@ export const fr: Record<MessageKey, string> = {
538 'error.unknownAgent': "L'agent « {agent} » n'est plus dans la configuration.",557 'error.unknownAgent': "L'agent « {agent} » n'est plus dans la configuration.",
539 'error.newerHistory': "L'historique a été écrit par un Sidekicks plus récent. Mettez Sidekicks à jour pour le lire.",558 'error.newerHistory': "L'historique a été écrit par un Sidekicks plus récent. Mettez Sidekicks à jour pour le lire.",
540 'error.channelBusy': "Un agent répond ici : arrêtez-le (■) ou attendez la fin de sa réponse, puis videz l'historique.",559 'error.channelBusy': "Un agent répond ici : arrêtez-le (■) ou attendez la fin de sa réponse, puis videz l'historique.",
560+ 'error.agentAnswering': "L'agent est en train de répondre : attendez la fin de sa réponse, puis déchargez son modèle.",
561+ 'error.notRunning': "L'agent ne tourne pas : il n'a pas de modèle chargé.",
562+ 'error.cannotUnload': 'Cet agent ne sait pas décharger son modèle : il ne propose pas de commande /unload.',
541 'code.copy': 'Copier',563 'code.copy': 'Copier',
542 'code.copied': 'Copié ✓',564 'code.copied': 'Copié ✓',
543 'message.copy': 'Copier la réponse',565 'message.copy': 'Copier la réponse',
modified frontend/src/lib/panels/AgentsPanel.svelte +10 -1
@@ -6,8 +6,9 @@
66 import ErrorText from '../chat/ErrorText.svelte'
77 import AgentAvatar from '../agent/AgentAvatar.svelte'
88 import { AgentService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
9- import { act, appState, channelOf, openAssistant, openDirect, openWorkspace } from '../state.svelte'
9+ import { act, appState, channelOf, loadCommands, openAssistant, openDirect, openWorkspace } from '../state.svelte'
1010 import { directOf } from '../conversation'
11+ import { canUnload, unloadReady } from '../unload'
1112
1213 // The agent of the direct conversation shown, to highlight it.
1314 const directAgent = $derived(channelOf(appState.selectedChannel)?.direct ?? '')
@@ -18,6 +19,11 @@
1819 const direct = directOf(appState.channels, agent)
1920 return direct ? appState.unread[direct.id] ?? 0 : 0
2021 }
22+
23+ // Issue #51: the agents that announced /unload get a ⏏ button.
24+ $effect(() => {
25+ for (const agent of appState.agents) void loadCommands(agent.name)
26+ })
2127 </script>
2228
2329 {#if appState.agents.length === 0}
@@ -40,6 +46,9 @@
4046 {#if agent.state === 'stopped' || agent.state === 'error'}
4147 <button onclick={() => act(() => AgentService.Start(agent.name))} aria-label={t('agent.start', { agent: agent.title })}>▶</button>
4248 {:else}
49+ {#if canUnload(appState.commands[agent.name])}
50+ <button disabled={!unloadReady(agent.state)} onclick={() => act(() => AgentService.Unload(agent.name))} aria-label={t('unload.agent', { agent: agent.title })} title={t('unload.oneHelp', { agent: agent.title })}>⏏</button>
51+ {/if}
4352 <button onclick={() => act(() => AgentService.Restart(agent.name))} aria-label={t('agent.restart', { agent: agent.title })}>↻</button>
4453 <button onclick={() => act(() => AgentService.Stop(agent.name))} aria-label={t('agent.stop', { agent: agent.title })}>■</button>
4554 {/if}
@@ -6,8 +6,9 @@
6 import ErrorText from '../chat/ErrorText.svelte'6 import ErrorText from '../chat/ErrorText.svelte'
7 import AgentAvatar from '../agent/AgentAvatar.svelte'7 import AgentAvatar from '../agent/AgentAvatar.svelte'
8 import { AgentService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'8 import { AgentService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
9- import { act, appState, channelOf, openAssistant, openDirect, openWorkspace } from '../state.svelte'9+ import { act, appState, channelOf, loadCommands, openAssistant, openDirect, openWorkspace } from '../state.svelte'
10 import { directOf } from '../conversation'10 import { directOf } from '../conversation'
11+ import { canUnload, unloadReady } from '../unload'
11 12
12 // The agent of the direct conversation shown, to highlight it.13 // The agent of the direct conversation shown, to highlight it.
13 const directAgent = $derived(channelOf(appState.selectedChannel)?.direct ?? '')14 const directAgent = $derived(channelOf(appState.selectedChannel)?.direct ?? '')
@@ -18,6 +19,11 @@
18 const direct = directOf(appState.channels, agent)19 const direct = directOf(appState.channels, agent)
19 return direct ? appState.unread[direct.id] ?? 0 : 020 return direct ? appState.unread[direct.id] ?? 0 : 0
20 }21 }
22+
23+ // Issue #51: the agents that announced /unload get a ⏏ button.
24+ $effect(() => {
25+ for (const agent of appState.agents) void loadCommands(agent.name)
26+ })
21 </script>27 </script>
22 28
23 {#if appState.agents.length === 0}29 {#if appState.agents.length === 0}
@@ -40,6 +46,9 @@
40 {#if agent.state === 'stopped' || agent.state === 'error'}46 {#if agent.state === 'stopped' || agent.state === 'error'}
41 <button onclick={() => act(() => AgentService.Start(agent.name))} aria-label={t('agent.start', { agent: agent.title })}>▶</button>47 <button onclick={() => act(() => AgentService.Start(agent.name))} aria-label={t('agent.start', { agent: agent.title })}>▶</button>
42 {:else}48 {:else}
49+ {#if canUnload(appState.commands[agent.name])}
50+ <button disabled={!unloadReady(agent.state)} onclick={() => act(() => AgentService.Unload(agent.name))} aria-label={t('unload.agent', { agent: agent.title })} title={t('unload.oneHelp', { agent: agent.title })}>⏏</button>
51+ {/if}
43 <button onclick={() => act(() => AgentService.Restart(agent.name))} aria-label={t('agent.restart', { agent: agent.title })}>↻</button>52 <button onclick={() => act(() => AgentService.Restart(agent.name))} aria-label={t('agent.restart', { agent: agent.title })}>↻</button>
44 <button onclick={() => act(() => AgentService.Stop(agent.name))} aria-label={t('agent.stop', { agent: agent.title })}>■</button>53 <button onclick={() => act(() => AgentService.Stop(agent.name))} aria-label={t('agent.stop', { agent: agent.title })}>■</button>
45 {/if}54 {/if}
modified frontend/src/lib/panels/LogsPanel.svelte +64 -4
@@ -1,12 +1,57 @@
11 <!-- Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE -->
22 <script lang="ts">
33 import { t } from '../i18n/index.svelte'
4- import { appState } from '../state.svelte'
4+ import { appState, loadCommands } from '../state.svelte'
5+ import { AgentService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
56 import AgentLog from '../agent/AgentLog.svelte'
7+ import ErrorText from '../chat/ErrorText.svelte'
68 import MemoryPressure from './MemoryPressure.svelte'
9+ import { canUnload, unloadReady, unloadSummary, type UnloadLine } from '../unload'
710
811 let selected = $state('')
912 const agentName = $derived(selected || appState.agents[0]?.name || '')
13+ const agent = $derived(appState.agents.find((candidate) => candidate.name === agentName))
14+
15+ // Issue #51: next to the memory pressure, unload the model of the agent
16+ // shown, or of every running agent that can.
17+ let unloading = $state(false)
18+ let notice = $state<UnloadLine[]>([])
19+ let problem = $state('')
20+ const anyRunning = $derived(appState.agents.some((candidate) => unloadReady(candidate.state) || candidate.state === 'busy'))
21+
22+ $effect(() => {
23+ for (const each of appState.agents) void loadCommands(each.name)
24+ })
25+
26+ async function unload(action: () => Promise<void>) {
27+ unloading = true
28+ notice = []
29+ problem = ''
30+ try {
31+ await action()
32+ } catch (error) {
33+ problem = error instanceof Error ? error.message : String(error)
34+ } finally {
35+ unloading = false
36+ }
37+ }
38+
39+ function titleOf(name: string): string {
40+ return appState.agents.find((candidate) => candidate.name === name)?.title ?? name
41+ }
42+
43+ const unloadOne = () =>
44+ unload(async () => {
45+ const name = agentName
46+ await AgentService.Unload(name)
47+ notice = [{ key: 'unload.done', vars: { agents: titleOf(name) } }]
48+ })
49+
50+ const unloadAll = () =>
51+ unload(async () => {
52+ const result = await AgentService.UnloadAll()
53+ notice = unloadSummary(result ?? { unloaded: [], skipped: [] }, titleOf)
54+ })
1055 </script>
1156
1257 <div class="logs">
@@ -14,19 +59,34 @@
1459 <label>
1560 {t('logs.of')}
1661 <select value={agentName} onchange={(event) => (selected = event.currentTarget.value)}>
17- {#each appState.agents as agent (agent.name)}
18- <option value={agent.name}>{agent.title}</option>
62+ {#each appState.agents as each (each.name)}
63+ <option value={each.name}>{each.title}</option>
1964 {/each}
2065 </select>
2166 </label>
67+ {#if agent && canUnload(appState.commands[agent.name])}
68+ <button disabled={unloading || !unloadReady(agent.state)} onclick={unloadOne} title={t('unload.oneHelp', { agent: agent.title })}>{t('unload.one')}</button>
69+ {/if}
70+ <button disabled={unloading || !anyRunning} onclick={unloadAll} title={t('unload.allHelp')}>{t('unload.all')}</button>
2271 <MemoryPressure />
2372 </div>
73+ {#if notice.length || problem}
74+ <p class="notice" class:failed={problem !== ''} role="status">
75+ {#if problem}<ErrorText raw={problem} />{:else}{notice.map((line) => t(line.key, line.vars)).join(' ')}{/if}
76+ <button onclick={() => ((notice = []), (problem = ''))} aria-label={t('error.dismiss')} title={t('error.dismiss')}>×</button>
77+ </p>
78+ {/if}
2479 <AgentLog agent={agentName} />
2580 </div>
2681
2782 <style>
2883 .logs { height: 100%; display: flex; flex-direction: column; }
29- .bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 4px 12px; padding: 0 8px 6px; }
84+ .bar { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; padding: 0 8px 6px; }
85+ .bar :global(.memory) { margin-left: auto; }
3086 label { color: var(--muted); font-size: 12px; }
3187 select { font: inherit; color: var(--text); background: var(--panel-2); border: 1px solid var(--border); border-radius: 4px; }
88+ .bar > button { font-size: 12px; padding: 1px 8px; }
89+ .notice { display: flex; gap: 6px; align-items: flex-start; margin: 0 8px 6px; color: var(--muted); font-size: 12px; }
90+ .notice.failed { color: var(--danger); }
91+ .notice button { margin-left: auto; border: none; background: none; color: inherit; padding: 0 4px; font-size: 14px; line-height: 1; }
3292 </style>
@@ -1,12 +1,57 @@
1 <!-- Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE -->1 <!-- Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE -->
2 <script lang="ts">2 <script lang="ts">
3 import { t } from '../i18n/index.svelte'3 import { t } from '../i18n/index.svelte'
4- import { appState } from '../state.svelte'4+ import { appState, loadCommands } from '../state.svelte'
5+ import { AgentService } from '../../../bindings/git.rickub.com/bots-garden/sidekicks/internal/app'
5 import AgentLog from '../agent/AgentLog.svelte'6 import AgentLog from '../agent/AgentLog.svelte'
7+ import ErrorText from '../chat/ErrorText.svelte'
6 import MemoryPressure from './MemoryPressure.svelte'8 import MemoryPressure from './MemoryPressure.svelte'
9+ import { canUnload, unloadReady, unloadSummary, type UnloadLine } from '../unload'
7 10
8 let selected = $state('')11 let selected = $state('')
9 const agentName = $derived(selected || appState.agents[0]?.name || '')12 const agentName = $derived(selected || appState.agents[0]?.name || '')
13+ const agent = $derived(appState.agents.find((candidate) => candidate.name === agentName))
14+
15+ // Issue #51: next to the memory pressure, unload the model of the agent
16+ // shown, or of every running agent that can.
17+ let unloading = $state(false)
18+ let notice = $state<UnloadLine[]>([])
19+ let problem = $state('')
20+ const anyRunning = $derived(appState.agents.some((candidate) => unloadReady(candidate.state) || candidate.state === 'busy'))
21+
22+ $effect(() => {
23+ for (const each of appState.agents) void loadCommands(each.name)
24+ })
25+
26+ async function unload(action: () => Promise<void>) {
27+ unloading = true
28+ notice = []
29+ problem = ''
30+ try {
31+ await action()
32+ } catch (error) {
33+ problem = error instanceof Error ? error.message : String(error)
34+ } finally {
35+ unloading = false
36+ }
37+ }
38+
39+ function titleOf(name: string): string {
40+ return appState.agents.find((candidate) => candidate.name === name)?.title ?? name
41+ }
42+
43+ const unloadOne = () =>
44+ unload(async () => {
45+ const name = agentName
46+ await AgentService.Unload(name)
47+ notice = [{ key: 'unload.done', vars: { agents: titleOf(name) } }]
48+ })
49+
50+ const unloadAll = () =>
51+ unload(async () => {
52+ const result = await AgentService.UnloadAll()
53+ notice = unloadSummary(result ?? { unloaded: [], skipped: [] }, titleOf)
54+ })
10 </script>55 </script>
11 56
12 <div class="logs">57 <div class="logs">
@@ -14,19 +59,34 @@
14 <label>59 <label>
15 {t('logs.of')}60 {t('logs.of')}
16 <select value={agentName} onchange={(event) => (selected = event.currentTarget.value)}>61 <select value={agentName} onchange={(event) => (selected = event.currentTarget.value)}>
17- {#each appState.agents as agent (agent.name)}62+ {#each appState.agents as each (each.name)}
18- <option value={agent.name}>{agent.title}</option>63+ <option value={each.name}>{each.title}</option>
19 {/each}64 {/each}
20 </select>65 </select>
21 </label>66 </label>
67+ {#if agent && canUnload(appState.commands[agent.name])}
68+ <button disabled={unloading || !unloadReady(agent.state)} onclick={unloadOne} title={t('unload.oneHelp', { agent: agent.title })}>{t('unload.one')}</button>
69+ {/if}
70+ <button disabled={unloading || !anyRunning} onclick={unloadAll} title={t('unload.allHelp')}>{t('unload.all')}</button>
22 <MemoryPressure />71 <MemoryPressure />
23 </div>72 </div>
73+ {#if notice.length || problem}
74+ <p class="notice" class:failed={problem !== ''} role="status">
75+ {#if problem}<ErrorText raw={problem} />{:else}{notice.map((line) => t(line.key, line.vars)).join(' ')}{/if}
76+ <button onclick={() => ((notice = []), (problem = ''))} aria-label={t('error.dismiss')} title={t('error.dismiss')}>×</button>
77+ </p>
78+ {/if}
24 <AgentLog agent={agentName} />79 <AgentLog agent={agentName} />
25 </div>80 </div>
26 81
27 <style>82 <style>
28 .logs { height: 100%; display: flex; flex-direction: column; }83 .logs { height: 100%; display: flex; flex-direction: column; }
29- .bar { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 4px 12px; padding: 0 8px 6px; }84+ .bar { display: flex; flex-wrap: wrap; align-items: center; gap: 4px 8px; padding: 0 8px 6px; }
85+ .bar :global(.memory) { margin-left: auto; }
30 label { color: var(--muted); font-size: 12px; }86 label { color: var(--muted); font-size: 12px; }
31 select { font: inherit; color: var(--text); background: var(--panel-2); border: 1px solid var(--border); border-radius: 4px; }87 select { font: inherit; color: var(--text); background: var(--panel-2); border: 1px solid var(--border); border-radius: 4px; }
88+ .bar > button { font-size: 12px; padding: 1px 8px; }
89+ .notice { display: flex; gap: 6px; align-items: flex-start; margin: 0 8px 6px; color: var(--muted); font-size: 12px; }
90+ .notice.failed { color: var(--danger); }
91+ .notice button { margin-left: auto; border: none; background: none; color: inherit; padding: 0 4px; font-size: 14px; line-height: 1; }
32 </style>92 </style>
modified frontend/src/lib/state.svelte.ts +2 -1
@@ -274,7 +274,8 @@ export async function prepareCommands(id: string) {
274274 }
275275 }
276276
277-async function loadCommands(agent: string) {
277+/** Loads the slash commands an agent announced, once. */
278+export async function loadCommands(agent: string) {
278279 if (appState.commands[agent]) return
279280 appState.commands[agent] = (await ChannelService.Commands(agent)) ?? []
280281 }
@@ -274,7 +274,8 @@ export async function prepareCommands(id: string) {
274 }274 }
275 }275 }
276 276
277-async function loadCommands(agent: string) {277+/** Loads the slash commands an agent announced, once. */
278+export async function loadCommands(agent: string) {
278 if (appState.commands[agent]) return279 if (appState.commands[agent]) return
279 appState.commands[agent] = (await ChannelService.Commands(agent)) ?? []280 appState.commands[agent] = (await ChannelService.Commands(agent)) ?? []
280 }281 }
added frontend/src/lib/unload.test.ts +32 -0
new file mode 100644
@@ -0,0 +1,32 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+import { describe, expect, it } from 'vitest'
4+import { canUnload, unloadReady, unloadSummary } from './unload'
5+
6+describe('canUnload', () => {
7+ it('needs the unload command', () => {
8+ expect(canUnload([{ name: 'compact' }, { name: 'unload' }])).toBe(true)
9+ expect(canUnload([{ name: 'compact' }])).toBe(false)
10+ expect(canUnload(undefined)).toBe(false)
11+ })
12+})
13+
14+describe('unloadReady', () => {
15+ it('only while the agent runs and does not answer', () => {
16+ expect(unloadReady('ready')).toBe(true)
17+ for (const state of ['busy', 'stopped', 'starting', 'error', undefined]) expect(unloadReady(state)).toBe(false)
18+ })
19+})
20+
21+describe('unloadSummary', () => {
22+ const title = (name: string) => name[0].toUpperCase() + name.slice(1)
23+ it('names the unloaded agents and the ones left alone', () => {
24+ expect(unloadSummary({ unloaded: ['alice', 'bob'], skipped: ['carol'] }, title)).toEqual([
25+ { key: 'unload.done', vars: { agents: 'Alice, Bob' } },
26+ { key: 'unload.skipped', vars: { agents: 'Carol' } },
27+ ])
28+ })
29+ it('says when there was nothing to unload', () => {
30+ expect(unloadSummary({ unloaded: null, skipped: [] }, title)).toEqual([{ key: 'unload.none', vars: {} }])
31+ })
32+})
new file mode 100644
@@ -0,0 +1,32 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+import { describe, expect, it } from 'vitest'
4+import { canUnload, unloadReady, unloadSummary } from './unload'
5+
6+describe('canUnload', () => {
7+ it('needs the unload command', () => {
8+ expect(canUnload([{ name: 'compact' }, { name: 'unload' }])).toBe(true)
9+ expect(canUnload([{ name: 'compact' }])).toBe(false)
10+ expect(canUnload(undefined)).toBe(false)
11+ })
12+})
13+
14+describe('unloadReady', () => {
15+ it('only while the agent runs and does not answer', () => {
16+ expect(unloadReady('ready')).toBe(true)
17+ for (const state of ['busy', 'stopped', 'starting', 'error', undefined]) expect(unloadReady(state)).toBe(false)
18+ })
19+})
20+
21+describe('unloadSummary', () => {
22+ const title = (name: string) => name[0].toUpperCase() + name.slice(1)
23+ it('names the unloaded agents and the ones left alone', () => {
24+ expect(unloadSummary({ unloaded: ['alice', 'bob'], skipped: ['carol'] }, title)).toEqual([
25+ { key: 'unload.done', vars: { agents: 'Alice, Bob' } },
26+ { key: 'unload.skipped', vars: { agents: 'Carol' } },
27+ ])
28+ })
29+ it('says when there was nothing to unload', () => {
30+ expect(unloadSummary({ unloaded: null, skipped: [] }, title)).toEqual([{ key: 'unload.none', vars: {} }])
31+ })
32+})
added frontend/src/lib/unload.ts +44 -0
new file mode 100644
@@ -0,0 +1,44 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+// Unloading an agent's model from memory (issue #51): an agent that announces
4+// the /unload command can do it; Sidekicks sends it the command in a session
5+// of its own, while it runs and does not answer.
6+
7+import type { MessageKey } from './i18n/index.svelte'
8+
9+/** The slash command that unloads an agent's model (announced by mm). */
10+export const unloadCommand = 'unload'
11+
12+/** Whether an agent that announced these commands can unload its model. */
13+export function canUnload(commands: readonly { name: string }[] | undefined): boolean {
14+ return (commands ?? []).some((command) => command.name === unloadCommand)
15+}
16+
17+/** Whether the button can be used now: the agent runs and does not answer. */
18+export function unloadReady(state: string | undefined): boolean {
19+ return state === 'ready'
20+}
21+
22+/** A sentence of the result of "Unload all", as message keys and variables. */
23+export type UnloadLine = { key: MessageKey; vars: Record<string, string> }
24+
25+/**
26+ * What "Unload all" says: the agents unloaded and the ones left alone, by
27+ * title, or that there was none.
28+ *
29+ * @example
30+ * unloadSummary({ unloaded: ['alice'], skipped: [] }, (name) => name.toUpperCase())
31+ * // [{ key: 'unload.done', vars: { agents: 'ALICE' } }]
32+ */
33+export function unloadSummary(
34+ result: { unloaded: string[] | null; skipped: string[] | null },
35+ titleOf: (name: string) => string,
36+): UnloadLine[] {
37+ const unloaded = result.unloaded ?? []
38+ const skipped = result.skipped ?? []
39+ const lines: UnloadLine[] = []
40+ if (unloaded.length) lines.push({ key: 'unload.done', vars: { agents: unloaded.map(titleOf).join(', ') } })
41+ if (skipped.length) lines.push({ key: 'unload.skipped', vars: { agents: skipped.map(titleOf).join(', ') } })
42+ if (!lines.length) lines.push({ key: 'unload.none', vars: {} })
43+ return lines
44+}
new file mode 100644
@@ -0,0 +1,44 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+// Unloading an agent's model from memory (issue #51): an agent that announces
4+// the /unload command can do it; Sidekicks sends it the command in a session
5+// of its own, while it runs and does not answer.
6+
7+import type { MessageKey } from './i18n/index.svelte'
8+
9+/** The slash command that unloads an agent's model (announced by mm). */
10+export const unloadCommand = 'unload'
11+
12+/** Whether an agent that announced these commands can unload its model. */
13+export function canUnload(commands: readonly { name: string }[] | undefined): boolean {
14+ return (commands ?? []).some((command) => command.name === unloadCommand)
15+}
16+
17+/** Whether the button can be used now: the agent runs and does not answer. */
18+export function unloadReady(state: string | undefined): boolean {
19+ return state === 'ready'
20+}
21+
22+/** A sentence of the result of "Unload all", as message keys and variables. */
23+export type UnloadLine = { key: MessageKey; vars: Record<string, string> }
24+
25+/**
26+ * What "Unload all" says: the agents unloaded and the ones left alone, by
27+ * title, or that there was none.
28+ *
29+ * @example
30+ * unloadSummary({ unloaded: ['alice'], skipped: [] }, (name) => name.toUpperCase())
31+ * // [{ key: 'unload.done', vars: { agents: 'ALICE' } }]
32+ */
33+export function unloadSummary(
34+ result: { unloaded: string[] | null; skipped: string[] | null },
35+ titleOf: (name: string) => string,
36+): UnloadLine[] {
37+ const unloaded = result.unloaded ?? []
38+ const skipped = result.skipped ?? []
39+ const lines: UnloadLine[] = []
40+ if (unloaded.length) lines.push({ key: 'unload.done', vars: { agents: unloaded.map(titleOf).join(', ') } })
41+ if (skipped.length) lines.push({ key: 'unload.skipped', vars: { agents: skipped.map(titleOf).join(', ') } })
42+ if (!lines.length) lines.push({ key: 'unload.none', vars: {} })
43+ return lines
44+}
added internal/app/unload.go +81 -0
new file mode 100644
@@ -0,0 +1,81 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package app
4+
5+import (
6+ "context"
7+ "errors"
8+ "fmt"
9+ "strings"
10+
11+ "git.rickub.com/bots-garden/sidekicks/internal/agents"
12+ "git.rickub.com/bots-garden/sidekicks/internal/channels"
13+)
14+
15+// ErrNotRunning is returned for an agent that is not running: it has no model loaded.
16+var ErrNotRunning = errors.New("the agent is not running: it has no model to unload")
17+
18+// Unload has the agent unload its model from memory, without stopping it
19+// (issue #51), when it offers the /unload command. Nothing appears in the
20+// conversations: what the agent answers goes to its log. The model is loaded
21+// again with the next message.
22+func (s *AgentService) Unload(ctx context.Context, name string) error {
23+ status, ok := s.Core.status(name)
24+ if !ok {
25+ return fmt.Errorf("%w: %s", agents.ErrUnknownAgent, name)
26+ }
27+ switch status.State {
28+ case agents.StateReady:
29+ case agents.StateBusy:
30+ return channels.ErrAgentAnswering
31+ default:
32+ return ErrNotRunning
33+ }
34+ log := func(line string) { _ = s.Core.manager.Log(name, "unload: "+line) }
35+ answer, err := s.Core.Channels().Unload(ctx, name)
36+ if err != nil {
37+ log(err.Error())
38+ return err
39+ }
40+ if answer == "" {
41+ answer = "done"
42+ }
43+ for _, line := range strings.Split(answer, "\n") {
44+ log(line)
45+ }
46+ return nil
47+}
48+
49+// UnloadResult says which agents unloaded their model, and which running
50+// agents were left alone: answering, unable to unload, or failing.
51+type UnloadResult struct {
52+ Unloaded []string `json:"unloaded"`
53+ Skipped []string `json:"skipped"`
54+}
55+
56+// UnloadAll has every running agent that offers /unload unload its model.
57+// Stopped agents are not counted; running agents that are answering or
58+// cannot unload are skipped.
59+func (s *AgentService) UnloadAll(ctx context.Context) UnloadResult {
60+ result := UnloadResult{Unloaded: []string{}, Skipped: []string{}}
61+ for _, status := range s.Core.manager.Statuses() {
62+ if status.State != agents.StateReady && status.State != agents.StateBusy {
63+ continue
64+ }
65+ if err := s.Unload(ctx, status.Name); err != nil {
66+ result.Skipped = append(result.Skipped, status.Name)
67+ continue
68+ }
69+ result.Unloaded = append(result.Unloaded, status.Name)
70+ }
71+ return result
72+}
73+
74+func (c *Core) status(name string) (agents.Status, bool) {
75+ for _, status := range c.manager.Statuses() {
76+ if status.Name == name {
77+ return status, true
78+ }
79+ }
80+ return agents.Status{}, false
81+}
new file mode 100644
@@ -0,0 +1,81 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package app
4+
5+import (
6+ "context"
7+ "errors"
8+ "fmt"
9+ "strings"
10+
11+ "git.rickub.com/bots-garden/sidekicks/internal/agents"
12+ "git.rickub.com/bots-garden/sidekicks/internal/channels"
13+)
14+
15+// ErrNotRunning is returned for an agent that is not running: it has no model loaded.
16+var ErrNotRunning = errors.New("the agent is not running: it has no model to unload")
17+
18+// Unload has the agent unload its model from memory, without stopping it
19+// (issue #51), when it offers the /unload command. Nothing appears in the
20+// conversations: what the agent answers goes to its log. The model is loaded
21+// again with the next message.
22+func (s *AgentService) Unload(ctx context.Context, name string) error {
23+ status, ok := s.Core.status(name)
24+ if !ok {
25+ return fmt.Errorf("%w: %s", agents.ErrUnknownAgent, name)
26+ }
27+ switch status.State {
28+ case agents.StateReady:
29+ case agents.StateBusy:
30+ return channels.ErrAgentAnswering
31+ default:
32+ return ErrNotRunning
33+ }
34+ log := func(line string) { _ = s.Core.manager.Log(name, "unload: "+line) }
35+ answer, err := s.Core.Channels().Unload(ctx, name)
36+ if err != nil {
37+ log(err.Error())
38+ return err
39+ }
40+ if answer == "" {
41+ answer = "done"
42+ }
43+ for _, line := range strings.Split(answer, "\n") {
44+ log(line)
45+ }
46+ return nil
47+}
48+
49+// UnloadResult says which agents unloaded their model, and which running
50+// agents were left alone: answering, unable to unload, or failing.
51+type UnloadResult struct {
52+ Unloaded []string `json:"unloaded"`
53+ Skipped []string `json:"skipped"`
54+}
55+
56+// UnloadAll has every running agent that offers /unload unload its model.
57+// Stopped agents are not counted; running agents that are answering or
58+// cannot unload are skipped.
59+func (s *AgentService) UnloadAll(ctx context.Context) UnloadResult {
60+ result := UnloadResult{Unloaded: []string{}, Skipped: []string{}}
61+ for _, status := range s.Core.manager.Statuses() {
62+ if status.State != agents.StateReady && status.State != agents.StateBusy {
63+ continue
64+ }
65+ if err := s.Unload(ctx, status.Name); err != nil {
66+ result.Skipped = append(result.Skipped, status.Name)
67+ continue
68+ }
69+ result.Unloaded = append(result.Unloaded, status.Name)
70+ }
71+ return result
72+}
73+
74+func (c *Core) status(name string) (agents.Status, bool) {
75+ for _, status := range c.manager.Statuses() {
76+ if status.Name == name {
77+ return status, true
78+ }
79+ }
80+ return agents.Status{}, false
81+}
added internal/app/unload_test.go +100 -0
new file mode 100644
@@ -0,0 +1,100 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package app_test
4+
5+import (
6+ "context"
7+ "errors"
8+ "path/filepath"
9+ "slices"
10+ "testing"
11+
12+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
13+ "git.rickub.com/bots-garden/sidekicks/internal/agents"
14+ "git.rickub.com/bots-garden/sidekicks/internal/app"
15+ "git.rickub.com/bots-garden/sidekicks/internal/channels"
16+ "git.rickub.com/bots-garden/sidekicks/internal/config"
17+)
18+
19+// unloadingConn announces the unload command, like mm, and answers it.
20+type unloadingConn struct{ conn }
21+
22+func (c *unloadingConn) NewSession(_ context.Context, _ string, handler acp.SessionHandler) (string, error) {
23+ c.handler = handler
24+ handler.Update(acp.Update{Kind: acp.UpdateCommands, Commands: []acp.Command{{Name: "compact"}, {Name: "unload"}}})
25+ return "s-1", nil
26+}
27+
28+func (c *unloadingConn) Prompt(_ context.Context, _ string, text string, _ ...acp.Attachment) (acp.TurnResult, error) {
29+ answer := "ok"
30+ if text == "/unload" {
31+ answer = "unloaded: gemma"
32+ }
33+ c.handler.Update(acp.Update{Kind: acp.UpdateMessage, Text: answer})
34+ return acp.TurnResult{StopReason: "end_turn"}, nil
35+}
36+
37+// unloadCore has three agents: alice and bob can unload their model, carol
38+// cannot.
39+func unloadCore(t *testing.T) (*app.AgentService, *app.ChannelService) {
40+ t.Helper()
41+ path := filepath.Join(t.TempDir(), "config.yaml")
42+ write(t, path, "version: 1\nagents:\n - name: alice\n command: sh\n - name: bob\n command: sh\n - name: carol\n command: sh\n")
43+ start := func(_ context.Context, spec acp.Spec, _ func(string)) (agents.Conn, error) {
44+ if spec.Name == "carol" {
45+ return &conn{done: make(chan struct{})}, nil
46+ }
47+ return &unloadingConn{conn{done: make(chan struct{})}}, nil
48+ }
49+ core := app.New(config.Location{Path: path, Source: config.SourceFlag}, app.Options{Starter: start})
50+ t.Cleanup(func() { core.Shutdown(context.Background()) })
51+ return &app.AgentService{Core: core}, &app.ChannelService{Core: core}
52+}
53+
54+// announce opens the direct conversation of each agent, which has it
55+// announce its commands.
56+func announce(t *testing.T, chat *app.ChannelService, names ...string) {
57+ t.Helper()
58+ for _, name := range names {
59+ direct, err := chat.Direct(name)
60+ if err != nil {
61+ t.Fatal(err)
62+ }
63+ if err := chat.Prepare(context.Background(), direct.ID); err != nil {
64+ t.Fatal(err)
65+ }
66+ }
67+}
68+
69+func TestUnloadAsksARunningAgentAndLogsItsAnswer(t *testing.T) {
70+ service, chat := unloadCore(t)
71+ ctx := context.Background()
72+ if err := service.Unload(ctx, "nobody"); !errors.Is(err, agents.ErrUnknownAgent) {
73+ t.Fatalf("unknown agent: %v", err)
74+ }
75+ if err := service.Unload(ctx, "alice"); !errors.Is(err, app.ErrNotRunning) {
76+ t.Fatalf("a stopped agent has nothing to unload: %v", err)
77+ }
78+ announce(t, chat, "alice", "carol")
79+ if err := service.Unload(ctx, "alice"); err != nil {
80+ t.Fatal(err)
81+ }
82+ if logs, _ := service.Logs("alice"); !slices.Contains(logs, "unload: unloaded: gemma") {
83+ t.Fatalf("the answer goes to the log: %q", logs)
84+ }
85+ if err := service.Unload(ctx, "carol"); !errors.Is(err, channels.ErrCannotUnload) {
86+ t.Fatalf("carol offers no /unload: %v", err)
87+ }
88+}
89+
90+func TestUnloadAllUnloadsTheRunningAgentsThatCan(t *testing.T) {
91+ service, chat := unloadCore(t)
92+ announce(t, chat, "alice", "carol") // bob stays stopped
93+ result := service.UnloadAll(context.Background())
94+ if !slices.Equal(result.Unloaded, []string{"alice"}) || !slices.Equal(result.Skipped, []string{"carol"}) {
95+ t.Fatalf("got %+v", result)
96+ }
97+ if service.List()[1].State != agents.StateStopped {
98+ t.Fatal("bob is not started to be unloaded")
99+ }
100+}
new file mode 100644
@@ -0,0 +1,100 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package app_test
4+
5+import (
6+ "context"
7+ "errors"
8+ "path/filepath"
9+ "slices"
10+ "testing"
11+
12+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
13+ "git.rickub.com/bots-garden/sidekicks/internal/agents"
14+ "git.rickub.com/bots-garden/sidekicks/internal/app"
15+ "git.rickub.com/bots-garden/sidekicks/internal/channels"
16+ "git.rickub.com/bots-garden/sidekicks/internal/config"
17+)
18+
19+// unloadingConn announces the unload command, like mm, and answers it.
20+type unloadingConn struct{ conn }
21+
22+func (c *unloadingConn) NewSession(_ context.Context, _ string, handler acp.SessionHandler) (string, error) {
23+ c.handler = handler
24+ handler.Update(acp.Update{Kind: acp.UpdateCommands, Commands: []acp.Command{{Name: "compact"}, {Name: "unload"}}})
25+ return "s-1", nil
26+}
27+
28+func (c *unloadingConn) Prompt(_ context.Context, _ string, text string, _ ...acp.Attachment) (acp.TurnResult, error) {
29+ answer := "ok"
30+ if text == "/unload" {
31+ answer = "unloaded: gemma"
32+ }
33+ c.handler.Update(acp.Update{Kind: acp.UpdateMessage, Text: answer})
34+ return acp.TurnResult{StopReason: "end_turn"}, nil
35+}
36+
37+// unloadCore has three agents: alice and bob can unload their model, carol
38+// cannot.
39+func unloadCore(t *testing.T) (*app.AgentService, *app.ChannelService) {
40+ t.Helper()
41+ path := filepath.Join(t.TempDir(), "config.yaml")
42+ write(t, path, "version: 1\nagents:\n - name: alice\n command: sh\n - name: bob\n command: sh\n - name: carol\n command: sh\n")
43+ start := func(_ context.Context, spec acp.Spec, _ func(string)) (agents.Conn, error) {
44+ if spec.Name == "carol" {
45+ return &conn{done: make(chan struct{})}, nil
46+ }
47+ return &unloadingConn{conn{done: make(chan struct{})}}, nil
48+ }
49+ core := app.New(config.Location{Path: path, Source: config.SourceFlag}, app.Options{Starter: start})
50+ t.Cleanup(func() { core.Shutdown(context.Background()) })
51+ return &app.AgentService{Core: core}, &app.ChannelService{Core: core}
52+}
53+
54+// announce opens the direct conversation of each agent, which has it
55+// announce its commands.
56+func announce(t *testing.T, chat *app.ChannelService, names ...string) {
57+ t.Helper()
58+ for _, name := range names {
59+ direct, err := chat.Direct(name)
60+ if err != nil {
61+ t.Fatal(err)
62+ }
63+ if err := chat.Prepare(context.Background(), direct.ID); err != nil {
64+ t.Fatal(err)
65+ }
66+ }
67+}
68+
69+func TestUnloadAsksARunningAgentAndLogsItsAnswer(t *testing.T) {
70+ service, chat := unloadCore(t)
71+ ctx := context.Background()
72+ if err := service.Unload(ctx, "nobody"); !errors.Is(err, agents.ErrUnknownAgent) {
73+ t.Fatalf("unknown agent: %v", err)
74+ }
75+ if err := service.Unload(ctx, "alice"); !errors.Is(err, app.ErrNotRunning) {
76+ t.Fatalf("a stopped agent has nothing to unload: %v", err)
77+ }
78+ announce(t, chat, "alice", "carol")
79+ if err := service.Unload(ctx, "alice"); err != nil {
80+ t.Fatal(err)
81+ }
82+ if logs, _ := service.Logs("alice"); !slices.Contains(logs, "unload: unloaded: gemma") {
83+ t.Fatalf("the answer goes to the log: %q", logs)
84+ }
85+ if err := service.Unload(ctx, "carol"); !errors.Is(err, channels.ErrCannotUnload) {
86+ t.Fatalf("carol offers no /unload: %v", err)
87+ }
88+}
89+
90+func TestUnloadAllUnloadsTheRunningAgentsThatCan(t *testing.T) {
91+ service, chat := unloadCore(t)
92+ announce(t, chat, "alice", "carol") // bob stays stopped
93+ result := service.UnloadAll(context.Background())
94+ if !slices.Equal(result.Unloaded, []string{"alice"}) || !slices.Equal(result.Skipped, []string{"carol"}) {
95+ t.Fatalf("got %+v", result)
96+ }
97+ if service.List()[1].State != agents.StateStopped {
98+ t.Fatal("bob is not started to be unloaded")
99+ }
100+}
modified internal/channels/turns.go +11 -5
@@ -564,11 +564,7 @@ func (h *handler) Update(update acp.Update) {
564564 m.emitter.Emit(events.UsageChanged, UsagePayload{Channel: ch.info.ID, Agent: h.agent, Usage: *update.Usage})
565565 return
566566 case acp.UpdateCommands:
567- m.commands[h.agent] = update.Commands
568- if data, err := json.Marshal(update.Commands); err == nil {
569- _ = m.db.SetValue("commands/"+h.agent, data)
570- }
571- m.emitter.Emit(events.CommandsChanged, CommandsPayload{Agent: h.agent, Commands: update.Commands})
567+ m.storeCommands(h.agent, update.Commands)
572568 return
573569 }
574570 message := ch.current
@@ -608,6 +604,16 @@ func (h *handler) Update(update acp.Update) {
608604 }
609605 }
610606
607+// storeCommands keeps the commands agent announced, for the next runs too,
608+// and tells the interface. The caller holds m.mu.
609+func (m *Manager) storeCommands(agent string, commands []acp.Command) {
610+ m.commands[agent] = commands
611+ if data, err := json.Marshal(commands); err == nil {
612+ _ = m.db.SetValue("commands/"+agent, data)
613+ }
614+ m.emitter.Emit(events.CommandsChanged, CommandsPayload{Agent: agent, Commands: commands})
615+}
616+
611617 // appendText adds a text or thought fragment to message. The caller holds m.mu.
612618 func (m *Manager) appendText(message *Message, update acp.Update) {
613619 kind := PartText
@@ -564,11 +564,7 @@ func (h *handler) Update(update acp.Update) {
564 m.emitter.Emit(events.UsageChanged, UsagePayload{Channel: ch.info.ID, Agent: h.agent, Usage: *update.Usage})564 m.emitter.Emit(events.UsageChanged, UsagePayload{Channel: ch.info.ID, Agent: h.agent, Usage: *update.Usage})
565 return565 return
566 case acp.UpdateCommands:566 case acp.UpdateCommands:
567- m.commands[h.agent] = update.Commands567+ m.storeCommands(h.agent, update.Commands)
568- if data, err := json.Marshal(update.Commands); err == nil {
569- _ = m.db.SetValue("commands/"+h.agent, data)
570- }
571- m.emitter.Emit(events.CommandsChanged, CommandsPayload{Agent: h.agent, Commands: update.Commands})
572 return568 return
573 }569 }
574 message := ch.current570 message := ch.current
@@ -608,6 +604,16 @@ func (h *handler) Update(update acp.Update) {
608 }604 }
609 }605 }
610 606
607+// storeCommands keeps the commands agent announced, for the next runs too,
608+// and tells the interface. The caller holds m.mu.
609+func (m *Manager) storeCommands(agent string, commands []acp.Command) {
610+ m.commands[agent] = commands
611+ if data, err := json.Marshal(commands); err == nil {
612+ _ = m.db.SetValue("commands/"+agent, data)
613+ }
614+ m.emitter.Emit(events.CommandsChanged, CommandsPayload{Agent: agent, Commands: commands})
615+}
616+
611 // appendText adds a text or thought fragment to message. The caller holds m.mu.617 // appendText adds a text or thought fragment to message. The caller holds m.mu.
612 func (m *Manager) appendText(message *Message, update acp.Update) {618 func (m *Manager) appendText(message *Message, update acp.Update) {
613 kind := PartText619 kind := PartText
added internal/channels/unload.go +99 -0
new file mode 100644
@@ -0,0 +1,99 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package channels
4+
5+import (
6+ "context"
7+ "errors"
8+ "strings"
9+
10+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
11+)
12+
13+// UnloadCommand is the slash command an agent announces when it can unload
14+// its model from memory (issue #51). ACP has no standard method for it: an
15+// agent that announces a command with this name is taken at its word.
16+const UnloadCommand = "unload"
17+
18+var (
19+ // ErrCannotUnload is returned for an agent that never announced an unload command.
20+ ErrCannotUnload = errors.New("this agent cannot unload its model: it offers no /unload command")
21+ // ErrAgentAnswering is returned while the agent answers a channel: unloading would only
22+ // make it load its model again.
23+ ErrAgentAnswering = errors.New("the agent is answering: wait for the end of its answer to unload its model")
24+)
25+
26+// CanUnload tells whether agent announced the unload command.
27+func (m *Manager) CanUnload(agent string) bool {
28+ m.mu.Lock()
29+ defer m.mu.Unlock()
30+ m.commandsKnown(agent)
31+ for _, command := range m.commands[agent] {
32+ if command.Name == UnloadCommand {
33+ return true
34+ }
35+ }
36+ return false
37+}
38+
39+// Unload has agent unload its model: it sends /unload in a session of its
40+// own, which no channel shows and which is forgotten afterwards. It returns
41+// what the agent answered. The agent is started if it is not running: the
42+// caller checks that it runs (there is nothing to unload otherwise).
43+//
44+// answer, err := manager.Unload(ctx, "alice") // "unloaded: gemma…"
45+func (m *Manager) Unload(ctx context.Context, agent string) (string, error) {
46+ if !m.CanUnload(agent) {
47+ return "", ErrCannotUnload
48+ }
49+ if !m.tryTurn(agent) {
50+ return "", ErrAgentAnswering
51+ }
52+ defer m.endTurn(agent)
53+ conn, release, err := m.agents.Acquire(ctx, agent)
54+ if err != nil {
55+ return "", err
56+ }
57+ defer release()
58+ definition, _ := m.agents.Definition(agent)
59+ handler := &unloadHandler{manager: m, agent: agent}
60+ sessionID, err := conn.NewSession(ctx, definition.Workspace, handler)
61+ if err != nil {
62+ return "", err
63+ }
64+ if _, err := conn.Prompt(ctx, sessionID, "/"+UnloadCommand); err != nil {
65+ return "", err
66+ }
67+ return strings.TrimSpace(handler.text()), nil
68+}
69+
70+// unloadHandler receives what the agent says in the session opened to
71+// unload it: its answer, kept for the log, and its commands, kept as usual.
72+type unloadHandler struct {
73+ manager *Manager
74+ agent string
75+ answer strings.Builder
76+}
77+
78+func (h *unloadHandler) Update(update acp.Update) {
79+ m := h.manager
80+ m.mu.Lock()
81+ defer m.mu.Unlock()
82+ switch update.Kind {
83+ case acp.UpdateCommands:
84+ m.storeCommands(h.agent, update.Commands)
85+ case acp.UpdateMessage:
86+ h.answer.WriteString(update.Text)
87+ }
88+}
89+
90+// RequestPermission refuses: unloading a model needs no tool.
91+func (h *unloadHandler) RequestPermission(context.Context, acp.PermissionRequest) acp.PermissionAnswer {
92+ return acp.PermissionAnswer{}
93+}
94+
95+func (h *unloadHandler) text() string {
96+ h.manager.mu.Lock()
97+ defer h.manager.mu.Unlock()
98+ return h.answer.String()
99+}
new file mode 100644
@@ -0,0 +1,99 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package channels
4+
5+import (
6+ "context"
7+ "errors"
8+ "strings"
9+
10+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
11+)
12+
13+// UnloadCommand is the slash command an agent announces when it can unload
14+// its model from memory (issue #51). ACP has no standard method for it: an
15+// agent that announces a command with this name is taken at its word.
16+const UnloadCommand = "unload"
17+
18+var (
19+ // ErrCannotUnload is returned for an agent that never announced an unload command.
20+ ErrCannotUnload = errors.New("this agent cannot unload its model: it offers no /unload command")
21+ // ErrAgentAnswering is returned while the agent answers a channel: unloading would only
22+ // make it load its model again.
23+ ErrAgentAnswering = errors.New("the agent is answering: wait for the end of its answer to unload its model")
24+)
25+
26+// CanUnload tells whether agent announced the unload command.
27+func (m *Manager) CanUnload(agent string) bool {
28+ m.mu.Lock()
29+ defer m.mu.Unlock()
30+ m.commandsKnown(agent)
31+ for _, command := range m.commands[agent] {
32+ if command.Name == UnloadCommand {
33+ return true
34+ }
35+ }
36+ return false
37+}
38+
39+// Unload has agent unload its model: it sends /unload in a session of its
40+// own, which no channel shows and which is forgotten afterwards. It returns
41+// what the agent answered. The agent is started if it is not running: the
42+// caller checks that it runs (there is nothing to unload otherwise).
43+//
44+// answer, err := manager.Unload(ctx, "alice") // "unloaded: gemma…"
45+func (m *Manager) Unload(ctx context.Context, agent string) (string, error) {
46+ if !m.CanUnload(agent) {
47+ return "", ErrCannotUnload
48+ }
49+ if !m.tryTurn(agent) {
50+ return "", ErrAgentAnswering
51+ }
52+ defer m.endTurn(agent)
53+ conn, release, err := m.agents.Acquire(ctx, agent)
54+ if err != nil {
55+ return "", err
56+ }
57+ defer release()
58+ definition, _ := m.agents.Definition(agent)
59+ handler := &unloadHandler{manager: m, agent: agent}
60+ sessionID, err := conn.NewSession(ctx, definition.Workspace, handler)
61+ if err != nil {
62+ return "", err
63+ }
64+ if _, err := conn.Prompt(ctx, sessionID, "/"+UnloadCommand); err != nil {
65+ return "", err
66+ }
67+ return strings.TrimSpace(handler.text()), nil
68+}
69+
70+// unloadHandler receives what the agent says in the session opened to
71+// unload it: its answer, kept for the log, and its commands, kept as usual.
72+type unloadHandler struct {
73+ manager *Manager
74+ agent string
75+ answer strings.Builder
76+}
77+
78+func (h *unloadHandler) Update(update acp.Update) {
79+ m := h.manager
80+ m.mu.Lock()
81+ defer m.mu.Unlock()
82+ switch update.Kind {
83+ case acp.UpdateCommands:
84+ m.storeCommands(h.agent, update.Commands)
85+ case acp.UpdateMessage:
86+ h.answer.WriteString(update.Text)
87+ }
88+}
89+
90+// RequestPermission refuses: unloading a model needs no tool.
91+func (h *unloadHandler) RequestPermission(context.Context, acp.PermissionRequest) acp.PermissionAnswer {
92+ return acp.PermissionAnswer{}
93+}
94+
95+func (h *unloadHandler) text() string {
96+ h.manager.mu.Lock()
97+ defer h.manager.mu.Unlock()
98+ return h.answer.String()
99+}
added internal/channels/unload_test.go +96 -0
new file mode 100644
@@ -0,0 +1,96 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package channels_test
4+
5+import (
6+ "context"
7+ "errors"
8+ "testing"
9+
10+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
11+ "git.rickub.com/bots-garden/sidekicks/internal/channels"
12+)
13+
14+// unloads is the fake agents' answer to /unload, like mm.
15+func unloads(_ context.Context, handler acp.SessionHandler) (acp.TurnResult, error) {
16+ handler.Update(acp.Update{Kind: acp.UpdateMessage, Text: "unloaded: gemma\n"})
17+ return acp.TurnResult{StopReason: "end_turn"}, nil
18+}
19+
20+func TestAnAgentWithoutTheUnloadCommandIsNotAskedToUnload(t *testing.T) {
21+ f := setup(t, map[string]script{"/unload": unloads})
22+ f.source.conn("alice").commands = []acp.Command{{Name: "compact"}}
23+ direct, _ := f.manager.Direct("alice")
24+ if err := f.manager.Prepare(context.Background(), direct.ID); err != nil {
25+ t.Fatal(err)
26+ }
27+ if f.manager.CanUnload("alice") || f.manager.CanUnload("bob") {
28+ t.Fatal("neither alice nor bob announced unload")
29+ }
30+ if _, err := f.manager.Unload(context.Background(), "alice"); !errors.Is(err, channels.ErrCannotUnload) {
31+ t.Fatalf("refused: %v", err)
32+ }
33+ if sent := f.source.conn("alice").sent(); len(sent) != 0 {
34+ t.Fatalf("nothing sent: %q", sent)
35+ }
36+}
37+
38+func TestUnloadSendsTheCommandInASessionOfItsOwn(t *testing.T) {
39+ f := setup(t, map[string]script{"/unload": unloads})
40+ alice := f.source.conn("alice")
41+ alice.commands = []acp.Command{{Name: "compact"}, {Name: "unload"}}
42+ direct, _ := f.manager.Direct("alice")
43+ f.send(t, direct.ID, "hello")
44+ f.idle(t, direct.ID, 2)
45+ if !f.manager.CanUnload("alice") {
46+ t.Fatal("alice announced unload")
47+ }
48+
49+ answer, err := f.manager.Unload(context.Background(), "alice")
50+ if err != nil {
51+ t.Fatal(err)
52+ }
53+ if answer != "unloaded: gemma" {
54+ t.Fatalf("answer: %q", answer)
55+ }
56+ if sent := alice.sent(); len(sent) != 2 || sent[1] != "/unload" {
57+ t.Fatalf("prompts: %q", sent)
58+ }
59+ if alice.sessionCount() != 2 {
60+ t.Fatalf("a session of its own: %d sessions", alice.sessionCount())
61+ }
62+ view := f.idle(t, direct.ID, 2)
63+ if len(view.Messages) != 2 {
64+ t.Fatalf("no trace in the conversation: %s", describe(view.Messages))
65+ }
66+ // The conversation goes on in its own session.
67+ f.send(t, direct.ID, "again")
68+ f.idle(t, direct.ID, 4)
69+ if alice.sessionCount() != 2 {
70+ t.Fatalf("the conversation keeps its session: %d sessions", alice.sessionCount())
71+ }
72+}
73+
74+func TestAnAnsweringAgentIsNotAskedToUnload(t *testing.T) {
75+ release := make(chan struct{})
76+ f := setup(t, map[string]script{
77+ "/unload": unloads,
78+ "slow": func(context.Context, acp.SessionHandler) (acp.TurnResult, error) {
79+ <-release
80+ return acp.TurnResult{StopReason: "end_turn"}, nil
81+ },
82+ })
83+ alice := f.source.conn("alice")
84+ alice.commands = []acp.Command{{Name: "unload"}}
85+ direct, _ := f.manager.Direct("alice")
86+ f.send(t, direct.ID, "slow")
87+ waitFor(t, func() bool { return len(alice.sent()) == 1 })
88+ if _, err := f.manager.Unload(context.Background(), "alice"); !errors.Is(err, channels.ErrAgentAnswering) {
89+ t.Fatalf("refused during an answer: %v", err)
90+ }
91+ close(release)
92+ f.idle(t, direct.ID, 2)
93+ if _, err := f.manager.Unload(context.Background(), "alice"); err != nil {
94+ t.Fatalf("accepted once the answer ended: %v", err)
95+ }
96+}
new file mode 100644
@@ -0,0 +1,96 @@
1+// Copyright (c) 2026 Philippe Charrière — Sidekicks Source-Available License 1.0, see LICENSE
2+
3+package channels_test
4+
5+import (
6+ "context"
7+ "errors"
8+ "testing"
9+
10+ "git.rickub.com/bots-garden/sidekicks/internal/acp"
11+ "git.rickub.com/bots-garden/sidekicks/internal/channels"
12+)
13+
14+// unloads is the fake agents' answer to /unload, like mm.
15+func unloads(_ context.Context, handler acp.SessionHandler) (acp.TurnResult, error) {
16+ handler.Update(acp.Update{Kind: acp.UpdateMessage, Text: "unloaded: gemma\n"})
17+ return acp.TurnResult{StopReason: "end_turn"}, nil
18+}
19+
20+func TestAnAgentWithoutTheUnloadCommandIsNotAskedToUnload(t *testing.T) {
21+ f := setup(t, map[string]script{"/unload": unloads})
22+ f.source.conn("alice").commands = []acp.Command{{Name: "compact"}}
23+ direct, _ := f.manager.Direct("alice")
24+ if err := f.manager.Prepare(context.Background(), direct.ID); err != nil {
25+ t.Fatal(err)
26+ }
27+ if f.manager.CanUnload("alice") || f.manager.CanUnload("bob") {
28+ t.Fatal("neither alice nor bob announced unload")
29+ }
30+ if _, err := f.manager.Unload(context.Background(), "alice"); !errors.Is(err, channels.ErrCannotUnload) {
31+ t.Fatalf("refused: %v", err)
32+ }
33+ if sent := f.source.conn("alice").sent(); len(sent) != 0 {
34+ t.Fatalf("nothing sent: %q", sent)
35+ }
36+}
37+
38+func TestUnloadSendsTheCommandInASessionOfItsOwn(t *testing.T) {
39+ f := setup(t, map[string]script{"/unload": unloads})
40+ alice := f.source.conn("alice")
41+ alice.commands = []acp.Command{{Name: "compact"}, {Name: "unload"}}
42+ direct, _ := f.manager.Direct("alice")
43+ f.send(t, direct.ID, "hello")
44+ f.idle(t, direct.ID, 2)
45+ if !f.manager.CanUnload("alice") {
46+ t.Fatal("alice announced unload")
47+ }
48+
49+ answer, err := f.manager.Unload(context.Background(), "alice")
50+ if err != nil {
51+ t.Fatal(err)
52+ }
53+ if answer != "unloaded: gemma" {
54+ t.Fatalf("answer: %q", answer)
55+ }
56+ if sent := alice.sent(); len(sent) != 2 || sent[1] != "/unload" {
57+ t.Fatalf("prompts: %q", sent)
58+ }
59+ if alice.sessionCount() != 2 {
60+ t.Fatalf("a session of its own: %d sessions", alice.sessionCount())
61+ }
62+ view := f.idle(t, direct.ID, 2)
63+ if len(view.Messages) != 2 {
64+ t.Fatalf("no trace in the conversation: %s", describe(view.Messages))
65+ }
66+ // The conversation goes on in its own session.
67+ f.send(t, direct.ID, "again")
68+ f.idle(t, direct.ID, 4)
69+ if alice.sessionCount() != 2 {
70+ t.Fatalf("the conversation keeps its session: %d sessions", alice.sessionCount())
71+ }
72+}
73+
74+func TestAnAnsweringAgentIsNotAskedToUnload(t *testing.T) {
75+ release := make(chan struct{})
76+ f := setup(t, map[string]script{
77+ "/unload": unloads,
78+ "slow": func(context.Context, acp.SessionHandler) (acp.TurnResult, error) {
79+ <-release
80+ return acp.TurnResult{StopReason: "end_turn"}, nil
81+ },
82+ })
83+ alice := f.source.conn("alice")
84+ alice.commands = []acp.Command{{Name: "unload"}}
85+ direct, _ := f.manager.Direct("alice")
86+ f.send(t, direct.ID, "slow")
87+ waitFor(t, func() bool { return len(alice.sent()) == 1 })
88+ if _, err := f.manager.Unload(context.Background(), "alice"); !errors.Is(err, channels.ErrAgentAnswering) {
89+ t.Fatalf("refused during an answer: %v", err)
90+ }
91+ close(release)
92+ f.idle(t, direct.ID, 2)
93+ if _, err := f.manager.Unload(context.Background(), "alice"); err != nil {
94+ t.Fatalf("accepted once the answer ended: %v", err)
95+ }
96+}