bots-garden/synedrionpublic Fork
⑂ f9b27cb
Commits
⬇ Clone ▾
git clone https://git.rickub.com/bots-garden/synedrion.git
git clone ssh://git@rickub.com/bots-garden/synedrion.git

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

Download ZIP

🛟 Updated.Unverified

k33g committed 2026-10-23T16:39:12+02:00 Browse files
f9b27cb parent: 0502ed3
added .memory/handoffs/2026-10-23-milestone-v0-2-0.md +36 -0
new file mode 100644
@@ -0,0 +1,36 @@
1+# Handoff — 2026-10-23 — milestone v0.2.0 and the folder browser
2+
3+## State
4+
5+Everything asked is built, tested (501 tests), documented in English and French, and the quality gate passes (run 15). Nothing was committed by me. In the code:
6+
7+- Context given to agents (#14): `crates/domain/src/context.rs`, used from `crates/ui/src/controller/prompts.rs`.
8+- Agents calling agents and Stop (#15): `crates/ui/src/controller/relay.rs`, hooked in `finish_answer` of `controller.rs`.
9+- Tool calls and plans (#17): `crates/acp/src/updates.rs` (translation), `crates/ui/src/controller/traces.rs` (storage), `crates/ui/src/trace_view.rs` (cards), `crates/domain/src/trace.rs` (format).
10+- No fs or terminal capability (#18): `initialize_request` in `crates/acp/src/worker.rs`, explanation in `docs/*/explanation/client-capabilities.md` and `capacites-du-client.md`.
11+- Settings panel (`crates/ui/src/settings_panel.rs`) and the folder browser (#20: `folders.rs`, `folder_browser.rs`).
12+
13+## In flight
14+
15+Nothing is half done. Tickets #14, #15, #17, #18 and #20 are ticked and commented but left open for the user to close. In #18 two boxes stay unticked on purpose (see its comment).
16+
17+## Next steps
18+
19+1. Ask the user to run the application and report: do the cards (tool calls, plans), the Settings panel and the folder browser look right? Does a real agent (mini-me) send `tool_call` and `plan` updates, and are they readable?
20+2. Before the user first starts the new version, suggest copying their database file (see `docs/en/reference/database.md` for its place): migration 3 rebuilds the `message` table and was tested only on in-memory data.
21+3. Ask the user to confirm the #18 decision (no fs and no terminal for agents), then close #18.
22+4. v0.3.0 is #16 (agents registering themselves): research, no code yet.
23+5. Ideas that came up and were not asked for: arrow-key navigation in the suggestion list; keeping the unfolded state of tool cards across a restart; resending the context after `/new`; reducing `controller.rs` further (complexity 30, 1,700 lines with its tests).
24+
25+## Open questions / blockers
26+
27+- #18 (no capabilities) is a decision I recommended; the user did not explicitly confirm it.
28+- Whether `Chain depth` 3 and `Messages of context` 20 are good defaults is a guess until the user tries them with a real model.
29+
30+## Watch out for
31+
32+- A turn that ends after `Stop` calls nobody, by design (`stop_requested`): do not "fix" a test that expects a relay after a stop.
33+- `Author` has a fourth variant, `Trace(AgentName)`: any new `match` on it must decide what a trace is (context and follow-ups ignore it).
34+- A mutation check with several `--test` arguments needs `--no-fail-fast`, or only the first failing binary is seen.
35+- After restoring a file from a mutation, `touch` it (stale cargo build seen before).
36+- `app.rs` is at complexity 40 of 60: new logic goes in a new module, as `dock.rs`, `suggestions.rs`, `folder_browser.rs`, `settings_panel.rs` and `trace_view.rs` did.
new file mode 100644
@@ -0,0 +1,36 @@
1+# Handoff — 2026-10-23 — milestone v0.2.0 and the folder browser
2+
3+## State
4+
5+Everything asked is built, tested (501 tests), documented in English and French, and the quality gate passes (run 15). Nothing was committed by me. In the code:
6+
7+- Context given to agents (#14): `crates/domain/src/context.rs`, used from `crates/ui/src/controller/prompts.rs`.
8+- Agents calling agents and Stop (#15): `crates/ui/src/controller/relay.rs`, hooked in `finish_answer` of `controller.rs`.
9+- Tool calls and plans (#17): `crates/acp/src/updates.rs` (translation), `crates/ui/src/controller/traces.rs` (storage), `crates/ui/src/trace_view.rs` (cards), `crates/domain/src/trace.rs` (format).
10+- No fs or terminal capability (#18): `initialize_request` in `crates/acp/src/worker.rs`, explanation in `docs/*/explanation/client-capabilities.md` and `capacites-du-client.md`.
11+- Settings panel (`crates/ui/src/settings_panel.rs`) and the folder browser (#20: `folders.rs`, `folder_browser.rs`).
12+
13+## In flight
14+
15+Nothing is half done. Tickets #14, #15, #17, #18 and #20 are ticked and commented but left open for the user to close. In #18 two boxes stay unticked on purpose (see its comment).
16+
17+## Next steps
18+
19+1. Ask the user to run the application and report: do the cards (tool calls, plans), the Settings panel and the folder browser look right? Does a real agent (mini-me) send `tool_call` and `plan` updates, and are they readable?
20+2. Before the user first starts the new version, suggest copying their database file (see `docs/en/reference/database.md` for its place): migration 3 rebuilds the `message` table and was tested only on in-memory data.
21+3. Ask the user to confirm the #18 decision (no fs and no terminal for agents), then close #18.
22+4. v0.3.0 is #16 (agents registering themselves): research, no code yet.
23+5. Ideas that came up and were not asked for: arrow-key navigation in the suggestion list; keeping the unfolded state of tool cards across a restart; resending the context after `/new`; reducing `controller.rs` further (complexity 30, 1,700 lines with its tests).
24+
25+## Open questions / blockers
26+
27+- #18 (no capabilities) is a decision I recommended; the user did not explicitly confirm it.
28+- Whether `Chain depth` 3 and `Messages of context` 20 are good defaults is a guess until the user tries them with a real model.
29+
30+## Watch out for
31+
32+- A turn that ends after `Stop` calls nobody, by design (`stop_requested`): do not "fix" a test that expects a relay after a stop.
33+- `Author` has a fourth variant, `Trace(AgentName)`: any new `match` on it must decide what a trace is (context and follow-ups ignore it).
34+- A mutation check with several `--test` arguments needs `--no-fail-fast`, or only the first failing binary is seen.
35+- After restoring a file from a mutation, `touch` it (stale cargo build seen before).
36+- `app.rs` is at complexity 40 of 60: new logic goes in a new module, as `dock.rs`, `suggestions.rs`, `folder_browser.rs`, `settings_panel.rs` and `trace_view.rs` did.
modified .memory/history.md +36 -0
@@ -96,3 +96,39 @@ Append only. One dated entry per session. Never rewrite past entries.
9696 - **Quality**: the gate FAILED once (run 12): `app.rs` reached a file complexity of 58 with my additions. It was fixed by splitting the file into `dock.rs`, `suggestions.rs` and the rest, not by touching the gate; run 13 PASS, same 361 tests.
9797 - **Not verified**: how the list, the chips and the copy buttons look; whether the usual copy shortcut works on a mouse selection in a message.
9898 - **Pitfall**: a first mutation script died on an assertion halfway and left the first mutation applied while I thought none was; read the output, not only the exit.
99+
100+## 2026-10-23 — Milestone v0.2.0 and the folder browser (#20)
101+
102+- **Goal**: After the user committed v0.1.0 and said "vas y", they chose (asked once) the whole of v0.2.0 including #18, and an in-app list of folders for their own ticket #20 (choosing the working folder of an agent).
103+- **Changes**: `domain::{context, settings, trace}`, `Author::Trace`; repository `load_settings`/`save_settings`; schema migrations 2 (`setting`) and 3 (message table rebuilt to allow the `trace` author kind); ACP: `updates.rs` translating every `session/update` (tool calls, plans, notices, degraded content), new events, `initialize_request` pinned to no capability; the controller split into `controller/{prompts,relay,traces}.rs` (context given to each agent and what it has already seen, agents calling agents with depth limit and stop, traces); UI: Settings panel, tool-call and plan cards that fold, folder browser in the agent form; the test agent got `tools`; docs EN+FR (settings, channel context, tool calls and plans, how-to let agents call each other, explanations on agents calling agents and on client capabilities, folder browser in the declaration pages, index, architecture, database, tests how-to), crate READMEs, tickets #14, #15, #17, #18, #20 ticked and commented (none closed).
104+- **Decisions**: a chain's limit is a depth (default 3, 0 forbids) rather than loop detection or a budget; an agent is called when the calling turn ends normally, with its whole answer; a stop marks the turns so that late answers call nobody; tool calls and plans are stored as messages (migration 3) rather than kept in memory, so history and order survive; context of a message stops before the first message of the calling turn; a context limit of 0 says nothing at all; #18: announce nothing (recommended by me, not explicitly confirmed by the user); folder browser in-app, not the OS dialog.
105+- **Tests**: 501 passing (was 361). New test files `crates/ui/tests/{conversation,folder_browser,settings_and_traces}.rs`; helpers moved to `tests/support/mod.rs`. Mutations caught: 12 on the controller logic (self-mention, limit off by one, stop not remembered, `seen` not recorded, answer segment not closed, own messages not skipped, context not cut before the turn, relay on a failed turn, depth 0, tools kept across turns, plan always new, update posting instead of updating), 5 on the windows, 2 on the folder browser.
106+- **Quality**: the gate FAILED once (run 14: 3 smells: a function with 7 parameters, one with 6 returns, one with 6 parameters). Fixed in the code (a `Colours` struct, a `Handover` struct, a `Behaviour` enum in the test agent), not in the config; run 15 PASS, 0 smells, complexity 380.
107+- **Not verified**: how any of the new screens looks; a real agent with any v0.2.0 feature; the migration on a real database file.
108+- **Pitfalls met**: `cargo test --test a --test b` stops at the first failing test binary (use `--no-fail-fast` when checking a mutation); two window-test helpers took `&'static str` ids, so run-time ids were leaked in the tests; with `test-support` enabled `.test_support()` returns a different type (`Observed<...>`), so helpers returning a `Stateful<Div>` compile in the normal build and fail in the test build: return `AnyElement`.
109+
110+## 2026-10-23 — Only the leading mentions address (after the first test of v0.2.0)
111+
112+- **Goal**: The user tried `@bob salue @mouse` with two real agents: both were called (every mention was a recipient), `mouse` greeted itself and `bob` greeted both. They chose, when asked, that only the mentions the text starts with address.
113+- **Changes**: `addressed_mentions` and `leading_mentions` in `crates/domain/src/mention.rs`, used by `resolve_mentions`; mentions reference in both languages.
114+- **Decisions**: kept one rule everywhere (user messages, follow-ups, agents' answers) instead of one for the user and another for agents; separators of leading mentions are spaces and commas only, so `@bob and @mouse` addresses bob alone (documented, not hidden). Rejected: telling each recipient who else was addressed; changing nothing.
115+- **Tests**: 514 passing (was 501). Mutation (back to all mentions) fails 9 tests. One test of mine (several mentions in an answer) encoded the old rule and was rewritten.
116+- **Not checked**: the diagnosis was inferred from the user's description and the code, not from their protocol log.
117+
118+## 2026-10-23 — Naming a file in the middle of a sentence with `$`
119+
120+- **Goal**: The user said `/file` works but wanted to use it in the middle of a sentence, like `@` for agents, and proposed `$`.
121+- **Changes**: `domain::file_reference` (pure), the suggestion list opens the file list for a `$` being typed and a pick writes the path into the sentence and attaches the file; the stored message no longer repeats an attached file that its text names; docs in both languages (reference and how-to), domain README.
122+- **Decisions**: the path is written in the sentence AND the file is attached (the agent gets the words and the link); `$` glued to a word (`US$5`) is not a trigger; one query without spaces (unlike `/file`, which takes several words); no refusal to send with an unfinished `$`.
123+- **Tests**: 536 passing (was 514); 4 mutations caught.
124+- **Not verified**: how it looks and feels in the real window; a path that contains spaces is written as it is in the sentence.
125+
126+## 2026-10-23 — Arrow keys in the suggestion list
127+
128+- **Goal**: The user noticed that the lists (agents, commands, files) could not be walked with the arrow keys.
129+- **Changes**: `selected_suggestion` and `suggestion_navigated` in the app state, `handle_list_key` and the pure `moved_selection` in `suggestions.rs`, the Tab interceptor of `app.rs` became a general key interceptor (Tab, Up, Down, Enter, Escape), the highlighted row in `view.rs` follows the selection; docs in both languages (a keyboard section in the commands and files reference, mentions, how-to).
130+- **Decisions**: Enter takes the highlighted row only after the arrows were used, so the habit of pressing Enter to send a message that happens to end with `@` or `$` is not broken (rejected: Enter always taking the row, as Claude Code does); arrows wrap at both ends; Escape closes the list without clearing the text; keys with a modifier are left alone.
131+- **Tests**: 552 passing (was 536), new file `crates/ui/tests/suggestion_keys.rs`; 6 mutations caught.
132+- **Pitfall**: my first test of Escape pressed Tab afterwards and expected to keep typing, but with no list open Tab moves the focus out of the box, which is intended; the test was wrong, not the code.
133+- **Not verified**: the feel in the real window, and that the highlight is visible enough.
134+
@@ -96,3 +96,39 @@ Append only. One dated entry per session. Never rewrite past entries.
96 - **Quality**: the gate FAILED once (run 12): `app.rs` reached a file complexity of 58 with my additions. It was fixed by splitting the file into `dock.rs`, `suggestions.rs` and the rest, not by touching the gate; run 13 PASS, same 361 tests.96 - **Quality**: the gate FAILED once (run 12): `app.rs` reached a file complexity of 58 with my additions. It was fixed by splitting the file into `dock.rs`, `suggestions.rs` and the rest, not by touching the gate; run 13 PASS, same 361 tests.
97 - **Not verified**: how the list, the chips and the copy buttons look; whether the usual copy shortcut works on a mouse selection in a message.97 - **Not verified**: how the list, the chips and the copy buttons look; whether the usual copy shortcut works on a mouse selection in a message.
98 - **Pitfall**: a first mutation script died on an assertion halfway and left the first mutation applied while I thought none was; read the output, not only the exit.98 - **Pitfall**: a first mutation script died on an assertion halfway and left the first mutation applied while I thought none was; read the output, not only the exit.
99+
100+## 2026-10-23 — Milestone v0.2.0 and the folder browser (#20)
101+
102+- **Goal**: After the user committed v0.1.0 and said "vas y", they chose (asked once) the whole of v0.2.0 including #18, and an in-app list of folders for their own ticket #20 (choosing the working folder of an agent).
103+- **Changes**: `domain::{context, settings, trace}`, `Author::Trace`; repository `load_settings`/`save_settings`; schema migrations 2 (`setting`) and 3 (message table rebuilt to allow the `trace` author kind); ACP: `updates.rs` translating every `session/update` (tool calls, plans, notices, degraded content), new events, `initialize_request` pinned to no capability; the controller split into `controller/{prompts,relay,traces}.rs` (context given to each agent and what it has already seen, agents calling agents with depth limit and stop, traces); UI: Settings panel, tool-call and plan cards that fold, folder browser in the agent form; the test agent got `tools`; docs EN+FR (settings, channel context, tool calls and plans, how-to let agents call each other, explanations on agents calling agents and on client capabilities, folder browser in the declaration pages, index, architecture, database, tests how-to), crate READMEs, tickets #14, #15, #17, #18, #20 ticked and commented (none closed).
104+- **Decisions**: a chain's limit is a depth (default 3, 0 forbids) rather than loop detection or a budget; an agent is called when the calling turn ends normally, with its whole answer; a stop marks the turns so that late answers call nobody; tool calls and plans are stored as messages (migration 3) rather than kept in memory, so history and order survive; context of a message stops before the first message of the calling turn; a context limit of 0 says nothing at all; #18: announce nothing (recommended by me, not explicitly confirmed by the user); folder browser in-app, not the OS dialog.
105+- **Tests**: 501 passing (was 361). New test files `crates/ui/tests/{conversation,folder_browser,settings_and_traces}.rs`; helpers moved to `tests/support/mod.rs`. Mutations caught: 12 on the controller logic (self-mention, limit off by one, stop not remembered, `seen` not recorded, answer segment not closed, own messages not skipped, context not cut before the turn, relay on a failed turn, depth 0, tools kept across turns, plan always new, update posting instead of updating), 5 on the windows, 2 on the folder browser.
106+- **Quality**: the gate FAILED once (run 14: 3 smells: a function with 7 parameters, one with 6 returns, one with 6 parameters). Fixed in the code (a `Colours` struct, a `Handover` struct, a `Behaviour` enum in the test agent), not in the config; run 15 PASS, 0 smells, complexity 380.
107+- **Not verified**: how any of the new screens looks; a real agent with any v0.2.0 feature; the migration on a real database file.
108+- **Pitfalls met**: `cargo test --test a --test b` stops at the first failing test binary (use `--no-fail-fast` when checking a mutation); two window-test helpers took `&'static str` ids, so run-time ids were leaked in the tests; with `test-support` enabled `.test_support()` returns a different type (`Observed<...>`), so helpers returning a `Stateful<Div>` compile in the normal build and fail in the test build: return `AnyElement`.
109+
110+## 2026-10-23 — Only the leading mentions address (after the first test of v0.2.0)
111+
112+- **Goal**: The user tried `@bob salue @mouse` with two real agents: both were called (every mention was a recipient), `mouse` greeted itself and `bob` greeted both. They chose, when asked, that only the mentions the text starts with address.
113+- **Changes**: `addressed_mentions` and `leading_mentions` in `crates/domain/src/mention.rs`, used by `resolve_mentions`; mentions reference in both languages.
114+- **Decisions**: kept one rule everywhere (user messages, follow-ups, agents' answers) instead of one for the user and another for agents; separators of leading mentions are spaces and commas only, so `@bob and @mouse` addresses bob alone (documented, not hidden). Rejected: telling each recipient who else was addressed; changing nothing.
115+- **Tests**: 514 passing (was 501). Mutation (back to all mentions) fails 9 tests. One test of mine (several mentions in an answer) encoded the old rule and was rewritten.
116+- **Not checked**: the diagnosis was inferred from the user's description and the code, not from their protocol log.
117+
118+## 2026-10-23 — Naming a file in the middle of a sentence with `$`
119+
120+- **Goal**: The user said `/file` works but wanted to use it in the middle of a sentence, like `@` for agents, and proposed `$`.
121+- **Changes**: `domain::file_reference` (pure), the suggestion list opens the file list for a `$` being typed and a pick writes the path into the sentence and attaches the file; the stored message no longer repeats an attached file that its text names; docs in both languages (reference and how-to), domain README.
122+- **Decisions**: the path is written in the sentence AND the file is attached (the agent gets the words and the link); `$` glued to a word (`US$5`) is not a trigger; one query without spaces (unlike `/file`, which takes several words); no refusal to send with an unfinished `$`.
123+- **Tests**: 536 passing (was 514); 4 mutations caught.
124+- **Not verified**: how it looks and feels in the real window; a path that contains spaces is written as it is in the sentence.
125+
126+## 2026-10-23 — Arrow keys in the suggestion list
127+
128+- **Goal**: The user noticed that the lists (agents, commands, files) could not be walked with the arrow keys.
129+- **Changes**: `selected_suggestion` and `suggestion_navigated` in the app state, `handle_list_key` and the pure `moved_selection` in `suggestions.rs`, the Tab interceptor of `app.rs` became a general key interceptor (Tab, Up, Down, Enter, Escape), the highlighted row in `view.rs` follows the selection; docs in both languages (a keyboard section in the commands and files reference, mentions, how-to).
130+- **Decisions**: Enter takes the highlighted row only after the arrows were used, so the habit of pressing Enter to send a message that happens to end with `@` or `$` is not broken (rejected: Enter always taking the row, as Claude Code does); arrows wrap at both ends; Escape closes the list without clearing the text; keys with a modifier are left alone.
131+- **Tests**: 552 passing (was 536), new file `crates/ui/tests/suggestion_keys.rs`; 6 mutations caught.
132+- **Pitfall**: my first test of Escape pressed Tab afterwards and expected to keep typing, but with no list open Tab moves the focus out of the box, which is intended; the test was wrong, not the code.
133+- **Not verified**: the feel in the real window, and that the highlight is visible enough.
134+
modified .memory/summary.md +21 -12
@@ -1,12 +1,12 @@
11 # Synedrion — project summary
22
3-Last updated: 2026-10-23 (milestone v0.1.0 built).
3+Last updated: 2026-10-23 (milestones v0.1.0 and v0.2.0 built).
44
55 ## What it is
66
77 A desktop application, written in Rust with GPUI Kit, that works like Slack or Discord but whose participants are external AI agents speaking the Agent Client Protocol (ACP), plus the single human who uses the machine. Channels have no public or private distinction. Agents are addressed with `@agent_name`. The application's own text is English. The author is a beginner in Rust, so code must be easy to read. The full request is ticket #1 in `.tickets/issues/0001-initialize-why.yaml`.
88
9-**State: version 0.1.0 is built and tested, but has never been seen on a screen and has never talked to a real agent. Nothing is committed yet. The quality gate passes, with a limit (see "Not yet established").**
9+**State: the features of v0.1.0 and v0.2.0 are built and tested. The user has run the application with the real mini-me for the v0.1.0 features; I have never seen the window; the v0.2.0 features (context, agents calling agents, tool calls and plans, settings panel, folder browser) have only run against the test agent and in headless windows, and the user has not tried them yet. The user committed after v0.1.0 (the history holds at least `0502ed3`). The quality gate passes, with a limit (see "Not yet established").**
1010
1111 ## Decisions in force
1212
@@ -16,26 +16,32 @@ Decided with the user on 2026-10-23. Each one is detailed in the tickets and in
1616 - Agents are declared by hand (name, command, args, env, working folder), stored in the database and edited from the interface (#8). The `AgentRegistry` trait planned in #8 was NOT built: declarations go through `Repository`, which is where a registration source would plug in (#16).
1717 - A sandboxed agent is launched with `sbx exec`, and ACP travels over its stdio (#8).
1818 - One ACP session per pair of agent and channel (#12).
19-- A mentioned agent receives the recent channel messages, not only the mention (#14, v0.2.0). Until #14 is done the prompt carries only the mentioning message.
20-- Agents may mention each other, with a maximum chain depth and a stop button (#15, v0.2.0).
19+- A mentioned agent receives what it has not seen of the channel, then the message (#14, built): `domain::context` (`select_context`, `render_prompt`) is pure; the controller keeps, per agent and channel, the last message handed over (`seen`, in memory); the agent's own messages, system notices and traces are left out; at most N messages (setting `context_messages`, default 20, 0 to 100, 0 means none), 2,000 characters per message and 12,000 in all, with markers when cut. A bare slash command gets no context. A user message with nothing to add goes as typed.
20+- Agents may mention each other, with a maximum chain depth and a stop button (#15, built): when a turn ends normally and was not stopped, the declared agents mentioned in its whole answer (self excluded, each once) are handed `[Message from @name]` + the answer, one hop deeper; setting `chain_depth` (default 3, 0 to 10, 0 forbids it silently); beyond it a system message says `Chain stopped: …`; Stop cancels every turn of the channel and answers arriving afterwards call nobody (`stop_requested`). Code in `crates/ui/src/controller/relay.rs`.
21+- What an agent does besides writing is part of the history (#17, built): tool calls and plans are stored as messages of author kind `trace` (schema version 3 rebuilt the `message` table to allow it), in a plain text format (`domain::trace`), updated in place by id, forgotten at turn end; text written after a trace starts a new message; traces are not context for other agents and do not set follow-up recipients. `session/update` is translated by the pure function `crates/acp/src/updates.rs`; what cannot be drawn becomes a bracketed note, an unknown update a notice; usage, mode, config, session info, compaction and the echo of the user's message are deliberately not shown. Drawn as cards in `crates/ui/src/trace_view.rs` (tool calls fold and unfold, state in memory).
22+- Synedrion announces NO fs or terminal client capability to agents (#18): a sandbox exists to keep an agent from the host, and these services would be a hole in it. A unit test pins it (`initialize_request`). I recommended this and the user included #18 in the work without objecting, but did not confirm it explicitly: ask before treating it as final.
2123 - ACP client: the official `agent-client-protocol` crate, version 3.5.0, protocol v1. It needs no async runtime (it uses `async-io`; tokio is only in its own tests), so each agent runs on its own thread inside `AgentHub` and events reach the window through a queue (#3, #12).
2224 - Interface: GPUI Kit 0.8.0 (on GPUI 0.3.9). Its site lists no chat component but `gpui-component` has `MessageScroller`, `Bubble`, `Message` and `Textarea`; the app uses the scroller, `Textarea`, `Input` and `Button` (not `Bubble`). All rules live in a window-free `ChatController` (`crates/ui/src/controller.rs`); the windows only draw.
23-- Window layout (user feedback of 2026-10-23, after a first real test; the user asked for vertical dock panels "like Zed", chose a dock at the left, several panels open side by side, width draggable): a bar of three icon buttons at the left edge (Channels `Hash`, Channel settings `Settings`, Agents `Bot`) opens and closes vertical full-height panels beside the conversation (each panel also has an x in its title that closes it); only Channels is open at first; the dock is one block whose edge is dragged (`resize_handle` of GPUI Kit, followed with `on_drag_move`), it widens by itself so that each open panel has at least `MIN_DOCK_WIDTH` (220 px), and the whole dock disappears when no panel is open. There is no separate agents screen any more: the Agents panel holds the agents with their status, Edit and Delete, and the declaration form. State: `Panel`/`OpenPanels`/`dock_width_*` in `crates/ui/src/app.rs`, drawing in `view.rs`. Channel rows are drawn by hand (left-aligned). Tab completes a mention with the first proposal, through `cx.intercept_keystrokes` (see handoff for why).
25+- Window layout (user feedback of 2026-10-23, after a first real test; the user asked for vertical dock panels "like Zed", chose a dock at the left, several panels open side by side, width draggable): a bar of four icon buttons at the left edge (Channels `Hash`, Channel settings `Settings`, Agents `Bot`, Settings `SlidersHorizontal`) opens and closes vertical full-height panels beside the conversation (each panel also has an x in its title that closes it); only Channels is open at first; the dock is one block whose edge is dragged (`resize_handle` of GPUI Kit, followed with `on_drag_move`), it widens by itself so that each open panel has at least `MIN_DOCK_WIDTH` (220 px), and the whole dock disappears when no panel is open. There is no separate agents screen any more: the Agents panel holds the agents with their status, Edit and Delete, and the declaration form. State: `Panel`/`OpenPanels`/`dock_width_*` in `crates/ui/src/dock.rs`, drawing in `view.rs`; the Settings panel is `settings_panel.rs`. Channel rows are drawn by hand (left-aligned). Tab completes a mention with the highlighted proposal, through `cx.intercept_keystrokes` (see handoff for why).
2426 - While an agent works in the active channel, a card shows a spinner and its reasoning as it streams in (`Thought` events from ACP thought chunks; the last 700 characters; kept in memory by the controller, never stored, forgotten when the turn ends). The arguments and environment fields of the agent form are 5 to 14 lines tall (`AGENT_FIELD_ROWS`). Setting `SYNEDRION_ACP_LOG=/path/file` logs every line exchanged with every agent (see `protocol_log.rs`).
27+- Who a message addresses (decided with the user on 2026-10-23, after they sent `@bob salue @mouse` and both agents were called): if the text starts with mentions (separated by spaces or commas), only those address; otherwise every mention does. `@bob salue @mouse` is for bob only; `@bob and @mouse ...` is also bob only (the word `and` ends the leading mentions; stated in the docs). One rule in `resolve_mentions` serves user messages, follow-up recipients and agents' answers (relay). A name only talked about raises no "unknown agent" notice.
28+- Files in a sentence (asked by the user on 2026-10-23: `@` and `/` being taken, `$`): `$` + the beginning of a name, being typed at the end of the text and not glued to a word, opens the `/file` list (same folder, same search); Tab or a click replaces `$query` with the relative path and a space, and attaches the file as `/file` does. The stored message skips the `[attached: …]` line of a file its text already names. Pure part: `domain::file_reference`; the rest in `crates/ui/src/suggestions.rs`.
29+- Keyboard in the suggestion list (asked by the user on 2026-10-23): Up/Down move the highlight (wrapping), Tab takes the highlighted row, Enter takes it only once the arrows were used (otherwise Enter still sends, as before), Escape closes the list. One key interceptor (`handle_list_key` in `suggestions.rs`, installed in `app.rs`) handles all of it, only while the composer is focused and the list is open.
2530 - A message that mentions nobody goes on with the agents the user last addressed in the channel (`follow_up_recipients` in `crates/domain/src/mention.rs`, derived from the stored messages, so it survives a restart); mentioning another agent changes the recipients; a mention of an unknown name is not a follow-up. A line above the message box says who a plain message goes to. Decided with the user on 2026-10-23.
2631 - Slash commands (decided with the user on 2026-10-23): the `/` list offers the commands the recipients of the message announced through ACP (`AvailableCommandsUpdate`, kept per agent in the controller) plus Synedrion's own `/file`; a command typed after mentions is handed to the agent as the bare command (the agent recognises it only at the start), but only if the agent announced it or announced none yet. `/file` lists the files of the first recipient's working folder (or the current folder) through `FileIndex` (hidden files and `target`, `node_modules`, `__pycache__`, `dist`, `build` left out), Tab or a click attaches one as a chip above the message box, and each attachment goes to the agent as an ACP `resource_link` (`file://` + path, not percent-encoded, because mini-me strips the prefix); the stored message gets one `[attached: path]` line per file. Commands only appear after the agent's first session in the channel. Copy buttons: one per message (Markdown source) and one per code block (code alone), through GPUI Kit's `Clipboard`. Verified with the real mini-me: it announces `compact`, `new` and `unload`, answers `/new`, and its model receives `[attached file: path]`.
2732 - Agents' messages are drawn as Markdown (GPUI Kit's `TextView::markdown`, with its `syntect` highlighter for code blocks, chosen over tree-sitter to avoid compiling C grammars); the user's text and the notices stay plain. A test shows an agent's `# Title` is drawn taller than the same text typed by the user. Code colouring and emphasis have never been seen.
28-- A mention is sent to the agent as typed, the agent's answer is streamed into one message, the Stop button cancels every agent working in the channel, permission questions are cards in the channel (#10 to #13).
33+- The agent's answer is streamed into one message (a new one after each tool call or plan), the Stop button cancels every agent working in the channel, permission questions are cards in the channel (#10 to #13).
34+- The agent form has a folder browser (#20, the user's own ticket): `Browse…` under Working folder opens an in-app list of folders (`folders.rs` pure, `folder_browser.rs` window part), `..` up, click to enter, `Use this folder`, `Cancel`; it opens on the typed folder, else `HOME`; hidden folders omitted, 200 at most. I chose an in-app list over the operating system's dialog (testable and identical everywhere); the user agreed to that option when asked.
2935
3036 ## Layout of the repository
3137
3238 | Path | Content |
3339 | --- | --- |
34-| `.tickets/` | Tickets managed with IssueSpec: `issues/` (#1 to #19), `epics.yaml`, `milestones.yaml`, `labels.yaml`. Hand edits are welcome as long as the schema stays valid. Ticket #1 and its two tasks are closed (by the user). A closed state is written `closed`, and a closed task also carries `updatedAt` and `closedAt`. An issue links others with `related:` followed by a list of ids, and tickets #2 to #19 use it for their dependencies. |
40+| `.tickets/` | Tickets managed with IssueSpec: `issues/` (#1 to #20; #20 is the user's own idea, epic IDEAS), `epics.yaml`, `milestones.yaml`, `labels.yaml`. Hand edits are welcome as long as the schema stays valid. Ticket #1 and its two tasks are closed (by the user). A closed state is written `closed`, and a closed task also carries `updatedAt` and `closedAt`. An issue links others with `related:` followed by a list of ids, and tickets #2 to #19 use it for their dependencies. |
3541 | `crates/` | The four crates of the Cargo workspace: `domain` (types, rules, `Repository` trait, depends on nothing), `store` (`SqliteRepository`), `acp` (`AgentHub`, plus the test agent binary `synedrion-fake-agent`), `ui` (controller, windows, the `synedrion` program). Each has a `README.md` listing its API. |
3642 | `Cargo.toml`, `rustfmt.toml`, `.gitignore` | Workspace (edition 2024, `clippy::all` as warnings); `rustfmt.toml` states the edition because qlty runs rustfmt file by file; `/target` is ignored. `Cargo.lock` was regenerated once (see handoff) and is not ignored. |
3743 | `.qlty/`, `.quality/` | qlty configuration and the quality reports and history written by the `quality` skill. |
38-| `docs/` | Diátaxis documentation in `en/` and `fr/` (14 pages each: one tutorial, four how-to guides, five references, three explanations, an index), plus `diagrams/packages.drawio`. |
44+| `docs/` | Diátaxis documentation in `en/` and `fr/` (each language: one tutorial, nine how-to guides, ten references, five explanations, an index), plus `diagrams/packages.drawio`. |
3945 | `.memory/` | This record. |
4046 | `.claude/` | Instructions and skills (`methodical-dev`, `quality`, `diataxis-doc`, `drawio-fancy-diagram`). |
4147 | `git.sh` | Commit helper: `./git.sh <type> "<message>"` runs `git add .`, commit with an emoji prefix, and push. It stages everything. |
@@ -45,14 +51,14 @@ Roadmap: epics Foundations, ACP, Chat, UI, Persistence, Registration. Milestones
4551 ## How to build, test and run
4652
4753 - Build: `cargo build --workspace`. Run: `cargo run -p synedrion-ui --bin synedrion` (needs a display).
48-- Test, one command: `cargo test --workspace`. Lint and format: `cargo clippy --workspace --all-targets` and `cargo fmt --all -- --check`. Last result on 2026-10-23: 361 tests pass (unit, integration and doc), clippy and fmt clean.
54+- Test, one command: `cargo test --workspace`. Lint and format: `cargo clippy --workspace --all-targets` and `cargo fmt --all -- --check`. Last result on 2026-10-23: 552 tests pass (unit, integration and doc), clippy and fmt clean. The window tests are spread over `crates/ui/tests/{window,folder_browser,settings_and_traces}.rs`, and `tests/conversation.rs` drives the controller without a window (shared helpers in `tests/support/mod.rs`).
4955 - Quality gate: `python3 .claude/skills/quality/scripts/quality_report.py --workspace .` (the skill's text says `~/.claude/skills/...`, which does not exist here; the script is in the repository).
5056 - Linux build needs `pkg-config libfontconfig1-dev libxcb1-dev libxkbcommon-dev libxkbcommon-x11-dev` (installed with `sudo apt-get`; sudo is passwordless in this sandbox). Without a display, the binary panics inside GPUI ("failed to connect to Wayland compositor").
5157 - The toolchain is Rust 1.99.1 (rustup, `--profile minimal` with clippy and rustfmt) and qlty 0.662.0 (release archive, not the install script: that script sends telemetry and installs completions). Both are on the `PATH` through `/etc/sandbox-persistent.sh`. Steps are in `docs/en/how-to/set-up-the-sandbox.md`.
5258
5359 ## Test agent
5460
55-`synedrion-fake-agent` (in `crates/acp`) is the agent all automated tests and the tutorial use. Its keyword is the first word that is not a `@mention`: `ask`, `slow`, `crash`, anything else is echoed. It is built on the same ACP library as Synedrion, so it cannot show that a real agent behaves the same.
61+`synedrion-fake-agent` (in `crates/acp`) is the agent all automated tests and the tutorial use. Its keyword is the first word that is not a `@mention`: `ask`, `slow`, `crash`, `think`, `tools` (a plan, a tool call and its completion), anything else is echoed; it also announces the commands `new` and `greet`. It is built on the same ACP library as Synedrion, so it cannot show that a real agent behaves the same.
5662
5763 mini-me, a Go ACP agent for local models, run with `mm -acp` and its configuration either as `-config <absolute path>` (the user's command: `mm -acp -config /Users/k33g/docker-working/agent.gemma.yaml`, one word per line of the Arguments field) or in the variable `AGENT_CONFIG`. The suggested test model is `unsloth/Qwen3.5-4B-GGUF`. Source: `https://rickub.com/bots-garden/mini-me`. The user has used it with Synedrion (first real test, 2026-10-23). It can also be built here: its source archive is `https://rickub.com/bots-garden/mini-me/archive/main.zip` and Go is installed (`go build`); a fake OpenAI-compatible model server (any small streaming SSE server answering `/v1/chat/completions`, with `reasoning_content` deltas) is enough to drive it.
5864
@@ -62,9 +68,12 @@ mini-me, a Go ACP agent for local models, run with `mm -acp` and its configurati
6268 - **The window had never been displayed by me.** The sandbox has no display. Behaviour is covered by 62 headless GPUI Kit window tests (found by identifier, clicked, typed into); looks, light and dark themes, the "active channel" highlight and the scroll-follows-latest behaviour are unverified.
6369 - **mini-me works against Synedrion in my reproduction, but the user reports that their agent answered only once.** With the real `mm` binary (built from source) and a fake streaming model, two successive prompts to the same session were both answered, both through the ACP client and through the controller. The cause of what the user saw is NOT established. Leading hypothesis (confirmed in effect: the user answered that it works, and asked that conversations go on without retyping the name, now built): the second message did not mention the agent. Other possibilities: the model or its config (tools, `yolo: false`, an error), or something only the real window shows. The protocol log (`SYNEDRION_ACP_LOG`) exists to settle it.
6470 - **`sbx exec` syntax** (options, interactive stdin, environment variables, path of `AGENT_CONFIG` inside the sandbox) is unverified because `sbx` is not installed in the sandbox. An earlier ticket draft invented a `-i` flag, which was removed.
65-- **The quality gate PASSES (runs 3 and 4: 0 smells, complexity 195, 205, then 207) because the user decided on 2026-10-23 to exclude `.claude/**`.** That hid 11 smells in the kit's scripts (`quality_report.py`, `build_deck.js`), recorded in a comment next to the pattern in `.qlty/qlty.toml`. None was ever in `crates/`. The pass is weaker than it looks: see the next point.
71+- **The quality gate PASSES (latest run 15: 0 smells, complexity 380; earlier runs 3 and 4: complexity 195, 205) because the user decided on 2026-10-23 to exclude `.claude/**`.** That hid 11 smells in the kit's scripts (`quality_report.py`, `build_deck.js`), recorded in a comment next to the pattern in `.qlty/qlty.toml`. None was ever in `crates/`. The pass is weaker than it looks: see the next point.
6672 - **`clippy` through qlty reports nothing even when it should, so the gate's lint count comes from `rustfmt` alone.** A deliberate `needless_return` was missing from `qlty check`'s output although the plugin's own captured output contained it; cause not found, even with `mode = "block"`. `rustfmt` through qlty does work (a deliberate mistake was reported). `cargo clippy` run directly is clean and is the reliable check.
6773 - **`qlty init` enabled no plugin** (probably because no file is tracked by git: there is no commit; not confirmed), so the first "0 lint issues" meant nothing. `clippy` and `rustfmt` were added by hand in `.qlty/qlty.toml`, with `[runtimes.enabled] rust = "1.99.1"` (qlty's default Rust 1.77.2 cannot read an edition 2024 manifest). `qlty plugins enable` did nothing, silently. Other qlty plugins (markdownlint, yamllint, shellcheck...) are not enabled: markdownlint would flag the project's deliberately unwrapped paragraphs.
68-- **Whether fs and terminal client capabilities are exposed to agents** (#18). Today none is.
74+- **Whether the decision not to expose fs and terminal capabilities (#18) is the user's final word.** It is built that way and documented; see "Decisions in force". mini-me answers without them, but its own bash tool was not exercised.
75+- **The v0.2.0 features were never run against a real agent or seen on a screen**: the context given to agents, agents calling agents, tool call and plan cards (and the colour of a failed one), the settings panel, the folder browser. Whether mini-me sends `tool_call` and `plan` updates, and what they look like, is unknown. The rebuilt `message` table (migration 3) was tested only on an in-memory copy of a version 1 database, not on the user's real file: it is worth keeping a copy of their database before they first start the new version.
76+- **Known limits of the context record** (documented in `docs/en/reference/channel-context.md`): `seen` is in memory, so after a Synedrion restart each agent is told the latest messages again; if an agent's process restarts while Synedrion runs, or after `/new` or `/compact`, what was already handed over is not sent again.
77+- **A tool call that updates an agent's turn after it ended** is not specified: the controller forgets calls at turn end, so such an update would make a card titled `Tool call`.
6978 - **Whether IssueSpec accepts tickets #2 to #19.** They use a `milestone:` field copied by convention, which no existing file confirmed, and no YAML parser was available to validate them. The only evidence is indirect: the user wrote `related: [2]` in ticket #1, which suggests ticket #2 is recognised.
7079 - A prompt sent to an agent immediately after it crashed can still fail instead of restarting it in a very small window (a turn can be reported failed by the dying worker just before its queue is closed). The common path is covered by tests and does restart.
@@ -1,12 +1,12 @@
1 # Synedrion — project summary1 # Synedrion — project summary
2 2
3-Last updated: 2026-10-23 (milestone v0.1.0 built).3+Last updated: 2026-10-23 (milestones v0.1.0 and v0.2.0 built).
4 4
5 ## What it is5 ## What it is
6 6
7 A desktop application, written in Rust with GPUI Kit, that works like Slack or Discord but whose participants are external AI agents speaking the Agent Client Protocol (ACP), plus the single human who uses the machine. Channels have no public or private distinction. Agents are addressed with `@agent_name`. The application's own text is English. The author is a beginner in Rust, so code must be easy to read. The full request is ticket #1 in `.tickets/issues/0001-initialize-why.yaml`.7 A desktop application, written in Rust with GPUI Kit, that works like Slack or Discord but whose participants are external AI agents speaking the Agent Client Protocol (ACP), plus the single human who uses the machine. Channels have no public or private distinction. Agents are addressed with `@agent_name`. The application's own text is English. The author is a beginner in Rust, so code must be easy to read. The full request is ticket #1 in `.tickets/issues/0001-initialize-why.yaml`.
8 8
9-**State: version 0.1.0 is built and tested, but has never been seen on a screen and has never talked to a real agent. Nothing is committed yet. The quality gate passes, with a limit (see "Not yet established").**9+**State: the features of v0.1.0 and v0.2.0 are built and tested. The user has run the application with the real mini-me for the v0.1.0 features; I have never seen the window; the v0.2.0 features (context, agents calling agents, tool calls and plans, settings panel, folder browser) have only run against the test agent and in headless windows, and the user has not tried them yet. The user committed after v0.1.0 (the history holds at least `0502ed3`). The quality gate passes, with a limit (see "Not yet established").**
10 10
11 ## Decisions in force11 ## Decisions in force
12 12
@@ -16,26 +16,32 @@ Decided with the user on 2026-10-23. Each one is detailed in the tickets and in
16 - Agents are declared by hand (name, command, args, env, working folder), stored in the database and edited from the interface (#8). The `AgentRegistry` trait planned in #8 was NOT built: declarations go through `Repository`, which is where a registration source would plug in (#16).16 - Agents are declared by hand (name, command, args, env, working folder), stored in the database and edited from the interface (#8). The `AgentRegistry` trait planned in #8 was NOT built: declarations go through `Repository`, which is where a registration source would plug in (#16).
17 - A sandboxed agent is launched with `sbx exec`, and ACP travels over its stdio (#8).17 - A sandboxed agent is launched with `sbx exec`, and ACP travels over its stdio (#8).
18 - One ACP session per pair of agent and channel (#12).18 - One ACP session per pair of agent and channel (#12).
19-- A mentioned agent receives the recent channel messages, not only the mention (#14, v0.2.0). Until #14 is done the prompt carries only the mentioning message.19+- A mentioned agent receives what it has not seen of the channel, then the message (#14, built): `domain::context` (`select_context`, `render_prompt`) is pure; the controller keeps, per agent and channel, the last message handed over (`seen`, in memory); the agent's own messages, system notices and traces are left out; at most N messages (setting `context_messages`, default 20, 0 to 100, 0 means none), 2,000 characters per message and 12,000 in all, with markers when cut. A bare slash command gets no context. A user message with nothing to add goes as typed.
20-- Agents may mention each other, with a maximum chain depth and a stop button (#15, v0.2.0).20+- Agents may mention each other, with a maximum chain depth and a stop button (#15, built): when a turn ends normally and was not stopped, the declared agents mentioned in its whole answer (self excluded, each once) are handed `[Message from @name]` + the answer, one hop deeper; setting `chain_depth` (default 3, 0 to 10, 0 forbids it silently); beyond it a system message says `Chain stopped: …`; Stop cancels every turn of the channel and answers arriving afterwards call nobody (`stop_requested`). Code in `crates/ui/src/controller/relay.rs`.
21+- What an agent does besides writing is part of the history (#17, built): tool calls and plans are stored as messages of author kind `trace` (schema version 3 rebuilt the `message` table to allow it), in a plain text format (`domain::trace`), updated in place by id, forgotten at turn end; text written after a trace starts a new message; traces are not context for other agents and do not set follow-up recipients. `session/update` is translated by the pure function `crates/acp/src/updates.rs`; what cannot be drawn becomes a bracketed note, an unknown update a notice; usage, mode, config, session info, compaction and the echo of the user's message are deliberately not shown. Drawn as cards in `crates/ui/src/trace_view.rs` (tool calls fold and unfold, state in memory).
22+- Synedrion announces NO fs or terminal client capability to agents (#18): a sandbox exists to keep an agent from the host, and these services would be a hole in it. A unit test pins it (`initialize_request`). I recommended this and the user included #18 in the work without objecting, but did not confirm it explicitly: ask before treating it as final.
21 - ACP client: the official `agent-client-protocol` crate, version 3.5.0, protocol v1. It needs no async runtime (it uses `async-io`; tokio is only in its own tests), so each agent runs on its own thread inside `AgentHub` and events reach the window through a queue (#3, #12).23 - ACP client: the official `agent-client-protocol` crate, version 3.5.0, protocol v1. It needs no async runtime (it uses `async-io`; tokio is only in its own tests), so each agent runs on its own thread inside `AgentHub` and events reach the window through a queue (#3, #12).
22 - Interface: GPUI Kit 0.8.0 (on GPUI 0.3.9). Its site lists no chat component but `gpui-component` has `MessageScroller`, `Bubble`, `Message` and `Textarea`; the app uses the scroller, `Textarea`, `Input` and `Button` (not `Bubble`). All rules live in a window-free `ChatController` (`crates/ui/src/controller.rs`); the windows only draw.24 - Interface: GPUI Kit 0.8.0 (on GPUI 0.3.9). Its site lists no chat component but `gpui-component` has `MessageScroller`, `Bubble`, `Message` and `Textarea`; the app uses the scroller, `Textarea`, `Input` and `Button` (not `Bubble`). All rules live in a window-free `ChatController` (`crates/ui/src/controller.rs`); the windows only draw.
23-- Window layout (user feedback of 2026-10-23, after a first real test; the user asked for vertical dock panels "like Zed", chose a dock at the left, several panels open side by side, width draggable): a bar of three icon buttons at the left edge (Channels `Hash`, Channel settings `Settings`, Agents `Bot`) opens and closes vertical full-height panels beside the conversation (each panel also has an x in its title that closes it); only Channels is open at first; the dock is one block whose edge is dragged (`resize_handle` of GPUI Kit, followed with `on_drag_move`), it widens by itself so that each open panel has at least `MIN_DOCK_WIDTH` (220 px), and the whole dock disappears when no panel is open. There is no separate agents screen any more: the Agents panel holds the agents with their status, Edit and Delete, and the declaration form. State: `Panel`/`OpenPanels`/`dock_width_*` in `crates/ui/src/app.rs`, drawing in `view.rs`. Channel rows are drawn by hand (left-aligned). Tab completes a mention with the first proposal, through `cx.intercept_keystrokes` (see handoff for why).25+- Window layout (user feedback of 2026-10-23, after a first real test; the user asked for vertical dock panels "like Zed", chose a dock at the left, several panels open side by side, width draggable): a bar of four icon buttons at the left edge (Channels `Hash`, Channel settings `Settings`, Agents `Bot`, Settings `SlidersHorizontal`) opens and closes vertical full-height panels beside the conversation (each panel also has an x in its title that closes it); only Channels is open at first; the dock is one block whose edge is dragged (`resize_handle` of GPUI Kit, followed with `on_drag_move`), it widens by itself so that each open panel has at least `MIN_DOCK_WIDTH` (220 px), and the whole dock disappears when no panel is open. There is no separate agents screen any more: the Agents panel holds the agents with their status, Edit and Delete, and the declaration form. State: `Panel`/`OpenPanels`/`dock_width_*` in `crates/ui/src/dock.rs`, drawing in `view.rs`; the Settings panel is `settings_panel.rs`. Channel rows are drawn by hand (left-aligned). Tab completes a mention with the highlighted proposal, through `cx.intercept_keystrokes` (see handoff for why).
24 - While an agent works in the active channel, a card shows a spinner and its reasoning as it streams in (`Thought` events from ACP thought chunks; the last 700 characters; kept in memory by the controller, never stored, forgotten when the turn ends). The arguments and environment fields of the agent form are 5 to 14 lines tall (`AGENT_FIELD_ROWS`). Setting `SYNEDRION_ACP_LOG=/path/file` logs every line exchanged with every agent (see `protocol_log.rs`).26 - While an agent works in the active channel, a card shows a spinner and its reasoning as it streams in (`Thought` events from ACP thought chunks; the last 700 characters; kept in memory by the controller, never stored, forgotten when the turn ends). The arguments and environment fields of the agent form are 5 to 14 lines tall (`AGENT_FIELD_ROWS`). Setting `SYNEDRION_ACP_LOG=/path/file` logs every line exchanged with every agent (see `protocol_log.rs`).
27+- Who a message addresses (decided with the user on 2026-10-23, after they sent `@bob salue @mouse` and both agents were called): if the text starts with mentions (separated by spaces or commas), only those address; otherwise every mention does. `@bob salue @mouse` is for bob only; `@bob and @mouse ...` is also bob only (the word `and` ends the leading mentions; stated in the docs). One rule in `resolve_mentions` serves user messages, follow-up recipients and agents' answers (relay). A name only talked about raises no "unknown agent" notice.
28+- Files in a sentence (asked by the user on 2026-10-23: `@` and `/` being taken, `$`): `$` + the beginning of a name, being typed at the end of the text and not glued to a word, opens the `/file` list (same folder, same search); Tab or a click replaces `$query` with the relative path and a space, and attaches the file as `/file` does. The stored message skips the `[attached: …]` line of a file its text already names. Pure part: `domain::file_reference`; the rest in `crates/ui/src/suggestions.rs`.
29+- Keyboard in the suggestion list (asked by the user on 2026-10-23): Up/Down move the highlight (wrapping), Tab takes the highlighted row, Enter takes it only once the arrows were used (otherwise Enter still sends, as before), Escape closes the list. One key interceptor (`handle_list_key` in `suggestions.rs`, installed in `app.rs`) handles all of it, only while the composer is focused and the list is open.
25 - A message that mentions nobody goes on with the agents the user last addressed in the channel (`follow_up_recipients` in `crates/domain/src/mention.rs`, derived from the stored messages, so it survives a restart); mentioning another agent changes the recipients; a mention of an unknown name is not a follow-up. A line above the message box says who a plain message goes to. Decided with the user on 2026-10-23.30 - A message that mentions nobody goes on with the agents the user last addressed in the channel (`follow_up_recipients` in `crates/domain/src/mention.rs`, derived from the stored messages, so it survives a restart); mentioning another agent changes the recipients; a mention of an unknown name is not a follow-up. A line above the message box says who a plain message goes to. Decided with the user on 2026-10-23.
26 - Slash commands (decided with the user on 2026-10-23): the `/` list offers the commands the recipients of the message announced through ACP (`AvailableCommandsUpdate`, kept per agent in the controller) plus Synedrion's own `/file`; a command typed after mentions is handed to the agent as the bare command (the agent recognises it only at the start), but only if the agent announced it or announced none yet. `/file` lists the files of the first recipient's working folder (or the current folder) through `FileIndex` (hidden files and `target`, `node_modules`, `__pycache__`, `dist`, `build` left out), Tab or a click attaches one as a chip above the message box, and each attachment goes to the agent as an ACP `resource_link` (`file://` + path, not percent-encoded, because mini-me strips the prefix); the stored message gets one `[attached: path]` line per file. Commands only appear after the agent's first session in the channel. Copy buttons: one per message (Markdown source) and one per code block (code alone), through GPUI Kit's `Clipboard`. Verified with the real mini-me: it announces `compact`, `new` and `unload`, answers `/new`, and its model receives `[attached file: path]`.31 - Slash commands (decided with the user on 2026-10-23): the `/` list offers the commands the recipients of the message announced through ACP (`AvailableCommandsUpdate`, kept per agent in the controller) plus Synedrion's own `/file`; a command typed after mentions is handed to the agent as the bare command (the agent recognises it only at the start), but only if the agent announced it or announced none yet. `/file` lists the files of the first recipient's working folder (or the current folder) through `FileIndex` (hidden files and `target`, `node_modules`, `__pycache__`, `dist`, `build` left out), Tab or a click attaches one as a chip above the message box, and each attachment goes to the agent as an ACP `resource_link` (`file://` + path, not percent-encoded, because mini-me strips the prefix); the stored message gets one `[attached: path]` line per file. Commands only appear after the agent's first session in the channel. Copy buttons: one per message (Markdown source) and one per code block (code alone), through GPUI Kit's `Clipboard`. Verified with the real mini-me: it announces `compact`, `new` and `unload`, answers `/new`, and its model receives `[attached file: path]`.
27 - Agents' messages are drawn as Markdown (GPUI Kit's `TextView::markdown`, with its `syntect` highlighter for code blocks, chosen over tree-sitter to avoid compiling C grammars); the user's text and the notices stay plain. A test shows an agent's `# Title` is drawn taller than the same text typed by the user. Code colouring and emphasis have never been seen.32 - Agents' messages are drawn as Markdown (GPUI Kit's `TextView::markdown`, with its `syntect` highlighter for code blocks, chosen over tree-sitter to avoid compiling C grammars); the user's text and the notices stay plain. A test shows an agent's `# Title` is drawn taller than the same text typed by the user. Code colouring and emphasis have never been seen.
28-- A mention is sent to the agent as typed, the agent's answer is streamed into one message, the Stop button cancels every agent working in the channel, permission questions are cards in the channel (#10 to #13).33+- The agent's answer is streamed into one message (a new one after each tool call or plan), the Stop button cancels every agent working in the channel, permission questions are cards in the channel (#10 to #13).
34+- The agent form has a folder browser (#20, the user's own ticket): `Browse…` under Working folder opens an in-app list of folders (`folders.rs` pure, `folder_browser.rs` window part), `..` up, click to enter, `Use this folder`, `Cancel`; it opens on the typed folder, else `HOME`; hidden folders omitted, 200 at most. I chose an in-app list over the operating system's dialog (testable and identical everywhere); the user agreed to that option when asked.
29 35
30 ## Layout of the repository36 ## Layout of the repository
31 37
32 | Path | Content |38 | Path | Content |
33 | --- | --- |39 | --- | --- |
34-| `.tickets/` | Tickets managed with IssueSpec: `issues/` (#1 to #19), `epics.yaml`, `milestones.yaml`, `labels.yaml`. Hand edits are welcome as long as the schema stays valid. Ticket #1 and its two tasks are closed (by the user). A closed state is written `closed`, and a closed task also carries `updatedAt` and `closedAt`. An issue links others with `related:` followed by a list of ids, and tickets #2 to #19 use it for their dependencies. |40+| `.tickets/` | Tickets managed with IssueSpec: `issues/` (#1 to #20; #20 is the user's own idea, epic IDEAS), `epics.yaml`, `milestones.yaml`, `labels.yaml`. Hand edits are welcome as long as the schema stays valid. Ticket #1 and its two tasks are closed (by the user). A closed state is written `closed`, and a closed task also carries `updatedAt` and `closedAt`. An issue links others with `related:` followed by a list of ids, and tickets #2 to #19 use it for their dependencies. |
35 | `crates/` | The four crates of the Cargo workspace: `domain` (types, rules, `Repository` trait, depends on nothing), `store` (`SqliteRepository`), `acp` (`AgentHub`, plus the test agent binary `synedrion-fake-agent`), `ui` (controller, windows, the `synedrion` program). Each has a `README.md` listing its API. |41 | `crates/` | The four crates of the Cargo workspace: `domain` (types, rules, `Repository` trait, depends on nothing), `store` (`SqliteRepository`), `acp` (`AgentHub`, plus the test agent binary `synedrion-fake-agent`), `ui` (controller, windows, the `synedrion` program). Each has a `README.md` listing its API. |
36 | `Cargo.toml`, `rustfmt.toml`, `.gitignore` | Workspace (edition 2024, `clippy::all` as warnings); `rustfmt.toml` states the edition because qlty runs rustfmt file by file; `/target` is ignored. `Cargo.lock` was regenerated once (see handoff) and is not ignored. |42 | `Cargo.toml`, `rustfmt.toml`, `.gitignore` | Workspace (edition 2024, `clippy::all` as warnings); `rustfmt.toml` states the edition because qlty runs rustfmt file by file; `/target` is ignored. `Cargo.lock` was regenerated once (see handoff) and is not ignored. |
37 | `.qlty/`, `.quality/` | qlty configuration and the quality reports and history written by the `quality` skill. |43 | `.qlty/`, `.quality/` | qlty configuration and the quality reports and history written by the `quality` skill. |
38-| `docs/` | Diátaxis documentation in `en/` and `fr/` (14 pages each: one tutorial, four how-to guides, five references, three explanations, an index), plus `diagrams/packages.drawio`. |44+| `docs/` | Diátaxis documentation in `en/` and `fr/` (each language: one tutorial, nine how-to guides, ten references, five explanations, an index), plus `diagrams/packages.drawio`. |
39 | `.memory/` | This record. |45 | `.memory/` | This record. |
40 | `.claude/` | Instructions and skills (`methodical-dev`, `quality`, `diataxis-doc`, `drawio-fancy-diagram`). |46 | `.claude/` | Instructions and skills (`methodical-dev`, `quality`, `diataxis-doc`, `drawio-fancy-diagram`). |
41 | `git.sh` | Commit helper: `./git.sh <type> "<message>"` runs `git add .`, commit with an emoji prefix, and push. It stages everything. |47 | `git.sh` | Commit helper: `./git.sh <type> "<message>"` runs `git add .`, commit with an emoji prefix, and push. It stages everything. |
@@ -45,14 +51,14 @@ Roadmap: epics Foundations, ACP, Chat, UI, Persistence, Registration. Milestones
45 ## How to build, test and run51 ## How to build, test and run
46 52
47 - Build: `cargo build --workspace`. Run: `cargo run -p synedrion-ui --bin synedrion` (needs a display).53 - Build: `cargo build --workspace`. Run: `cargo run -p synedrion-ui --bin synedrion` (needs a display).
48-- Test, one command: `cargo test --workspace`. Lint and format: `cargo clippy --workspace --all-targets` and `cargo fmt --all -- --check`. Last result on 2026-10-23: 361 tests pass (unit, integration and doc), clippy and fmt clean.54+- Test, one command: `cargo test --workspace`. Lint and format: `cargo clippy --workspace --all-targets` and `cargo fmt --all -- --check`. Last result on 2026-10-23: 552 tests pass (unit, integration and doc), clippy and fmt clean. The window tests are spread over `crates/ui/tests/{window,folder_browser,settings_and_traces}.rs`, and `tests/conversation.rs` drives the controller without a window (shared helpers in `tests/support/mod.rs`).
49 - Quality gate: `python3 .claude/skills/quality/scripts/quality_report.py --workspace .` (the skill's text says `~/.claude/skills/...`, which does not exist here; the script is in the repository).55 - Quality gate: `python3 .claude/skills/quality/scripts/quality_report.py --workspace .` (the skill's text says `~/.claude/skills/...`, which does not exist here; the script is in the repository).
50 - Linux build needs `pkg-config libfontconfig1-dev libxcb1-dev libxkbcommon-dev libxkbcommon-x11-dev` (installed with `sudo apt-get`; sudo is passwordless in this sandbox). Without a display, the binary panics inside GPUI ("failed to connect to Wayland compositor").56 - Linux build needs `pkg-config libfontconfig1-dev libxcb1-dev libxkbcommon-dev libxkbcommon-x11-dev` (installed with `sudo apt-get`; sudo is passwordless in this sandbox). Without a display, the binary panics inside GPUI ("failed to connect to Wayland compositor").
51 - The toolchain is Rust 1.99.1 (rustup, `--profile minimal` with clippy and rustfmt) and qlty 0.662.0 (release archive, not the install script: that script sends telemetry and installs completions). Both are on the `PATH` through `/etc/sandbox-persistent.sh`. Steps are in `docs/en/how-to/set-up-the-sandbox.md`.57 - The toolchain is Rust 1.99.1 (rustup, `--profile minimal` with clippy and rustfmt) and qlty 0.662.0 (release archive, not the install script: that script sends telemetry and installs completions). Both are on the `PATH` through `/etc/sandbox-persistent.sh`. Steps are in `docs/en/how-to/set-up-the-sandbox.md`.
52 58
53 ## Test agent59 ## Test agent
54 60
55-`synedrion-fake-agent` (in `crates/acp`) is the agent all automated tests and the tutorial use. Its keyword is the first word that is not a `@mention`: `ask`, `slow`, `crash`, anything else is echoed. It is built on the same ACP library as Synedrion, so it cannot show that a real agent behaves the same.61+`synedrion-fake-agent` (in `crates/acp`) is the agent all automated tests and the tutorial use. Its keyword is the first word that is not a `@mention`: `ask`, `slow`, `crash`, `think`, `tools` (a plan, a tool call and its completion), anything else is echoed; it also announces the commands `new` and `greet`. It is built on the same ACP library as Synedrion, so it cannot show that a real agent behaves the same.
56 62
57 mini-me, a Go ACP agent for local models, run with `mm -acp` and its configuration either as `-config <absolute path>` (the user's command: `mm -acp -config /Users/k33g/docker-working/agent.gemma.yaml`, one word per line of the Arguments field) or in the variable `AGENT_CONFIG`. The suggested test model is `unsloth/Qwen3.5-4B-GGUF`. Source: `https://rickub.com/bots-garden/mini-me`. The user has used it with Synedrion (first real test, 2026-10-23). It can also be built here: its source archive is `https://rickub.com/bots-garden/mini-me/archive/main.zip` and Go is installed (`go build`); a fake OpenAI-compatible model server (any small streaming SSE server answering `/v1/chat/completions`, with `reasoning_content` deltas) is enough to drive it.63 mini-me, a Go ACP agent for local models, run with `mm -acp` and its configuration either as `-config <absolute path>` (the user's command: `mm -acp -config /Users/k33g/docker-working/agent.gemma.yaml`, one word per line of the Arguments field) or in the variable `AGENT_CONFIG`. The suggested test model is `unsloth/Qwen3.5-4B-GGUF`. Source: `https://rickub.com/bots-garden/mini-me`. The user has used it with Synedrion (first real test, 2026-10-23). It can also be built here: its source archive is `https://rickub.com/bots-garden/mini-me/archive/main.zip` and Go is installed (`go build`); a fake OpenAI-compatible model server (any small streaming SSE server answering `/v1/chat/completions`, with `reasoning_content` deltas) is enough to drive it.
58 64
@@ -62,9 +68,12 @@ mini-me, a Go ACP agent for local models, run with `mm -acp` and its configurati
62 - **The window had never been displayed by me.** The sandbox has no display. Behaviour is covered by 62 headless GPUI Kit window tests (found by identifier, clicked, typed into); looks, light and dark themes, the "active channel" highlight and the scroll-follows-latest behaviour are unverified.68 - **The window had never been displayed by me.** The sandbox has no display. Behaviour is covered by 62 headless GPUI Kit window tests (found by identifier, clicked, typed into); looks, light and dark themes, the "active channel" highlight and the scroll-follows-latest behaviour are unverified.
63 - **mini-me works against Synedrion in my reproduction, but the user reports that their agent answered only once.** With the real `mm` binary (built from source) and a fake streaming model, two successive prompts to the same session were both answered, both through the ACP client and through the controller. The cause of what the user saw is NOT established. Leading hypothesis (confirmed in effect: the user answered that it works, and asked that conversations go on without retyping the name, now built): the second message did not mention the agent. Other possibilities: the model or its config (tools, `yolo: false`, an error), or something only the real window shows. The protocol log (`SYNEDRION_ACP_LOG`) exists to settle it.69 - **mini-me works against Synedrion in my reproduction, but the user reports that their agent answered only once.** With the real `mm` binary (built from source) and a fake streaming model, two successive prompts to the same session were both answered, both through the ACP client and through the controller. The cause of what the user saw is NOT established. Leading hypothesis (confirmed in effect: the user answered that it works, and asked that conversations go on without retyping the name, now built): the second message did not mention the agent. Other possibilities: the model or its config (tools, `yolo: false`, an error), or something only the real window shows. The protocol log (`SYNEDRION_ACP_LOG`) exists to settle it.
64 - **`sbx exec` syntax** (options, interactive stdin, environment variables, path of `AGENT_CONFIG` inside the sandbox) is unverified because `sbx` is not installed in the sandbox. An earlier ticket draft invented a `-i` flag, which was removed.70 - **`sbx exec` syntax** (options, interactive stdin, environment variables, path of `AGENT_CONFIG` inside the sandbox) is unverified because `sbx` is not installed in the sandbox. An earlier ticket draft invented a `-i` flag, which was removed.
65-- **The quality gate PASSES (runs 3 and 4: 0 smells, complexity 195, 205, then 207) because the user decided on 2026-10-23 to exclude `.claude/**`.** That hid 11 smells in the kit's scripts (`quality_report.py`, `build_deck.js`), recorded in a comment next to the pattern in `.qlty/qlty.toml`. None was ever in `crates/`. The pass is weaker than it looks: see the next point.71+- **The quality gate PASSES (latest run 15: 0 smells, complexity 380; earlier runs 3 and 4: complexity 195, 205) because the user decided on 2026-10-23 to exclude `.claude/**`.** That hid 11 smells in the kit's scripts (`quality_report.py`, `build_deck.js`), recorded in a comment next to the pattern in `.qlty/qlty.toml`. None was ever in `crates/`. The pass is weaker than it looks: see the next point.
66 - **`clippy` through qlty reports nothing even when it should, so the gate's lint count comes from `rustfmt` alone.** A deliberate `needless_return` was missing from `qlty check`'s output although the plugin's own captured output contained it; cause not found, even with `mode = "block"`. `rustfmt` through qlty does work (a deliberate mistake was reported). `cargo clippy` run directly is clean and is the reliable check.72 - **`clippy` through qlty reports nothing even when it should, so the gate's lint count comes from `rustfmt` alone.** A deliberate `needless_return` was missing from `qlty check`'s output although the plugin's own captured output contained it; cause not found, even with `mode = "block"`. `rustfmt` through qlty does work (a deliberate mistake was reported). `cargo clippy` run directly is clean and is the reliable check.
67 - **`qlty init` enabled no plugin** (probably because no file is tracked by git: there is no commit; not confirmed), so the first "0 lint issues" meant nothing. `clippy` and `rustfmt` were added by hand in `.qlty/qlty.toml`, with `[runtimes.enabled] rust = "1.99.1"` (qlty's default Rust 1.77.2 cannot read an edition 2024 manifest). `qlty plugins enable` did nothing, silently. Other qlty plugins (markdownlint, yamllint, shellcheck...) are not enabled: markdownlint would flag the project's deliberately unwrapped paragraphs.73 - **`qlty init` enabled no plugin** (probably because no file is tracked by git: there is no commit; not confirmed), so the first "0 lint issues" meant nothing. `clippy` and `rustfmt` were added by hand in `.qlty/qlty.toml`, with `[runtimes.enabled] rust = "1.99.1"` (qlty's default Rust 1.77.2 cannot read an edition 2024 manifest). `qlty plugins enable` did nothing, silently. Other qlty plugins (markdownlint, yamllint, shellcheck...) are not enabled: markdownlint would flag the project's deliberately unwrapped paragraphs.
68-- **Whether fs and terminal client capabilities are exposed to agents** (#18). Today none is.74+- **Whether the decision not to expose fs and terminal capabilities (#18) is the user's final word.** It is built that way and documented; see "Decisions in force". mini-me answers without them, but its own bash tool was not exercised.
75+- **The v0.2.0 features were never run against a real agent or seen on a screen**: the context given to agents, agents calling agents, tool call and plan cards (and the colour of a failed one), the settings panel, the folder browser. Whether mini-me sends `tool_call` and `plan` updates, and what they look like, is unknown. The rebuilt `message` table (migration 3) was tested only on an in-memory copy of a version 1 database, not on the user's real file: it is worth keeping a copy of their database before they first start the new version.
76+- **Known limits of the context record** (documented in `docs/en/reference/channel-context.md`): `seen` is in memory, so after a Synedrion restart each agent is told the latest messages again; if an agent's process restarts while Synedrion runs, or after `/new` or `/compact`, what was already handed over is not sent again.
77+- **A tool call that updates an agent's turn after it ended** is not specified: the controller forgets calls at turn end, so such an update would make a card titled `Tool call`.
69 - **Whether IssueSpec accepts tickets #2 to #19.** They use a `milestone:` field copied by convention, which no existing file confirmed, and no YAML parser was available to validate them. The only evidence is indirect: the user wrote `related: [2]` in ticket #1, which suggests ticket #2 is recognised.78 - **Whether IssueSpec accepts tickets #2 to #19.** They use a `milestone:` field copied by convention, which no existing file confirmed, and no YAML parser was available to validate them. The only evidence is indirect: the user wrote `related: [2]` in ticket #1, which suggests ticket #2 is recognised.
70 - A prompt sent to an agent immediately after it crashed can still fail instead of restarting it in a very small window (a turn can be reported failed by the dying worker just before its queue is closed). The common path is covered by tests and does restart.79 - A prompt sent to an agent immediately after it crashed can still fail instead of restarting it in a very small window (a turn can be reported failed by the dying worker just before its queue is closed). The common path is covered by tests and does restart.
modified .quality/history.jsonl +6 -0
@@ -11,3 +11,9 @@
1111 {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 56, "complex": 233, "cyclo": 509, "fields": 149, "funcs": 517, "lcom": 20, "lines": 8573, "loc": 7702}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 11, "smells": 0, "timestamp": "2026-10-23T11:54:46Z"}
1212 {"branch": "", "breaches": ["code smells: 1 (max 0)"], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 64, "complex": 292, "cyclo": 619, "fields": 173, "funcs": 630, "lcom": 22, "lines": 10557, "loc": 9514}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 12, "smells": 1, "timestamp": "2026-10-23T12:17:25Z"}
1313 {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 64, "complex": 292, "cyclo": 621, "fields": 183, "funcs": 630, "lcom": 24, "lines": 10587, "loc": 9541}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 13, "smells": 0, "timestamp": "2026-10-23T12:19:19Z"}
14+{"branch": "main", "breaches": ["code smells: 3 (max 0)"], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 79, "complex": 382, "cyclo": 882, "fields": 254, "funcs": 873, "lcom": 39, "lines": 14789, "loc": 13362}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 14, "smells": 3, "timestamp": "2026-10-23T13:14:22Z"}
15+{"branch": "main", "breaches": [], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 82, "complex": 380, "cyclo": 889, "fields": 260, "funcs": 874, "lcom": 39, "lines": 14855, "loc": 13425}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 15, "smells": 0, "timestamp": "2026-10-23T13:15:13Z"}
16+{"branch": "main", "breaches": [], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 82, "complex": 380, "cyclo": 889, "fields": 260, "funcs": 874, "lcom": 39, "lines": 14855, "loc": 13425}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 16, "smells": 0, "timestamp": "2026-10-23T13:21:05Z"}
17+{"branch": "main", "breaches": [], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 82, "complex": 393, "cyclo": 902, "fields": 260, "funcs": 889, "lcom": 39, "lines": 15037, "loc": 13587}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 17, "smells": 0, "timestamp": "2026-10-23T13:49:34Z"}
18+{"branch": "main", "breaches": [], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 83, "complex": 400, "cyclo": 914, "fields": 261, "funcs": 915, "lcom": 39, "lines": 15384, "loc": 13895}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 18, "smells": 0, "timestamp": "2026-10-23T14:03:25Z"}
19+{"branch": "main", "breaches": [], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 84, "complex": 410, "cyclo": 927, "fields": 266, "funcs": 937, "lcom": 39, "lines": 15649, "loc": 14130}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 19, "smells": 0, "timestamp": "2026-10-23T14:10:47Z"}
@@ -11,3 +11,9 @@
11 {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 56, "complex": 233, "cyclo": 509, "fields": 149, "funcs": 517, "lcom": 20, "lines": 8573, "loc": 7702}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 11, "smells": 0, "timestamp": "2026-10-23T11:54:46Z"}11 {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 56, "complex": 233, "cyclo": 509, "fields": 149, "funcs": 517, "lcom": 20, "lines": 8573, "loc": 7702}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 11, "smells": 0, "timestamp": "2026-10-23T11:54:46Z"}
12 {"branch": "", "breaches": ["code smells: 1 (max 0)"], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 64, "complex": 292, "cyclo": 619, "fields": 173, "funcs": 630, "lcom": 22, "lines": 10557, "loc": 9514}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 12, "smells": 1, "timestamp": "2026-10-23T12:17:25Z"}12 {"branch": "", "breaches": ["code smells: 1 (max 0)"], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 64, "complex": 292, "cyclo": 619, "fields": 173, "funcs": 630, "lcom": 22, "lines": 10557, "loc": 9514}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 12, "smells": 1, "timestamp": "2026-10-23T12:17:25Z"}
13 {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 64, "complex": 292, "cyclo": 621, "fields": 183, "funcs": 630, "lcom": 24, "lines": 10587, "loc": 9541}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 13, "smells": 0, "timestamp": "2026-10-23T12:19:19Z"}13 {"branch": "", "breaches": [], "commit": "", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 64, "complex": 292, "cyclo": 621, "fields": 183, "funcs": 630, "lcom": 24, "lines": 10587, "loc": 9541}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 13, "smells": 0, "timestamp": "2026-10-23T12:19:19Z"}
14+{"branch": "main", "breaches": ["code smells: 3 (max 0)"], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": false, "metrics": {"classes": 79, "complex": 382, "cyclo": 882, "fields": 254, "funcs": 873, "lcom": 39, "lines": 14789, "loc": 13362}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 14, "smells": 3, "timestamp": "2026-10-23T13:14:22Z"}
15+{"branch": "main", "breaches": [], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 82, "complex": 380, "cyclo": 889, "fields": 260, "funcs": 874, "lcom": 39, "lines": 14855, "loc": 13425}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 15, "smells": 0, "timestamp": "2026-10-23T13:15:13Z"}
16+{"branch": "main", "breaches": [], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 82, "complex": 380, "cyclo": 889, "fields": 260, "funcs": 874, "lcom": 39, "lines": 14855, "loc": 13425}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 16, "smells": 0, "timestamp": "2026-10-23T13:21:05Z"}
17+{"branch": "main", "breaches": [], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 82, "complex": 393, "cyclo": 902, "fields": 260, "funcs": 889, "lcom": 39, "lines": 15037, "loc": 13587}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 17, "smells": 0, "timestamp": "2026-10-23T13:49:34Z"}
18+{"branch": "main", "breaches": [], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 83, "complex": 400, "cyclo": 914, "fields": 261, "funcs": 915, "lcom": 39, "lines": 15384, "loc": 13895}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 18, "smells": 0, "timestamp": "2026-10-23T14:03:25Z"}
19+{"branch": "main", "breaches": [], "commit": "0502ed3", "counts": {}, "gate": {"max_error": 0, "max_smells": 0, "max_warning": 0}, "gate_passed": true, "metrics": {"classes": 84, "complex": 410, "cyclo": 927, "fields": 266, "funcs": 937, "lcom": 39, "lines": 15649, "loc": 14130}, "qlty_version": "qlty 0.662.0 linux-arm64 (f48face 2026-10-23)", "run": 19, "smells": 0, "timestamp": "2026-10-23T14:10:47Z"}
added .quality/report-20261023T131422Z.md +80 -0
new file mode 100644
@@ -0,0 +1,80 @@
1+# Quality report — 2026-10-23T13:14:22Z
2+
3+- **Gate**: ❌ **FAIL**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #14 (previous: 2026-10-23T12:19:19Z)
7+
8+## Gate violations
9+
10+- code smells: 3 (max 0)
11+
12+## Lint issues (`qlty check`)
13+
14+_none_
15+
16+### Top rules
17+
18+_none_
19+
20+### Most affected files
21+
22+_none_
23+
24+## Code smells (`qlty smells`)
25+
26+Total: **3** (vs previous: +3)
27+
28+| smell | file | line | detail |
29+|---|---|---|---|
30+| qlty:function-parameters | crates/ui/src/trace_view.rs | 64 | Function with many parameters (count = 7): tool_call |
31+| qlty:return-statements | crates/acp/src/bin/synedrion-fake-agent.rs | 107 | Function with many returns (count = 6): answer |
32+| qlty:function-parameters | crates/ui/src/controller/prompts.rs | 70 | Function with many parameters (count = 6): deliver |
33+
34+## Metrics (`qlty metrics`)
35+
36+| metric | total | vs previous |
37+|---|---|---|
38+| funcs | 873 | +243 |
39+| classes | 79 | +15 |
40+| fields | 254 | +71 |
41+| cyclo | 882 | +261 |
42+| complex | 382 | +90 |
43+| lcom | 39 | +15 |
44+| lines | 14789 | +4202 |
45+| loc | 13362 | +3821 |
46+
47+### Most complex files
48+
49+| file | complex | cyclo | loc |
50+|---|---|---|---|
51+| crates/ui/src/app.rs | 40 | 47 | 510 |
52+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
53+| crates/ui/src/controller.rs | 30 | 89 | 1678 |
54+| crates/acp/src/worker.rs | 22 | 49 | 502 |
55+| crates/acp/src/bin/synedrion-fake-agent.rs | 17 | 33 | 255 |
56+| crates/ui/src/files.rs | 17 | 18 | 242 |
57+| crates/acp/src/updates.rs | 16 | 57 | 433 |
58+| crates/ui/src/view.rs | 16 | 39 | 904 |
59+| crates/ui/src/suggestions.rs | 15 | 27 | 202 |
60+| crates/domain/src/mention.rs | 14 | 26 | 382 |
61+| crates/domain/src/context.rs | 13 | 20 | 372 |
62+| crates/domain/src/trace.rs | 12 | 35 | 373 |
63+| crates/ui/src/controller/relay.rs | 11 | 21 | 103 |
64+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
65+| crates/ui/src/trace_view.rs | 10 | 16 | 176 |
66+
67+## Trend
68+
69+| run | timestamp | error | warning | smells | complex | gate |
70+|---|---|---|---|---|---|---|
71+| 5 | 2026-10-23T11:11:12Z | 0 | 0 | 0 | 207 | PASS |
72+| 6 | 2026-10-23T11:16:31Z | 0 | 0 | 0 | 208 | PASS |
73+| 7 | 2026-10-23T11:21:42Z | 0 | 0 | 0 | 209 | PASS |
74+| 8 | 2026-10-23T11:22:20Z | 0 | 0 | 0 | 209 | PASS |
75+| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
76+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
77+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
78+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
79+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
80+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
new file mode 100644
@@ -0,0 +1,80 @@
1+# Quality report — 2026-10-23T13:14:22Z
2+
3+- **Gate**: ❌ **FAIL**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #14 (previous: 2026-10-23T12:19:19Z)
7+
8+## Gate violations
9+
10+- code smells: 3 (max 0)
11+
12+## Lint issues (`qlty check`)
13+
14+_none_
15+
16+### Top rules
17+
18+_none_
19+
20+### Most affected files
21+
22+_none_
23+
24+## Code smells (`qlty smells`)
25+
26+Total: **3** (vs previous: +3)
27+
28+| smell | file | line | detail |
29+|---|---|---|---|
30+| qlty:function-parameters | crates/ui/src/trace_view.rs | 64 | Function with many parameters (count = 7): tool_call |
31+| qlty:return-statements | crates/acp/src/bin/synedrion-fake-agent.rs | 107 | Function with many returns (count = 6): answer |
32+| qlty:function-parameters | crates/ui/src/controller/prompts.rs | 70 | Function with many parameters (count = 6): deliver |
33+
34+## Metrics (`qlty metrics`)
35+
36+| metric | total | vs previous |
37+|---|---|---|
38+| funcs | 873 | +243 |
39+| classes | 79 | +15 |
40+| fields | 254 | +71 |
41+| cyclo | 882 | +261 |
42+| complex | 382 | +90 |
43+| lcom | 39 | +15 |
44+| lines | 14789 | +4202 |
45+| loc | 13362 | +3821 |
46+
47+### Most complex files
48+
49+| file | complex | cyclo | loc |
50+|---|---|---|---|
51+| crates/ui/src/app.rs | 40 | 47 | 510 |
52+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
53+| crates/ui/src/controller.rs | 30 | 89 | 1678 |
54+| crates/acp/src/worker.rs | 22 | 49 | 502 |
55+| crates/acp/src/bin/synedrion-fake-agent.rs | 17 | 33 | 255 |
56+| crates/ui/src/files.rs | 17 | 18 | 242 |
57+| crates/acp/src/updates.rs | 16 | 57 | 433 |
58+| crates/ui/src/view.rs | 16 | 39 | 904 |
59+| crates/ui/src/suggestions.rs | 15 | 27 | 202 |
60+| crates/domain/src/mention.rs | 14 | 26 | 382 |
61+| crates/domain/src/context.rs | 13 | 20 | 372 |
62+| crates/domain/src/trace.rs | 12 | 35 | 373 |
63+| crates/ui/src/controller/relay.rs | 11 | 21 | 103 |
64+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
65+| crates/ui/src/trace_view.rs | 10 | 16 | 176 |
66+
67+## Trend
68+
69+| run | timestamp | error | warning | smells | complex | gate |
70+|---|---|---|---|---|---|---|
71+| 5 | 2026-10-23T11:11:12Z | 0 | 0 | 0 | 207 | PASS |
72+| 6 | 2026-10-23T11:16:31Z | 0 | 0 | 0 | 208 | PASS |
73+| 7 | 2026-10-23T11:21:42Z | 0 | 0 | 0 | 209 | PASS |
74+| 8 | 2026-10-23T11:22:20Z | 0 | 0 | 0 | 209 | PASS |
75+| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
76+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
77+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
78+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
79+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
80+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
added .quality/report-20261023T131513Z.md +72 -0
new file mode 100644
@@ -0,0 +1,72 @@
1+# Quality report — 2026-10-23T13:15:13Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #15 (previous: 2026-10-23T13:14:22Z)
7+
8+## Lint issues (`qlty check`)
9+
10+_none_
11+
12+### Top rules
13+
14+_none_
15+
16+### Most affected files
17+
18+_none_
19+
20+## Code smells (`qlty smells`)
21+
22+Total: **0** (vs previous: -3)
23+
24+_none_
25+
26+## Metrics (`qlty metrics`)
27+
28+| metric | total | vs previous |
29+|---|---|---|
30+| funcs | 874 | +1 |
31+| classes | 82 | +3 |
32+| fields | 260 | +6 |
33+| cyclo | 889 | +7 |
34+| complex | 380 | -2 |
35+| lcom | 39 | ±0 |
36+| lines | 14855 | +66 |
37+| loc | 13425 | +63 |
38+
39+### Most complex files
40+
41+| file | complex | cyclo | loc |
42+|---|---|---|---|
43+| crates/ui/src/app.rs | 40 | 47 | 510 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 89 | 1685 |
46+| crates/acp/src/worker.rs | 22 | 49 | 502 |
47+| crates/ui/src/files.rs | 17 | 18 | 242 |
48+| crates/acp/src/updates.rs | 16 | 57 | 433 |
49+| crates/ui/src/view.rs | 16 | 39 | 904 |
50+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
51+| crates/ui/src/suggestions.rs | 15 | 27 | 202 |
52+| crates/domain/src/mention.rs | 14 | 26 | 382 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
58+
59+## Trend
60+
61+| run | timestamp | error | warning | smells | complex | gate |
62+|---|---|---|---|---|---|---|
63+| 6 | 2026-10-23T11:16:31Z | 0 | 0 | 0 | 208 | PASS |
64+| 7 | 2026-10-23T11:21:42Z | 0 | 0 | 0 | 209 | PASS |
65+| 8 | 2026-10-23T11:22:20Z | 0 | 0 | 0 | 209 | PASS |
66+| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
67+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
68+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
69+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
70+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
71+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
72+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
new file mode 100644
@@ -0,0 +1,72 @@
1+# Quality report — 2026-10-23T13:15:13Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #15 (previous: 2026-10-23T13:14:22Z)
7+
8+## Lint issues (`qlty check`)
9+
10+_none_
11+
12+### Top rules
13+
14+_none_
15+
16+### Most affected files
17+
18+_none_
19+
20+## Code smells (`qlty smells`)
21+
22+Total: **0** (vs previous: -3)
23+
24+_none_
25+
26+## Metrics (`qlty metrics`)
27+
28+| metric | total | vs previous |
29+|---|---|---|
30+| funcs | 874 | +1 |
31+| classes | 82 | +3 |
32+| fields | 260 | +6 |
33+| cyclo | 889 | +7 |
34+| complex | 380 | -2 |
35+| lcom | 39 | ±0 |
36+| lines | 14855 | +66 |
37+| loc | 13425 | +63 |
38+
39+### Most complex files
40+
41+| file | complex | cyclo | loc |
42+|---|---|---|---|
43+| crates/ui/src/app.rs | 40 | 47 | 510 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 89 | 1685 |
46+| crates/acp/src/worker.rs | 22 | 49 | 502 |
47+| crates/ui/src/files.rs | 17 | 18 | 242 |
48+| crates/acp/src/updates.rs | 16 | 57 | 433 |
49+| crates/ui/src/view.rs | 16 | 39 | 904 |
50+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
51+| crates/ui/src/suggestions.rs | 15 | 27 | 202 |
52+| crates/domain/src/mention.rs | 14 | 26 | 382 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
58+
59+## Trend
60+
61+| run | timestamp | error | warning | smells | complex | gate |
62+|---|---|---|---|---|---|---|
63+| 6 | 2026-10-23T11:16:31Z | 0 | 0 | 0 | 208 | PASS |
64+| 7 | 2026-10-23T11:21:42Z | 0 | 0 | 0 | 209 | PASS |
65+| 8 | 2026-10-23T11:22:20Z | 0 | 0 | 0 | 209 | PASS |
66+| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
67+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
68+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
69+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
70+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
71+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
72+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
added .quality/report-20261023T132105Z.md +72 -0
new file mode 100644
@@ -0,0 +1,72 @@
1+# Quality report — 2026-10-23T13:21:05Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #16 (previous: 2026-10-23T13:15:13Z)
7+
8+## Lint issues (`qlty check`)
9+
10+_none_
11+
12+### Top rules
13+
14+_none_
15+
16+### Most affected files
17+
18+_none_
19+
20+## Code smells (`qlty smells`)
21+
22+Total: **0** (vs previous: ±0)
23+
24+_none_
25+
26+## Metrics (`qlty metrics`)
27+
28+| metric | total | vs previous |
29+|---|---|---|
30+| funcs | 874 | ±0 |
31+| classes | 82 | ±0 |
32+| fields | 260 | ±0 |
33+| cyclo | 889 | ±0 |
34+| complex | 380 | ±0 |
35+| lcom | 39 | ±0 |
36+| lines | 14855 | ±0 |
37+| loc | 13425 | ±0 |
38+
39+### Most complex files
40+
41+| file | complex | cyclo | loc |
42+|---|---|---|---|
43+| crates/ui/src/app.rs | 40 | 47 | 510 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 89 | 1685 |
46+| crates/acp/src/worker.rs | 22 | 49 | 502 |
47+| crates/ui/src/files.rs | 17 | 18 | 242 |
48+| crates/acp/src/updates.rs | 16 | 57 | 433 |
49+| crates/ui/src/view.rs | 16 | 39 | 904 |
50+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
51+| crates/ui/src/suggestions.rs | 15 | 27 | 202 |
52+| crates/domain/src/mention.rs | 14 | 26 | 382 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
58+
59+## Trend
60+
61+| run | timestamp | error | warning | smells | complex | gate |
62+|---|---|---|---|---|---|---|
63+| 7 | 2026-10-23T11:21:42Z | 0 | 0 | 0 | 209 | PASS |
64+| 8 | 2026-10-23T11:22:20Z | 0 | 0 | 0 | 209 | PASS |
65+| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
66+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
67+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
68+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
69+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
70+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
71+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
72+| 16 | 2026-10-23T13:21:05Z | 0 | 0 | 0 | 380 | PASS |
new file mode 100644
@@ -0,0 +1,72 @@
1+# Quality report — 2026-10-23T13:21:05Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #16 (previous: 2026-10-23T13:15:13Z)
7+
8+## Lint issues (`qlty check`)
9+
10+_none_
11+
12+### Top rules
13+
14+_none_
15+
16+### Most affected files
17+
18+_none_
19+
20+## Code smells (`qlty smells`)
21+
22+Total: **0** (vs previous: ±0)
23+
24+_none_
25+
26+## Metrics (`qlty metrics`)
27+
28+| metric | total | vs previous |
29+|---|---|---|
30+| funcs | 874 | ±0 |
31+| classes | 82 | ±0 |
32+| fields | 260 | ±0 |
33+| cyclo | 889 | ±0 |
34+| complex | 380 | ±0 |
35+| lcom | 39 | ±0 |
36+| lines | 14855 | ±0 |
37+| loc | 13425 | ±0 |
38+
39+### Most complex files
40+
41+| file | complex | cyclo | loc |
42+|---|---|---|---|
43+| crates/ui/src/app.rs | 40 | 47 | 510 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 89 | 1685 |
46+| crates/acp/src/worker.rs | 22 | 49 | 502 |
47+| crates/ui/src/files.rs | 17 | 18 | 242 |
48+| crates/acp/src/updates.rs | 16 | 57 | 433 |
49+| crates/ui/src/view.rs | 16 | 39 | 904 |
50+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
51+| crates/ui/src/suggestions.rs | 15 | 27 | 202 |
52+| crates/domain/src/mention.rs | 14 | 26 | 382 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
58+
59+## Trend
60+
61+| run | timestamp | error | warning | smells | complex | gate |
62+|---|---|---|---|---|---|---|
63+| 7 | 2026-10-23T11:21:42Z | 0 | 0 | 0 | 209 | PASS |
64+| 8 | 2026-10-23T11:22:20Z | 0 | 0 | 0 | 209 | PASS |
65+| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
66+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
67+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
68+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
69+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
70+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
71+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
72+| 16 | 2026-10-23T13:21:05Z | 0 | 0 | 0 | 380 | PASS |
added .quality/report-20261023T134934Z.md +72 -0
new file mode 100644
@@ -0,0 +1,72 @@
1+# Quality report — 2026-10-23T13:49:34Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #17 (previous: 2026-10-23T13:21:05Z)
7+
8+## Lint issues (`qlty check`)
9+
10+_none_
11+
12+### Top rules
13+
14+_none_
15+
16+### Most affected files
17+
18+_none_
19+
20+## Code smells (`qlty smells`)
21+
22+Total: **0** (vs previous: ±0)
23+
24+_none_
25+
26+## Metrics (`qlty metrics`)
27+
28+| metric | total | vs previous |
29+|---|---|---|
30+| funcs | 889 | +15 |
31+| classes | 82 | ±0 |
32+| fields | 260 | ±0 |
33+| cyclo | 902 | +13 |
34+| complex | 393 | +13 |
35+| lcom | 39 | ±0 |
36+| lines | 15037 | +182 |
37+| loc | 13587 | +162 |
38+
39+### Most complex files
40+
41+| file | complex | cyclo | loc |
42+|---|---|---|---|
43+| crates/ui/src/app.rs | 40 | 47 | 510 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 89 | 1685 |
46+| crates/domain/src/mention.rs | 27 | 36 | 501 |
47+| crates/acp/src/worker.rs | 22 | 49 | 502 |
48+| crates/ui/src/files.rs | 17 | 18 | 242 |
49+| crates/acp/src/updates.rs | 16 | 57 | 433 |
50+| crates/ui/src/view.rs | 16 | 39 | 904 |
51+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
52+| crates/ui/src/suggestions.rs | 15 | 27 | 202 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
58+
59+## Trend
60+
61+| run | timestamp | error | warning | smells | complex | gate |
62+|---|---|---|---|---|---|---|
63+| 8 | 2026-10-23T11:22:20Z | 0 | 0 | 0 | 209 | PASS |
64+| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
65+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
66+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
67+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
68+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
69+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
70+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
71+| 16 | 2026-10-23T13:21:05Z | 0 | 0 | 0 | 380 | PASS |
72+| 17 | 2026-10-23T13:49:34Z | 0 | 0 | 0 | 393 | PASS |
new file mode 100644
@@ -0,0 +1,72 @@
1+# Quality report — 2026-10-23T13:49:34Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #17 (previous: 2026-10-23T13:21:05Z)
7+
8+## Lint issues (`qlty check`)
9+
10+_none_
11+
12+### Top rules
13+
14+_none_
15+
16+### Most affected files
17+
18+_none_
19+
20+## Code smells (`qlty smells`)
21+
22+Total: **0** (vs previous: ±0)
23+
24+_none_
25+
26+## Metrics (`qlty metrics`)
27+
28+| metric | total | vs previous |
29+|---|---|---|
30+| funcs | 889 | +15 |
31+| classes | 82 | ±0 |
32+| fields | 260 | ±0 |
33+| cyclo | 902 | +13 |
34+| complex | 393 | +13 |
35+| lcom | 39 | ±0 |
36+| lines | 15037 | +182 |
37+| loc | 13587 | +162 |
38+
39+### Most complex files
40+
41+| file | complex | cyclo | loc |
42+|---|---|---|---|
43+| crates/ui/src/app.rs | 40 | 47 | 510 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 89 | 1685 |
46+| crates/domain/src/mention.rs | 27 | 36 | 501 |
47+| crates/acp/src/worker.rs | 22 | 49 | 502 |
48+| crates/ui/src/files.rs | 17 | 18 | 242 |
49+| crates/acp/src/updates.rs | 16 | 57 | 433 |
50+| crates/ui/src/view.rs | 16 | 39 | 904 |
51+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
52+| crates/ui/src/suggestions.rs | 15 | 27 | 202 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
58+
59+## Trend
60+
61+| run | timestamp | error | warning | smells | complex | gate |
62+|---|---|---|---|---|---|---|
63+| 8 | 2026-10-23T11:22:20Z | 0 | 0 | 0 | 209 | PASS |
64+| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
65+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
66+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
67+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
68+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
69+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
70+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
71+| 16 | 2026-10-23T13:21:05Z | 0 | 0 | 0 | 380 | PASS |
72+| 17 | 2026-10-23T13:49:34Z | 0 | 0 | 0 | 393 | PASS |
added .quality/report-20261023T140325Z.md +72 -0
new file mode 100644
@@ -0,0 +1,72 @@
1+# Quality report — 2026-10-23T14:03:25Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #18 (previous: 2026-10-23T13:49:34Z)
7+
8+## Lint issues (`qlty check`)
9+
10+_none_
11+
12+### Top rules
13+
14+_none_
15+
16+### Most affected files
17+
18+_none_
19+
20+## Code smells (`qlty smells`)
21+
22+Total: **0** (vs previous: ±0)
23+
24+_none_
25+
26+## Metrics (`qlty metrics`)
27+
28+| metric | total | vs previous |
29+|---|---|---|
30+| funcs | 915 | +26 |
31+| classes | 83 | +1 |
32+| fields | 261 | +1 |
33+| cyclo | 914 | +12 |
34+| complex | 400 | +7 |
35+| lcom | 39 | ±0 |
36+| lines | 15384 | +347 |
37+| loc | 13895 | +308 |
38+
39+### Most complex files
40+
41+| file | complex | cyclo | loc |
42+|---|---|---|---|
43+| crates/ui/src/app.rs | 40 | 47 | 510 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 90 | 1704 |
46+| crates/domain/src/mention.rs | 27 | 36 | 501 |
47+| crates/acp/src/worker.rs | 22 | 49 | 502 |
48+| crates/ui/src/suggestions.rs | 18 | 28 | 209 |
49+| crates/ui/src/files.rs | 17 | 18 | 242 |
50+| crates/acp/src/updates.rs | 16 | 57 | 433 |
51+| crates/ui/src/view.rs | 16 | 39 | 904 |
52+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
58+
59+## Trend
60+
61+| run | timestamp | error | warning | smells | complex | gate |
62+|---|---|---|---|---|---|---|
63+| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
64+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
65+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
66+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
67+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
68+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
69+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
70+| 16 | 2026-10-23T13:21:05Z | 0 | 0 | 0 | 380 | PASS |
71+| 17 | 2026-10-23T13:49:34Z | 0 | 0 | 0 | 393 | PASS |
72+| 18 | 2026-10-23T14:03:25Z | 0 | 0 | 0 | 400 | PASS |
new file mode 100644
@@ -0,0 +1,72 @@
1+# Quality report — 2026-10-23T14:03:25Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #18 (previous: 2026-10-23T13:49:34Z)
7+
8+## Lint issues (`qlty check`)
9+
10+_none_
11+
12+### Top rules
13+
14+_none_
15+
16+### Most affected files
17+
18+_none_
19+
20+## Code smells (`qlty smells`)
21+
22+Total: **0** (vs previous: ±0)
23+
24+_none_
25+
26+## Metrics (`qlty metrics`)
27+
28+| metric | total | vs previous |
29+|---|---|---|
30+| funcs | 915 | +26 |
31+| classes | 83 | +1 |
32+| fields | 261 | +1 |
33+| cyclo | 914 | +12 |
34+| complex | 400 | +7 |
35+| lcom | 39 | ±0 |
36+| lines | 15384 | +347 |
37+| loc | 13895 | +308 |
38+
39+### Most complex files
40+
41+| file | complex | cyclo | loc |
42+|---|---|---|---|
43+| crates/ui/src/app.rs | 40 | 47 | 510 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 90 | 1704 |
46+| crates/domain/src/mention.rs | 27 | 36 | 501 |
47+| crates/acp/src/worker.rs | 22 | 49 | 502 |
48+| crates/ui/src/suggestions.rs | 18 | 28 | 209 |
49+| crates/ui/src/files.rs | 17 | 18 | 242 |
50+| crates/acp/src/updates.rs | 16 | 57 | 433 |
51+| crates/ui/src/view.rs | 16 | 39 | 904 |
52+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
58+
59+## Trend
60+
61+| run | timestamp | error | warning | smells | complex | gate |
62+|---|---|---|---|---|---|---|
63+| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
64+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
65+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
66+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
67+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
68+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
69+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
70+| 16 | 2026-10-23T13:21:05Z | 0 | 0 | 0 | 380 | PASS |
71+| 17 | 2026-10-23T13:49:34Z | 0 | 0 | 0 | 393 | PASS |
72+| 18 | 2026-10-23T14:03:25Z | 0 | 0 | 0 | 400 | PASS |
added .quality/report-20261023T141047Z.md +72 -0
new file mode 100644
@@ -0,0 +1,72 @@
1+# Quality report — 2026-10-23T14:10:47Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #19 (previous: 2026-10-23T14:03:25Z)
7+
8+## Lint issues (`qlty check`)
9+
10+_none_
11+
12+### Top rules
13+
14+_none_
15+
16+### Most affected files
17+
18+_none_
19+
20+## Code smells (`qlty smells`)
21+
22+Total: **0** (vs previous: ±0)
23+
24+_none_
25+
26+## Metrics (`qlty metrics`)
27+
28+| metric | total | vs previous |
29+|---|---|---|
30+| funcs | 937 | +22 |
31+| classes | 84 | +1 |
32+| fields | 266 | +5 |
33+| cyclo | 927 | +13 |
34+| complex | 410 | +10 |
35+| lcom | 39 | ±0 |
36+| lines | 15649 | +265 |
37+| loc | 14130 | +235 |
38+
39+### Most complex files
40+
41+| file | complex | cyclo | loc |
42+|---|---|---|---|
43+| crates/ui/src/app.rs | 40 | 46 | 526 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 90 | 1704 |
46+| crates/domain/src/mention.rs | 27 | 36 | 501 |
47+| crates/ui/src/suggestions.rs | 26 | 39 | 291 |
48+| crates/acp/src/worker.rs | 22 | 49 | 502 |
49+| crates/ui/src/files.rs | 17 | 18 | 242 |
50+| crates/acp/src/updates.rs | 16 | 57 | 433 |
51+| crates/ui/src/view.rs | 16 | 39 | 907 |
52+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
58+
59+## Trend
60+
61+| run | timestamp | error | warning | smells | complex | gate |
62+|---|---|---|---|---|---|---|
63+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
64+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
65+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
66+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
67+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
68+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
69+| 16 | 2026-10-23T13:21:05Z | 0 | 0 | 0 | 380 | PASS |
70+| 17 | 2026-10-23T13:49:34Z | 0 | 0 | 0 | 393 | PASS |
71+| 18 | 2026-10-23T14:03:25Z | 0 | 0 | 0 | 400 | PASS |
72+| 19 | 2026-10-23T14:10:47Z | 0 | 0 | 0 | 410 | PASS |
new file mode 100644
@@ -0,0 +1,72 @@
1+# Quality report — 2026-10-23T14:10:47Z
2+
3+- **Gate**: ✅ **PASS**
4+- **Commit**: `0502ed3` on `main`
5+- **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6+- **Run**: #19 (previous: 2026-10-23T14:03:25Z)
7+
8+## Lint issues (`qlty check`)
9+
10+_none_
11+
12+### Top rules
13+
14+_none_
15+
16+### Most affected files
17+
18+_none_
19+
20+## Code smells (`qlty smells`)
21+
22+Total: **0** (vs previous: ±0)
23+
24+_none_
25+
26+## Metrics (`qlty metrics`)
27+
28+| metric | total | vs previous |
29+|---|---|---|
30+| funcs | 937 | +22 |
31+| classes | 84 | +1 |
32+| fields | 266 | +5 |
33+| cyclo | 927 | +13 |
34+| complex | 410 | +10 |
35+| lcom | 39 | ±0 |
36+| lines | 15649 | +265 |
37+| loc | 14130 | +235 |
38+
39+### Most complex files
40+
41+| file | complex | cyclo | loc |
42+|---|---|---|---|
43+| crates/ui/src/app.rs | 40 | 46 | 526 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 90 | 1704 |
46+| crates/domain/src/mention.rs | 27 | 36 | 501 |
47+| crates/ui/src/suggestions.rs | 26 | 39 | 291 |
48+| crates/acp/src/worker.rs | 22 | 49 | 502 |
49+| crates/ui/src/files.rs | 17 | 18 | 242 |
50+| crates/acp/src/updates.rs | 16 | 57 | 433 |
51+| crates/ui/src/view.rs | 16 | 39 | 907 |
52+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
58+
59+## Trend
60+
61+| run | timestamp | error | warning | smells | complex | gate |
62+|---|---|---|---|---|---|---|
63+| 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
64+| 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
65+| 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
66+| 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
67+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
68+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
69+| 16 | 2026-10-23T13:21:05Z | 0 | 0 | 0 | 380 | PASS |
70+| 17 | 2026-10-23T13:49:34Z | 0 | 0 | 0 | 393 | PASS |
71+| 18 | 2026-10-23T14:03:25Z | 0 | 0 | 0 | 400 | PASS |
72+| 19 | 2026-10-23T14:10:47Z | 0 | 0 | 0 | 410 | PASS |
modified .quality/report-latest.md +32 -32
@@ -1,9 +1,9 @@
1-# Quality report — 2026-10-23T12:19:19Z
1+# Quality report — 2026-10-23T14:10:47Z
22
33 - **Gate**: ✅ **PASS**
4-- **Commit**: `n/a` on `n/a`
4+- **Commit**: `0502ed3` on `main`
55 - **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6-- **Run**: #13 (previous: 2026-10-23T12:17:25Z)
6+- **Run**: #19 (previous: 2026-10-23T14:03:25Z)
77
88 ## Lint issues (`qlty check`)
99
@@ -19,7 +19,7 @@ _none_
1919
2020 ## Code smells (`qlty smells`)
2121
22-Total: **0** (vs previous: -1)
22+Total: **0** (vs previous: ±0)
2323
2424 _none_
2525
@@ -27,46 +27,46 @@ _none_
2727
2828 | metric | total | vs previous |
2929 |---|---|---|
30-| funcs | 630 | ±0 |
31-| classes | 64 | ±0 |
32-| fields | 183 | +10 |
33-| cyclo | 621 | +2 |
34-| complex | 292 | ±0 |
35-| lcom | 24 | +2 |
36-| lines | 10587 | +30 |
37-| loc | 9541 | +27 |
30+| funcs | 937 | +22 |
31+| classes | 84 | +1 |
32+| fields | 266 | +5 |
33+| cyclo | 927 | +13 |
34+| complex | 410 | +10 |
35+| lcom | 39 | ±0 |
36+| lines | 15649 | +265 |
37+| loc | 14130 | +235 |
3838
3939 ### Most complex files
4040
4141 | file | complex | cyclo | loc |
4242 |---|---|---|---|
43-| crates/ui/src/app.rs | 41 | 48 | 487 |
44-| crates/acp/tests/hub.rs | 36 | 37 | 396 |
45-| crates/ui/src/controller.rs | 30 | 88 | 1632 |
46-| crates/acp/src/worker.rs | 26 | 53 | 504 |
43+| crates/ui/src/app.rs | 40 | 46 | 526 |
44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45+| crates/ui/src/controller.rs | 30 | 90 | 1704 |
46+| crates/domain/src/mention.rs | 27 | 36 | 501 |
47+| crates/ui/src/suggestions.rs | 26 | 39 | 291 |
48+| crates/acp/src/worker.rs | 22 | 49 | 502 |
4749 | crates/ui/src/files.rs | 17 | 18 | 242 |
48-| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 28 | 216 |
49-| crates/ui/src/suggestions.rs | 15 | 27 | 202 |
50-| crates/domain/src/mention.rs | 14 | 26 | 382 |
51-| crates/ui/src/view.rs | 14 | 35 | 867 |
52-| crates/store/src/sqlite.rs | 10 | 68 | 685 |
53-| crates/ui/tests/window.rs | 10 | 25 | 1223 |
54-| crates/domain/src/command.rs | 9 | 22 | 257 |
55-| crates/ui/src/agent_form.rs | 9 | 19 | 268 |
56-| crates/acp/src/hub.rs | 7 | 12 | 180 |
57-| crates/ui/src/main.rs | 6 | 5 | 53 |
50+| crates/acp/src/updates.rs | 16 | 57 | 433 |
51+| crates/ui/src/view.rs | 16 | 39 | 907 |
52+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
53+| crates/domain/src/context.rs | 13 | 20 | 372 |
54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
5858
5959 ## Trend
6060
6161 | run | timestamp | error | warning | smells | complex | gate |
6262 |---|---|---|---|---|---|---|
63-| 4 | 2026-10-23T11:00:05Z | 0 | 0 | 0 | 205 | PASS |
64-| 5 | 2026-10-23T11:11:12Z | 0 | 0 | 0 | 207 | PASS |
65-| 6 | 2026-10-23T11:16:31Z | 0 | 0 | 0 | 208 | PASS |
66-| 7 | 2026-10-23T11:21:42Z | 0 | 0 | 0 | 209 | PASS |
67-| 8 | 2026-10-23T11:22:20Z | 0 | 0 | 0 | 209 | PASS |
68-| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
6963 | 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
7064 | 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
7165 | 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
7266 | 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
67+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
68+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
69+| 16 | 2026-10-23T13:21:05Z | 0 | 0 | 0 | 380 | PASS |
70+| 17 | 2026-10-23T13:49:34Z | 0 | 0 | 0 | 393 | PASS |
71+| 18 | 2026-10-23T14:03:25Z | 0 | 0 | 0 | 400 | PASS |
72+| 19 | 2026-10-23T14:10:47Z | 0 | 0 | 0 | 410 | PASS |
@@ -1,9 +1,9 @@
1-# Quality report — 2026-10-23T12:19:19Z1+# Quality report — 2026-10-23T14:10:47Z
2 2
3 - **Gate**: ✅ **PASS**3 - **Gate**: ✅ **PASS**
4-- **Commit**: `n/a` on `n/a`4+- **Commit**: `0502ed3` on `main`
5 - **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)5 - **qlty**: qlty 0.662.0 linux-arm64 (f48face 2026-10-23)
6-- **Run**: #13 (previous: 2026-10-23T12:17:25Z)6+- **Run**: #19 (previous: 2026-10-23T14:03:25Z)
7 7
8 ## Lint issues (`qlty check`)8 ## Lint issues (`qlty check`)
9 9
@@ -19,7 +19,7 @@ _none_
19 19
20 ## Code smells (`qlty smells`)20 ## Code smells (`qlty smells`)
21 21
22-Total: **0** (vs previous: -1)22+Total: **0** (vs previous: ±0)
23 23
24 _none_24 _none_
25 25
@@ -27,46 +27,46 @@ _none_
27 27
28 | metric | total | vs previous |28 | metric | total | vs previous |
29 |---|---|---|29 |---|---|---|
30-| funcs | 630 | ±0 |30+| funcs | 937 | +22 |
31-| classes | 64 | ±0 |31+| classes | 84 | +1 |
32-| fields | 183 | +10 |32+| fields | 266 | +5 |
33-| cyclo | 621 | +2 |33+| cyclo | 927 | +13 |
34-| complex | 292 | ±0 |34+| complex | 410 | +10 |
35-| lcom | 24 | +2 |35+| lcom | 39 | ±0 |
36-| lines | 10587 | +30 |36+| lines | 15649 | +265 |
37-| loc | 9541 | +27 |37+| loc | 14130 | +235 |
38 38
39 ### Most complex files39 ### Most complex files
40 40
41 | file | complex | cyclo | loc |41 | file | complex | cyclo | loc |
42 |---|---|---|---|42 |---|---|---|---|
43-| crates/ui/src/app.rs | 41 | 48 | 487 |43+| crates/ui/src/app.rs | 40 | 46 | 526 |
44-| crates/acp/tests/hub.rs | 36 | 37 | 396 |44+| crates/acp/tests/hub.rs | 38 | 43 | 433 |
45-| crates/ui/src/controller.rs | 30 | 88 | 1632 |45+| crates/ui/src/controller.rs | 30 | 90 | 1704 |
46-| crates/acp/src/worker.rs | 26 | 53 | 504 |46+| crates/domain/src/mention.rs | 27 | 36 | 501 |
47+| crates/ui/src/suggestions.rs | 26 | 39 | 291 |
48+| crates/acp/src/worker.rs | 22 | 49 | 502 |
47 | crates/ui/src/files.rs | 17 | 18 | 242 |49 | crates/ui/src/files.rs | 17 | 18 | 242 |
48-| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 28 | 216 |50+| crates/acp/src/updates.rs | 16 | 57 | 433 |
49-| crates/ui/src/suggestions.rs | 15 | 27 | 202 |51+| crates/ui/src/view.rs | 16 | 39 | 907 |
50-| crates/domain/src/mention.rs | 14 | 26 | 382 |52+| crates/acp/src/bin/synedrion-fake-agent.rs | 15 | 40 | 278 |
51-| crates/ui/src/view.rs | 14 | 35 | 867 |53+| crates/domain/src/context.rs | 13 | 20 | 372 |
52-| crates/store/src/sqlite.rs | 10 | 68 | 685 |54+| crates/domain/src/trace.rs | 12 | 35 | 373 |
53-| crates/ui/tests/window.rs | 10 | 25 | 1223 |55+| crates/ui/src/controller/relay.rs | 11 | 21 | 110 |
54-| crates/domain/src/command.rs | 9 | 22 | 257 |56+| crates/store/src/sqlite.rs | 10 | 75 | 781 |
55-| crates/ui/src/agent_form.rs | 9 | 19 | 268 |57+| crates/ui/src/trace_view.rs | 10 | 16 | 188 |
56-| crates/acp/src/hub.rs | 7 | 12 | 180 |
57-| crates/ui/src/main.rs | 6 | 5 | 53 |
58 58
59 ## Trend59 ## Trend
60 60
61 | run | timestamp | error | warning | smells | complex | gate |61 | run | timestamp | error | warning | smells | complex | gate |
62 |---|---|---|---|---|---|---|62 |---|---|---|---|---|---|---|
63-| 4 | 2026-10-23T11:00:05Z | 0 | 0 | 0 | 205 | PASS |
64-| 5 | 2026-10-23T11:11:12Z | 0 | 0 | 0 | 207 | PASS |
65-| 6 | 2026-10-23T11:16:31Z | 0 | 0 | 0 | 208 | PASS |
66-| 7 | 2026-10-23T11:21:42Z | 0 | 0 | 0 | 209 | PASS |
67-| 8 | 2026-10-23T11:22:20Z | 0 | 0 | 0 | 209 | PASS |
68-| 9 | 2026-10-23T11:41:09Z | 0 | 0 | 0 | 226 | PASS |
69 | 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |63 | 10 | 2026-10-23T11:42:18Z | 0 | 0 | 0 | 226 | PASS |
70 | 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |64 | 11 | 2026-10-23T11:54:46Z | 0 | 0 | 0 | 233 | PASS |
71 | 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |65 | 12 | 2026-10-23T12:17:25Z | 0 | 0 | 1 | 292 | FAIL |
72 | 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |66 | 13 | 2026-10-23T12:19:19Z | 0 | 0 | 0 | 292 | PASS |
67+| 14 | 2026-10-23T13:14:22Z | 0 | 0 | 3 | 382 | FAIL |
68+| 15 | 2026-10-23T13:15:13Z | 0 | 0 | 0 | 380 | PASS |
69+| 16 | 2026-10-23T13:21:05Z | 0 | 0 | 0 | 380 | PASS |
70+| 17 | 2026-10-23T13:49:34Z | 0 | 0 | 0 | 393 | PASS |
71+| 18 | 2026-10-23T14:03:25Z | 0 | 0 | 0 | 400 | PASS |
72+| 19 | 2026-10-23T14:10:47Z | 0 | 0 | 0 | 410 | PASS |
modified .tickets/issues/0014-channel-context-in-prompt.yaml +16 -6
@@ -6,7 +6,7 @@ author:
66 name: Claude
77 email: noreply@anthropic.com
88 createdAt: 2026-10-23T11:00:00.000Z
9-updatedAt: 2026-10-23T11:00:00.000Z
9+updatedAt: 2026-10-23T14:30:00.000Z
1010 labels: ["kind::feature", "priority::high"]
1111 epic: ACP
1212 milestone: v0.2.0
@@ -21,9 +21,19 @@ body: |
2121
2222 ### Critères d'acceptation
2323
24- - [ ] Le prompt contient les N derniers messages (N configurable) puis le message mentionné, avec l'auteur de chacun
25- - [ ] Un agent ne reçoit pas deux fois les mêmes messages d'un tour à l'autre dans une même session (seulement ceux apparus depuis son dernier tour)
26- - [ ] La construction du prompt est une fonction pure testée à part
27- - [ ] La limite de taille est documentée, et un message tronqué est signalé comme tel à l'agent
24+ - [x] Le prompt contient les N derniers messages (N configurable) puis le message mentionné, avec l'auteur de chacun
25+ - [x] Un agent ne reçoit pas deux fois les mêmes messages d'un tour à l'autre dans une même session (seulement ceux apparus depuis son dernier tour)
26+ - [x] La construction du prompt est une fonction pure testée à part
27+ - [x] La limite de taille est documentée, et un message tronqué est signalé comme tel à l'agent
2828 tasks: []
29-comments: []
29+comments:
30+ - id: 1
31+ author:
32+ name: Claude
33+ email: noreply@anthropic.com
34+ createdAt: 2026-10-23T14:30:00.000Z
35+ body: |
36+ Fait. `domain::context` (`select_context`, `render_prompt`) est pur et testé à part ; le contrôleur retient le dernier message remis à chaque agent par channel. N (0 à 100, 20 par défaut) se règle dans le panneau Settings. Limites : 2 000 caractères par message (marqueur `[message cut: N more character(s)]`) et 12 000 au total (`[N earlier message(s) not shown]`). Un message de l'utilisateur sans rien à ajouter part tel que saisi, une commande part nue.
37+ Testé : tests de domaine et de contrôleur, plus des mutations (suivi de ce qui a été vu, messages propres de l'agent, coupure avant le tour) qui font échouer les tests.
38+ Non vérifié : un vrai agent. Limites connues, écrites dans la référence : le suivi est en mémoire, et un redémarrage du processus d'un agent seul ne renvoie pas ce qui avait déjà été remis.
39+
@@ -6,7 +6,7 @@ author:
6 name: Claude6 name: Claude
7 email: noreply@anthropic.com7 email: noreply@anthropic.com
8 createdAt: 2026-10-23T11:00:00.000Z8 createdAt: 2026-10-23T11:00:00.000Z
9-updatedAt: 2026-10-23T11:00:00.000Z9+updatedAt: 2026-10-23T14:30:00.000Z
10 labels: ["kind::feature", "priority::high"]10 labels: ["kind::feature", "priority::high"]
11 epic: ACP11 epic: ACP
12 milestone: v0.2.012 milestone: v0.2.0
@@ -21,9 +21,19 @@ body: |
21 21
22 ### Critères d'acceptation22 ### Critères d'acceptation
23 23
24- - [ ] Le prompt contient les N derniers messages (N configurable) puis le message mentionné, avec l'auteur de chacun24+ - [x] Le prompt contient les N derniers messages (N configurable) puis le message mentionné, avec l'auteur de chacun
25- - [ ] Un agent ne reçoit pas deux fois les mêmes messages d'un tour à l'autre dans une même session (seulement ceux apparus depuis son dernier tour)25+ - [x] Un agent ne reçoit pas deux fois les mêmes messages d'un tour à l'autre dans une même session (seulement ceux apparus depuis son dernier tour)
26- - [ ] La construction du prompt est une fonction pure testée à part26+ - [x] La construction du prompt est une fonction pure testée à part
27- - [ ] La limite de taille est documentée, et un message tronqué est signalé comme tel à l'agent27+ - [x] La limite de taille est documentée, et un message tronqué est signalé comme tel à l'agent
28 tasks: []28 tasks: []
29-comments: []29+comments:
30+ - id: 1
31+ author:
32+ name: Claude
33+ email: noreply@anthropic.com
34+ createdAt: 2026-10-23T14:30:00.000Z
35+ body: |
36+ Fait. `domain::context` (`select_context`, `render_prompt`) est pur et testé à part ; le contrôleur retient le dernier message remis à chaque agent par channel. N (0 à 100, 20 par défaut) se règle dans le panneau Settings. Limites : 2 000 caractères par message (marqueur `[message cut: N more character(s)]`) et 12 000 au total (`[N earlier message(s) not shown]`). Un message de l'utilisateur sans rien à ajouter part tel que saisi, une commande part nue.
37+ Testé : tests de domaine et de contrôleur, plus des mutations (suivi de ce qui a été vu, messages propres de l'agent, coupure avant le tour) qui font échouer les tests.
38+ Non vérifié : un vrai agent. Limites connues, écrites dans la référence : le suivi est en mémoire, et un redémarrage du processus d'un agent seul ne renvoie pas ce qui avait déjà été remis.
39+
modified .tickets/issues/0015-agent-to-agent-mentions.yaml +17 -7
@@ -6,7 +6,7 @@ author:
66 name: Claude
77 email: noreply@anthropic.com
88 createdAt: 2026-10-23T11:00:00.000Z
9-updatedAt: 2026-10-23T11:00:00.000Z
9+updatedAt: 2026-10-23T14:30:00.000Z
1010 labels: ["kind::feature", "priority::high"]
1111 epic: ACP
1212 milestone: v0.2.0
@@ -21,10 +21,20 @@ body: |
2121
2222 ### Critères d'acceptation
2323
24- - [ ] Une mention dans la réponse d'un agent déclenche l'agent mentionné
25- - [ ] Profondeur maximale de chaîne configurable, avec une valeur par défaut basse ; au-delà, la chaîne s'arrête et un message système l'indique
26- - [ ] Un bouton « stop » interrompt toute la chaîne en cours (annule tous les tours liés)
27- - [ ] Un agent qui se mentionne lui-même est ignoré
28- - [ ] Tests : chaîne A vers B vers A arrêtée par la limite, interruption manuelle, auto-mention
24+ - [x] Une mention dans la réponse d'un agent déclenche l'agent mentionné
25+ - [x] Profondeur maximale de chaîne configurable, avec une valeur par défaut basse ; au-delà, la chaîne s'arrête et un message système l'indique
26+ - [x] Un bouton « stop » interrompt toute la chaîne en cours (annule tous les tours liés)
27+ - [x] Un agent qui se mentionne lui-même est ignoré
28+ - [x] Tests : chaîne A vers B vers A arrêtée par la limite, interruption manuelle, auto-mention
2929 tasks: []
30-comments: []
30+comments:
31+ - id: 1
32+ author:
33+ name: Claude
34+ email: noreply@anthropic.com
35+ createdAt: 2026-10-23T14:30:00.000Z
36+ body: |
37+ Fait. L'agent mentionné est appelé quand le tour de l'agent se termine normalement, avec la réponse entière (`[Message from @nom]`). Profondeur réglable de 0 à 10, 3 par défaut, 0 interdisant les appels ; au-delà, un message de Synedrion dit `Chain stopped: …`. Le bouton Stop annule tous les tours du channel, et une réponse qui arrive après le clic n'appelle personne.
38+ Testé (controller et fenêtre) : chaîne A→B→A arrêtée par la limite, la limite à 3 par défaut, nouvelle chaîne à chaque message de l'utilisateur, arrêt, auto-mention, nom inconnu, tour annulé ou échoué, mention coupée entre deux morceaux, agent injoignable. 12 mutations du code font échouer au moins un test.
39+ Voir `docs/en/explanation/agents-calling-agents.md`. Non vérifié : un vrai agent.
40+
@@ -6,7 +6,7 @@ author:
6 name: Claude6 name: Claude
7 email: noreply@anthropic.com7 email: noreply@anthropic.com
8 createdAt: 2026-10-23T11:00:00.000Z8 createdAt: 2026-10-23T11:00:00.000Z
9-updatedAt: 2026-10-23T11:00:00.000Z9+updatedAt: 2026-10-23T14:30:00.000Z
10 labels: ["kind::feature", "priority::high"]10 labels: ["kind::feature", "priority::high"]
11 epic: ACP11 epic: ACP
12 milestone: v0.2.012 milestone: v0.2.0
@@ -21,10 +21,20 @@ body: |
21 21
22 ### Critères d'acceptation22 ### Critères d'acceptation
23 23
24- - [ ] Une mention dans la réponse d'un agent déclenche l'agent mentionné24+ - [x] Une mention dans la réponse d'un agent déclenche l'agent mentionné
25- - [ ] Profondeur maximale de chaîne configurable, avec une valeur par défaut basse ; au-delà, la chaîne s'arrête et un message système l'indique25+ - [x] Profondeur maximale de chaîne configurable, avec une valeur par défaut basse ; au-delà, la chaîne s'arrête et un message système l'indique
26- - [ ] Un bouton « stop » interrompt toute la chaîne en cours (annule tous les tours liés)26+ - [x] Un bouton « stop » interrompt toute la chaîne en cours (annule tous les tours liés)
27- - [ ] Un agent qui se mentionne lui-même est ignoré27+ - [x] Un agent qui se mentionne lui-même est ignoré
28- - [ ] Tests : chaîne A vers B vers A arrêtée par la limite, interruption manuelle, auto-mention28+ - [x] Tests : chaîne A vers B vers A arrêtée par la limite, interruption manuelle, auto-mention
29 tasks: []29 tasks: []
30-comments: []30+comments:
31+ - id: 1
32+ author:
33+ name: Claude
34+ email: noreply@anthropic.com
35+ createdAt: 2026-10-23T14:30:00.000Z
36+ body: |
37+ Fait. L'agent mentionné est appelé quand le tour de l'agent se termine normalement, avec la réponse entière (`[Message from @nom]`). Profondeur réglable de 0 à 10, 3 par défaut, 0 interdisant les appels ; au-delà, un message de Synedrion dit `Chain stopped: …`. Le bouton Stop annule tous les tours du channel, et une réponse qui arrive après le clic n'appelle personne.
38+ Testé (controller et fenêtre) : chaîne A→B→A arrêtée par la limite, la limite à 3 par défaut, nouvelle chaîne à chaque message de l'utilisateur, arrêt, auto-mention, nom inconnu, tour annulé ou échoué, mention coupée entre deux morceaux, agent injoignable. 12 mutations du code font échouer au moins un test.
39+ Voir `docs/en/explanation/agents-calling-agents.md`. Non vérifié : un vrai agent.
40+
modified .tickets/issues/0017-render-tool-calls-and-plans.yaml +16 -6
@@ -6,7 +6,7 @@ author:
66 name: Claude
77 email: noreply@anthropic.com
88 createdAt: 2026-10-23T11:00:00.000Z
9-updatedAt: 2026-10-23T11:00:00.000Z
9+updatedAt: 2026-10-23T14:30:00.000Z
1010 labels: ["kind::feature", "priority::medium"]
1111 epic: UI
1212 milestone: v0.2.0
@@ -20,9 +20,19 @@ body: |
2020
2121 ### Critères d'acceptation
2222
23- - [ ] Les `tool_call` et leurs mises à jour sont affichés sous forme repliable (titre, statut, sortie)
24- - [ ] Les `plan` envoyés par l'agent sont affichés et mis à jour
25- - [ ] Les types de contenu non gérés sont affichés de façon dégradée (jamais ignorés en silence)
26- - [ ] Tests sur la traduction des `session/update` en éléments d'affichage
23+ - [x] Les `tool_call` et leurs mises à jour sont affichés sous forme repliable (titre, statut, sortie)
24+ - [x] Les `plan` envoyés par l'agent sont affichés et mis à jour
25+ - [x] Les types de contenu non gérés sont affichés de façon dégradée (jamais ignorés en silence)
26+ - [x] Tests sur la traduction des `session/update` en éléments d'affichage
2727 tasks: []
28-comments: []
28+comments:
29+ - id: 1
30+ author:
31+ name: Claude
32+ email: noreply@anthropic.com
33+ createdAt: 2026-10-23T14:30:00.000Z
34+ body: |
35+ Fait. Les appels d'outils et les plans sont des messages d'un genre `trace` (migration 3 du schéma), mis à jour sur place, ordonnés avec le texte. Carte repliable avec titre, genre, statut et bouton Show/Hide output ; le plan est une carte à étapes. Le contenu qui ne peut pas être dessiné (image, audio, terminal, diff, lien, ressource binaire, mise à jour inconnue) devient une note entre crochets ou une notice.
36+ Testé : traduction de chaque genre de `session/update` (module `updates`), stockage, contrôleur, fenêtre, et le chemin complet avec l'agent de test (mot-clé `tools`).
37+ Non vérifié : l'apparence des cartes (jamais vue sur un écran), et un vrai agent qui envoie ces mises à jour. Voir `docs/en/reference/tool-calls-and-plans.md`.
38+
@@ -6,7 +6,7 @@ author:
6 name: Claude6 name: Claude
7 email: noreply@anthropic.com7 email: noreply@anthropic.com
8 createdAt: 2026-10-23T11:00:00.000Z8 createdAt: 2026-10-23T11:00:00.000Z
9-updatedAt: 2026-10-23T11:00:00.000Z9+updatedAt: 2026-10-23T14:30:00.000Z
10 labels: ["kind::feature", "priority::medium"]10 labels: ["kind::feature", "priority::medium"]
11 epic: UI11 epic: UI
12 milestone: v0.2.012 milestone: v0.2.0
@@ -20,9 +20,19 @@ body: |
20 20
21 ### Critères d'acceptation21 ### Critères d'acceptation
22 22
23- - [ ] Les `tool_call` et leurs mises à jour sont affichés sous forme repliable (titre, statut, sortie)23+ - [x] Les `tool_call` et leurs mises à jour sont affichés sous forme repliable (titre, statut, sortie)
24- - [ ] Les `plan` envoyés par l'agent sont affichés et mis à jour24+ - [x] Les `plan` envoyés par l'agent sont affichés et mis à jour
25- - [ ] Les types de contenu non gérés sont affichés de façon dégradée (jamais ignorés en silence)25+ - [x] Les types de contenu non gérés sont affichés de façon dégradée (jamais ignorés en silence)
26- - [ ] Tests sur la traduction des `session/update` en éléments d'affichage26+ - [x] Tests sur la traduction des `session/update` en éléments d'affichage
27 tasks: []27 tasks: []
28-comments: []28+comments:
29+ - id: 1
30+ author:
31+ name: Claude
32+ email: noreply@anthropic.com
33+ createdAt: 2026-10-23T14:30:00.000Z
34+ body: |
35+ Fait. Les appels d'outils et les plans sont des messages d'un genre `trace` (migration 3 du schéma), mis à jour sur place, ordonnés avec le texte. Carte repliable avec titre, genre, statut et bouton Show/Hide output ; le plan est une carte à étapes. Le contenu qui ne peut pas être dessiné (image, audio, terminal, diff, lien, ressource binaire, mise à jour inconnue) devient une note entre crochets ou une notice.
36+ Testé : traduction de chaque genre de `session/update` (module `updates`), stockage, contrôleur, fenêtre, et le chemin complet avec l'agent de test (mot-clé `tools`).
37+ Non vérifié : l'apparence des cartes (jamais vue sur un écran), et un vrai agent qui envoie ces mises à jour. Voir `docs/en/reference/tool-calls-and-plans.md`.
38+
modified .tickets/issues/0018-acp-client-fs-terminal-capabilities.yaml +14 -4
@@ -6,7 +6,7 @@ author:
66 name: Claude
77 email: noreply@anthropic.com
88 createdAt: 2026-10-23T11:00:00.000Z
9-updatedAt: 2026-10-23T11:00:00.000Z
9+updatedAt: 2026-10-23T14:30:00.000Z
1010 labels: ["kind::feature", "priority::medium", "question"]
1111 epic: ACP
1212 milestone: v0.2.0
@@ -20,9 +20,19 @@ body: |
2020
2121 ### À trancher
2222
23- - [ ] Annoncer ou non ces capacités à l'`initialize`, par agent ou globalement
23+ - [x] Annoncer ou non ces capacités à l'`initialize`, par agent ou globalement
2424 - [ ] Si oui : périmètre autorisé (dossier de travail de l'agent seulement), confirmation de l'utilisateur pour les écritures
2525 - [ ] Si non : confirmer que mini-me fonctionne sans, avec son propre outil `bash`
26- - [ ] Livrable : décision écrite dans `docs/explanation/`, puis ticket d'implémentation si nécessaire
26+ - [x] Livrable : décision écrite dans `docs/explanation/`, puis ticket d'implémentation si nécessaire
2727 tasks: []
28-comments: []
28+comments:
29+ - id: 1
30+ author:
31+ name: Claude
32+ email: noreply@anthropic.com
33+ createdAt: 2026-10-23T14:30:00.000Z
34+ body: |
35+ Décision prise et écrite : Synedrion n'annonce aucune capacité fs ni terminal (`docs/en/explanation/client-capabilities.md`, et la version française). Raison : une sandbox sert à garder l'agent loin de l'hôte, et ces services seraient un trou dans ce mur. Un test fige la décision (`synedrion_announces_no_file_or_terminal_capability_to_agents`). Aucun ticket d'implémentation n'est nécessaire.
36+ Non coché : « Si oui » (sans objet), et « confirmer que mini-me fonctionne sans, avec son propre outil bash » : mini-me démarre et répond sans ces capacités, mais son outil bash n'a pas été exercé.
37+ Cette décision a été prise en suivant la recommandation proposée ; elle attend la confirmation explicite de k33g.
38+
@@ -6,7 +6,7 @@ author:
6 name: Claude6 name: Claude
7 email: noreply@anthropic.com7 email: noreply@anthropic.com
8 createdAt: 2026-10-23T11:00:00.000Z8 createdAt: 2026-10-23T11:00:00.000Z
9-updatedAt: 2026-10-23T11:00:00.000Z9+updatedAt: 2026-10-23T14:30:00.000Z
10 labels: ["kind::feature", "priority::medium", "question"]10 labels: ["kind::feature", "priority::medium", "question"]
11 epic: ACP11 epic: ACP
12 milestone: v0.2.012 milestone: v0.2.0
@@ -20,9 +20,19 @@ body: |
20 20
21 ### À trancher21 ### À trancher
22 22
23- - [ ] Annoncer ou non ces capacités à l'`initialize`, par agent ou globalement23+ - [x] Annoncer ou non ces capacités à l'`initialize`, par agent ou globalement
24 - [ ] Si oui : périmètre autorisé (dossier de travail de l'agent seulement), confirmation de l'utilisateur pour les écritures24 - [ ] Si oui : périmètre autorisé (dossier de travail de l'agent seulement), confirmation de l'utilisateur pour les écritures
25 - [ ] Si non : confirmer que mini-me fonctionne sans, avec son propre outil `bash`25 - [ ] Si non : confirmer que mini-me fonctionne sans, avec son propre outil `bash`
26- - [ ] Livrable : décision écrite dans `docs/explanation/`, puis ticket d'implémentation si nécessaire26+ - [x] Livrable : décision écrite dans `docs/explanation/`, puis ticket d'implémentation si nécessaire
27 tasks: []27 tasks: []
28-comments: []28+comments:
29+ - id: 1
30+ author:
31+ name: Claude
32+ email: noreply@anthropic.com
33+ createdAt: 2026-10-23T14:30:00.000Z
34+ body: |
35+ Décision prise et écrite : Synedrion n'annonce aucune capacité fs ni terminal (`docs/en/explanation/client-capabilities.md`, et la version française). Raison : une sandbox sert à garder l'agent loin de l'hôte, et ces services seraient un trou dans ce mur. Un test fige la décision (`synedrion_announces_no_file_or_terminal_capability_to_agents`). Aucun ticket d'implémentation n'est nécessaire.
36+ Non coché : « Si oui » (sans objet), et « confirmer que mini-me fonctionne sans, avec son propre outil bash » : mini-me démarre et répond sans ces capacités, mais son outil bash n'a pas été exercé.
37+ Cette décision a été prise en suivant la recommandation proposée ; elle attend la confirmation explicite de k33g.
38+
modified .tickets/issues/0020-pouvoir-choisir-la-localisation-du-dossier-de-l.yaml +12 -2
@@ -6,9 +6,19 @@ author:
66 name: k33g
77 email: ph.charriere@gmail.com
88 createdAt: 2026-10-23T11:51:51.755Z
9-updatedAt: 2026-10-23T11:51:51.755Z
9+updatedAt: 2026-10-23T14:30:00.000Z
1010 labels: []
1111 epic: IDEAS
1212 body: ""
1313 tasks: []
14-comments: []
14+comments:
15+ - id: 1
16+ author:
17+ name: Claude
18+ email: noreply@anthropic.com
19+ createdAt: 2026-10-23T14:30:00.000Z
20+ body: |
21+ Fait, à valider à l'écran. Le formulaire d'un agent a un bouton Browse… sous le champ Working folder : liste de dossiers dans l'application (pas la boîte de dialogue du système), `..` pour monter, clic pour entrer, Use this folder pour remplir le champ, Cancel pour fermer. Il s'ouvre sur le dossier saisi s'il existe, sinon sur HOME. Dossiers cachés omis, 200 dossiers au plus.
22+ Testé : 10 tests du module `folders` et 7 tests de fenêtre, dont l'enregistrement du dossier choisi avec l'agent. L'apparence n'a pas été vue.
23+ Je n'ai pas fermé le ticket.
24+
@@ -6,9 +6,19 @@ author:
6 name: k33g6 name: k33g
7 email: ph.charriere@gmail.com7 email: ph.charriere@gmail.com
8 createdAt: 2026-10-23T11:51:51.755Z8 createdAt: 2026-10-23T11:51:51.755Z
9-updatedAt: 2026-10-23T11:51:51.755Z9+updatedAt: 2026-10-23T14:30:00.000Z
10 labels: []10 labels: []
11 epic: IDEAS11 epic: IDEAS
12 body: ""12 body: ""
13 tasks: []13 tasks: []
14-comments: []14+comments:
15+ - id: 1
16+ author:
17+ name: Claude
18+ email: noreply@anthropic.com
19+ createdAt: 2026-10-23T14:30:00.000Z
20+ body: |
21+ Fait, à valider à l'écran. Le formulaire d'un agent a un bouton Browse… sous le champ Working folder : liste de dossiers dans l'application (pas la boîte de dialogue du système), `..` pour monter, clic pour entrer, Use this folder pour remplir le champ, Cancel pour fermer. Il s'ouvre sur le dossier saisi s'il existe, sinon sur HOME. Dossiers cachés omis, 200 dossiers au plus.
22+ Testé : 10 tests du module `folders` et 7 tests de fenêtre, dont l'enregistrement du dossier choisi avec l'agent. L'apparence n'a pas été vue.
23+ Je n'ai pas fermé le ticket.
24+
modified Cargo.lock +1 -0
@@ -7028,6 +7028,7 @@ dependencies = [
70287028 "async-channel",
70297029 "async-io",
70307030 "futures",
7031+ "serde_json",
70317032 "synedrion-domain",
70327033 ]
70337034
@@ -7028,6 +7028,7 @@ dependencies = [
7028 "async-channel",7028 "async-channel",
7029 "async-io",7029 "async-io",
7030 "futures",7030 "futures",
7031+ "serde_json",
7031 "synedrion-domain",7032 "synedrion-domain",
7032 ]7033 ]
7033 7034
modified crates/acp/Cargo.toml +1 -0
@@ -12,4 +12,5 @@ agent-client-protocol = { version = "3.5.0", features = ["process", "stdio"] }
1212 async-channel = "2.5.0"
1313 async-io = "2.6.0"
1414 futures = "0.3.34"
15+serde_json = "1.0.154"
1516 synedrion-domain = { version = "0.1.0", path = "../domain" }
@@ -12,4 +12,5 @@ agent-client-protocol = { version = "3.5.0", features = ["process", "stdio"] }
12 async-channel = "2.5.0"12 async-channel = "2.5.0"
13 async-io = "2.6.0"13 async-io = "2.6.0"
14 futures = "0.3.34"14 futures = "0.3.34"
15+serde_json = "1.0.154"
15 synedrion-domain = { version = "0.1.0", path = "../domain" }16 synedrion-domain = { version = "0.1.0", path = "../domain" }
modified crates/acp/README.md +3 -1
@@ -23,7 +23,9 @@ hub.send_prompt(&agent, ChannelId(1), "hello").unwrap();
2323 | `AgentHub` | `new(sink)`, `send_prompt`, `send_prompt_with_files` (links to files), `cancel_turn`, `answer_permission`, `status`, `stop_all` |
2424 | `HubError` | Why a prompt could not be handed over |
2525 | `protocol_log` | The optional log of the raw conversation with an agent, turned on by `SYNEDRION_ACP_LOG` (`LOG_VARIABLE`, `format_line`, `direction_label`) |
26-| `events` | `AgentEvent` (including `Thought` and `CommandsAvailable`), `AgentCommand`, `EventSink`, `TurnOutcome`, `PermissionRequest`, `PermissionRequestId`, `PermissionOption`, `PermissionKind`, `PermissionChoice` |
26+| `events` | `AgentEvent` (including `Thought`, `CommandsAvailable`, `ToolCall`, `ToolCallUpdated`, `Plan` and `Notice`), `AgentCommand`, `EventSink`, `TurnOutcome`, `PermissionRequest`, `PermissionRequestId`, `PermissionOption`, `PermissionKind`, `PermissionChoice` |
2727 | `permission` | `PermissionBroker`: matches a user's answer with the request waiting for it |
2828
29+Every `session/update` is translated into an event by a private function, tested for each kind of update: see [tool calls, plans and what cannot be shown](../../docs/en/reference/tool-calls-and-plans.md). The client announces no capability to agents: see [client capabilities](../../docs/en/explanation/client-capabilities.md).
30+
2931 The crate also holds the binary `synedrion-fake-agent`, a test agent described in the [test agent reference](../../docs/en/reference/test-agent.md). The protocol calls are in the [ACP methods reference](../../docs/en/reference/acp-methods.md). Run the tests with `cargo test -p synedrion-acp`.
@@ -23,7 +23,9 @@ hub.send_prompt(&agent, ChannelId(1), "hello").unwrap();
23 | `AgentHub` | `new(sink)`, `send_prompt`, `send_prompt_with_files` (links to files), `cancel_turn`, `answer_permission`, `status`, `stop_all` |23 | `AgentHub` | `new(sink)`, `send_prompt`, `send_prompt_with_files` (links to files), `cancel_turn`, `answer_permission`, `status`, `stop_all` |
24 | `HubError` | Why a prompt could not be handed over |24 | `HubError` | Why a prompt could not be handed over |
25 | `protocol_log` | The optional log of the raw conversation with an agent, turned on by `SYNEDRION_ACP_LOG` (`LOG_VARIABLE`, `format_line`, `direction_label`) |25 | `protocol_log` | The optional log of the raw conversation with an agent, turned on by `SYNEDRION_ACP_LOG` (`LOG_VARIABLE`, `format_line`, `direction_label`) |
26-| `events` | `AgentEvent` (including `Thought` and `CommandsAvailable`), `AgentCommand`, `EventSink`, `TurnOutcome`, `PermissionRequest`, `PermissionRequestId`, `PermissionOption`, `PermissionKind`, `PermissionChoice` |26+| `events` | `AgentEvent` (including `Thought`, `CommandsAvailable`, `ToolCall`, `ToolCallUpdated`, `Plan` and `Notice`), `AgentCommand`, `EventSink`, `TurnOutcome`, `PermissionRequest`, `PermissionRequestId`, `PermissionOption`, `PermissionKind`, `PermissionChoice` |
27 | `permission` | `PermissionBroker`: matches a user's answer with the request waiting for it |27 | `permission` | `PermissionBroker`: matches a user's answer with the request waiting for it |
28 28
29+Every `session/update` is translated into an event by a private function, tested for each kind of update: see [tool calls, plans and what cannot be shown](../../docs/en/reference/tool-calls-and-plans.md). The client announces no capability to agents: see [client capabilities](../../docs/en/explanation/client-capabilities.md).
30+
29 The crate also holds the binary `synedrion-fake-agent`, a test agent described in the [test agent reference](../../docs/en/reference/test-agent.md). The protocol calls are in the [ACP methods reference](../../docs/en/reference/acp-methods.md). Run the tests with `cargo test -p synedrion-acp`.31 The crate also holds the binary `synedrion-fake-agent`, a test agent described in the [test agent reference](../../docs/en/reference/test-agent.md). The protocol calls are in the [ACP methods reference](../../docs/en/reference/acp-methods.md). Run the tests with `cargo test -p synedrion-acp`.
modified crates/acp/src/bin/synedrion-fake-agent.rs +93 -30
@@ -9,6 +9,7 @@
99 //! | `ask` | asks permission, then says whether it was granted |
1010 //! | `slow` | waits until the turn is cancelled |
1111 //! | `think` | sends a few pieces of reasoning, then answers `done` |
12+//! | `tools` | sends a plan, a tool call and its completion, then answers `tools done` |
1213 //! | `/new` | answers `fresh start` |
1314 //! | `/greet Bob` | answers `hello Bob` |
1415 //!
@@ -25,10 +26,11 @@ use std::time::Duration;
2526 use agent_client_protocol::schema::v1::{
2627 AgentCapabilities, AvailableCommand, AvailableCommandInput, AvailableCommandsUpdate,
2728 CancelNotification, ContentBlock, ContentChunk, InitializeRequest, InitializeResponse,
28- NewSessionRequest, NewSessionResponse, PermissionOption, PermissionOptionKind, PromptRequest,
29- PromptResponse, RequestPermissionOutcome, RequestPermissionRequest, SessionId,
30- SessionNotification, SessionUpdate, StopReason, TextContent, ToolCallUpdate,
31- ToolCallUpdateFields, UnstructuredCommandInput,
29+ NewSessionRequest, NewSessionResponse, PermissionOption, PermissionOptionKind, Plan, PlanEntry,
30+ PlanEntryPriority, PlanEntryStatus, PromptRequest, PromptResponse, RequestPermissionOutcome,
31+ RequestPermissionRequest, SessionId, SessionNotification, SessionUpdate, StopReason,
32+ TextContent, ToolCall, ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields,
33+ ToolKind, UnstructuredCommandInput,
3234 };
3335 use agent_client_protocol::{Agent, ConnectionTo, Error, Stdio};
3436
@@ -110,37 +112,98 @@ async fn answer(
110112 let session = request.session_id;
111113 let text = prompt_text(&request.prompt);
112114
113- let keyword = first_word_that_is_not_a_mention(&text);
114-
115- if keyword == "crash" {
116- std::process::exit(3);
117- }
118- if keyword == "ask" {
119- return ask_permission(connection, &session).await;
120- }
121- if text.starts_with("/new") {
122- say(connection, &session, "fresh start")?;
123- return Ok(StopReason::EndTurn);
124- }
125- if let Some(who) = text.strip_prefix("/greet") {
126- say(connection, &session, &format!("hello{who}"))?;
127- return Ok(StopReason::EndTurn);
128- }
129- if keyword == "think" {
130- for piece in ["pondering ", "the ", "question "] {
131- think(connection, &session, piece)?;
115+ match Behaviour::of(&text) {
116+ Behaviour::Crash => std::process::exit(3),
117+ Behaviour::Ask => ask_permission(connection, &session).await,
118+ Behaviour::Slow => wait_for_cancellation(connection, &session, cancelled).await,
119+ Behaviour::Say(reply) => {
120+ say(connection, &session, &reply)?;
121+ Ok(StopReason::EndTurn)
122+ }
123+ Behaviour::Think => {
124+ for piece in ["pondering ", "the ", "question "] {
125+ think(connection, &session, piece)?;
126+ }
127+ say(connection, &session, "done")?;
128+ Ok(StopReason::EndTurn)
129+ }
130+ Behaviour::Tools => {
131+ use_tools(connection, &session)?;
132+ say(connection, &session, "tools done")?;
133+ Ok(StopReason::EndTurn)
134+ }
135+ Behaviour::Repeat => {
136+ for word in text.split_whitespace() {
137+ say(connection, &session, &format!("{word} "))?;
138+ }
139+ Ok(StopReason::EndTurn)
132140 }
133- say(connection, &session, "done")?;
134- return Ok(StopReason::EndTurn);
135141 }
136- if keyword == "slow" {
137- return wait_for_cancellation(connection, &session, cancelled).await;
142+}
143+
144+/// What the agent does for a prompt, chosen from its text.
145+enum Behaviour {
146+ Crash,
147+ Ask,
148+ Slow,
149+ Think,
150+ Tools,
151+ /// Answers with this text in one piece.
152+ Say(String),
153+ /// Repeats the prompt, one word per chunk.
154+ Repeat,
155+}
156+
157+impl Behaviour {
158+ fn of(text: &str) -> Self {
159+ if text.starts_with("/new") {
160+ return Self::Say("fresh start".to_string());
161+ }
162+ if let Some(who) = text.strip_prefix("/greet") {
163+ return Self::Say(format!("hello{who}"));
164+ }
165+ match first_word_that_is_not_a_mention(text) {
166+ "crash" => Self::Crash,
167+ "ask" => Self::Ask,
168+ "slow" => Self::Slow,
169+ "think" => Self::Think,
170+ "tools" => Self::Tools,
171+ _ => Self::Repeat,
172+ }
138173 }
174+}
139175
140- for word in text.split_whitespace() {
141- say(connection, &session, &format!("{word} "))?;
176+/// Sends a plan, a tool call that starts, and the update that completes it with an output.
177+fn use_tools(
178+ connection: &ConnectionTo<agent_client_protocol::Client>,
179+ session: &SessionId,
180+) -> Result<(), Error> {
181+ let steps = vec![
182+ PlanEntry::new(
183+ "Read the file",
184+ PlanEntryPriority::High,
185+ PlanEntryStatus::InProgress,
186+ ),
187+ PlanEntry::new("Report", PlanEntryPriority::Low, PlanEntryStatus::Pending),
188+ ];
189+ let updates = [
190+ SessionUpdate::Plan(Plan::new(steps)),
191+ SessionUpdate::ToolCall(
192+ ToolCall::new("tool-1", "Read notes.md")
193+ .kind(ToolKind::Read)
194+ .status(ToolCallStatus::InProgress),
195+ ),
196+ SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
197+ "tool-1",
198+ ToolCallUpdateFields::new()
199+ .status(ToolCallStatus::Completed)
200+ .content(vec![ToolCallContent::from("the notes")]),
201+ )),
202+ ];
203+ for update in updates {
204+ connection.send_notification(SessionNotification::new(session.clone(), update))?;
142205 }
143- Ok(StopReason::EndTurn)
206+ Ok(())
144207 }
145208
146209 async fn ask_permission(
@@ -9,6 +9,7 @@
9 //! | `ask` | asks permission, then says whether it was granted |9 //! | `ask` | asks permission, then says whether it was granted |
10 //! | `slow` | waits until the turn is cancelled |10 //! | `slow` | waits until the turn is cancelled |
11 //! | `think` | sends a few pieces of reasoning, then answers `done` |11 //! | `think` | sends a few pieces of reasoning, then answers `done` |
12+//! | `tools` | sends a plan, a tool call and its completion, then answers `tools done` |
12 //! | `/new` | answers `fresh start` |13 //! | `/new` | answers `fresh start` |
13 //! | `/greet Bob` | answers `hello Bob` |14 //! | `/greet Bob` | answers `hello Bob` |
14 //!15 //!
@@ -25,10 +26,11 @@ use std::time::Duration;
25 use agent_client_protocol::schema::v1::{26 use agent_client_protocol::schema::v1::{
26 AgentCapabilities, AvailableCommand, AvailableCommandInput, AvailableCommandsUpdate,27 AgentCapabilities, AvailableCommand, AvailableCommandInput, AvailableCommandsUpdate,
27 CancelNotification, ContentBlock, ContentChunk, InitializeRequest, InitializeResponse,28 CancelNotification, ContentBlock, ContentChunk, InitializeRequest, InitializeResponse,
28- NewSessionRequest, NewSessionResponse, PermissionOption, PermissionOptionKind, PromptRequest,29+ NewSessionRequest, NewSessionResponse, PermissionOption, PermissionOptionKind, Plan, PlanEntry,
29- PromptResponse, RequestPermissionOutcome, RequestPermissionRequest, SessionId,30+ PlanEntryPriority, PlanEntryStatus, PromptRequest, PromptResponse, RequestPermissionOutcome,
30- SessionNotification, SessionUpdate, StopReason, TextContent, ToolCallUpdate,31+ RequestPermissionRequest, SessionId, SessionNotification, SessionUpdate, StopReason,
31- ToolCallUpdateFields, UnstructuredCommandInput,32+ TextContent, ToolCall, ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolCallUpdateFields,
33+ ToolKind, UnstructuredCommandInput,
32 };34 };
33 use agent_client_protocol::{Agent, ConnectionTo, Error, Stdio};35 use agent_client_protocol::{Agent, ConnectionTo, Error, Stdio};
34 36
@@ -110,37 +112,98 @@ async fn answer(
110 let session = request.session_id;112 let session = request.session_id;
111 let text = prompt_text(&request.prompt);113 let text = prompt_text(&request.prompt);
112 114
113- let keyword = first_word_that_is_not_a_mention(&text);115+ match Behaviour::of(&text) {
114-116+ Behaviour::Crash => std::process::exit(3),
115- if keyword == "crash" {117+ Behaviour::Ask => ask_permission(connection, &session).await,
116- std::process::exit(3);118+ Behaviour::Slow => wait_for_cancellation(connection, &session, cancelled).await,
117- }119+ Behaviour::Say(reply) => {
118- if keyword == "ask" {120+ say(connection, &session, &reply)?;
119- return ask_permission(connection, &session).await;121+ Ok(StopReason::EndTurn)
120- }122+ }
121- if text.starts_with("/new") {123+ Behaviour::Think => {
122- say(connection, &session, "fresh start")?;124+ for piece in ["pondering ", "the ", "question "] {
123- return Ok(StopReason::EndTurn);125+ think(connection, &session, piece)?;
124- }126+ }
125- if let Some(who) = text.strip_prefix("/greet") {127+ say(connection, &session, "done")?;
126- say(connection, &session, &format!("hello{who}"))?;128+ Ok(StopReason::EndTurn)
127- return Ok(StopReason::EndTurn);129+ }
128- }130+ Behaviour::Tools => {
129- if keyword == "think" {131+ use_tools(connection, &session)?;
130- for piece in ["pondering ", "the ", "question "] {132+ say(connection, &session, "tools done")?;
131- think(connection, &session, piece)?;133+ Ok(StopReason::EndTurn)
134+ }
135+ Behaviour::Repeat => {
136+ for word in text.split_whitespace() {
137+ say(connection, &session, &format!("{word} "))?;
138+ }
139+ Ok(StopReason::EndTurn)
132 }140 }
133- say(connection, &session, "done")?;
134- return Ok(StopReason::EndTurn);
135 }141 }
136- if keyword == "slow" {142+}
137- return wait_for_cancellation(connection, &session, cancelled).await;143+
144+/// What the agent does for a prompt, chosen from its text.
145+enum Behaviour {
146+ Crash,
147+ Ask,
148+ Slow,
149+ Think,
150+ Tools,
151+ /// Answers with this text in one piece.
152+ Say(String),
153+ /// Repeats the prompt, one word per chunk.
154+ Repeat,
155+}
156+
157+impl Behaviour {
158+ fn of(text: &str) -> Self {
159+ if text.starts_with("/new") {
160+ return Self::Say("fresh start".to_string());
161+ }
162+ if let Some(who) = text.strip_prefix("/greet") {
163+ return Self::Say(format!("hello{who}"));
164+ }
165+ match first_word_that_is_not_a_mention(text) {
166+ "crash" => Self::Crash,
167+ "ask" => Self::Ask,
168+ "slow" => Self::Slow,
169+ "think" => Self::Think,
170+ "tools" => Self::Tools,
171+ _ => Self::Repeat,
172+ }
138 }173 }
174+}
139 175
140- for word in text.split_whitespace() {176+/// Sends a plan, a tool call that starts, and the update that completes it with an output.
141- say(connection, &session, &format!("{word} "))?;177+fn use_tools(
178+ connection: &ConnectionTo<agent_client_protocol::Client>,
179+ session: &SessionId,
180+) -> Result<(), Error> {
181+ let steps = vec![
182+ PlanEntry::new(
183+ "Read the file",
184+ PlanEntryPriority::High,
185+ PlanEntryStatus::InProgress,
186+ ),
187+ PlanEntry::new("Report", PlanEntryPriority::Low, PlanEntryStatus::Pending),
188+ ];
189+ let updates = [
190+ SessionUpdate::Plan(Plan::new(steps)),
191+ SessionUpdate::ToolCall(
192+ ToolCall::new("tool-1", "Read notes.md")
193+ .kind(ToolKind::Read)
194+ .status(ToolCallStatus::InProgress),
195+ ),
196+ SessionUpdate::ToolCallUpdate(ToolCallUpdate::new(
197+ "tool-1",
198+ ToolCallUpdateFields::new()
199+ .status(ToolCallStatus::Completed)
200+ .content(vec![ToolCallContent::from("the notes")]),
201+ )),
202+ ];
203+ for update in updates {
204+ connection.send_notification(SessionNotification::new(session.clone(), update))?;
142 }205 }
143- Ok(StopReason::EndTurn)206+ Ok(())
144 }207 }
145 208
146 async fn ask_permission(209 async fn ask_permission(
modified crates/acp/src/events.rs +27 -0
@@ -8,6 +8,7 @@ use std::sync::Arc;
88
99 use synedrion_domain::agent::{AgentName, AgentStatus};
1010 use synedrion_domain::channel::ChannelId;
11+use synedrion_domain::trace::{PlanStep, ToolCallChange, ToolCallTrace};
1112
1213 /// The function that receives every [`AgentEvent`].
1314 ///
@@ -49,6 +50,32 @@ pub enum AgentEvent {
4950 channel: ChannelId,
5051 chunk: String,
5152 },
53+ /// The agent started a tool call.
54+ ToolCall {
55+ agent: AgentName,
56+ channel: ChannelId,
57+ call: ToolCallTrace,
58+ },
59+ /// The agent changed a tool call it announced: its status, its output, its title.
60+ ToolCallUpdated {
61+ agent: AgentName,
62+ channel: ChannelId,
63+ /// The identifier the agent gave the call.
64+ id: String,
65+ change: ToolCallChange,
66+ },
67+ /// The agent sent its plan, or a new version of it: the whole list of steps.
68+ Plan {
69+ agent: AgentName,
70+ channel: ChannelId,
71+ steps: Vec<PlanStep>,
72+ },
73+ /// The agent sent a notice for the user, or sent something this version cannot show.
74+ Notice {
75+ agent: AgentName,
76+ channel: ChannelId,
77+ text: String,
78+ },
5279 /// The agent finished answering a prompt, one way or another.
5380 TurnFinished {
5481 agent: AgentName,
@@ -8,6 +8,7 @@ use std::sync::Arc;
8 8
9 use synedrion_domain::agent::{AgentName, AgentStatus};9 use synedrion_domain::agent::{AgentName, AgentStatus};
10 use synedrion_domain::channel::ChannelId;10 use synedrion_domain::channel::ChannelId;
11+use synedrion_domain::trace::{PlanStep, ToolCallChange, ToolCallTrace};
11 12
12 /// The function that receives every [`AgentEvent`].13 /// The function that receives every [`AgentEvent`].
13 ///14 ///
@@ -49,6 +50,32 @@ pub enum AgentEvent {
49 channel: ChannelId,50 channel: ChannelId,
50 chunk: String,51 chunk: String,
51 },52 },
53+ /// The agent started a tool call.
54+ ToolCall {
55+ agent: AgentName,
56+ channel: ChannelId,
57+ call: ToolCallTrace,
58+ },
59+ /// The agent changed a tool call it announced: its status, its output, its title.
60+ ToolCallUpdated {
61+ agent: AgentName,
62+ channel: ChannelId,
63+ /// The identifier the agent gave the call.
64+ id: String,
65+ change: ToolCallChange,
66+ },
67+ /// The agent sent its plan, or a new version of it: the whole list of steps.
68+ Plan {
69+ agent: AgentName,
70+ channel: ChannelId,
71+ steps: Vec<PlanStep>,
72+ },
73+ /// The agent sent a notice for the user, or sent something this version cannot show.
74+ Notice {
75+ agent: AgentName,
76+ channel: ChannelId,
77+ text: String,
78+ },
52 /// The agent finished answering a prompt, one way or another.79 /// The agent finished answering a prompt, one way or another.
53 TurnFinished {80 TurnFinished {
54 agent: AgentName,81 agent: AgentName,
modified crates/acp/src/lib.rs +1 -0
@@ -32,6 +32,7 @@ pub mod events;
3232 mod hub;
3333 pub mod permission;
3434 pub mod protocol_log;
35+mod updates;
3536 mod worker;
3637
3738 pub use hub::{AgentHub, HubError};
@@ -32,6 +32,7 @@ pub mod events;
32 mod hub;32 mod hub;
33 pub mod permission;33 pub mod permission;
34 pub mod protocol_log;34 pub mod protocol_log;
35+mod updates;
35 mod worker;36 mod worker;
36 37
37 pub use hub::{AgentHub, HubError};38 pub use hub::{AgentHub, HubError};
added crates/acp/src/updates.rs +464 -0
new file mode 100644
@@ -0,0 +1,464 @@
1+//! Turning what an agent sends during a turn (`session/update`) into [`AgentEvent`]s.
2+//!
3+//! This is a plain function of its arguments, so that every kind of update is tested without a
4+//! process. The rule that governs it: nothing the agent sends for the user to read is dropped
5+//! silently. What cannot be drawn (an image, a terminal, an update this version does not know)
6+//! comes through as a short bracketed text that says what it was.
7+
8+use agent_client_protocol::schema::v1::{
9+ ContentBlock, EmbeddedResourceResource, Plan, PlanEntryStatus, SessionUpdate, ToolCall,
10+ ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolKind,
11+};
12+use synedrion_domain::agent::AgentName;
13+use synedrion_domain::channel::ChannelId;
14+use synedrion_domain::trace::{PlanStep, Progress, ToolCallChange, ToolCallTrace};
15+
16+use crate::events::AgentEvent;
17+
18+/// The event for an update of the agent's session in `channel`, or `None` for an update that
19+/// carries nothing for the user: usage figures, the current mode, the title of the session, the
20+/// echo of the user's own message, and the commands (which are not tied to a channel and are
21+/// handled before this).
22+///
23+/// ```
24+/// use agent_client_protocol::schema::v1::{ContentChunk, SessionUpdate};
25+/// use synedrion_acp::events::AgentEvent;
26+/// use synedrion_domain::agent::AgentName;
27+/// use synedrion_domain::channel::ChannelId;
28+///
29+/// // `event_for` is used by the hub; this shows the kind of event a text chunk gives.
30+/// let event = AgentEvent::Text {
31+/// agent: AgentName::new("bob").unwrap(),
32+/// channel: ChannelId(1),
33+/// chunk: "hello".to_string(),
34+/// };
35+/// assert!(matches!(event, AgentEvent::Text { .. }));
36+/// let _unused: Option<(ContentChunk, SessionUpdate)> = None;
37+/// ```
38+pub(crate) fn event_for(
39+ agent: &AgentName,
40+ channel: ChannelId,
41+ update: SessionUpdate,
42+) -> Option<AgentEvent> {
43+ let agent = agent.clone();
44+ match update {
45+ SessionUpdate::AgentMessageChunk(chunk) => Some(AgentEvent::Text {
46+ agent,
47+ channel,
48+ chunk: describe_block(&chunk.content),
49+ }),
50+ SessionUpdate::AgentThoughtChunk(chunk) => Some(AgentEvent::Thought {
51+ agent,
52+ channel,
53+ chunk: describe_block(&chunk.content),
54+ }),
55+ SessionUpdate::ToolCall(call) => Some(AgentEvent::ToolCall {
56+ agent,
57+ channel,
58+ call: tool_call_trace(&call),
59+ }),
60+ SessionUpdate::ToolCallUpdate(update) => Some(AgentEvent::ToolCallUpdated {
61+ agent,
62+ channel,
63+ id: update.tool_call_id.to_string(),
64+ change: tool_call_change(&update),
65+ }),
66+ SessionUpdate::Plan(plan) => Some(AgentEvent::Plan {
67+ agent,
68+ channel,
69+ steps: plan_steps(&plan),
70+ }),
71+ SessionUpdate::Notice(notice) => Some(AgentEvent::Notice {
72+ agent,
73+ channel,
74+ text: match &notice.description {
75+ Some(detail) if !detail.trim().is_empty() => {
76+ format!("{}: {detail}", notice.title)
77+ }
78+ _ => notice.title.clone(),
79+ },
80+ }),
81+ SessionUpdate::UserMessageChunk(_)
82+ | SessionUpdate::AvailableCommandsUpdate(_)
83+ | SessionUpdate::CurrentModeUpdate(_)
84+ | SessionUpdate::ConfigOptionUpdate(_)
85+ | SessionUpdate::SessionInfoUpdate(_)
86+ | SessionUpdate::UsageUpdate(_)
87+ | SessionUpdate::CompactionUpdate(_)
88+ | SessionUpdate::CompactionSummaryChunk(_) => None,
89+ _ => Some(AgentEvent::Notice {
90+ agent,
91+ channel,
92+ text: "The agent sent an update that this version of Synedrion cannot show."
93+ .to_string(),
94+ }),
95+ }
96+}
97+
98+/// A block of content as text: its text, or a bracketed note saying what could not be shown.
99+pub(crate) fn describe_block(block: &ContentBlock) -> String {
100+ match block {
101+ ContentBlock::Text(text) => text.text.clone(),
102+ ContentBlock::Image(_) => "[image: not displayed]".to_string(),
103+ ContentBlock::Audio(_) => "[audio: not displayed]".to_string(),
104+ ContentBlock::ResourceLink(link) => format!("[link: {}]", link.uri),
105+ ContentBlock::Resource(resource) => match &resource.resource {
106+ EmbeddedResourceResource::TextResourceContents(text) => text.text.clone(),
107+ EmbeddedResourceResource::BlobResourceContents(blob) => {
108+ format!("[binary resource: {}]", blob.uri)
109+ }
110+ _ => "[resource: not displayed]".to_string(),
111+ },
112+ _ => "[content: not displayed]".to_string(),
113+ }
114+}
115+
116+fn tool_call_trace(call: &ToolCall) -> ToolCallTrace {
117+ let mut output = describe_contents(&call.content);
118+ if output.is_empty() {
119+ output = raw_output_text(call.raw_output.as_ref());
120+ }
121+ ToolCallTrace {
122+ id: call.tool_call_id.to_string(),
123+ title: call.title.clone(),
124+ kind: kind_word(&call.kind),
125+ progress: progress_of_tool(&call.status),
126+ output,
127+ }
128+}
129+
130+fn tool_call_change(update: &ToolCallUpdate) -> ToolCallChange {
131+ let fields = &update.fields;
132+ let output = match (&fields.content, &fields.raw_output) {
133+ (Some(content), _) => Some(describe_contents(content)),
134+ (None, Some(raw)) => Some(raw_output_text(Some(raw))),
135+ (None, None) => None,
136+ };
137+ ToolCallChange {
138+ title: fields.title.clone(),
139+ kind: fields.kind.as_ref().map(kind_word),
140+ progress: fields.status.as_ref().map(progress_of_tool),
141+ output,
142+ }
143+}
144+
145+fn plan_steps(plan: &Plan) -> Vec<PlanStep> {
146+ plan.entries
147+ .iter()
148+ .map(|entry| PlanStep {
149+ text: entry.content.clone(),
150+ progress: match entry.status {
151+ PlanEntryStatus::InProgress => Progress::InProgress,
152+ PlanEntryStatus::Completed => Progress::Completed,
153+ _ => Progress::Pending,
154+ },
155+ })
156+ .collect()
157+}
158+
159+fn progress_of_tool(status: &ToolCallStatus) -> Progress {
160+ match status {
161+ ToolCallStatus::InProgress => Progress::InProgress,
162+ ToolCallStatus::Completed => Progress::Completed,
163+ ToolCallStatus::Failed => Progress::Failed,
164+ _ => Progress::Pending,
165+ }
166+}
167+
168+fn kind_word(kind: &ToolKind) -> String {
169+ match kind {
170+ ToolKind::Read => "read",
171+ ToolKind::Edit => "edit",
172+ ToolKind::Delete => "delete",
173+ ToolKind::Move => "move",
174+ ToolKind::Search => "search",
175+ ToolKind::Execute => "execute",
176+ ToolKind::Think => "think",
177+ ToolKind::Fetch => "fetch",
178+ ToolKind::SwitchMode => "switch_mode",
179+ _ => "other",
180+ }
181+ .to_string()
182+}
183+
184+/// The content a tool produced, one item after the other.
185+fn describe_contents(contents: &[ToolCallContent]) -> String {
186+ contents
187+ .iter()
188+ .map(|content| match content {
189+ ToolCallContent::Content(content) => describe_block(&content.content),
190+ ToolCallContent::Diff(diff) => describe_diff(
191+ &diff.path.display().to_string(),
192+ diff.old_text.as_deref(),
193+ &diff.new_text,
194+ ),
195+ ToolCallContent::Terminal(terminal) => {
196+ format!(
197+ "[terminal {}: its output is not displayed]",
198+ terminal.terminal_id
199+ )
200+ }
201+ _ => "[content: not displayed]".to_string(),
202+ })
203+ .collect::<Vec<_>>()
204+ .join("\n")
205+}
206+
207+/// A change to a file as text: the lines that went, marked `-`, then the lines that came, marked
208+/// `+`. A file that did not exist is shown as it now is.
209+fn describe_diff(path: &str, old: Option<&str>, new: &str) -> String {
210+ match old {
211+ None => format!("New file {path}:\n{new}"),
212+ Some(old) => {
213+ let marked = |sign: &str, text: &str| {
214+ text.lines()
215+ .map(|line| format!("{sign} {line}"))
216+ .collect::<Vec<_>>()
217+ .join("\n")
218+ };
219+ format!(
220+ "Changes to {path}:\n{}\n{}",
221+ marked("-", old),
222+ marked("+", new)
223+ )
224+ }
225+ }
226+}
227+
228+/// What a tool returned without describing it as content: a string as it is, anything else as
229+/// compact JSON.
230+fn raw_output_text(raw: Option<&serde_json::Value>) -> String {
231+ match raw {
232+ None | Some(serde_json::Value::Null) => String::new(),
233+ Some(serde_json::Value::String(text)) => text.clone(),
234+ Some(other) => other.to_string(),
235+ }
236+}
237+
238+#[cfg(test)]
239+mod tests {
240+ use super::*;
241+ use agent_client_protocol::schema::v1::{
242+ AudioContent, ContentChunk, Diff, ImageContent, Notice, NoticeSeverity, PlanEntry,
243+ PlanEntryPriority, ResourceLink, Terminal, ToolCallUpdateFields, UsageUpdate,
244+ };
245+
246+ fn bob() -> AgentName {
247+ AgentName::new("bob").unwrap()
248+ }
249+
250+ fn event(update: SessionUpdate) -> Option<AgentEvent> {
251+ event_for(&bob(), ChannelId(7), update)
252+ }
253+
254+ fn text_chunk(text: &str) -> ContentChunk {
255+ ContentChunk::new(ContentBlock::from(text))
256+ }
257+
258+ #[test]
259+ fn a_text_chunk_of_the_answer_is_text() {
260+ let got = event(SessionUpdate::AgentMessageChunk(text_chunk("hello")));
261+ assert_eq!(
262+ got,
263+ Some(AgentEvent::Text {
264+ agent: bob(),
265+ channel: ChannelId(7),
266+ chunk: "hello".to_string()
267+ })
268+ );
269+ }
270+
271+ #[test]
272+ fn a_text_chunk_of_the_reasoning_is_a_thought() {
273+ let got = event(SessionUpdate::AgentThoughtChunk(text_chunk("hmm")));
274+ assert!(matches!(got, Some(AgentEvent::Thought { chunk, .. }) if chunk == "hmm"));
275+ }
276+
277+ #[test]
278+ fn content_that_cannot_be_drawn_is_named_not_dropped() {
279+ let image = ContentBlock::Image(ImageContent::new("AAAA", "image/png"));
280+ let audio = ContentBlock::Audio(AudioContent::new("AAAA", "audio/wav"));
281+ let link = ContentBlock::ResourceLink(ResourceLink::new("notes", "file:///notes.md"));
282+ assert_eq!(describe_block(&image), "[image: not displayed]");
283+ assert_eq!(describe_block(&audio), "[audio: not displayed]");
284+ assert_eq!(describe_block(&link), "[link: file:///notes.md]");
285+ }
286+
287+ #[test]
288+ fn an_image_in_the_answer_leaves_its_mark_in_the_answer() {
289+ let image = ContentBlock::Image(ImageContent::new("AAAA", "image/png"));
290+ let got = event(SessionUpdate::AgentMessageChunk(ContentChunk::new(image)));
291+ assert!(matches!(got, Some(AgentEvent::Text { chunk, .. }) if chunk.contains("image")));
292+ }
293+
294+ #[test]
295+ fn a_tool_call_carries_its_title_kind_status_and_output() {
296+ let call = ToolCall::new("t1", "Read Cargo.toml")
297+ .kind(ToolKind::Read)
298+ .status(ToolCallStatus::InProgress)
299+ .content(vec![ToolCallContent::from("[workspace]")]);
300+ let got = event(SessionUpdate::ToolCall(call));
301+ let Some(AgentEvent::ToolCall { call, channel, .. }) = got else {
302+ panic!("expected a tool call, got {got:?}");
303+ };
304+ assert_eq!(channel, ChannelId(7));
305+ assert_eq!(
306+ (call.id.as_str(), call.title.as_str(), call.kind.as_str()),
307+ ("t1", "Read Cargo.toml", "read")
308+ );
309+ assert_eq!(call.progress, Progress::InProgress);
310+ assert_eq!(call.output, "[workspace]");
311+ }
312+
313+ #[test]
314+ fn a_tool_call_without_content_shows_its_raw_output() {
315+ let call = ToolCall::new("t1", "Run").raw_output(serde_json::json!({"exit": 0}));
316+ let Some(AgentEvent::ToolCall { call, .. }) = event(SessionUpdate::ToolCall(call)) else {
317+ panic!("expected a tool call");
318+ };
319+ assert_eq!(call.output, "{\"exit\":0}");
320+ }
321+
322+ #[test]
323+ fn a_raw_output_that_is_a_string_is_shown_without_quotes() {
324+ let call = ToolCall::new("t1", "Run").raw_output(serde_json::json!("done"));
325+ let Some(AgentEvent::ToolCall { call, .. }) = event(SessionUpdate::ToolCall(call)) else {
326+ panic!("expected a tool call");
327+ };
328+ assert_eq!(call.output, "done");
329+ }
330+
331+ #[test]
332+ fn an_update_carries_only_what_changed() {
333+ let update = ToolCallUpdate::new(
334+ "t1",
335+ ToolCallUpdateFields::new().status(ToolCallStatus::Completed),
336+ );
337+ let Some(AgentEvent::ToolCallUpdated { id, change, .. }) =
338+ event(SessionUpdate::ToolCallUpdate(update))
339+ else {
340+ panic!("expected an update");
341+ };
342+ assert_eq!(id, "t1");
343+ assert_eq!(change.progress, Some(Progress::Completed));
344+ assert_eq!(change.title, None);
345+ assert_eq!(change.output, None);
346+ }
347+
348+ #[test]
349+ fn an_update_with_content_replaces_the_output() {
350+ let update = ToolCallUpdate::new(
351+ "t1",
352+ ToolCallUpdateFields::new().content(vec![ToolCallContent::from("ok")]),
353+ );
354+ let Some(AgentEvent::ToolCallUpdated { change, .. }) =
355+ event(SessionUpdate::ToolCallUpdate(update))
356+ else {
357+ panic!("expected an update");
358+ };
359+ assert_eq!(change.output.as_deref(), Some("ok"));
360+ }
361+
362+ #[test]
363+ fn a_failed_tool_call_is_failed() {
364+ let call = ToolCall::new("t1", "Run").status(ToolCallStatus::Failed);
365+ let Some(AgentEvent::ToolCall { call, .. }) = event(SessionUpdate::ToolCall(call)) else {
366+ panic!("expected a tool call");
367+ };
368+ assert_eq!(call.progress, Progress::Failed);
369+ }
370+
371+ #[test]
372+ fn every_kind_of_tool_has_its_own_word() {
373+ let kinds = [
374+ ToolKind::Read,
375+ ToolKind::Edit,
376+ ToolKind::Delete,
377+ ToolKind::Move,
378+ ToolKind::Search,
379+ ToolKind::Execute,
380+ ToolKind::Think,
381+ ToolKind::Fetch,
382+ ToolKind::SwitchMode,
383+ ToolKind::Other,
384+ ];
385+ let mut words: Vec<String> = kinds.iter().map(kind_word).collect();
386+ words.sort();
387+ words.dedup();
388+ assert_eq!(words.len(), kinds.len());
389+ }
390+
391+ #[test]
392+ fn a_new_file_is_shown_as_it_is_and_a_change_as_removed_and_added_lines() {
393+ assert_eq!(
394+ describe_diff("a.txt", None, "one\ntwo"),
395+ "New file a.txt:\none\ntwo"
396+ );
397+ assert_eq!(
398+ describe_diff("a.txt", Some("old1\nold2"), "new"),
399+ "Changes to a.txt:\n- old1\n- old2\n+ new"
400+ );
401+ }
402+
403+ #[test]
404+ fn a_diff_and_a_terminal_in_a_tool_call_are_described() {
405+ let call = ToolCall::new("t1", "Edit").content(vec![
406+ ToolCallContent::Diff(Diff::new("/work/a.rs", "fn main() {}").old_text("fn main()")),
407+ ToolCallContent::Terminal(Terminal::new("term-1")),
408+ ]);
409+ let Some(AgentEvent::ToolCall { call, .. }) = event(SessionUpdate::ToolCall(call)) else {
410+ panic!("expected a tool call");
411+ };
412+ assert!(call.output.contains("Changes to /work/a.rs"));
413+ assert!(call.output.contains("- fn main()\n+ fn main() {}"));
414+ assert!(
415+ call.output
416+ .contains("[terminal term-1: its output is not displayed]")
417+ );
418+ }
419+
420+ #[test]
421+ fn a_plan_keeps_its_steps_in_order_with_their_progress() {
422+ let plan = Plan::new(vec![
423+ PlanEntry::new("read", PlanEntryPriority::High, PlanEntryStatus::Completed),
424+ PlanEntry::new("write", PlanEntryPriority::Low, PlanEntryStatus::InProgress),
425+ PlanEntry::new("test", PlanEntryPriority::Low, PlanEntryStatus::Pending),
426+ ]);
427+ let Some(AgentEvent::Plan { steps, .. }) = event(SessionUpdate::Plan(plan)) else {
428+ panic!("expected a plan");
429+ };
430+ let shown: Vec<(&str, Progress)> = steps
431+ .iter()
432+ .map(|step| (step.text.as_str(), step.progress))
433+ .collect();
434+ assert_eq!(
435+ shown,
436+ vec![
437+ ("read", Progress::Completed),
438+ ("write", Progress::InProgress),
439+ ("test", Progress::Pending)
440+ ]
441+ );
442+ }
443+
444+ #[test]
445+ fn a_notice_of_the_agent_is_passed_on_with_its_detail() {
446+ let notice = Notice::new(NoticeSeverity::Info, "Context nearly full")
447+ .description("Run /compact".to_string());
448+ let got = event(SessionUpdate::Notice(notice));
449+ assert!(matches!(
450+ got,
451+ Some(AgentEvent::Notice { text, .. }) if text == "Context nearly full: Run /compact"
452+ ));
453+ }
454+
455+ #[test]
456+ fn bookkeeping_updates_show_nothing() {
457+ let usage = SessionUpdate::UsageUpdate(UsageUpdate::new(10, 100));
458+ assert_eq!(event(usage), None);
459+ assert_eq!(
460+ event(SessionUpdate::UserMessageChunk(text_chunk("echo"))),
461+ None
462+ );
463+ }
464+}
new file mode 100644
@@ -0,0 +1,464 @@
1+//! Turning what an agent sends during a turn (`session/update`) into [`AgentEvent`]s.
2+//!
3+//! This is a plain function of its arguments, so that every kind of update is tested without a
4+//! process. The rule that governs it: nothing the agent sends for the user to read is dropped
5+//! silently. What cannot be drawn (an image, a terminal, an update this version does not know)
6+//! comes through as a short bracketed text that says what it was.
7+
8+use agent_client_protocol::schema::v1::{
9+ ContentBlock, EmbeddedResourceResource, Plan, PlanEntryStatus, SessionUpdate, ToolCall,
10+ ToolCallContent, ToolCallStatus, ToolCallUpdate, ToolKind,
11+};
12+use synedrion_domain::agent::AgentName;
13+use synedrion_domain::channel::ChannelId;
14+use synedrion_domain::trace::{PlanStep, Progress, ToolCallChange, ToolCallTrace};
15+
16+use crate::events::AgentEvent;
17+
18+/// The event for an update of the agent's session in `channel`, or `None` for an update that
19+/// carries nothing for the user: usage figures, the current mode, the title of the session, the
20+/// echo of the user's own message, and the commands (which are not tied to a channel and are
21+/// handled before this).
22+///
23+/// ```
24+/// use agent_client_protocol::schema::v1::{ContentChunk, SessionUpdate};
25+/// use synedrion_acp::events::AgentEvent;
26+/// use synedrion_domain::agent::AgentName;
27+/// use synedrion_domain::channel::ChannelId;
28+///
29+/// // `event_for` is used by the hub; this shows the kind of event a text chunk gives.
30+/// let event = AgentEvent::Text {
31+/// agent: AgentName::new("bob").unwrap(),
32+/// channel: ChannelId(1),
33+/// chunk: "hello".to_string(),
34+/// };
35+/// assert!(matches!(event, AgentEvent::Text { .. }));
36+/// let _unused: Option<(ContentChunk, SessionUpdate)> = None;
37+/// ```
38+pub(crate) fn event_for(
39+ agent: &AgentName,
40+ channel: ChannelId,
41+ update: SessionUpdate,
42+) -> Option<AgentEvent> {
43+ let agent = agent.clone();
44+ match update {
45+ SessionUpdate::AgentMessageChunk(chunk) => Some(AgentEvent::Text {
46+ agent,
47+ channel,
48+ chunk: describe_block(&chunk.content),
49+ }),
50+ SessionUpdate::AgentThoughtChunk(chunk) => Some(AgentEvent::Thought {
51+ agent,
52+ channel,
53+ chunk: describe_block(&chunk.content),
54+ }),
55+ SessionUpdate::ToolCall(call) => Some(AgentEvent::ToolCall {
56+ agent,
57+ channel,
58+ call: tool_call_trace(&call),
59+ }),
60+ SessionUpdate::ToolCallUpdate(update) => Some(AgentEvent::ToolCallUpdated {
61+ agent,
62+ channel,
63+ id: update.tool_call_id.to_string(),
64+ change: tool_call_change(&update),
65+ }),
66+ SessionUpdate::Plan(plan) => Some(AgentEvent::Plan {
67+ agent,
68+ channel,
69+ steps: plan_steps(&plan),
70+ }),
71+ SessionUpdate::Notice(notice) => Some(AgentEvent::Notice {
72+ agent,
73+ channel,
74+ text: match &notice.description {
75+ Some(detail) if !detail.trim().is_empty() => {
76+ format!("{}: {detail}", notice.title)
77+ }
78+ _ => notice.title.clone(),
79+ },
80+ }),
81+ SessionUpdate::UserMessageChunk(_)
82+ | SessionUpdate::AvailableCommandsUpdate(_)
83+ | SessionUpdate::CurrentModeUpdate(_)
84+ | SessionUpdate::ConfigOptionUpdate(_)
85+ | SessionUpdate::SessionInfoUpdate(_)
86+ | SessionUpdate::UsageUpdate(_)
87+ | SessionUpdate::CompactionUpdate(_)
88+ | SessionUpdate::CompactionSummaryChunk(_) => None,
89+ _ => Some(AgentEvent::Notice {
90+ agent,
91+ channel,
92+ text: "The agent sent an update that this version of Synedrion cannot show."
93+ .to_string(),
94+ }),
95+ }
96+}
97+
98+/// A block of content as text: its text, or a bracketed note saying what could not be shown.
99+pub(crate) fn describe_block(block: &ContentBlock) -> String {
100+ match block {
101+ ContentBlock::Text(text) => text.text.clone(),
102+ ContentBlock::Image(_) => "[image: not displayed]".to_string(),
103+ ContentBlock::Audio(_) => "[audio: not displayed]".to_string(),
104+ ContentBlock::ResourceLink(link) => format!("[link: {}]", link.uri),
105+ ContentBlock::Resource(resource) => match &resource.resource {
106+ EmbeddedResourceResource::TextResourceContents(text) => text.text.clone(),
107+ EmbeddedResourceResource::BlobResourceContents(blob) => {
108+ format!("[binary resource: {}]", blob.uri)
109+ }
110+ _ => "[resource: not displayed]".to_string(),
111+ },
112+ _ => "[content: not displayed]".to_string(),
113+ }
114+}
115+
116+fn tool_call_trace(call: &ToolCall) -> ToolCallTrace {
117+ let mut output = describe_contents(&call.content);
118+ if output.is_empty() {
119+ output = raw_output_text(call.raw_output.as_ref());
120+ }
121+ ToolCallTrace {
122+ id: call.tool_call_id.to_string(),
123+ title: call.title.clone(),
124+ kind: kind_word(&call.kind),
125+ progress: progress_of_tool(&call.status),
126+ output,
127+ }
128+}
129+
130+fn tool_call_change(update: &ToolCallUpdate) -> ToolCallChange {
131+ let fields = &update.fields;
132+ let output = match (&fields.content, &fields.raw_output) {
133+ (Some(content), _) => Some(describe_contents(content)),
134+ (None, Some(raw)) => Some(raw_output_text(Some(raw))),
135+ (None, None) => None,
136+ };
137+ ToolCallChange {
138+ title: fields.title.clone(),
139+ kind: fields.kind.as_ref().map(kind_word),
140+ progress: fields.status.as_ref().map(progress_of_tool),
141+ output,
142+ }
143+}
144+
145+fn plan_steps(plan: &Plan) -> Vec<PlanStep> {
146+ plan.entries
147+ .iter()
148+ .map(|entry| PlanStep {
149+ text: entry.content.clone(),
150+ progress: match entry.status {
151+ PlanEntryStatus::InProgress => Progress::InProgress,
152+ PlanEntryStatus::Completed => Progress::Completed,
153+ _ => Progress::Pending,
154+ },
155+ })
156+ .collect()
157+}
158+
159+fn progress_of_tool(status: &ToolCallStatus) -> Progress {
160+ match status {
161+ ToolCallStatus::InProgress => Progress::InProgress,
162+ ToolCallStatus::Completed => Progress::Completed,
163+ ToolCallStatus::Failed => Progress::Failed,
164+ _ => Progress::Pending,
165+ }
166+}
167+
168+fn kind_word(kind: &ToolKind) -> String {
169+ match kind {
170+ ToolKind::Read => "read",
171+ ToolKind::Edit => "edit",
172+ ToolKind::Delete => "delete",
173+ ToolKind::Move => "move",
174+ ToolKind::Search => "search",
175+ ToolKind::Execute => "execute",
176+ ToolKind::Think => "think",
177+ ToolKind::Fetch => "fetch",
178+ ToolKind::SwitchMode => "switch_mode",
179+ _ => "other",
180+ }
181+ .to_string()
182+}
183+
184+/// The content a tool produced, one item after the other.
185+fn describe_contents(contents: &[ToolCallContent]) -> String {
186+ contents
187+ .iter()
188+ .map(|content| match content {
189+ ToolCallContent::Content(content) => describe_block(&content.content),
190+ ToolCallContent::Diff(diff) => describe_diff(
191+ &diff.path.display().to_string(),
192+ diff.old_text.as_deref(),
193+ &diff.new_text,
194+ ),
195+ ToolCallContent::Terminal(terminal) => {
196+ format!(
197+ "[terminal {}: its output is not displayed]",
198+ terminal.terminal_id
199+ )
200+ }
201+ _ => "[content: not displayed]".to_string(),
202+ })
203+ .collect::<Vec<_>>()
204+ .join("\n")
205+}
206+
207+/// A change to a file as text: the lines that went, marked `-`, then the lines that came, marked
208+/// `+`. A file that did not exist is shown as it now is.
209+fn describe_diff(path: &str, old: Option<&str>, new: &str) -> String {
210+ match old {
211+ None => format!("New file {path}:\n{new}"),
212+ Some(old) => {
213+ let marked = |sign: &str, text: &str| {
214+ text.lines()
215+ .map(|line| format!("{sign} {line}"))
216+ .collect::<Vec<_>>()
217+ .join("\n")
218+ };
219+ format!(
220+ "Changes to {path}:\n{}\n{}",
221+ marked("-", old),
222+ marked("+", new)
223+ )
224+ }
225+ }
226+}
227+
228+/// What a tool returned without describing it as content: a string as it is, anything else as
229+/// compact JSON.
230+fn raw_output_text(raw: Option<&serde_json::Value>) -> String {
231+ match raw {
232+ None | Some(serde_json::Value::Null) => String::new(),
233+ Some(serde_json::Value::String(text)) => text.clone(),
234+ Some(other) => other.to_string(),
235+ }
236+}
237+
238+#[cfg(test)]
239+mod tests {
240+ use super::*;
241+ use agent_client_protocol::schema::v1::{
242+ AudioContent, ContentChunk, Diff, ImageContent, Notice, NoticeSeverity, PlanEntry,
243+ PlanEntryPriority, ResourceLink, Terminal, ToolCallUpdateFields, UsageUpdate,
244+ };
245+
246+ fn bob() -> AgentName {
247+ AgentName::new("bob").unwrap()
248+ }
249+
250+ fn event(update: SessionUpdate) -> Option<AgentEvent> {
251+ event_for(&bob(), ChannelId(7), update)
252+ }
253+
254+ fn text_chunk(text: &str) -> ContentChunk {
255+ ContentChunk::new(ContentBlock::from(text))
256+ }
257+
258+ #[test]
259+ fn a_text_chunk_of_the_answer_is_text() {
260+ let got = event(SessionUpdate::AgentMessageChunk(text_chunk("hello")));
261+ assert_eq!(
262+ got,
263+ Some(AgentEvent::Text {
264+ agent: bob(),
265+ channel: ChannelId(7),
266+ chunk: "hello".to_string()
267+ })
268+ );
269+ }
270+
271+ #[test]
272+ fn a_text_chunk_of_the_reasoning_is_a_thought() {
273+ let got = event(SessionUpdate::AgentThoughtChunk(text_chunk("hmm")));
274+ assert!(matches!(got, Some(AgentEvent::Thought { chunk, .. }) if chunk == "hmm"));
275+ }
276+
277+ #[test]
278+ fn content_that_cannot_be_drawn_is_named_not_dropped() {
279+ let image = ContentBlock::Image(ImageContent::new("AAAA", "image/png"));
280+ let audio = ContentBlock::Audio(AudioContent::new("AAAA", "audio/wav"));
281+ let link = ContentBlock::ResourceLink(ResourceLink::new("notes", "file:///notes.md"));
282+ assert_eq!(describe_block(&image), "[image: not displayed]");
283+ assert_eq!(describe_block(&audio), "[audio: not displayed]");
284+ assert_eq!(describe_block(&link), "[link: file:///notes.md]");
285+ }
286+
287+ #[test]
288+ fn an_image_in_the_answer_leaves_its_mark_in_the_answer() {
289+ let image = ContentBlock::Image(ImageContent::new("AAAA", "image/png"));
290+ let got = event(SessionUpdate::AgentMessageChunk(ContentChunk::new(image)));
291+ assert!(matches!(got, Some(AgentEvent::Text { chunk, .. }) if chunk.contains("image")));
292+ }
293+
294+ #[test]
295+ fn a_tool_call_carries_its_title_kind_status_and_output() {
296+ let call = ToolCall::new("t1", "Read Cargo.toml")
297+ .kind(ToolKind::Read)
298+ .status(ToolCallStatus::InProgress)
299+ .content(vec![ToolCallContent::from("[workspace]")]);
300+ let got = event(SessionUpdate::ToolCall(call));
301+ let Some(AgentEvent::ToolCall { call, channel, .. }) = got else {
302+ panic!("expected a tool call, got {got:?}");
303+ };
304+ assert_eq!(channel, ChannelId(7));
305+ assert_eq!(
306+ (call.id.as_str(), call.title.as_str(), call.kind.as_str()),
307+ ("t1", "Read Cargo.toml", "read")
308+ );
309+ assert_eq!(call.progress, Progress::InProgress);
310+ assert_eq!(call.output, "[workspace]");
311+ }
312+
313+ #[test]
314+ fn a_tool_call_without_content_shows_its_raw_output() {
315+ let call = ToolCall::new("t1", "Run").raw_output(serde_json::json!({"exit": 0}));
316+ let Some(AgentEvent::ToolCall { call, .. }) = event(SessionUpdate::ToolCall(call)) else {
317+ panic!("expected a tool call");
318+ };
319+ assert_eq!(call.output, "{\"exit\":0}");
320+ }
321+
322+ #[test]
323+ fn a_raw_output_that_is_a_string_is_shown_without_quotes() {
324+ let call = ToolCall::new("t1", "Run").raw_output(serde_json::json!("done"));
325+ let Some(AgentEvent::ToolCall { call, .. }) = event(SessionUpdate::ToolCall(call)) else {
326+ panic!("expected a tool call");
327+ };
328+ assert_eq!(call.output, "done");
329+ }
330+
331+ #[test]
332+ fn an_update_carries_only_what_changed() {
333+ let update = ToolCallUpdate::new(
334+ "t1",
335+ ToolCallUpdateFields::new().status(ToolCallStatus::Completed),
336+ );
337+ let Some(AgentEvent::ToolCallUpdated { id, change, .. }) =
338+ event(SessionUpdate::ToolCallUpdate(update))
339+ else {
340+ panic!("expected an update");
341+ };
342+ assert_eq!(id, "t1");
343+ assert_eq!(change.progress, Some(Progress::Completed));
344+ assert_eq!(change.title, None);
345+ assert_eq!(change.output, None);
346+ }
347+
348+ #[test]
349+ fn an_update_with_content_replaces_the_output() {
350+ let update = ToolCallUpdate::new(
351+ "t1",
352+ ToolCallUpdateFields::new().content(vec![ToolCallContent::from("ok")]),
353+ );
354+ let Some(AgentEvent::ToolCallUpdated { change, .. }) =
355+ event(SessionUpdate::ToolCallUpdate(update))
356+ else {
357+ panic!("expected an update");
358+ };
359+ assert_eq!(change.output.as_deref(), Some("ok"));
360+ }
361+
362+ #[test]
363+ fn a_failed_tool_call_is_failed() {
364+ let call = ToolCall::new("t1", "Run").status(ToolCallStatus::Failed);
365+ let Some(AgentEvent::ToolCall { call, .. }) = event(SessionUpdate::ToolCall(call)) else {
366+ panic!("expected a tool call");
367+ };
368+ assert_eq!(call.progress, Progress::Failed);
369+ }
370+
371+ #[test]
372+ fn every_kind_of_tool_has_its_own_word() {
373+ let kinds = [
374+ ToolKind::Read,
375+ ToolKind::Edit,
376+ ToolKind::Delete,
377+ ToolKind::Move,
378+ ToolKind::Search,
379+ ToolKind::Execute,
380+ ToolKind::Think,
381+ ToolKind::Fetch,
382+ ToolKind::SwitchMode,
383+ ToolKind::Other,
384+ ];
385+ let mut words: Vec<String> = kinds.iter().map(kind_word).collect();
386+ words.sort();
387+ words.dedup();
388+ assert_eq!(words.len(), kinds.len());
389+ }
390+
391+ #[test]
392+ fn a_new_file_is_shown_as_it_is_and_a_change_as_removed_and_added_lines() {
393+ assert_eq!(
394+ describe_diff("a.txt", None, "one\ntwo"),
395+ "New file a.txt:\none\ntwo"
396+ );
397+ assert_eq!(
398+ describe_diff("a.txt", Some("old1\nold2"), "new"),
399+ "Changes to a.txt:\n- old1\n- old2\n+ new"
400+ );
401+ }
402+
403+ #[test]
404+ fn a_diff_and_a_terminal_in_a_tool_call_are_described() {
405+ let call = ToolCall::new("t1", "Edit").content(vec![
406+ ToolCallContent::Diff(Diff::new("/work/a.rs", "fn main() {}").old_text("fn main()")),
407+ ToolCallContent::Terminal(Terminal::new("term-1")),
408+ ]);
409+ let Some(AgentEvent::ToolCall { call, .. }) = event(SessionUpdate::ToolCall(call)) else {
410+ panic!("expected a tool call");
411+ };
412+ assert!(call.output.contains("Changes to /work/a.rs"));
413+ assert!(call.output.contains("- fn main()\n+ fn main() {}"));
414+ assert!(
415+ call.output
416+ .contains("[terminal term-1: its output is not displayed]")
417+ );
418+ }
419+
420+ #[test]
421+ fn a_plan_keeps_its_steps_in_order_with_their_progress() {
422+ let plan = Plan::new(vec![
423+ PlanEntry::new("read", PlanEntryPriority::High, PlanEntryStatus::Completed),
424+ PlanEntry::new("write", PlanEntryPriority::Low, PlanEntryStatus::InProgress),
425+ PlanEntry::new("test", PlanEntryPriority::Low, PlanEntryStatus::Pending),
426+ ]);
427+ let Some(AgentEvent::Plan { steps, .. }) = event(SessionUpdate::Plan(plan)) else {
428+ panic!("expected a plan");
429+ };
430+ let shown: Vec<(&str, Progress)> = steps
431+ .iter()
432+ .map(|step| (step.text.as_str(), step.progress))
433+ .collect();
434+ assert_eq!(
435+ shown,
436+ vec![
437+ ("read", Progress::Completed),
438+ ("write", Progress::InProgress),
439+ ("test", Progress::Pending)
440+ ]
441+ );
442+ }
443+
444+ #[test]
445+ fn a_notice_of_the_agent_is_passed_on_with_its_detail() {
446+ let notice = Notice::new(NoticeSeverity::Info, "Context nearly full")
447+ .description("Run /compact".to_string());
448+ let got = event(SessionUpdate::Notice(notice));
449+ assert!(matches!(
450+ got,
451+ Some(AgentEvent::Notice { text, .. }) if text == "Context nearly full: Run /compact"
452+ ));
453+ }
454+
455+ #[test]
456+ fn bookkeeping_updates_show_nothing() {
457+ let usage = SessionUpdate::UsageUpdate(UsageUpdate::new(10, 100));
458+ assert_eq!(event(usage), None);
459+ assert_eq!(
460+ event(SessionUpdate::UserMessageChunk(text_chunk("echo"))),
461+ None
462+ );
463+ }
464+}
modified crates/acp/src/worker.rs +24 -24
@@ -29,6 +29,7 @@ use crate::events::{
2929 };
3030 use crate::permission::PermissionBroker;
3131 use crate::protocol_log;
32+use crate::updates::event_for;
3233
3334 /// What the hub asks a worker to do.
3435 pub(crate) enum Command {
@@ -126,8 +127,8 @@ impl WorkerShared {
126127 gates.entry(channel).or_default().clone()
127128 }
128129
129- /// An update from the agent. Only the text of its answer and of its reasoning are passed
130- /// on for now. Tool calls and plans are ignored until ticket #17 shows them.
130+ /// An update from the agent: its answer, its reasoning, its tool calls, its plan. What each
131+ /// becomes is decided in [`crate::updates::event_for`].
131132 fn handle_update(&self, notification: SessionNotification) {
132133 // The commands belong to the agent, not to a channel: they count even before a session is
133134 // tied to one.
@@ -146,27 +147,8 @@ impl WorkerShared {
146147 let Some(channel) = self.channel_of(&notification.session_id) else {
147148 return;
148149 };
149- let agent = self.agent.clone();
150- match notification.update {
151- SessionUpdate::AgentMessageChunk(chunk) => {
152- if let ContentBlock::Text(text) = chunk.content {
153- self.emit(AgentEvent::Text {
154- agent,
155- channel,
156- chunk: text.text,
157- });
158- }
159- }
160- SessionUpdate::AgentThoughtChunk(chunk) => {
161- if let ContentBlock::Text(text) = chunk.content {
162- self.emit(AgentEvent::Thought {
163- agent,
164- channel,
165- chunk: text.text,
166- });
167- }
168- }
169- _ => {}
150+ if let Some(event) = event_for(&self.agent, channel, notification.update) {
151+ self.emit(event);
170152 }
171153 }
172154
@@ -410,7 +392,7 @@ async fn command_loop(
410392 shared: Arc<WorkerShared>,
411393 ) -> Result<(), Error> {
412394 connection
413- .send_request(InitializeRequest::new(ProtocolVersion::V1))
395+ .send_request(initialize_request())
414396 .block_task()
415397 .await?;
416398 shared
@@ -441,6 +423,16 @@ async fn command_loop(
441423 Ok(())
442424 }
443425
426+/// What Synedrion says about itself when it starts an agent.
427+///
428+/// It announces no capability: neither reading and writing files (`fs/*`) nor terminals
429+/// (`terminal/*`). An agent that wants to read or run something does it with its own tools, in
430+/// its own process, which is what lets a sandbox keep it away from the host. Offering these would
431+/// be a decision about security, written down in the explanation "Client capabilities".
432+pub(crate) fn initialize_request() -> InitializeRequest {
433+ InitializeRequest::new(ProtocolVersion::V1)
434+}
435+
444436 /// The content of a prompt: the text, then one link per attached file, which every agent must
445437 /// accept.
446438 pub(crate) fn prompt_blocks(text: String, files: &[PathBuf]) -> Vec<ContentBlock> {
@@ -511,6 +503,14 @@ fn to_permission_option(
511503 mod tests {
512504 use super::*;
513505
506+ #[test]
507+ fn synedrion_announces_no_file_or_terminal_capability_to_agents() {
508+ let capabilities = initialize_request().client_capabilities;
509+ assert!(!capabilities.fs.read_text_file);
510+ assert!(!capabilities.fs.write_text_file);
511+ assert!(!capabilities.terminal);
512+ }
513+
514514 #[test]
515515 fn a_prompt_is_the_text_followed_by_one_link_per_file() {
516516 let blocks = prompt_blocks(
@@ -29,6 +29,7 @@ use crate::events::{
29 };29 };
30 use crate::permission::PermissionBroker;30 use crate::permission::PermissionBroker;
31 use crate::protocol_log;31 use crate::protocol_log;
32+use crate::updates::event_for;
32 33
33 /// What the hub asks a worker to do.34 /// What the hub asks a worker to do.
34 pub(crate) enum Command {35 pub(crate) enum Command {
@@ -126,8 +127,8 @@ impl WorkerShared {
126 gates.entry(channel).or_default().clone()127 gates.entry(channel).or_default().clone()
127 }128 }
128 129
129- /// An update from the agent. Only the text of its answer and of its reasoning are passed130+ /// An update from the agent: its answer, its reasoning, its tool calls, its plan. What each
130- /// on for now. Tool calls and plans are ignored until ticket #17 shows them.131+ /// becomes is decided in [`crate::updates::event_for`].
131 fn handle_update(&self, notification: SessionNotification) {132 fn handle_update(&self, notification: SessionNotification) {
132 // The commands belong to the agent, not to a channel: they count even before a session is133 // The commands belong to the agent, not to a channel: they count even before a session is
133 // tied to one.134 // tied to one.
@@ -146,27 +147,8 @@ impl WorkerShared {
146 let Some(channel) = self.channel_of(&notification.session_id) else {147 let Some(channel) = self.channel_of(&notification.session_id) else {
147 return;148 return;
148 };149 };
149- let agent = self.agent.clone();150+ if let Some(event) = event_for(&self.agent, channel, notification.update) {
150- match notification.update {151+ self.emit(event);
151- SessionUpdate::AgentMessageChunk(chunk) => {
152- if let ContentBlock::Text(text) = chunk.content {
153- self.emit(AgentEvent::Text {
154- agent,
155- channel,
156- chunk: text.text,
157- });
158- }
159- }
160- SessionUpdate::AgentThoughtChunk(chunk) => {
161- if let ContentBlock::Text(text) = chunk.content {
162- self.emit(AgentEvent::Thought {
163- agent,
164- channel,
165- chunk: text.text,
166- });
167- }
168- }
169- _ => {}
170 }152 }
171 }153 }
172 154
@@ -410,7 +392,7 @@ async fn command_loop(
410 shared: Arc<WorkerShared>,392 shared: Arc<WorkerShared>,
411 ) -> Result<(), Error> {393 ) -> Result<(), Error> {
412 connection394 connection
413- .send_request(InitializeRequest::new(ProtocolVersion::V1))395+ .send_request(initialize_request())
414 .block_task()396 .block_task()
415 .await?;397 .await?;
416 shared398 shared
@@ -441,6 +423,16 @@ async fn command_loop(
441 Ok(())423 Ok(())
442 }424 }
443 425
426+/// What Synedrion says about itself when it starts an agent.
427+///
428+/// It announces no capability: neither reading and writing files (`fs/*`) nor terminals
429+/// (`terminal/*`). An agent that wants to read or run something does it with its own tools, in
430+/// its own process, which is what lets a sandbox keep it away from the host. Offering these would
431+/// be a decision about security, written down in the explanation "Client capabilities".
432+pub(crate) fn initialize_request() -> InitializeRequest {
433+ InitializeRequest::new(ProtocolVersion::V1)
434+}
435+
444 /// The content of a prompt: the text, then one link per attached file, which every agent must436 /// The content of a prompt: the text, then one link per attached file, which every agent must
445 /// accept.437 /// accept.
446 pub(crate) fn prompt_blocks(text: String, files: &[PathBuf]) -> Vec<ContentBlock> {438 pub(crate) fn prompt_blocks(text: String, files: &[PathBuf]) -> Vec<ContentBlock> {
@@ -511,6 +503,14 @@ fn to_permission_option(
511 mod tests {503 mod tests {
512 use super::*;504 use super::*;
513 505
506+ #[test]
507+ fn synedrion_announces_no_file_or_terminal_capability_to_agents() {
508+ let capabilities = initialize_request().client_capabilities;
509+ assert!(!capabilities.fs.read_text_file);
510+ assert!(!capabilities.fs.write_text_file);
511+ assert!(!capabilities.terminal);
512+ }
513+
514 #[test]514 #[test]
515 fn a_prompt_is_the_text_followed_by_one_link_per_file() {515 fn a_prompt_is_the_text_followed_by_one_link_per_file() {
516 let blocks = prompt_blocks(516 let blocks = prompt_blocks(
modified crates/acp/tests/hub.rs +40 -0
@@ -248,6 +248,46 @@ fn the_reasoning_of_an_agent_arrives_as_thoughts_apart_from_its_answer() {
248248 assert_eq!(answer, "done");
249249 }
250250
251+#[test]
252+fn the_tool_calls_and_the_plan_of_an_agent_arrive_as_events_in_order() {
253+ let (hub, events) = hub();
254+ hub.send_prompt(&fake_agent("fake"), CHANNEL, "@fake tools")
255+ .unwrap();
256+
257+ let mut seen: Vec<String> = Vec::new();
258+ events.until(|event| match event {
259+ AgentEvent::Plan { steps, .. } => {
260+ seen.push(format!("plan of {}", steps.len()));
261+ None
262+ }
263+ AgentEvent::ToolCall { call, .. } => {
264+ seen.push(format!("call {} {}", call.title, call.progress.label()));
265+ None
266+ }
267+ AgentEvent::ToolCallUpdated { id, change, .. } => {
268+ let output = change.output.clone().unwrap_or_default();
269+ seen.push(format!("update {id} {output}"));
270+ None
271+ }
272+ AgentEvent::Text { chunk, .. } => {
273+ seen.push(format!("text {chunk}"));
274+ None
275+ }
276+ AgentEvent::TurnFinished { .. } => Some(()),
277+ _ => None,
278+ });
279+
280+ assert_eq!(
281+ seen,
282+ vec![
283+ "plan of 2",
284+ "call Read notes.md running",
285+ "update tool-1 the notes",
286+ "text tools done"
287+ ]
288+ );
289+}
290+
251291 #[test]
252292 fn the_commands_an_agent_announces_are_reported_with_their_hints() {
253293 let (hub, events) = hub();
@@ -248,6 +248,46 @@ fn the_reasoning_of_an_agent_arrives_as_thoughts_apart_from_its_answer() {
248 assert_eq!(answer, "done");248 assert_eq!(answer, "done");
249 }249 }
250 250
251+#[test]
252+fn the_tool_calls_and_the_plan_of_an_agent_arrive_as_events_in_order() {
253+ let (hub, events) = hub();
254+ hub.send_prompt(&fake_agent("fake"), CHANNEL, "@fake tools")
255+ .unwrap();
256+
257+ let mut seen: Vec<String> = Vec::new();
258+ events.until(|event| match event {
259+ AgentEvent::Plan { steps, .. } => {
260+ seen.push(format!("plan of {}", steps.len()));
261+ None
262+ }
263+ AgentEvent::ToolCall { call, .. } => {
264+ seen.push(format!("call {} {}", call.title, call.progress.label()));
265+ None
266+ }
267+ AgentEvent::ToolCallUpdated { id, change, .. } => {
268+ let output = change.output.clone().unwrap_or_default();
269+ seen.push(format!("update {id} {output}"));
270+ None
271+ }
272+ AgentEvent::Text { chunk, .. } => {
273+ seen.push(format!("text {chunk}"));
274+ None
275+ }
276+ AgentEvent::TurnFinished { .. } => Some(()),
277+ _ => None,
278+ });
279+
280+ assert_eq!(
281+ seen,
282+ vec![
283+ "plan of 2",
284+ "call Read notes.md running",
285+ "update tool-1 the notes",
286+ "text tools done"
287+ ]
288+ );
289+}
290+
251 #[test]291 #[test]
252 fn the_commands_an_agent_announces_are_reported_with_their_hints() {292 fn the_commands_an_agent_announces_are_reported_with_their_hints() {
253 let (hub, events) = hub();293 let (hub, events) = hub();
modified crates/domain/README.md +6 -2
@@ -15,11 +15,15 @@ assert_eq!(extract_mentions("hello @mini-me"), vec!["mini-me".to_string()]);
1515 | `agent` | `AgentName` (validated, case-insensitive match), `AgentDeclaration` (command, args, env, working folder), `AgentStatus`, `is_name_character` |
1616 | `command` | `parse_slash`, `SlashCommand`, `trailing_command_prefix`, `complete_command`, `file_query`, `without_file_command`, `FILE_COMMAND`: reading slash commands and `/file` in a message |
1717 | `channel` | `Channel`, `ChannelId`, `ChannelName`, `DEFAULT_CHANNEL_NAME` |
18+| `context` | `select_context`, `render_prompt`, `Context`, `ContextLine`, `MAX_LINE_CHARS`, `MAX_CONTEXT_CHARS`: what an agent is told about the channel besides the message that calls it |
1819 | `error` | `ValidationError` |
20+| `file_reference` | `trailing_file_query`, `complete_file_reference`, `FILE_REFERENCE_MARK`: naming a file with `$` in the middle of a sentence |
1921 | `mention` | `extract_mentions`, `resolve_mentions` and `ResolvedMentions`, `follow_up_recipients` (who a message without a mention goes to), `trailing_mention_prefix`, `complete_trailing_mention`, `agents_starting_with` |
20-| `message` | `Message`, `NewMessage`, `MessageId`, `Author` |
21-| `repository` | The `Repository` trait, `RepositoryError`, `RepositoryResult` |
22+| `message` | `Message`, `NewMessage`, `MessageId`, `Author` (user, agent, system, or the trace of an agent) |
23+| `repository` | The `Repository` trait (including `load_settings` and `save_settings`), `RepositoryError`, `RepositoryResult` |
24+| `settings` | `ChatSettings` (messages of context, chain depth), `SettingsError`, the defaults and the limits |
2225 | `time` | `unix_millis_now`, the one place the clock is read |
26+| `trace` | `Trace`, `ToolCallTrace`, `ToolCallChange`, `PlanStep`, `Progress`, `shorten`, `MAX_OUTPUT_CHARS`: what an agent does besides writing, and its stored text form |
2327 | `user` | `UserProfile`, `DisplayName` |
2428
2529 Run its tests with `cargo test -p synedrion-domain`.
@@ -15,11 +15,15 @@ assert_eq!(extract_mentions("hello @mini-me"), vec!["mini-me".to_string()]);
15 | `agent` | `AgentName` (validated, case-insensitive match), `AgentDeclaration` (command, args, env, working folder), `AgentStatus`, `is_name_character` |15 | `agent` | `AgentName` (validated, case-insensitive match), `AgentDeclaration` (command, args, env, working folder), `AgentStatus`, `is_name_character` |
16 | `command` | `parse_slash`, `SlashCommand`, `trailing_command_prefix`, `complete_command`, `file_query`, `without_file_command`, `FILE_COMMAND`: reading slash commands and `/file` in a message |16 | `command` | `parse_slash`, `SlashCommand`, `trailing_command_prefix`, `complete_command`, `file_query`, `without_file_command`, `FILE_COMMAND`: reading slash commands and `/file` in a message |
17 | `channel` | `Channel`, `ChannelId`, `ChannelName`, `DEFAULT_CHANNEL_NAME` |17 | `channel` | `Channel`, `ChannelId`, `ChannelName`, `DEFAULT_CHANNEL_NAME` |
18+| `context` | `select_context`, `render_prompt`, `Context`, `ContextLine`, `MAX_LINE_CHARS`, `MAX_CONTEXT_CHARS`: what an agent is told about the channel besides the message that calls it |
18 | `error` | `ValidationError` |19 | `error` | `ValidationError` |
20+| `file_reference` | `trailing_file_query`, `complete_file_reference`, `FILE_REFERENCE_MARK`: naming a file with `$` in the middle of a sentence |
19 | `mention` | `extract_mentions`, `resolve_mentions` and `ResolvedMentions`, `follow_up_recipients` (who a message without a mention goes to), `trailing_mention_prefix`, `complete_trailing_mention`, `agents_starting_with` |21 | `mention` | `extract_mentions`, `resolve_mentions` and `ResolvedMentions`, `follow_up_recipients` (who a message without a mention goes to), `trailing_mention_prefix`, `complete_trailing_mention`, `agents_starting_with` |
20-| `message` | `Message`, `NewMessage`, `MessageId`, `Author` |22+| `message` | `Message`, `NewMessage`, `MessageId`, `Author` (user, agent, system, or the trace of an agent) |
21-| `repository` | The `Repository` trait, `RepositoryError`, `RepositoryResult` |23+| `repository` | The `Repository` trait (including `load_settings` and `save_settings`), `RepositoryError`, `RepositoryResult` |
24+| `settings` | `ChatSettings` (messages of context, chain depth), `SettingsError`, the defaults and the limits |
22 | `time` | `unix_millis_now`, the one place the clock is read |25 | `time` | `unix_millis_now`, the one place the clock is read |
26+| `trace` | `Trace`, `ToolCallTrace`, `ToolCallChange`, `PlanStep`, `Progress`, `shorten`, `MAX_OUTPUT_CHARS`: what an agent does besides writing, and its stored text form |
23 | `user` | `UserProfile`, `DisplayName` |27 | `user` | `UserProfile`, `DisplayName` |
24 28
25 Run its tests with `cargo test -p synedrion-domain`.29 Run its tests with `cargo test -p synedrion-domain`.
added crates/domain/src/context.rs +408 -0
new file mode 100644
@@ -0,0 +1,408 @@
1+//! What an agent is told about the channel besides the message that calls it.
2+//!
3+//! An agent keeps its own conversation, so it already knows what it and the user said to one
4+//! another. What it cannot know is what was said around it: by the user to nobody, and by the
5+//! other agents. The prompt it receives starts with those messages, sent since its last turn,
6+//! and then comes the message itself.
7+//!
8+//! Everything here is a plain function of its arguments, so it is tested without a database.
9+
10+use crate::agent::AgentName;
11+use crate::message::{Author, Message, MessageId};
12+
13+/// The most characters of one earlier message that are handed over. A longer one is cut, and
14+/// says so, so that a long answer of another agent does not drown the prompt.
15+pub const MAX_LINE_CHARS: usize = 2_000;
16+
17+/// The most characters of context altogether. When the messages do not fit, the oldest are left
18+/// out, and the prompt says how many.
19+pub const MAX_CONTEXT_CHARS: usize = 12_000;
20+
21+/// One earlier message, as the agent will read it.
22+#[derive(Debug, Clone, PartialEq, Eq)]
23+pub struct ContextLine {
24+ /// The name of the user or of the agent who wrote it.
25+ pub author: String,
26+ pub text: String,
27+}
28+
29+/// The earlier messages chosen for an agent, and how many were left out for lack of room.
30+#[derive(Debug, Clone, Default, PartialEq, Eq)]
31+pub struct Context {
32+ pub lines: Vec<ContextLine>,
33+ /// Messages the agent has not seen and will not be told about, because of the limit on their
34+ /// number or on their size.
35+ pub omitted: usize,
36+}
37+
38+impl Context {
39+ /// True when there is nothing to tell.
40+ pub fn is_empty(&self) -> bool {
41+ self.lines.is_empty() && self.omitted == 0
42+ }
43+}
44+
45+/// Chooses what `recipient` has not seen yet: the messages after `seen` (all of them when it has
46+/// seen none), without its own words, without the application's notices and without traces, at
47+/// most `limit` of them, the latest ones. A `limit` of zero chooses nothing.
48+///
49+/// `messages` are the earlier messages of the channel, oldest first, and must not hold the
50+/// message being sent. `user_name` is how the user's own messages are signed.
51+///
52+/// ```
53+/// use synedrion_domain::agent::AgentName;
54+/// use synedrion_domain::channel::ChannelId;
55+/// use synedrion_domain::context::select_context;
56+/// use synedrion_domain::message::{Author, Message, MessageId};
57+///
58+/// let said = |id, author, text: &str| Message {
59+/// id: MessageId(id),
60+/// channel_id: ChannelId(1),
61+/// author,
62+/// content: text.to_string(),
63+/// created_at_ms: 0,
64+/// };
65+/// let bob = AgentName::new("bob").unwrap();
66+/// let messages = vec![
67+/// said(1, Author::User, "hello"),
68+/// said(2, Author::Agent(AgentName::new("amy").unwrap()), "hi"),
69+/// ];
70+/// let context = select_context(&messages, &bob, None, "Ada", 10);
71+/// assert_eq!(context.lines.len(), 2);
72+/// assert_eq!(context.lines[1].author, "amy");
73+/// ```
74+pub fn select_context(
75+ messages: &[Message],
76+ recipient: &AgentName,
77+ seen: Option<MessageId>,
78+ user_name: &str,
79+ limit: usize,
80+) -> Context {
81+ // A limit of zero means the user wants no context at all, not "a context that says it is empty".
82+ if limit == 0 {
83+ return Context::default();
84+ }
85+ let unseen: Vec<ContextLine> = messages
86+ .iter()
87+ .filter(|message| seen.is_none_or(|last| message.id.0 > last.0))
88+ .filter_map(|message| match &message.author {
89+ Author::User => Some(line(user_name, message)),
90+ Author::Agent(name) if !recipient.matches(name.as_str()) => {
91+ Some(line(name.as_str(), message))
92+ }
93+ Author::Agent(_) | Author::System | Author::Trace(_) => None,
94+ })
95+ .collect();
96+ let skipped = unseen.len().saturating_sub(limit);
97+ Context {
98+ lines: unseen.into_iter().skip(skipped).collect(),
99+ omitted: skipped,
100+ }
101+}
102+
103+fn line(author: &str, message: &Message) -> ContextLine {
104+ ContextLine {
105+ author: author.to_string(),
106+ text: message.content.clone(),
107+ }
108+}
109+
110+/// Builds the text an agent receives.
111+///
112+/// - A message from the user, with no context, is handed over exactly as typed.
113+/// - Context comes first, under a header, then the message.
114+/// - A message from another agent (`from`) is introduced as such, because nothing else would say
115+/// who is speaking.
116+///
117+/// A message of the context that is longer than [`MAX_LINE_CHARS`] is cut and marked, and the
118+/// oldest messages are dropped, and counted, until the context fits [`MAX_CONTEXT_CHARS`].
119+///
120+/// ```
121+/// use synedrion_domain::context::{Context, ContextLine, render_prompt};
122+///
123+/// assert_eq!(render_prompt(&Context::default(), None, "hi @bob"), "hi @bob");
124+///
125+/// let context = Context {
126+/// lines: vec![ContextLine { author: "Ada".to_string(), text: "hello".to_string() }],
127+/// omitted: 0,
128+/// };
129+/// let prompt = render_prompt(&context, Some("amy"), "your turn");
130+/// assert!(prompt.contains("Ada: hello"));
131+/// assert!(prompt.ends_with("[Message from @amy]\nyour turn"));
132+/// ```
133+pub fn render_prompt(context: &Context, from: Option<&str>, message: &str) -> String {
134+ let mut sections: Vec<String> = Vec::new();
135+ if !context.is_empty() {
136+ sections.push(render_context(context));
137+ }
138+ sections.push(match from {
139+ Some(agent) => format!("[Message from @{agent}]\n{message}"),
140+ None => message.to_string(),
141+ });
142+ sections.join("\n\n")
143+}
144+
145+fn render_context(context: &Context) -> String {
146+ let rendered: Vec<String> = context.lines.iter().map(render_line).collect();
147+
148+ // Keep the latest lines that fit, dropping the oldest first.
149+ let mut kept_from = rendered.len();
150+ let mut total = 0;
151+ while kept_from > 0 {
152+ let size = rendered[kept_from - 1].chars().count() + 1;
153+ if total + size > MAX_CONTEXT_CHARS {
154+ break;
155+ }
156+ total += size;
157+ kept_from -= 1;
158+ }
159+ let omitted = context.omitted + kept_from;
160+
161+ let mut text = String::from("[Channel context: what was said since your last turn]\n");
162+ if omitted > 0 {
163+ text.push_str(&format!("[{omitted} earlier message(s) not shown]\n"));
164+ }
165+ for rendered_line in &rendered[kept_from..] {
166+ text.push_str(rendered_line);
167+ text.push('\n');
168+ }
169+ text.push_str("[End of channel context]");
170+ text
171+}
172+
173+fn render_line(line: &ContextLine) -> String {
174+ let length = line.text.chars().count();
175+ if length <= MAX_LINE_CHARS {
176+ return format!("{}: {}", line.author, line.text);
177+ }
178+ let kept: String = line.text.chars().take(MAX_LINE_CHARS).collect();
179+ format!(
180+ "{}: {kept} [message cut: {} more character(s)]",
181+ line.author,
182+ length - MAX_LINE_CHARS
183+ )
184+}
185+
186+#[cfg(test)]
187+mod tests {
188+ use super::*;
189+ use crate::channel::ChannelId;
190+
191+ fn said(id: i64, author: Author, text: &str) -> Message {
192+ Message {
193+ id: MessageId(id),
194+ channel_id: ChannelId(1),
195+ author,
196+ content: text.to_string(),
197+ created_at_ms: 0,
198+ }
199+ }
200+
201+ fn agent(name: &str) -> AgentName {
202+ AgentName::new(name).unwrap()
203+ }
204+
205+ fn from_agent(id: i64, name: &str, text: &str) -> Message {
206+ said(id, Author::Agent(agent(name)), text)
207+ }
208+
209+ fn texts(context: &Context) -> Vec<String> {
210+ context
211+ .lines
212+ .iter()
213+ .map(|line| format!("{}: {}", line.author, line.text))
214+ .collect()
215+ }
216+
217+ #[test]
218+ fn nothing_earlier_gives_an_empty_context() {
219+ let context = select_context(&[], &agent("bob"), None, "Ada", 10);
220+ assert!(context.is_empty());
221+ }
222+
223+ #[test]
224+ fn an_agent_that_has_seen_nothing_gets_the_latest_messages_signed() {
225+ let messages = vec![
226+ said(1, Author::User, "hello"),
227+ from_agent(2, "amy", "hi"),
228+ said(3, Author::User, "go on"),
229+ ];
230+ let context = select_context(&messages, &agent("bob"), None, "Ada", 10);
231+ assert_eq!(texts(&context), vec!["Ada: hello", "amy: hi", "Ada: go on"]);
232+ assert_eq!(context.omitted, 0);
233+ }
234+
235+ #[test]
236+ fn messages_up_to_the_last_one_seen_are_not_repeated() {
237+ let messages = vec![
238+ said(1, Author::User, "old"),
239+ said(2, Author::User, "seen"),
240+ said(3, Author::User, "new"),
241+ ];
242+ let context = select_context(&messages, &agent("bob"), Some(MessageId(2)), "Ada", 10);
243+ assert_eq!(texts(&context), vec!["Ada: new"]);
244+ }
245+
246+ #[test]
247+ fn the_recipients_own_messages_are_left_out() {
248+ let messages = vec![
249+ from_agent(1, "bob", "my own answer"),
250+ from_agent(2, "BOB", "same name in another case"),
251+ from_agent(3, "amy", "hers"),
252+ ];
253+ let context = select_context(&messages, &agent("bob"), None, "Ada", 10);
254+ assert_eq!(texts(&context), vec!["amy: hers"]);
255+ }
256+
257+ #[test]
258+ fn notices_of_the_application_are_not_conversation() {
259+ let messages = vec![
260+ said(1, Author::System, "Could not reach @bob"),
261+ said(2, Author::User, "hello"),
262+ ];
263+ let context = select_context(&messages, &agent("bob"), None, "Ada", 10);
264+ assert_eq!(texts(&context), vec!["Ada: hello"]);
265+ }
266+
267+ #[test]
268+ fn only_the_latest_messages_are_kept_and_the_others_are_counted() {
269+ let messages: Vec<Message> = (1..=5)
270+ .map(|id| said(id, Author::User, &format!("m{id}")))
271+ .collect();
272+ let context = select_context(&messages, &agent("bob"), None, "Ada", 2);
273+ assert_eq!(texts(&context), vec!["Ada: m4", "Ada: m5"]);
274+ assert_eq!(context.omitted, 3);
275+ }
276+
277+ #[test]
278+ fn a_limit_of_zero_hands_over_nothing_and_does_not_mention_it() {
279+ let messages = vec![said(1, Author::User, "hello")];
280+ let context = select_context(&messages, &agent("bob"), None, "Ada", 0);
281+ assert!(context.is_empty());
282+ }
283+
284+ #[test]
285+ fn without_context_a_user_message_is_handed_over_exactly_as_typed() {
286+ assert_eq!(
287+ render_prompt(&Context::default(), None, " @bob hi\n"),
288+ " @bob hi\n"
289+ );
290+ }
291+
292+ #[test]
293+ fn context_comes_first_under_a_header_and_then_the_message() {
294+ let context = Context {
295+ lines: vec![
296+ ContextLine {
297+ author: "Ada".into(),
298+ text: "one".into(),
299+ },
300+ ContextLine {
301+ author: "amy".into(),
302+ text: "two".into(),
303+ },
304+ ],
305+ omitted: 0,
306+ };
307+ assert_eq!(
308+ render_prompt(&context, None, "@bob and you?"),
309+ "[Channel context: what was said since your last turn]\n\
310+ Ada: one\n\
311+ amy: two\n\
312+ [End of channel context]\n\n\
313+ @bob and you?"
314+ );
315+ }
316+
317+ #[test]
318+ fn a_message_from_an_agent_is_introduced_even_without_context() {
319+ assert_eq!(
320+ render_prompt(&Context::default(), Some("amy"), "please check"),
321+ "[Message from @amy]\nplease check"
322+ );
323+ }
324+
325+ #[test]
326+ fn omitted_messages_are_announced_before_the_others() {
327+ let context = Context {
328+ lines: vec![ContextLine {
329+ author: "Ada".into(),
330+ text: "last".into(),
331+ }],
332+ omitted: 4,
333+ };
334+ let prompt = render_prompt(&context, None, "go");
335+ assert!(prompt.contains("[4 earlier message(s) not shown]\nAda: last"));
336+ }
337+
338+ #[test]
339+ fn omitted_messages_are_announced_even_when_none_is_kept() {
340+ let context = Context {
341+ lines: vec![],
342+ omitted: 2,
343+ };
344+ assert!(render_prompt(&context, None, "go").contains("[2 earlier message(s) not shown]"));
345+ }
346+
347+ #[test]
348+ fn a_long_message_is_cut_and_marked() {
349+ let long = "x".repeat(MAX_LINE_CHARS + 50);
350+ let context = Context {
351+ lines: vec![ContextLine {
352+ author: "amy".into(),
353+ text: long,
354+ }],
355+ omitted: 0,
356+ };
357+ let prompt = render_prompt(&context, None, "go");
358+ assert!(prompt.contains("[message cut: 50 more character(s)]"));
359+ assert!(!prompt.contains(&"x".repeat(MAX_LINE_CHARS + 1)));
360+ }
361+
362+ #[test]
363+ fn a_message_exactly_at_the_limit_is_not_cut() {
364+ let context = Context {
365+ lines: vec![ContextLine {
366+ author: "amy".into(),
367+ text: "x".repeat(MAX_LINE_CHARS),
368+ }],
369+ omitted: 0,
370+ };
371+ assert!(!render_prompt(&context, None, "go").contains("message cut"));
372+ }
373+
374+ #[test]
375+ fn cutting_counts_characters_and_never_splits_one() {
376+ let context = Context {
377+ lines: vec![ContextLine {
378+ author: "amy".into(),
379+ text: "é".repeat(MAX_LINE_CHARS + 1),
380+ }],
381+ omitted: 0,
382+ };
383+ let prompt = render_prompt(&context, None, "go");
384+ assert!(prompt.contains("[message cut: 1 more character(s)]"));
385+ }
386+
387+ #[test]
388+ fn the_oldest_messages_are_dropped_when_the_context_is_too_big() {
389+ let lines: Vec<ContextLine> = (0..10)
390+ .map(|n| ContextLine {
391+ author: "amy".into(),
392+ text: format!("{n}{}", "y".repeat(MAX_LINE_CHARS - 1)),
393+ })
394+ .collect();
395+ let context = Context { lines, omitted: 1 };
396+ let prompt = render_prompt(&context, None, "go");
397+
398+ let kept = prompt.matches("amy: ").count();
399+ assert!(kept < 10 && kept > 0, "kept {kept}");
400+ assert!(prompt.contains(&format!("[{} earlier message(s) not shown]", 1 + 10 - kept)));
401+ assert!(
402+ prompt.contains(&format!("amy: 9{}", "y".repeat(5))),
403+ "the latest is kept"
404+ );
405+ assert!(!prompt.contains("amy: 0y"), "the oldest is dropped");
406+ assert!(prompt.chars().count() < MAX_CONTEXT_CHARS + 300);
407+ }
408+}
new file mode 100644
@@ -0,0 +1,408 @@
1+//! What an agent is told about the channel besides the message that calls it.
2+//!
3+//! An agent keeps its own conversation, so it already knows what it and the user said to one
4+//! another. What it cannot know is what was said around it: by the user to nobody, and by the
5+//! other agents. The prompt it receives starts with those messages, sent since its last turn,
6+//! and then comes the message itself.
7+//!
8+//! Everything here is a plain function of its arguments, so it is tested without a database.
9+
10+use crate::agent::AgentName;
11+use crate::message::{Author, Message, MessageId};
12+
13+/// The most characters of one earlier message that are handed over. A longer one is cut, and
14+/// says so, so that a long answer of another agent does not drown the prompt.
15+pub const MAX_LINE_CHARS: usize = 2_000;
16+
17+/// The most characters of context altogether. When the messages do not fit, the oldest are left
18+/// out, and the prompt says how many.
19+pub const MAX_CONTEXT_CHARS: usize = 12_000;
20+
21+/// One earlier message, as the agent will read it.
22+#[derive(Debug, Clone, PartialEq, Eq)]
23+pub struct ContextLine {
24+ /// The name of the user or of the agent who wrote it.
25+ pub author: String,
26+ pub text: String,
27+}
28+
29+/// The earlier messages chosen for an agent, and how many were left out for lack of room.
30+#[derive(Debug, Clone, Default, PartialEq, Eq)]
31+pub struct Context {
32+ pub lines: Vec<ContextLine>,
33+ /// Messages the agent has not seen and will not be told about, because of the limit on their
34+ /// number or on their size.
35+ pub omitted: usize,
36+}
37+
38+impl Context {
39+ /// True when there is nothing to tell.
40+ pub fn is_empty(&self) -> bool {
41+ self.lines.is_empty() && self.omitted == 0
42+ }
43+}
44+
45+/// Chooses what `recipient` has not seen yet: the messages after `seen` (all of them when it has
46+/// seen none), without its own words, without the application's notices and without traces, at
47+/// most `limit` of them, the latest ones. A `limit` of zero chooses nothing.
48+///
49+/// `messages` are the earlier messages of the channel, oldest first, and must not hold the
50+/// message being sent. `user_name` is how the user's own messages are signed.
51+///
52+/// ```
53+/// use synedrion_domain::agent::AgentName;
54+/// use synedrion_domain::channel::ChannelId;
55+/// use synedrion_domain::context::select_context;
56+/// use synedrion_domain::message::{Author, Message, MessageId};
57+///
58+/// let said = |id, author, text: &str| Message {
59+/// id: MessageId(id),
60+/// channel_id: ChannelId(1),
61+/// author,
62+/// content: text.to_string(),
63+/// created_at_ms: 0,
64+/// };
65+/// let bob = AgentName::new("bob").unwrap();
66+/// let messages = vec![
67+/// said(1, Author::User, "hello"),
68+/// said(2, Author::Agent(AgentName::new("amy").unwrap()), "hi"),
69+/// ];
70+/// let context = select_context(&messages, &bob, None, "Ada", 10);
71+/// assert_eq!(context.lines.len(), 2);
72+/// assert_eq!(context.lines[1].author, "amy");
73+/// ```
74+pub fn select_context(
75+ messages: &[Message],
76+ recipient: &AgentName,
77+ seen: Option<MessageId>,
78+ user_name: &str,
79+ limit: usize,
80+) -> Context {
81+ // A limit of zero means the user wants no context at all, not "a context that says it is empty".
82+ if limit == 0 {
83+ return Context::default();
84+ }
85+ let unseen: Vec<ContextLine> = messages
86+ .iter()
87+ .filter(|message| seen.is_none_or(|last| message.id.0 > last.0))
88+ .filter_map(|message| match &message.author {
89+ Author::User => Some(line(user_name, message)),
90+ Author::Agent(name) if !recipient.matches(name.as_str()) => {
91+ Some(line(name.as_str(), message))
92+ }
93+ Author::Agent(_) | Author::System | Author::Trace(_) => None,
94+ })
95+ .collect();
96+ let skipped = unseen.len().saturating_sub(limit);
97+ Context {
98+ lines: unseen.into_iter().skip(skipped).collect(),
99+ omitted: skipped,
100+ }
101+}
102+
103+fn line(author: &str, message: &Message) -> ContextLine {
104+ ContextLine {
105+ author: author.to_string(),
106+ text: message.content.clone(),
107+ }
108+}
109+
110+/// Builds the text an agent receives.
111+///
112+/// - A message from the user, with no context, is handed over exactly as typed.
113+/// - Context comes first, under a header, then the message.
114+/// - A message from another agent (`from`) is introduced as such, because nothing else would say
115+/// who is speaking.
116+///
117+/// A message of the context that is longer than [`MAX_LINE_CHARS`] is cut and marked, and the
118+/// oldest messages are dropped, and counted, until the context fits [`MAX_CONTEXT_CHARS`].
119+///
120+/// ```
121+/// use synedrion_domain::context::{Context, ContextLine, render_prompt};
122+///
123+/// assert_eq!(render_prompt(&Context::default(), None, "hi @bob"), "hi @bob");
124+///
125+/// let context = Context {
126+/// lines: vec![ContextLine { author: "Ada".to_string(), text: "hello".to_string() }],
127+/// omitted: 0,
128+/// };
129+/// let prompt = render_prompt(&context, Some("amy"), "your turn");
130+/// assert!(prompt.contains("Ada: hello"));
131+/// assert!(prompt.ends_with("[Message from @amy]\nyour turn"));
132+/// ```
133+pub fn render_prompt(context: &Context, from: Option<&str>, message: &str) -> String {
134+ let mut sections: Vec<String> = Vec::new();
135+ if !context.is_empty() {
136+ sections.push(render_context(context));
137+ }
138+ sections.push(match from {
139+ Some(agent) => format!("[Message from @{agent}]\n{message}"),
140+ None => message.to_string(),
141+ });
142+ sections.join("\n\n")
143+}
144+
145+fn render_context(context: &Context) -> String {
146+ let rendered: Vec<String> = context.lines.iter().map(render_line).collect();
147+
148+ // Keep the latest lines that fit, dropping the oldest first.
149+ let mut kept_from = rendered.len();
150+ let mut total = 0;
151+ while kept_from > 0 {
152+ let size = rendered[kept_from - 1].chars().count() + 1;
153+ if total + size > MAX_CONTEXT_CHARS {
154+ break;
155+ }
156+ total += size;
157+ kept_from -= 1;
158+ }
159+ let omitted = context.omitted + kept_from;
160+
161+ let mut text = String::from("[Channel context: what was said since your last turn]\n");
162+ if omitted > 0 {
163+ text.push_str(&format!("[{omitted} earlier message(s) not shown]\n"));
164+ }
165+ for rendered_line in &rendered[kept_from..] {
166+ text.push_str(rendered_line);
167+ text.push('\n');
168+ }
169+ text.push_str("[End of channel context]");
170+ text
171+}
172+
173+fn render_line(line: &ContextLine) -> String {
174+ let length = line.text.chars().count();
175+ if length <= MAX_LINE_CHARS {
176+ return format!("{}: {}", line.author, line.text);
177+ }
178+ let kept: String = line.text.chars().take(MAX_LINE_CHARS).collect();
179+ format!(
180+ "{}: {kept} [message cut: {} more character(s)]",
181+ line.author,
182+ length - MAX_LINE_CHARS
183+ )
184+}
185+
186+#[cfg(test)]
187+mod tests {
188+ use super::*;
189+ use crate::channel::ChannelId;
190+
191+ fn said(id: i64, author: Author, text: &str) -> Message {
192+ Message {
193+ id: MessageId(id),
194+ channel_id: ChannelId(1),
195+ author,
196+ content: text.to_string(),
197+ created_at_ms: 0,
198+ }
199+ }
200+
201+ fn agent(name: &str) -> AgentName {
202+ AgentName::new(name).unwrap()
203+ }
204+
205+ fn from_agent(id: i64, name: &str, text: &str) -> Message {
206+ said(id, Author::Agent(agent(name)), text)
207+ }
208+
209+ fn texts(context: &Context) -> Vec<String> {
210+ context
211+ .lines
212+ .iter()
213+ .map(|line| format!("{}: {}", line.author, line.text))
214+ .collect()
215+ }
216+
217+ #[test]
218+ fn nothing_earlier_gives_an_empty_context() {
219+ let context = select_context(&[], &agent("bob"), None, "Ada", 10);
220+ assert!(context.is_empty());
221+ }
222+
223+ #[test]
224+ fn an_agent_that_has_seen_nothing_gets_the_latest_messages_signed() {
225+ let messages = vec![
226+ said(1, Author::User, "hello"),
227+ from_agent(2, "amy", "hi"),
228+ said(3, Author::User, "go on"),
229+ ];
230+ let context = select_context(&messages, &agent("bob"), None, "Ada", 10);
231+ assert_eq!(texts(&context), vec!["Ada: hello", "amy: hi", "Ada: go on"]);
232+ assert_eq!(context.omitted, 0);
233+ }
234+
235+ #[test]
236+ fn messages_up_to_the_last_one_seen_are_not_repeated() {
237+ let messages = vec![
238+ said(1, Author::User, "old"),
239+ said(2, Author::User, "seen"),
240+ said(3, Author::User, "new"),
241+ ];
242+ let context = select_context(&messages, &agent("bob"), Some(MessageId(2)), "Ada", 10);
243+ assert_eq!(texts(&context), vec!["Ada: new"]);
244+ }
245+
246+ #[test]
247+ fn the_recipients_own_messages_are_left_out() {
248+ let messages = vec![
249+ from_agent(1, "bob", "my own answer"),
250+ from_agent(2, "BOB", "same name in another case"),
251+ from_agent(3, "amy", "hers"),
252+ ];
253+ let context = select_context(&messages, &agent("bob"), None, "Ada", 10);
254+ assert_eq!(texts(&context), vec!["amy: hers"]);
255+ }
256+
257+ #[test]
258+ fn notices_of_the_application_are_not_conversation() {
259+ let messages = vec![
260+ said(1, Author::System, "Could not reach @bob"),
261+ said(2, Author::User, "hello"),
262+ ];
263+ let context = select_context(&messages, &agent("bob"), None, "Ada", 10);
264+ assert_eq!(texts(&context), vec!["Ada: hello"]);
265+ }
266+
267+ #[test]
268+ fn only_the_latest_messages_are_kept_and_the_others_are_counted() {
269+ let messages: Vec<Message> = (1..=5)
270+ .map(|id| said(id, Author::User, &format!("m{id}")))
271+ .collect();
272+ let context = select_context(&messages, &agent("bob"), None, "Ada", 2);
273+ assert_eq!(texts(&context), vec!["Ada: m4", "Ada: m5"]);
274+ assert_eq!(context.omitted, 3);
275+ }
276+
277+ #[test]
278+ fn a_limit_of_zero_hands_over_nothing_and_does_not_mention_it() {
279+ let messages = vec![said(1, Author::User, "hello")];
280+ let context = select_context(&messages, &agent("bob"), None, "Ada", 0);
281+ assert!(context.is_empty());
282+ }
283+
284+ #[test]
285+ fn without_context_a_user_message_is_handed_over_exactly_as_typed() {
286+ assert_eq!(
287+ render_prompt(&Context::default(), None, " @bob hi\n"),
288+ " @bob hi\n"
289+ );
290+ }
291+
292+ #[test]
293+ fn context_comes_first_under_a_header_and_then_the_message() {
294+ let context = Context {
295+ lines: vec![
296+ ContextLine {
297+ author: "Ada".into(),
298+ text: "one".into(),
299+ },
300+ ContextLine {
301+ author: "amy".into(),
302+ text: "two".into(),
303+ },
304+ ],
305+ omitted: 0,
306+ };
307+ assert_eq!(
308+ render_prompt(&context, None, "@bob and you?"),
309+ "[Channel context: what was said since your last turn]\n\
310+ Ada: one\n\
311+ amy: two\n\
312+ [End of channel context]\n\n\
313+ @bob and you?"
314+ );
315+ }
316+
317+ #[test]
318+ fn a_message_from_an_agent_is_introduced_even_without_context() {
319+ assert_eq!(
320+ render_prompt(&Context::default(), Some("amy"), "please check"),
321+ "[Message from @amy]\nplease check"
322+ );
323+ }
324+
325+ #[test]
326+ fn omitted_messages_are_announced_before_the_others() {
327+ let context = Context {
328+ lines: vec![ContextLine {
329+ author: "Ada".into(),
330+ text: "last".into(),
331+ }],
332+ omitted: 4,
333+ };
334+ let prompt = render_prompt(&context, None, "go");
335+ assert!(prompt.contains("[4 earlier message(s) not shown]\nAda: last"));
336+ }
337+
338+ #[test]
339+ fn omitted_messages_are_announced_even_when_none_is_kept() {
340+ let context = Context {
341+ lines: vec![],
342+ omitted: 2,
343+ };
344+ assert!(render_prompt(&context, None, "go").contains("[2 earlier message(s) not shown]"));
345+ }
346+
347+ #[test]
348+ fn a_long_message_is_cut_and_marked() {
349+ let long = "x".repeat(MAX_LINE_CHARS + 50);
350+ let context = Context {
351+ lines: vec![ContextLine {
352+ author: "amy".into(),
353+ text: long,
354+ }],
355+ omitted: 0,
356+ };
357+ let prompt = render_prompt(&context, None, "go");
358+ assert!(prompt.contains("[message cut: 50 more character(s)]"));
359+ assert!(!prompt.contains(&"x".repeat(MAX_LINE_CHARS + 1)));
360+ }
361+
362+ #[test]
363+ fn a_message_exactly_at_the_limit_is_not_cut() {
364+ let context = Context {
365+ lines: vec![ContextLine {
366+ author: "amy".into(),
367+ text: "x".repeat(MAX_LINE_CHARS),
368+ }],
369+ omitted: 0,
370+ };
371+ assert!(!render_prompt(&context, None, "go").contains("message cut"));
372+ }
373+
374+ #[test]
375+ fn cutting_counts_characters_and_never_splits_one() {
376+ let context = Context {
377+ lines: vec![ContextLine {
378+ author: "amy".into(),
379+ text: "é".repeat(MAX_LINE_CHARS + 1),
380+ }],
381+ omitted: 0,
382+ };
383+ let prompt = render_prompt(&context, None, "go");
384+ assert!(prompt.contains("[message cut: 1 more character(s)]"));
385+ }
386+
387+ #[test]
388+ fn the_oldest_messages_are_dropped_when_the_context_is_too_big() {
389+ let lines: Vec<ContextLine> = (0..10)
390+ .map(|n| ContextLine {
391+ author: "amy".into(),
392+ text: format!("{n}{}", "y".repeat(MAX_LINE_CHARS - 1)),
393+ })
394+ .collect();
395+ let context = Context { lines, omitted: 1 };
396+ let prompt = render_prompt(&context, None, "go");
397+
398+ let kept = prompt.matches("amy: ").count();
399+ assert!(kept < 10 && kept > 0, "kept {kept}");
400+ assert!(prompt.contains(&format!("[{} earlier message(s) not shown]", 1 + 10 - kept)));
401+ assert!(
402+ prompt.contains(&format!("amy: 9{}", "y".repeat(5))),
403+ "the latest is kept"
404+ );
405+ assert!(!prompt.contains("amy: 0y"), "the oldest is dropped");
406+ assert!(prompt.chars().count() < MAX_CONTEXT_CHARS + 300);
407+ }
408+}
added crates/domain/src/file_reference.rs +152 -0
new file mode 100644
@@ -0,0 +1,152 @@
1+//! Naming a file in the middle of a sentence: `look at $main.rs and fix it`.
2+//!
3+//! `@` names an agent and `/` starts a command, so `$` names a file. While the text ends with `$`
4+//! and the beginning of a name, the application lists the files that match, and picking one puts
5+//! its path in the sentence. Everything here is a pure function of the text.
6+
7+/// The character that starts a file reference.
8+///
9+/// ```
10+/// assert_eq!(synedrion_domain::file_reference::FILE_REFERENCE_MARK, '$');
11+/// ```
12+pub const FILE_REFERENCE_MARK: char = '$';
13+
14+/// The words typed after a `$` at the very end of `text`: what to search the files for. `Some("")`
15+/// right after a lone `$`. `None` when the text does not end in a file reference being typed.
16+///
17+/// The `$` must not be glued to the end of a word (`US$5` is not a reference), and the query ends
18+/// at the first space, so a reference that was followed by a space is complete.
19+///
20+/// ```
21+/// use synedrion_domain::file_reference::trailing_file_query;
22+///
23+/// assert_eq!(trailing_file_query("look at $main"), Some("main".to_string()));
24+/// assert_eq!(trailing_file_query("look at $"), Some(String::new()));
25+/// assert_eq!(trailing_file_query("look at $main.rs and"), None);
26+/// assert_eq!(trailing_file_query("it costs US$5"), None);
27+/// ```
28+pub fn trailing_file_query(text: &str) -> Option<String> {
29+ let mark = reference_start(text)?;
30+ Some(text[mark + FILE_REFERENCE_MARK.len_utf8()..].to_string())
31+}
32+
33+/// Replaces the file reference being typed at the end of `text` with `path`, followed by a space
34+/// to go on typing. Returns `text` unchanged when no reference is being typed.
35+///
36+/// ```
37+/// use synedrion_domain::file_reference::complete_file_reference;
38+///
39+/// assert_eq!(
40+/// complete_file_reference("look at $ma", "src/main.rs"),
41+/// "look at src/main.rs "
42+/// );
43+/// ```
44+pub fn complete_file_reference(text: &str, path: &str) -> String {
45+ match reference_start(text) {
46+ Some(mark) => format!("{}{path} ", &text[..mark]),
47+ None => text.to_string(),
48+ }
49+}
50+
51+/// The byte position of the `$` that starts the reference being typed at the end of `text`.
52+fn reference_start(text: &str) -> Option<usize> {
53+ let mark = text.rfind(FILE_REFERENCE_MARK)?;
54+ let query = &text[mark + FILE_REFERENCE_MARK.len_utf8()..];
55+ if query.contains(char::is_whitespace) {
56+ return None;
57+ }
58+ let before = text[..mark].chars().next_back();
59+ let glued_to_a_word =
60+ before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == FILE_REFERENCE_MARK);
61+ (!glued_to_a_word).then_some(mark)
62+}
63+
64+#[cfg(test)]
65+mod tests {
66+ use super::*;
67+
68+ #[test]
69+ fn a_reference_being_typed_exposes_what_follows_the_mark() {
70+ assert_eq!(trailing_file_query("$"), Some(String::new()));
71+ assert_eq!(trailing_file_query("$ma"), Some("ma".to_string()));
72+ assert_eq!(
73+ trailing_file_query("look at $src/ma"),
74+ Some("src/ma".to_string())
75+ );
76+ }
77+
78+ #[test]
79+ fn a_reference_in_the_middle_of_a_sentence_is_found_while_it_is_the_last_thing_typed() {
80+ assert_eq!(
81+ trailing_file_query("compare these two: a.rs and $b"),
82+ Some("b".to_string())
83+ );
84+ }
85+
86+ #[test]
87+ fn a_reference_followed_by_a_space_is_complete() {
88+ assert_eq!(trailing_file_query("look at $main.rs "), None);
89+ assert_eq!(trailing_file_query("look at $main.rs and"), None);
90+ }
91+
92+ #[test]
93+ fn a_mark_glued_to_a_word_is_not_a_reference() {
94+ assert_eq!(trailing_file_query("it costs US$5"), None);
95+ assert_eq!(trailing_file_query("a_$b"), None);
96+ assert_eq!(trailing_file_query("$$"), None);
97+ }
98+
99+ #[test]
100+ fn a_mark_after_punctuation_is_a_reference() {
101+ assert_eq!(trailing_file_query("(see $ma"), Some("ma".to_string()));
102+ assert_eq!(trailing_file_query("(see:$ma"), Some("ma".to_string()));
103+ }
104+
105+ #[test]
106+ fn text_without_a_mark_is_no_reference() {
107+ assert_eq!(trailing_file_query(""), None);
108+ assert_eq!(trailing_file_query("hello"), None);
109+ }
110+
111+ #[test]
112+ fn only_the_last_mark_counts() {
113+ assert_eq!(
114+ trailing_file_query("$one and $two"),
115+ Some("two".to_string())
116+ );
117+ assert_eq!(trailing_file_query("$one and two"), None);
118+ }
119+
120+ #[test]
121+ fn completing_puts_the_path_where_the_reference_was_and_a_space_after() {
122+ assert_eq!(
123+ complete_file_reference("look at $ma", "src/main.rs"),
124+ "look at src/main.rs "
125+ );
126+ assert_eq!(complete_file_reference("$", "a.txt"), "a.txt ");
127+ assert_eq!(
128+ complete_file_reference("$one and $tw", "two.rs"),
129+ "$one and two.rs "
130+ );
131+ }
132+
133+ #[test]
134+ fn completing_leaves_other_text_alone() {
135+ assert_eq!(complete_file_reference("hello", "a.txt"), "hello");
136+ assert_eq!(
137+ complete_file_reference("see $a.rs now", "b.rs"),
138+ "see $a.rs now"
139+ );
140+ }
141+
142+ #[test]
143+ fn text_with_non_ascii_characters_does_not_break_the_scan() {
144+ assert_eq!(
145+ trailing_file_query("regarde é$ma"),
146+ None,
147+ "an accented letter before the mark glues it to a word"
148+ );
149+ assert_eq!(trailing_file_query("regarde $né"), Some("né".to_string()));
150+ assert_eq!(complete_file_reference("café $", "é.rs"), "café é.rs ");
151+ }
152+}
new file mode 100644
@@ -0,0 +1,152 @@
1+//! Naming a file in the middle of a sentence: `look at $main.rs and fix it`.
2+//!
3+//! `@` names an agent and `/` starts a command, so `$` names a file. While the text ends with `$`
4+//! and the beginning of a name, the application lists the files that match, and picking one puts
5+//! its path in the sentence. Everything here is a pure function of the text.
6+
7+/// The character that starts a file reference.
8+///
9+/// ```
10+/// assert_eq!(synedrion_domain::file_reference::FILE_REFERENCE_MARK, '$');
11+/// ```
12+pub const FILE_REFERENCE_MARK: char = '$';
13+
14+/// The words typed after a `$` at the very end of `text`: what to search the files for. `Some("")`
15+/// right after a lone `$`. `None` when the text does not end in a file reference being typed.
16+///
17+/// The `$` must not be glued to the end of a word (`US$5` is not a reference), and the query ends
18+/// at the first space, so a reference that was followed by a space is complete.
19+///
20+/// ```
21+/// use synedrion_domain::file_reference::trailing_file_query;
22+///
23+/// assert_eq!(trailing_file_query("look at $main"), Some("main".to_string()));
24+/// assert_eq!(trailing_file_query("look at $"), Some(String::new()));
25+/// assert_eq!(trailing_file_query("look at $main.rs and"), None);
26+/// assert_eq!(trailing_file_query("it costs US$5"), None);
27+/// ```
28+pub fn trailing_file_query(text: &str) -> Option<String> {
29+ let mark = reference_start(text)?;
30+ Some(text[mark + FILE_REFERENCE_MARK.len_utf8()..].to_string())
31+}
32+
33+/// Replaces the file reference being typed at the end of `text` with `path`, followed by a space
34+/// to go on typing. Returns `text` unchanged when no reference is being typed.
35+///
36+/// ```
37+/// use synedrion_domain::file_reference::complete_file_reference;
38+///
39+/// assert_eq!(
40+/// complete_file_reference("look at $ma", "src/main.rs"),
41+/// "look at src/main.rs "
42+/// );
43+/// ```
44+pub fn complete_file_reference(text: &str, path: &str) -> String {
45+ match reference_start(text) {
46+ Some(mark) => format!("{}{path} ", &text[..mark]),
47+ None => text.to_string(),
48+ }
49+}
50+
51+/// The byte position of the `$` that starts the reference being typed at the end of `text`.
52+fn reference_start(text: &str) -> Option<usize> {
53+ let mark = text.rfind(FILE_REFERENCE_MARK)?;
54+ let query = &text[mark + FILE_REFERENCE_MARK.len_utf8()..];
55+ if query.contains(char::is_whitespace) {
56+ return None;
57+ }
58+ let before = text[..mark].chars().next_back();
59+ let glued_to_a_word =
60+ before.is_some_and(|c| c.is_alphanumeric() || c == '_' || c == FILE_REFERENCE_MARK);
61+ (!glued_to_a_word).then_some(mark)
62+}
63+
64+#[cfg(test)]
65+mod tests {
66+ use super::*;
67+
68+ #[test]
69+ fn a_reference_being_typed_exposes_what_follows_the_mark() {
70+ assert_eq!(trailing_file_query("$"), Some(String::new()));
71+ assert_eq!(trailing_file_query("$ma"), Some("ma".to_string()));
72+ assert_eq!(
73+ trailing_file_query("look at $src/ma"),
74+ Some("src/ma".to_string())
75+ );
76+ }
77+
78+ #[test]
79+ fn a_reference_in_the_middle_of_a_sentence_is_found_while_it_is_the_last_thing_typed() {
80+ assert_eq!(
81+ trailing_file_query("compare these two: a.rs and $b"),
82+ Some("b".to_string())
83+ );
84+ }
85+
86+ #[test]
87+ fn a_reference_followed_by_a_space_is_complete() {
88+ assert_eq!(trailing_file_query("look at $main.rs "), None);
89+ assert_eq!(trailing_file_query("look at $main.rs and"), None);
90+ }
91+
92+ #[test]
93+ fn a_mark_glued_to_a_word_is_not_a_reference() {
94+ assert_eq!(trailing_file_query("it costs US$5"), None);
95+ assert_eq!(trailing_file_query("a_$b"), None);
96+ assert_eq!(trailing_file_query("$$"), None);
97+ }
98+
99+ #[test]
100+ fn a_mark_after_punctuation_is_a_reference() {
101+ assert_eq!(trailing_file_query("(see $ma"), Some("ma".to_string()));
102+ assert_eq!(trailing_file_query("(see:$ma"), Some("ma".to_string()));
103+ }
104+
105+ #[test]
106+ fn text_without_a_mark_is_no_reference() {
107+ assert_eq!(trailing_file_query(""), None);
108+ assert_eq!(trailing_file_query("hello"), None);
109+ }
110+
111+ #[test]
112+ fn only_the_last_mark_counts() {
113+ assert_eq!(
114+ trailing_file_query("$one and $two"),
115+ Some("two".to_string())
116+ );
117+ assert_eq!(trailing_file_query("$one and two"), None);
118+ }
119+
120+ #[test]
121+ fn completing_puts_the_path_where_the_reference_was_and_a_space_after() {
122+ assert_eq!(
123+ complete_file_reference("look at $ma", "src/main.rs"),
124+ "look at src/main.rs "
125+ );
126+ assert_eq!(complete_file_reference("$", "a.txt"), "a.txt ");
127+ assert_eq!(
128+ complete_file_reference("$one and $tw", "two.rs"),
129+ "$one and two.rs "
130+ );
131+ }
132+
133+ #[test]
134+ fn completing_leaves_other_text_alone() {
135+ assert_eq!(complete_file_reference("hello", "a.txt"), "hello");
136+ assert_eq!(
137+ complete_file_reference("see $a.rs now", "b.rs"),
138+ "see $a.rs now"
139+ );
140+ }
141+
142+ #[test]
143+ fn text_with_non_ascii_characters_does_not_break_the_scan() {
144+ assert_eq!(
145+ trailing_file_query("regarde é$ma"),
146+ None,
147+ "an accented letter before the mark glues it to a word"
148+ );
149+ assert_eq!(trailing_file_query("regarde $né"), Some("né".to_string()));
150+ assert_eq!(complete_file_reference("café $", "é.rs"), "café é.rs ");
151+ }
152+}
modified crates/domain/src/lib.rs +4 -0
@@ -15,9 +15,13 @@
1515 pub mod agent;
1616 pub mod channel;
1717 pub mod command;
18+pub mod context;
1819 pub mod error;
20+pub mod file_reference;
1921 pub mod mention;
2022 pub mod message;
2123 pub mod repository;
24+pub mod settings;
2225 pub mod time;
26+pub mod trace;
2327 pub mod user;
@@ -15,9 +15,13 @@
15 pub mod agent;15 pub mod agent;
16 pub mod channel;16 pub mod channel;
17 pub mod command;17 pub mod command;
18+pub mod context;
18 pub mod error;19 pub mod error;
20+pub mod file_reference;
19 pub mod mention;21 pub mod mention;
20 pub mod message;22 pub mod message;
21 pub mod repository;23 pub mod repository;
24+pub mod settings;
22 pub mod time;25 pub mod time;
26+pub mod trace;
23 pub mod user;27 pub mod user;
modified crates/domain/src/mention.rs +135 -3
@@ -12,7 +12,7 @@ use crate::message::{Author, Message};
1212 /// use synedrion_domain::mention::resolve_mentions;
1313 ///
1414 /// let declared = [AgentName::new("mini-me").unwrap()];
15-/// let resolved = resolve_mentions("@mini-me and @ghost, hello", &declared);
15+/// let resolved = resolve_mentions("hello @mini-me and @ghost", &declared);
1616 /// assert_eq!(resolved.agents.len(), 1);
1717 /// assert_eq!(resolved.unknown, vec!["ghost".to_string()]);
1818 /// ```
@@ -153,12 +153,27 @@ pub fn follow_up_recipients(messages: &[Message], declared: &[AgentName]) -> Vec
153153 .unwrap_or_default()
154154 }
155155
156-/// Sorts the mentions of `text` into declared agents and unknown names.
156+/// Sorts the mentions that address someone in `text` into declared agents and unknown names.
157+///
158+/// A message that starts with mentions addresses those, and only those: `@bob say hi to @mouse`
159+/// is for `bob`, and `@mouse` is only talked about. A message that does not start with a mention
160+/// addresses every agent it mentions: `say hi to @bob and @mouse` is for both. Mentions at the
161+/// start may be separated by spaces and commas: `@bob, @mouse discuss it`.
162+///
163+/// ```
164+/// use synedrion_domain::agent::AgentName;
165+/// use synedrion_domain::mention::resolve_mentions;
166+///
167+/// let declared = [AgentName::new("bob").unwrap(), AgentName::new("mouse").unwrap()];
168+/// assert_eq!(resolve_mentions("@bob say hi to @mouse", &declared).agents.len(), 1);
169+/// assert_eq!(resolve_mentions("@bob @mouse discuss it", &declared).agents.len(), 2);
170+/// assert_eq!(resolve_mentions("say hi to @bob and @mouse", &declared).agents.len(), 2);
171+/// ```
157172 pub fn resolve_mentions(text: &str, declared: &[AgentName]) -> ResolvedMentions {
158173 let mut agents = Vec::new();
159174 let mut unknown = Vec::new();
160175
161- for mention in extract_mentions(text) {
176+ for mention in addressed_mentions(text) {
162177 match declared.iter().find(|agent| agent.matches(&mention)) {
163178 Some(agent) => agents.push(agent.clone()),
164179 None => unknown.push(mention),
@@ -167,6 +182,43 @@ pub fn resolve_mentions(text: &str, declared: &[AgentName]) -> ResolvedMentions
167182 ResolvedMentions { agents, unknown }
168183 }
169184
185+/// The mentions that address someone: those the text starts with, or, when it does not start
186+/// with a mention, all of them.
187+fn addressed_mentions(text: &str) -> Vec<String> {
188+ let leading = leading_mentions(text);
189+ if leading.is_empty() {
190+ extract_mentions(text)
191+ } else {
192+ leading
193+ }
194+}
195+
196+/// The mentions the text starts with, separated only by spaces and commas, without duplicates.
197+fn leading_mentions(text: &str) -> Vec<String> {
198+ let characters: Vec<char> = text.chars().collect();
199+ let mut mentions: Vec<String> = Vec::new();
200+ let mut index = 0;
201+
202+ loop {
203+ while index < characters.len()
204+ && (characters[index].is_whitespace() || characters[index] == ',')
205+ {
206+ index += 1;
207+ }
208+ if index >= characters.len() || characters[index] != '@' {
209+ return mentions;
210+ }
211+ let name = read_name(&characters, index + 1);
212+ if name.is_empty() {
213+ return mentions;
214+ }
215+ index += 1 + name.chars().count();
216+ if !already_listed(&mentions, &name) {
217+ mentions.push(name);
218+ }
219+ }
220+}
221+
170222 /// True when the `@` at `at` is not glued to the end of a word (like in an e-mail address).
171223 fn starts_a_word(characters: &[char], at: usize) -> bool {
172224 match at.checked_sub(1).map(|previous| characters[previous]) {
@@ -201,6 +253,86 @@ mod tests {
201253 .collect()
202254 }
203255
256+ fn addressed(text: &str, declared: &[&str]) -> Vec<String> {
257+ resolve_mentions(text, &agents(declared))
258+ .agents
259+ .iter()
260+ .map(|agent| agent.to_string())
261+ .collect()
262+ }
263+
264+ #[test]
265+ fn a_message_that_starts_with_a_mention_addresses_only_the_leading_ones() {
266+ assert_eq!(
267+ addressed("@bob say hi to @mouse", &["bob", "mouse"]),
268+ vec!["bob"]
269+ );
270+ }
271+
272+ #[test]
273+ fn several_leading_mentions_all_address() {
274+ assert_eq!(
275+ addressed("@bob @mouse discuss it", &["bob", "mouse"]),
276+ vec!["bob", "mouse"]
277+ );
278+ assert_eq!(
279+ addressed("@bob, @mouse discuss it", &["bob", "mouse"]),
280+ vec!["bob", "mouse"]
281+ );
282+ assert_eq!(
283+ addressed(" @bob , @mouse\n discuss", &["bob", "mouse"]),
284+ vec!["bob", "mouse"]
285+ );
286+ }
287+
288+ #[test]
289+ fn a_message_that_does_not_start_with_a_mention_addresses_all_of_them() {
290+ assert_eq!(
291+ addressed("say hi to @bob and @mouse", &["bob", "mouse"]),
292+ vec!["bob", "mouse"]
293+ );
294+ assert_eq!(addressed("hey @bob", &["bob"]), vec!["bob"]);
295+ }
296+
297+ #[test]
298+ fn a_mention_after_text_following_the_leading_ones_is_only_talked_about() {
299+ assert_eq!(
300+ addressed("@bob and @mouse: hello @amy", &["bob", "mouse", "amy"]),
301+ vec!["bob"],
302+ "the word `and` ends the leading mentions"
303+ );
304+ }
305+
306+ #[test]
307+ fn a_leading_mention_of_an_unknown_name_is_reported_but_a_later_one_is_not() {
308+ let resolved = resolve_mentions("@ghost greet @bob", &agents(&["bob"]));
309+ assert!(resolved.agents.is_empty());
310+ assert_eq!(resolved.unknown, vec!["ghost"]);
311+
312+ let resolved = resolve_mentions("@bob greet @ghost", &agents(&["bob"]));
313+ assert_eq!(resolved.agents, agents(&["bob"]));
314+ assert!(resolved.unknown.is_empty());
315+ }
316+
317+ #[test]
318+ fn a_repeated_leading_mention_counts_once() {
319+ assert_eq!(addressed("@bob @BOB hi", &["bob"]), vec!["bob"]);
320+ }
321+
322+ #[test]
323+ fn a_leading_lone_at_sign_addresses_nobody_and_the_rest_counts_as_usual() {
324+ assert_eq!(addressed("@ hello @bob", &["bob"]), vec!["bob"]);
325+ }
326+
327+ #[test]
328+ fn who_a_plain_message_goes_to_follows_the_leading_mentions_of_the_last_one() {
329+ let messages = vec![said(Author::User, "@bob ask @mouse")];
330+ assert_eq!(
331+ follow_up_recipients(&messages, &agents(&["bob", "mouse"])),
332+ agents(&["bob"])
333+ );
334+ }
335+
204336 #[test]
205337 fn mention_at_the_start_of_the_text_is_found() {
206338 assert_eq!(extract_mentions("@bob hello"), vec!["bob"]);
@@ -12,7 +12,7 @@ use crate::message::{Author, Message};
12 /// use synedrion_domain::mention::resolve_mentions;12 /// use synedrion_domain::mention::resolve_mentions;
13 ///13 ///
14 /// let declared = [AgentName::new("mini-me").unwrap()];14 /// let declared = [AgentName::new("mini-me").unwrap()];
15-/// let resolved = resolve_mentions("@mini-me and @ghost, hello", &declared);15+/// let resolved = resolve_mentions("hello @mini-me and @ghost", &declared);
16 /// assert_eq!(resolved.agents.len(), 1);16 /// assert_eq!(resolved.agents.len(), 1);
17 /// assert_eq!(resolved.unknown, vec!["ghost".to_string()]);17 /// assert_eq!(resolved.unknown, vec!["ghost".to_string()]);
18 /// ```18 /// ```
@@ -153,12 +153,27 @@ pub fn follow_up_recipients(messages: &[Message], declared: &[AgentName]) -> Vec
153 .unwrap_or_default()153 .unwrap_or_default()
154 }154 }
155 155
156-/// Sorts the mentions of `text` into declared agents and unknown names.156+/// Sorts the mentions that address someone in `text` into declared agents and unknown names.
157+///
158+/// A message that starts with mentions addresses those, and only those: `@bob say hi to @mouse`
159+/// is for `bob`, and `@mouse` is only talked about. A message that does not start with a mention
160+/// addresses every agent it mentions: `say hi to @bob and @mouse` is for both. Mentions at the
161+/// start may be separated by spaces and commas: `@bob, @mouse discuss it`.
162+///
163+/// ```
164+/// use synedrion_domain::agent::AgentName;
165+/// use synedrion_domain::mention::resolve_mentions;
166+///
167+/// let declared = [AgentName::new("bob").unwrap(), AgentName::new("mouse").unwrap()];
168+/// assert_eq!(resolve_mentions("@bob say hi to @mouse", &declared).agents.len(), 1);
169+/// assert_eq!(resolve_mentions("@bob @mouse discuss it", &declared).agents.len(), 2);
170+/// assert_eq!(resolve_mentions("say hi to @bob and @mouse", &declared).agents.len(), 2);
171+/// ```
157 pub fn resolve_mentions(text: &str, declared: &[AgentName]) -> ResolvedMentions {172 pub fn resolve_mentions(text: &str, declared: &[AgentName]) -> ResolvedMentions {
158 let mut agents = Vec::new();173 let mut agents = Vec::new();
159 let mut unknown = Vec::new();174 let mut unknown = Vec::new();
160 175
161- for mention in extract_mentions(text) {176+ for mention in addressed_mentions(text) {
162 match declared.iter().find(|agent| agent.matches(&mention)) {177 match declared.iter().find(|agent| agent.matches(&mention)) {
163 Some(agent) => agents.push(agent.clone()),178 Some(agent) => agents.push(agent.clone()),
164 None => unknown.push(mention),179 None => unknown.push(mention),
@@ -167,6 +182,43 @@ pub fn resolve_mentions(text: &str, declared: &[AgentName]) -> ResolvedMentions
167 ResolvedMentions { agents, unknown }182 ResolvedMentions { agents, unknown }
168 }183 }
169 184
185+/// The mentions that address someone: those the text starts with, or, when it does not start
186+/// with a mention, all of them.
187+fn addressed_mentions(text: &str) -> Vec<String> {
188+ let leading = leading_mentions(text);
189+ if leading.is_empty() {
190+ extract_mentions(text)
191+ } else {
192+ leading
193+ }
194+}
195+
196+/// The mentions the text starts with, separated only by spaces and commas, without duplicates.
197+fn leading_mentions(text: &str) -> Vec<String> {
198+ let characters: Vec<char> = text.chars().collect();
199+ let mut mentions: Vec<String> = Vec::new();
200+ let mut index = 0;
201+
202+ loop {
203+ while index < characters.len()
204+ && (characters[index].is_whitespace() || characters[index] == ',')
205+ {
206+ index += 1;
207+ }
208+ if index >= characters.len() || characters[index] != '@' {
209+ return mentions;
210+ }
211+ let name = read_name(&characters, index + 1);
212+ if name.is_empty() {
213+ return mentions;
214+ }
215+ index += 1 + name.chars().count();
216+ if !already_listed(&mentions, &name) {
217+ mentions.push(name);
218+ }
219+ }
220+}
221+
170 /// True when the `@` at `at` is not glued to the end of a word (like in an e-mail address).222 /// True when the `@` at `at` is not glued to the end of a word (like in an e-mail address).
171 fn starts_a_word(characters: &[char], at: usize) -> bool {223 fn starts_a_word(characters: &[char], at: usize) -> bool {
172 match at.checked_sub(1).map(|previous| characters[previous]) {224 match at.checked_sub(1).map(|previous| characters[previous]) {
@@ -201,6 +253,86 @@ mod tests {
201 .collect()253 .collect()
202 }254 }
203 255
256+ fn addressed(text: &str, declared: &[&str]) -> Vec<String> {
257+ resolve_mentions(text, &agents(declared))
258+ .agents
259+ .iter()
260+ .map(|agent| agent.to_string())
261+ .collect()
262+ }
263+
264+ #[test]
265+ fn a_message_that_starts_with_a_mention_addresses_only_the_leading_ones() {
266+ assert_eq!(
267+ addressed("@bob say hi to @mouse", &["bob", "mouse"]),
268+ vec!["bob"]
269+ );
270+ }
271+
272+ #[test]
273+ fn several_leading_mentions_all_address() {
274+ assert_eq!(
275+ addressed("@bob @mouse discuss it", &["bob", "mouse"]),
276+ vec!["bob", "mouse"]
277+ );
278+ assert_eq!(
279+ addressed("@bob, @mouse discuss it", &["bob", "mouse"]),
280+ vec!["bob", "mouse"]
281+ );
282+ assert_eq!(
283+ addressed(" @bob , @mouse\n discuss", &["bob", "mouse"]),
284+ vec!["bob", "mouse"]
285+ );
286+ }
287+
288+ #[test]
289+ fn a_message_that_does_not_start_with_a_mention_addresses_all_of_them() {
290+ assert_eq!(
291+ addressed("say hi to @bob and @mouse", &["bob", "mouse"]),
292+ vec!["bob", "mouse"]
293+ );
294+ assert_eq!(addressed("hey @bob", &["bob"]), vec!["bob"]);
295+ }
296+
297+ #[test]
298+ fn a_mention_after_text_following_the_leading_ones_is_only_talked_about() {
299+ assert_eq!(
300+ addressed("@bob and @mouse: hello @amy", &["bob", "mouse", "amy"]),
301+ vec!["bob"],
302+ "the word `and` ends the leading mentions"
303+ );
304+ }
305+
306+ #[test]
307+ fn a_leading_mention_of_an_unknown_name_is_reported_but_a_later_one_is_not() {
308+ let resolved = resolve_mentions("@ghost greet @bob", &agents(&["bob"]));
309+ assert!(resolved.agents.is_empty());
310+ assert_eq!(resolved.unknown, vec!["ghost"]);
311+
312+ let resolved = resolve_mentions("@bob greet @ghost", &agents(&["bob"]));
313+ assert_eq!(resolved.agents, agents(&["bob"]));
314+ assert!(resolved.unknown.is_empty());
315+ }
316+
317+ #[test]
318+ fn a_repeated_leading_mention_counts_once() {
319+ assert_eq!(addressed("@bob @BOB hi", &["bob"]), vec!["bob"]);
320+ }
321+
322+ #[test]
323+ fn a_leading_lone_at_sign_addresses_nobody_and_the_rest_counts_as_usual() {
324+ assert_eq!(addressed("@ hello @bob", &["bob"]), vec!["bob"]);
325+ }
326+
327+ #[test]
328+ fn who_a_plain_message_goes_to_follows_the_leading_mentions_of_the_last_one() {
329+ let messages = vec![said(Author::User, "@bob ask @mouse")];
330+ assert_eq!(
331+ follow_up_recipients(&messages, &agents(&["bob", "mouse"])),
332+ agents(&["bob"])
333+ );
334+ }
335+
204 #[test]336 #[test]
205 fn mention_at_the_start_of_the_text_is_found() {337 fn mention_at_the_start_of_the_text_is_found() {
206 assert_eq!(extract_mentions("@bob hello"), vec!["bob"]);338 assert_eq!(extract_mentions("@bob hello"), vec!["bob"]);
modified crates/domain/src/message.rs +2 -0
@@ -25,6 +25,8 @@ pub enum Author {
2525 Agent(AgentName),
2626 /// The application itself (for example "agent crashed").
2727 System,
28+ /// What an agent did besides writing: a tool call or a plan, as a [`Trace`](crate::trace::Trace).
29+ Trace(AgentName),
2830 }
2931
3032 impl Author {
@@ -25,6 +25,8 @@ pub enum Author {
25 Agent(AgentName),25 Agent(AgentName),
26 /// The application itself (for example "agent crashed").26 /// The application itself (for example "agent crashed").
27 System,27 System,
28+ /// What an agent did besides writing: a tool call or a plan, as a [`Trace`](crate::trace::Trace).
29+ Trace(AgentName),
28 }30 }
29 31
30 impl Author {32 impl Author {
modified crates/domain/src/repository.rs +7 -0
@@ -8,6 +8,7 @@ use std::fmt;
88 use crate::agent::{AgentDeclaration, AgentName};
99 use crate::channel::{Channel, ChannelId, ChannelName, DEFAULT_CHANNEL_NAME};
1010 use crate::message::{Message, MessageId, NewMessage};
11+use crate::settings::ChatSettings;
1112 use crate::user::UserProfile;
1213
1314 /// Why a [`Repository`] call failed.
@@ -89,6 +90,12 @@ pub trait Repository: Send + Sync {
8990 /// Removes an agent's declaration. Its past messages stay.
9091 fn delete_agent(&self, name: &AgentName) -> RepositoryResult<()>;
9192
93+ /// The settings the user chose, or the defaults before they chose any.
94+ fn load_settings(&self) -> RepositoryResult<ChatSettings>;
95+
96+ /// Stores the settings, replacing the ones stored before.
97+ fn save_settings(&self, settings: &ChatSettings) -> RepositoryResult<()>;
98+
9299 /// Creates the default channel when there is no channel at all, which is the case the
93100 /// first time the application starts. Does nothing otherwise.
94101 fn ensure_default_channel(&self) -> RepositoryResult<()> {
@@ -8,6 +8,7 @@ use std::fmt;
8 use crate::agent::{AgentDeclaration, AgentName};8 use crate::agent::{AgentDeclaration, AgentName};
9 use crate::channel::{Channel, ChannelId, ChannelName, DEFAULT_CHANNEL_NAME};9 use crate::channel::{Channel, ChannelId, ChannelName, DEFAULT_CHANNEL_NAME};
10 use crate::message::{Message, MessageId, NewMessage};10 use crate::message::{Message, MessageId, NewMessage};
11+use crate::settings::ChatSettings;
11 use crate::user::UserProfile;12 use crate::user::UserProfile;
12 13
13 /// Why a [`Repository`] call failed.14 /// Why a [`Repository`] call failed.
@@ -89,6 +90,12 @@ pub trait Repository: Send + Sync {
89 /// Removes an agent's declaration. Its past messages stay.90 /// Removes an agent's declaration. Its past messages stay.
90 fn delete_agent(&self, name: &AgentName) -> RepositoryResult<()>;91 fn delete_agent(&self, name: &AgentName) -> RepositoryResult<()>;
91 92
93+ /// The settings the user chose, or the defaults before they chose any.
94+ fn load_settings(&self) -> RepositoryResult<ChatSettings>;
95+
96+ /// Stores the settings, replacing the ones stored before.
97+ fn save_settings(&self, settings: &ChatSettings) -> RepositoryResult<()>;
98+
92 /// Creates the default channel when there is no channel at all, which is the case the99 /// Creates the default channel when there is no channel at all, which is the case the
93 /// first time the application starts. Does nothing otherwise.100 /// first time the application starts. Does nothing otherwise.
94 fn ensure_default_channel(&self) -> RepositoryResult<()> {101 fn ensure_default_channel(&self) -> RepositoryResult<()> {
added crates/domain/src/settings.rs +190 -0
new file mode 100644
@@ -0,0 +1,190 @@
1+//! The few settings the user can change, with the limits that keep them reasonable.
2+
3+use std::fmt;
4+
5+/// The most earlier messages an agent can be given as context.
6+pub const MAX_CONTEXT_MESSAGES: usize = 100;
7+
8+/// The longest chain of agents calling agents that can be allowed.
9+pub const MAX_CHAIN_DEPTH: usize = 10;
10+
11+/// How many earlier messages are given to an agent unless the user chose otherwise.
12+pub const DEFAULT_CONTEXT_MESSAGES: usize = 20;
13+
14+/// How many agents may call one another in a row unless the user chose otherwise. Low on purpose:
15+/// every hop costs a turn of a model, and a loop between two agents never ends by itself.
16+pub const DEFAULT_CHAIN_DEPTH: usize = 3;
17+
18+/// The settings of the conversation.
19+///
20+/// ```
21+/// use synedrion_domain::settings::ChatSettings;
22+///
23+/// let settings = ChatSettings::parse("30", "2").unwrap();
24+/// assert_eq!((settings.context_messages, settings.chain_depth), (30, 2));
25+/// assert_eq!(ChatSettings::default().chain_depth, 3);
26+/// ```
27+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28+pub struct ChatSettings {
29+ /// How many messages, at most, an agent is told about besides the one that calls it: those
30+ /// sent since its last turn. `0` gives it the message alone.
31+ pub context_messages: usize,
32+ /// How many times in a row an agent's answer may call another agent. `0` turns it off: agents
33+ /// never call one another. A call to `@bob` in the answer of a turn that the user started is
34+ /// the first of these.
35+ pub chain_depth: usize,
36+}
37+
38+impl Default for ChatSettings {
39+ fn default() -> Self {
40+ Self {
41+ context_messages: DEFAULT_CONTEXT_MESSAGES,
42+ chain_depth: DEFAULT_CHAIN_DEPTH,
43+ }
44+ }
45+}
46+
47+/// Which setting is wrong, and why.
48+#[derive(Debug, Clone, PartialEq, Eq)]
49+pub enum SettingsError {
50+ /// The text is not a whole number.
51+ NotANumber { setting: &'static str, text: String },
52+ /// The number is above what is allowed.
53+ TooBig { setting: &'static str, max: usize },
54+}
55+
56+impl fmt::Display for SettingsError {
57+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
58+ match self {
59+ Self::NotANumber { setting, text } => {
60+ write!(formatter, "{setting} must be a whole number, not {text:?}")
61+ }
62+ Self::TooBig { setting, max } => {
63+ write!(formatter, "{setting} must be at most {max}")
64+ }
65+ }
66+ }
67+}
68+
69+impl std::error::Error for SettingsError {}
70+
71+impl ChatSettings {
72+ /// Reads what the user typed in the two fields.
73+ ///
74+ /// ```
75+ /// use synedrion_domain::settings::{ChatSettings, SettingsError};
76+ ///
77+ /// assert!(matches!(
78+ /// ChatSettings::parse("many", "3"),
79+ /// Err(SettingsError::NotANumber { .. })
80+ /// ));
81+ /// ```
82+ pub fn parse(context_messages: &str, chain_depth: &str) -> Result<Self, SettingsError> {
83+ Ok(Self {
84+ context_messages: number(
85+ "Messages of context",
86+ context_messages,
87+ MAX_CONTEXT_MESSAGES,
88+ )?,
89+ chain_depth: number("Chain depth", chain_depth, MAX_CHAIN_DEPTH)?,
90+ })
91+ }
92+}
93+
94+fn number(setting: &'static str, text: &str, max: usize) -> Result<usize, SettingsError> {
95+ let value: usize = text.trim().parse().map_err(|_| SettingsError::NotANumber {
96+ setting,
97+ text: text.trim().to_string(),
98+ })?;
99+ if value > max {
100+ return Err(SettingsError::TooBig { setting, max });
101+ }
102+ Ok(value)
103+}
104+
105+#[cfg(test)]
106+mod tests {
107+ use super::*;
108+
109+ #[test]
110+ fn the_defaults_are_inside_the_limits() {
111+ let settings = ChatSettings::default();
112+ assert!(settings.context_messages <= MAX_CONTEXT_MESSAGES);
113+ assert!(settings.chain_depth <= MAX_CHAIN_DEPTH);
114+ }
115+
116+ #[test]
117+ fn numbers_are_read_with_their_surrounding_spaces_ignored() {
118+ let settings = ChatSettings::parse(" 5 ", "\t1").unwrap();
119+ assert_eq!((settings.context_messages, settings.chain_depth), (5, 1));
120+ }
121+
122+ #[test]
123+ fn zero_is_allowed_for_both() {
124+ let settings = ChatSettings::parse("0", "0").unwrap();
125+ assert_eq!((settings.context_messages, settings.chain_depth), (0, 0));
126+ }
127+
128+ #[test]
129+ fn the_limits_themselves_are_allowed_and_one_more_is_not() {
130+ let at_limit = ChatSettings::parse(
131+ &MAX_CONTEXT_MESSAGES.to_string(),
132+ &MAX_CHAIN_DEPTH.to_string(),
133+ );
134+ assert!(at_limit.is_ok());
135+ assert_eq!(
136+ ChatSettings::parse(&(MAX_CONTEXT_MESSAGES + 1).to_string(), "1").unwrap_err(),
137+ SettingsError::TooBig {
138+ setting: "Messages of context",
139+ max: MAX_CONTEXT_MESSAGES
140+ }
141+ );
142+ assert_eq!(
143+ ChatSettings::parse("1", &(MAX_CHAIN_DEPTH + 1).to_string()).unwrap_err(),
144+ SettingsError::TooBig {
145+ setting: "Chain depth",
146+ max: MAX_CHAIN_DEPTH
147+ }
148+ );
149+ }
150+
151+ #[test]
152+ fn text_that_is_not_a_whole_number_is_refused_and_named() {
153+ for bad in ["", "abc", "-1", "2.5"] {
154+ let error = ChatSettings::parse("1", bad).unwrap_err();
155+ assert!(
156+ matches!(
157+ &error,
158+ SettingsError::NotANumber {
159+ setting: "Chain depth",
160+ ..
161+ }
162+ ),
163+ "{bad:?}: {error:?}"
164+ );
165+ }
166+ }
167+
168+ #[test]
169+ fn the_first_wrong_field_is_the_one_reported() {
170+ let error = ChatSettings::parse("x", "y").unwrap_err();
171+ assert!(matches!(
172+ error,
173+ SettingsError::NotANumber {
174+ setting: "Messages of context",
175+ ..
176+ }
177+ ));
178+ }
179+
180+ #[test]
181+ fn errors_read_as_sentences_that_name_the_setting() {
182+ let error = ChatSettings::parse("1", "99").unwrap_err();
183+ assert_eq!(error.to_string(), "Chain depth must be at most 10");
184+ let error = ChatSettings::parse("a", "1").unwrap_err();
185+ assert_eq!(
186+ error.to_string(),
187+ "Messages of context must be a whole number, not \"a\""
188+ );
189+ }
190+}
new file mode 100644
@@ -0,0 +1,190 @@
1+//! The few settings the user can change, with the limits that keep them reasonable.
2+
3+use std::fmt;
4+
5+/// The most earlier messages an agent can be given as context.
6+pub const MAX_CONTEXT_MESSAGES: usize = 100;
7+
8+/// The longest chain of agents calling agents that can be allowed.
9+pub const MAX_CHAIN_DEPTH: usize = 10;
10+
11+/// How many earlier messages are given to an agent unless the user chose otherwise.
12+pub const DEFAULT_CONTEXT_MESSAGES: usize = 20;
13+
14+/// How many agents may call one another in a row unless the user chose otherwise. Low on purpose:
15+/// every hop costs a turn of a model, and a loop between two agents never ends by itself.
16+pub const DEFAULT_CHAIN_DEPTH: usize = 3;
17+
18+/// The settings of the conversation.
19+///
20+/// ```
21+/// use synedrion_domain::settings::ChatSettings;
22+///
23+/// let settings = ChatSettings::parse("30", "2").unwrap();
24+/// assert_eq!((settings.context_messages, settings.chain_depth), (30, 2));
25+/// assert_eq!(ChatSettings::default().chain_depth, 3);
26+/// ```
27+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28+pub struct ChatSettings {
29+ /// How many messages, at most, an agent is told about besides the one that calls it: those
30+ /// sent since its last turn. `0` gives it the message alone.
31+ pub context_messages: usize,
32+ /// How many times in a row an agent's answer may call another agent. `0` turns it off: agents
33+ /// never call one another. A call to `@bob` in the answer of a turn that the user started is
34+ /// the first of these.
35+ pub chain_depth: usize,
36+}
37+
38+impl Default for ChatSettings {
39+ fn default() -> Self {
40+ Self {
41+ context_messages: DEFAULT_CONTEXT_MESSAGES,
42+ chain_depth: DEFAULT_CHAIN_DEPTH,
43+ }
44+ }
45+}
46+
47+/// Which setting is wrong, and why.
48+#[derive(Debug, Clone, PartialEq, Eq)]
49+pub enum SettingsError {
50+ /// The text is not a whole number.
51+ NotANumber { setting: &'static str, text: String },
52+ /// The number is above what is allowed.
53+ TooBig { setting: &'static str, max: usize },
54+}
55+
56+impl fmt::Display for SettingsError {
57+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
58+ match self {
59+ Self::NotANumber { setting, text } => {
60+ write!(formatter, "{setting} must be a whole number, not {text:?}")
61+ }
62+ Self::TooBig { setting, max } => {
63+ write!(formatter, "{setting} must be at most {max}")
64+ }
65+ }
66+ }
67+}
68+
69+impl std::error::Error for SettingsError {}
70+
71+impl ChatSettings {
72+ /// Reads what the user typed in the two fields.
73+ ///
74+ /// ```
75+ /// use synedrion_domain::settings::{ChatSettings, SettingsError};
76+ ///
77+ /// assert!(matches!(
78+ /// ChatSettings::parse("many", "3"),
79+ /// Err(SettingsError::NotANumber { .. })
80+ /// ));
81+ /// ```
82+ pub fn parse(context_messages: &str, chain_depth: &str) -> Result<Self, SettingsError> {
83+ Ok(Self {
84+ context_messages: number(
85+ "Messages of context",
86+ context_messages,
87+ MAX_CONTEXT_MESSAGES,
88+ )?,
89+ chain_depth: number("Chain depth", chain_depth, MAX_CHAIN_DEPTH)?,
90+ })
91+ }
92+}
93+
94+fn number(setting: &'static str, text: &str, max: usize) -> Result<usize, SettingsError> {
95+ let value: usize = text.trim().parse().map_err(|_| SettingsError::NotANumber {
96+ setting,
97+ text: text.trim().to_string(),
98+ })?;
99+ if value > max {
100+ return Err(SettingsError::TooBig { setting, max });
101+ }
102+ Ok(value)
103+}
104+
105+#[cfg(test)]
106+mod tests {
107+ use super::*;
108+
109+ #[test]
110+ fn the_defaults_are_inside_the_limits() {
111+ let settings = ChatSettings::default();
112+ assert!(settings.context_messages <= MAX_CONTEXT_MESSAGES);
113+ assert!(settings.chain_depth <= MAX_CHAIN_DEPTH);
114+ }
115+
116+ #[test]
117+ fn numbers_are_read_with_their_surrounding_spaces_ignored() {
118+ let settings = ChatSettings::parse(" 5 ", "\t1").unwrap();
119+ assert_eq!((settings.context_messages, settings.chain_depth), (5, 1));
120+ }
121+
122+ #[test]
123+ fn zero_is_allowed_for_both() {
124+ let settings = ChatSettings::parse("0", "0").unwrap();
125+ assert_eq!((settings.context_messages, settings.chain_depth), (0, 0));
126+ }
127+
128+ #[test]
129+ fn the_limits_themselves_are_allowed_and_one_more_is_not() {
130+ let at_limit = ChatSettings::parse(
131+ &MAX_CONTEXT_MESSAGES.to_string(),
132+ &MAX_CHAIN_DEPTH.to_string(),
133+ );
134+ assert!(at_limit.is_ok());
135+ assert_eq!(
136+ ChatSettings::parse(&(MAX_CONTEXT_MESSAGES + 1).to_string(), "1").unwrap_err(),
137+ SettingsError::TooBig {
138+ setting: "Messages of context",
139+ max: MAX_CONTEXT_MESSAGES
140+ }
141+ );
142+ assert_eq!(
143+ ChatSettings::parse("1", &(MAX_CHAIN_DEPTH + 1).to_string()).unwrap_err(),
144+ SettingsError::TooBig {
145+ setting: "Chain depth",
146+ max: MAX_CHAIN_DEPTH
147+ }
148+ );
149+ }
150+
151+ #[test]
152+ fn text_that_is_not_a_whole_number_is_refused_and_named() {
153+ for bad in ["", "abc", "-1", "2.5"] {
154+ let error = ChatSettings::parse("1", bad).unwrap_err();
155+ assert!(
156+ matches!(
157+ &error,
158+ SettingsError::NotANumber {
159+ setting: "Chain depth",
160+ ..
161+ }
162+ ),
163+ "{bad:?}: {error:?}"
164+ );
165+ }
166+ }
167+
168+ #[test]
169+ fn the_first_wrong_field_is_the_one_reported() {
170+ let error = ChatSettings::parse("x", "y").unwrap_err();
171+ assert!(matches!(
172+ error,
173+ SettingsError::NotANumber {
174+ setting: "Messages of context",
175+ ..
176+ }
177+ ));
178+ }
179+
180+ #[test]
181+ fn errors_read_as_sentences_that_name_the_setting() {
182+ let error = ChatSettings::parse("1", "99").unwrap_err();
183+ assert_eq!(error.to_string(), "Chain depth must be at most 10");
184+ let error = ChatSettings::parse("a", "1").unwrap_err();
185+ assert_eq!(
186+ error.to_string(),
187+ "Messages of context must be a whole number, not \"a\""
188+ );
189+ }
190+}
added crates/domain/src/trace.rs +405 -0
new file mode 100644
@@ -0,0 +1,405 @@
1+//! What an agent does besides writing text: the tools it calls and the plan it follows.
2+//!
3+//! These are kept in the channel next to the messages, so that the history shows how an answer
4+//! came about. A trace is stored as text in the content of a message written by
5+//! [`Author::Trace`](crate::message::Author::Trace): the first line says what kind of trace it is
6+//! and the lines after hold the details. The format is plain on purpose, so that it needs no
7+//! library and so that anything this code cannot read is still readable by a person.
8+
9+use std::fmt;
10+
11+/// How far a tool call or a step of a plan has got.
12+///
13+/// ```
14+/// use synedrion_domain::trace::Progress;
15+///
16+/// assert_eq!(Progress::Completed.label(), "done");
17+/// assert_eq!(Progress::from_word("in_progress"), Some(Progress::InProgress));
18+/// ```
19+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20+pub enum Progress {
21+ Pending,
22+ InProgress,
23+ Completed,
24+ Failed,
25+}
26+
27+impl Progress {
28+ /// The word written in the stored text.
29+ fn word(self) -> &'static str {
30+ match self {
31+ Self::Pending => "pending",
32+ Self::InProgress => "in_progress",
33+ Self::Completed => "completed",
34+ Self::Failed => "failed",
35+ }
36+ }
37+
38+ /// The reverse of the stored word, `None` for a word nobody wrote.
39+ pub fn from_word(word: &str) -> Option<Self> {
40+ [
41+ Self::Pending,
42+ Self::InProgress,
43+ Self::Completed,
44+ Self::Failed,
45+ ]
46+ .into_iter()
47+ .find(|progress| progress.word() == word)
48+ }
49+
50+ /// The word shown to the user.
51+ pub fn label(self) -> &'static str {
52+ match self {
53+ Self::Pending => "waiting",
54+ Self::InProgress => "running",
55+ Self::Completed => "done",
56+ Self::Failed => "failed",
57+ }
58+ }
59+}
60+
61+/// The most characters of a tool's output that are kept, so that a tool that prints a whole file
62+/// does not fill the database and the window.
63+pub const MAX_OUTPUT_CHARS: usize = 4_000;
64+
65+/// A call of a tool by an agent: what it is for, how it went, what it printed.
66+///
67+/// ```
68+/// use synedrion_domain::trace::{Progress, ToolCallTrace, Trace};
69+///
70+/// let call = ToolCallTrace {
71+/// id: "call-1".to_string(),
72+/// title: "Read Cargo.toml".to_string(),
73+/// kind: "read".to_string(),
74+/// progress: Progress::Completed,
75+/// output: "[workspace]".to_string(),
76+/// };
77+/// let stored = Trace::ToolCall(call.clone()).to_text();
78+/// assert_eq!(Trace::from_text(&stored), Some(Trace::ToolCall(call)));
79+/// ```
80+#[derive(Debug, Clone, PartialEq, Eq)]
81+pub struct ToolCallTrace {
82+ /// The identifier the agent gave the call, to tell it which later update is about it.
83+ pub id: String,
84+ pub title: String,
85+ /// The category the agent gave (`read`, `edit`, `execute`, ...), or `other`.
86+ pub kind: String,
87+ pub progress: Progress,
88+ /// What the call produced, as text. Empty while there is nothing.
89+ pub output: String,
90+}
91+
92+/// What an agent changed about a tool call it announced earlier. Only what it sent is set.
93+///
94+/// ```
95+/// use synedrion_domain::trace::{Progress, ToolCallChange, ToolCallTrace};
96+///
97+/// let mut call = ToolCallTrace {
98+/// id: "c1".to_string(),
99+/// title: "Run".to_string(),
100+/// kind: "execute".to_string(),
101+/// progress: Progress::InProgress,
102+/// output: String::new(),
103+/// };
104+/// let change = ToolCallChange { progress: Some(Progress::Completed), ..Default::default() };
105+/// change.apply(&mut call);
106+/// assert_eq!(call.progress, Progress::Completed);
107+/// assert_eq!(call.title, "Run");
108+/// ```
109+#[derive(Debug, Clone, Default, PartialEq, Eq)]
110+pub struct ToolCallChange {
111+ pub title: Option<String>,
112+ pub kind: Option<String>,
113+ pub progress: Option<Progress>,
114+ /// The whole output, which replaces the one before.
115+ pub output: Option<String>,
116+}
117+
118+impl ToolCallChange {
119+ /// Puts the change into `call`.
120+ pub fn apply(&self, call: &mut ToolCallTrace) {
121+ if let Some(title) = &self.title {
122+ call.title = title.clone();
123+ }
124+ if let Some(kind) = &self.kind {
125+ call.kind = kind.clone();
126+ }
127+ if let Some(progress) = self.progress {
128+ call.progress = progress;
129+ }
130+ if let Some(output) = &self.output {
131+ call.output = output.clone();
132+ }
133+ }
134+}
135+
136+impl ToolCallTrace {
137+ /// A call that an update mentions before the agent announced it: all that is known is the
138+ /// identifier, so the title says so.
139+ pub fn unannounced(id: &str) -> Self {
140+ Self {
141+ id: id.to_string(),
142+ title: "Tool call".to_string(),
143+ kind: "other".to_string(),
144+ progress: Progress::Pending,
145+ output: String::new(),
146+ }
147+ }
148+}
149+
150+/// One step of an agent's plan.
151+#[derive(Debug, Clone, PartialEq, Eq)]
152+pub struct PlanStep {
153+ pub text: String,
154+ pub progress: Progress,
155+}
156+
157+/// What an agent did, other than writing.
158+#[derive(Debug, Clone, PartialEq, Eq)]
159+pub enum Trace {
160+ ToolCall(ToolCallTrace),
161+ /// The plan the agent follows. It is sent whole each time it changes.
162+ Plan(Vec<PlanStep>),
163+}
164+
165+impl Trace {
166+ /// The text that is stored in a message.
167+ pub fn to_text(&self) -> String {
168+ match self {
169+ Self::ToolCall(call) => format!(
170+ "tool\t{}\t{}\t{}\t{}\n{}",
171+ call.progress.word(),
172+ one_line(&call.id),
173+ one_line(&call.kind),
174+ one_line(&call.title),
175+ shorten(&call.output)
176+ ),
177+ Self::Plan(steps) => {
178+ let lines: Vec<String> = steps
179+ .iter()
180+ .map(|step| format!("{}\t{}", step.progress.word(), one_line(&step.text)))
181+ .collect();
182+ format!("plan\n{}", lines.join("\n"))
183+ }
184+ }
185+ }
186+
187+ /// Reads a stored text back. `None` when it is not one: the caller then shows it as it is.
188+ pub fn from_text(text: &str) -> Option<Self> {
189+ let (first, rest) = text.split_once('\n').unwrap_or((text, ""));
190+ let mut fields = first.split('\t');
191+ match fields.next()? {
192+ "tool" => {
193+ let progress = Progress::from_word(fields.next()?)?;
194+ let id = fields.next()?.to_string();
195+ let kind = fields.next()?.to_string();
196+ let title = fields.next()?.to_string();
197+ Some(Self::ToolCall(ToolCallTrace {
198+ id,
199+ title,
200+ kind,
201+ progress,
202+ output: rest.to_string(),
203+ }))
204+ }
205+ "plan" if fields.next().is_none() => rest
206+ .lines()
207+ .map(|line| {
208+ let (word, text) = line.split_once('\t')?;
209+ Some(PlanStep {
210+ text: text.to_string(),
211+ progress: Progress::from_word(word)?,
212+ })
213+ })
214+ .collect::<Option<Vec<_>>>()
215+ .map(Self::Plan),
216+ _ => None,
217+ }
218+ }
219+}
220+
221+impl fmt::Display for Trace {
222+ /// A one-line summary, for places that cannot draw the details.
223+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
224+ match self {
225+ Self::ToolCall(call) => write!(formatter, "{} ({})", call.title, call.progress.label()),
226+ Self::Plan(steps) => write!(formatter, "Plan ({} steps)", steps.len()),
227+ }
228+ }
229+}
230+
231+/// `text` on one line: line breaks and tabs, which the stored format uses as separators, become
232+/// spaces.
233+fn one_line(text: &str) -> String {
234+ text.replace(['\n', '\r', '\t'], " ")
235+}
236+
237+/// Cuts `text` to [`MAX_OUTPUT_CHARS`] characters and says how much was cut.
238+///
239+/// ```
240+/// use synedrion_domain::trace::{MAX_OUTPUT_CHARS, shorten};
241+///
242+/// assert_eq!(shorten("short"), "short");
243+/// assert!(shorten(&"x".repeat(MAX_OUTPUT_CHARS + 3)).ends_with("[output cut: 3 more character(s)]"));
244+/// ```
245+pub fn shorten(text: &str) -> String {
246+ let length = text.chars().count();
247+ if length <= MAX_OUTPUT_CHARS {
248+ return text.to_string();
249+ }
250+ let kept: String = text.chars().take(MAX_OUTPUT_CHARS).collect();
251+ format!(
252+ "{kept}\n[output cut: {} more character(s)]",
253+ length - MAX_OUTPUT_CHARS
254+ )
255+}
256+
257+#[cfg(test)]
258+mod tests {
259+ use super::*;
260+
261+ fn call(output: &str) -> ToolCallTrace {
262+ ToolCallTrace {
263+ id: "c1".into(),
264+ title: "Run the tests".into(),
265+ kind: "execute".into(),
266+ progress: Progress::InProgress,
267+ output: output.into(),
268+ }
269+ }
270+
271+ #[test]
272+ fn a_tool_call_survives_being_stored() {
273+ let original = Trace::ToolCall(call("line one\nline two\n\ttabbed"));
274+ assert_eq!(Trace::from_text(&original.to_text()), Some(original));
275+ }
276+
277+ #[test]
278+ fn a_tool_call_without_output_survives_being_stored() {
279+ let original = Trace::ToolCall(call(""));
280+ assert_eq!(Trace::from_text(&original.to_text()), Some(original));
281+ }
282+
283+ #[test]
284+ fn a_title_with_line_breaks_and_tabs_is_put_on_one_line() {
285+ let mut tool = call("");
286+ tool.title = "a\tb\nc".into();
287+ let read = Trace::from_text(&Trace::ToolCall(tool).to_text()).unwrap();
288+ assert!(matches!(read, Trace::ToolCall(call) if call.title == "a b c"));
289+ }
290+
291+ #[test]
292+ fn a_plan_survives_being_stored() {
293+ let original = Trace::Plan(vec![
294+ PlanStep {
295+ text: "read the code".into(),
296+ progress: Progress::Completed,
297+ },
298+ PlanStep {
299+ text: "write the fix".into(),
300+ progress: Progress::Pending,
301+ },
302+ ]);
303+ assert_eq!(Trace::from_text(&original.to_text()), Some(original));
304+ }
305+
306+ #[test]
307+ fn an_empty_plan_survives_being_stored() {
308+ let original = Trace::Plan(vec![]);
309+ assert_eq!(Trace::from_text(&original.to_text()), Some(original));
310+ }
311+
312+ #[test]
313+ fn text_that_is_not_a_trace_is_not_read_as_one() {
314+ for text in [
315+ "",
316+ "hello",
317+ "tool",
318+ "tool\tnonsense\tc\tk\tt",
319+ "tool\tdone",
320+ "plan\textra",
321+ "plan\nno-tab-here",
322+ "plan\nwhoknows\tstep",
323+ ] {
324+ assert_eq!(Trace::from_text(text), None, "{text:?}");
325+ }
326+ }
327+
328+ #[test]
329+ fn long_output_is_cut_when_stored_and_says_so() {
330+ let stored = Trace::ToolCall(call(&"z".repeat(MAX_OUTPUT_CHARS + 10))).to_text();
331+ assert!(stored.ends_with("[output cut: 10 more character(s)]"));
332+ assert!(stored.matches('z').count() == MAX_OUTPUT_CHARS);
333+ }
334+
335+ #[test]
336+ fn output_exactly_at_the_limit_is_not_cut() {
337+ assert_eq!(
338+ shorten(&"é".repeat(MAX_OUTPUT_CHARS)).chars().count(),
339+ MAX_OUTPUT_CHARS
340+ );
341+ }
342+
343+ #[test]
344+ fn every_progress_has_a_word_that_reads_back() {
345+ for progress in [
346+ Progress::Pending,
347+ Progress::InProgress,
348+ Progress::Completed,
349+ Progress::Failed,
350+ ] {
351+ assert_eq!(Progress::from_word(progress.word()), Some(progress));
352+ }
353+ assert_eq!(Progress::from_word("done"), None);
354+ }
355+
356+ #[test]
357+ fn a_change_replaces_only_what_it_carries() {
358+ let mut tool = call("old output");
359+ let change = ToolCallChange {
360+ title: Some("New title".into()),
361+ output: Some("new output".into()),
362+ ..Default::default()
363+ };
364+ change.apply(&mut tool);
365+ assert_eq!(tool.title, "New title");
366+ assert_eq!(tool.output, "new output");
367+ assert_eq!(tool.kind, "execute");
368+ assert_eq!(tool.progress, Progress::InProgress);
369+ }
370+
371+ #[test]
372+ fn an_empty_change_changes_nothing() {
373+ let mut tool = call("out");
374+ let before = tool.clone();
375+ ToolCallChange::default().apply(&mut tool);
376+ assert_eq!(tool, before);
377+ }
378+
379+ #[test]
380+ fn an_empty_output_in_a_change_does_clear_the_output() {
381+ let mut tool = call("out");
382+ ToolCallChange {
383+ output: Some(String::new()),
384+ ..Default::default()
385+ }
386+ .apply(&mut tool);
387+ assert_eq!(tool.output, "");
388+ }
389+
390+ #[test]
391+ fn a_call_known_only_by_its_id_has_a_generic_title() {
392+ let tool = ToolCallTrace::unannounced("x9");
393+ assert_eq!((tool.id.as_str(), tool.title.as_str()), ("x9", "Tool call"));
394+ assert_eq!(tool.progress, Progress::Pending);
395+ }
396+
397+ #[test]
398+ fn a_trace_has_a_one_line_summary() {
399+ assert_eq!(
400+ Trace::ToolCall(call("")).to_string(),
401+ "Run the tests (running)"
402+ );
403+ assert_eq!(Trace::Plan(vec![]).to_string(), "Plan (0 steps)");
404+ }
405+}
new file mode 100644
@@ -0,0 +1,405 @@
1+//! What an agent does besides writing text: the tools it calls and the plan it follows.
2+//!
3+//! These are kept in the channel next to the messages, so that the history shows how an answer
4+//! came about. A trace is stored as text in the content of a message written by
5+//! [`Author::Trace`](crate::message::Author::Trace): the first line says what kind of trace it is
6+//! and the lines after hold the details. The format is plain on purpose, so that it needs no
7+//! library and so that anything this code cannot read is still readable by a person.
8+
9+use std::fmt;
10+
11+/// How far a tool call or a step of a plan has got.
12+///
13+/// ```
14+/// use synedrion_domain::trace::Progress;
15+///
16+/// assert_eq!(Progress::Completed.label(), "done");
17+/// assert_eq!(Progress::from_word("in_progress"), Some(Progress::InProgress));
18+/// ```
19+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20+pub enum Progress {
21+ Pending,
22+ InProgress,
23+ Completed,
24+ Failed,
25+}
26+
27+impl Progress {
28+ /// The word written in the stored text.
29+ fn word(self) -> &'static str {
30+ match self {
31+ Self::Pending => "pending",
32+ Self::InProgress => "in_progress",
33+ Self::Completed => "completed",
34+ Self::Failed => "failed",
35+ }
36+ }
37+
38+ /// The reverse of the stored word, `None` for a word nobody wrote.
39+ pub fn from_word(word: &str) -> Option<Self> {
40+ [
41+ Self::Pending,
42+ Self::InProgress,
43+ Self::Completed,
44+ Self::Failed,
45+ ]
46+ .into_iter()
47+ .find(|progress| progress.word() == word)
48+ }
49+
50+ /// The word shown to the user.
51+ pub fn label(self) -> &'static str {
52+ match self {
53+ Self::Pending => "waiting",
54+ Self::InProgress => "running",
55+ Self::Completed => "done",
56+ Self::Failed => "failed",
57+ }
58+ }
59+}
60+
61+/// The most characters of a tool's output that are kept, so that a tool that prints a whole file
62+/// does not fill the database and the window.
63+pub const MAX_OUTPUT_CHARS: usize = 4_000;
64+
65+/// A call of a tool by an agent: what it is for, how it went, what it printed.
66+///
67+/// ```
68+/// use synedrion_domain::trace::{Progress, ToolCallTrace, Trace};
69+///
70+/// let call = ToolCallTrace {
71+/// id: "call-1".to_string(),
72+/// title: "Read Cargo.toml".to_string(),
73+/// kind: "read".to_string(),
74+/// progress: Progress::Completed,
75+/// output: "[workspace]".to_string(),
76+/// };
77+/// let stored = Trace::ToolCall(call.clone()).to_text();
78+/// assert_eq!(Trace::from_text(&stored), Some(Trace::ToolCall(call)));
79+/// ```
80+#[derive(Debug, Clone, PartialEq, Eq)]
81+pub struct ToolCallTrace {
82+ /// The identifier the agent gave the call, to tell it which later update is about it.
83+ pub id: String,
84+ pub title: String,
85+ /// The category the agent gave (`read`, `edit`, `execute`, ...), or `other`.
86+ pub kind: String,
87+ pub progress: Progress,
88+ /// What the call produced, as text. Empty while there is nothing.
89+ pub output: String,
90+}
91+
92+/// What an agent changed about a tool call it announced earlier. Only what it sent is set.
93+///
94+/// ```
95+/// use synedrion_domain::trace::{Progress, ToolCallChange, ToolCallTrace};
96+///
97+/// let mut call = ToolCallTrace {
98+/// id: "c1".to_string(),
99+/// title: "Run".to_string(),
100+/// kind: "execute".to_string(),
101+/// progress: Progress::InProgress,
102+/// output: String::new(),
103+/// };
104+/// let change = ToolCallChange { progress: Some(Progress::Completed), ..Default::default() };
105+/// change.apply(&mut call);
106+/// assert_eq!(call.progress, Progress::Completed);
107+/// assert_eq!(call.title, "Run");
108+/// ```
109+#[derive(Debug, Clone, Default, PartialEq, Eq)]
110+pub struct ToolCallChange {
111+ pub title: Option<String>,
112+ pub kind: Option<String>,
113+ pub progress: Option<Progress>,
114+ /// The whole output, which replaces the one before.
115+ pub output: Option<String>,
116+}
117+
118+impl ToolCallChange {
119+ /// Puts the change into `call`.
120+ pub fn apply(&self, call: &mut ToolCallTrace) {
121+ if let Some(title) = &self.title {
122+ call.title = title.clone();
123+ }
124+ if let Some(kind) = &self.kind {
125+ call.kind = kind.clone();
126+ }
127+ if let Some(progress) = self.progress {
128+ call.progress = progress;
129+ }
130+ if let Some(output) = &self.output {
131+ call.output = output.clone();
132+ }
133+ }
134+}
135+
136+impl ToolCallTrace {
137+ /// A call that an update mentions before the agent announced it: all that is known is the
138+ /// identifier, so the title says so.
139+ pub fn unannounced(id: &str) -> Self {
140+ Self {
141+ id: id.to_string(),
142+ title: "Tool call".to_string(),
143+ kind: "other".to_string(),
144+ progress: Progress::Pending,
145+ output: String::new(),
146+ }
147+ }
148+}
149+
150+/// One step of an agent's plan.
151+#[derive(Debug, Clone, PartialEq, Eq)]
152+pub struct PlanStep {
153+ pub text: String,
154+ pub progress: Progress,
155+}
156+
157+/// What an agent did, other than writing.
158+#[derive(Debug, Clone, PartialEq, Eq)]
159+pub enum Trace {
160+ ToolCall(ToolCallTrace),
161+ /// The plan the agent follows. It is sent whole each time it changes.
162+ Plan(Vec<PlanStep>),
163+}
164+
165+impl Trace {
166+ /// The text that is stored in a message.
167+ pub fn to_text(&self) -> String {
168+ match self {
169+ Self::ToolCall(call) => format!(
170+ "tool\t{}\t{}\t{}\t{}\n{}",
171+ call.progress.word(),
172+ one_line(&call.id),
173+ one_line(&call.kind),
174+ one_line(&call.title),
175+ shorten(&call.output)
176+ ),
177+ Self::Plan(steps) => {
178+ let lines: Vec<String> = steps
179+ .iter()
180+ .map(|step| format!("{}\t{}", step.progress.word(), one_line(&step.text)))
181+ .collect();
182+ format!("plan\n{}", lines.join("\n"))
183+ }
184+ }
185+ }
186+
187+ /// Reads a stored text back. `None` when it is not one: the caller then shows it as it is.
188+ pub fn from_text(text: &str) -> Option<Self> {
189+ let (first, rest) = text.split_once('\n').unwrap_or((text, ""));
190+ let mut fields = first.split('\t');
191+ match fields.next()? {
192+ "tool" => {
193+ let progress = Progress::from_word(fields.next()?)?;
194+ let id = fields.next()?.to_string();
195+ let kind = fields.next()?.to_string();
196+ let title = fields.next()?.to_string();
197+ Some(Self::ToolCall(ToolCallTrace {
198+ id,
199+ title,
200+ kind,
201+ progress,
202+ output: rest.to_string(),
203+ }))
204+ }
205+ "plan" if fields.next().is_none() => rest
206+ .lines()
207+ .map(|line| {
208+ let (word, text) = line.split_once('\t')?;
209+ Some(PlanStep {
210+ text: text.to_string(),
211+ progress: Progress::from_word(word)?,
212+ })
213+ })
214+ .collect::<Option<Vec<_>>>()
215+ .map(Self::Plan),
216+ _ => None,
217+ }
218+ }
219+}
220+
221+impl fmt::Display for Trace {
222+ /// A one-line summary, for places that cannot draw the details.
223+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
224+ match self {
225+ Self::ToolCall(call) => write!(formatter, "{} ({})", call.title, call.progress.label()),
226+ Self::Plan(steps) => write!(formatter, "Plan ({} steps)", steps.len()),
227+ }
228+ }
229+}
230+
231+/// `text` on one line: line breaks and tabs, which the stored format uses as separators, become
232+/// spaces.
233+fn one_line(text: &str) -> String {
234+ text.replace(['\n', '\r', '\t'], " ")
235+}
236+
237+/// Cuts `text` to [`MAX_OUTPUT_CHARS`] characters and says how much was cut.
238+///
239+/// ```
240+/// use synedrion_domain::trace::{MAX_OUTPUT_CHARS, shorten};
241+///
242+/// assert_eq!(shorten("short"), "short");
243+/// assert!(shorten(&"x".repeat(MAX_OUTPUT_CHARS + 3)).ends_with("[output cut: 3 more character(s)]"));
244+/// ```
245+pub fn shorten(text: &str) -> String {
246+ let length = text.chars().count();
247+ if length <= MAX_OUTPUT_CHARS {
248+ return text.to_string();
249+ }
250+ let kept: String = text.chars().take(MAX_OUTPUT_CHARS).collect();
251+ format!(
252+ "{kept}\n[output cut: {} more character(s)]",
253+ length - MAX_OUTPUT_CHARS
254+ )
255+}
256+
257+#[cfg(test)]
258+mod tests {
259+ use super::*;
260+
261+ fn call(output: &str) -> ToolCallTrace {
262+ ToolCallTrace {
263+ id: "c1".into(),
264+ title: "Run the tests".into(),
265+ kind: "execute".into(),
266+ progress: Progress::InProgress,
267+ output: output.into(),
268+ }
269+ }
270+
271+ #[test]
272+ fn a_tool_call_survives_being_stored() {
273+ let original = Trace::ToolCall(call("line one\nline two\n\ttabbed"));
274+ assert_eq!(Trace::from_text(&original.to_text()), Some(original));
275+ }
276+
277+ #[test]
278+ fn a_tool_call_without_output_survives_being_stored() {
279+ let original = Trace::ToolCall(call(""));
280+ assert_eq!(Trace::from_text(&original.to_text()), Some(original));
281+ }
282+
283+ #[test]
284+ fn a_title_with_line_breaks_and_tabs_is_put_on_one_line() {
285+ let mut tool = call("");
286+ tool.title = "a\tb\nc".into();
287+ let read = Trace::from_text(&Trace::ToolCall(tool).to_text()).unwrap();
288+ assert!(matches!(read, Trace::ToolCall(call) if call.title == "a b c"));
289+ }
290+
291+ #[test]
292+ fn a_plan_survives_being_stored() {
293+ let original = Trace::Plan(vec![
294+ PlanStep {
295+ text: "read the code".into(),
296+ progress: Progress::Completed,
297+ },
298+ PlanStep {
299+ text: "write the fix".into(),
300+ progress: Progress::Pending,
301+ },
302+ ]);
303+ assert_eq!(Trace::from_text(&original.to_text()), Some(original));
304+ }
305+
306+ #[test]
307+ fn an_empty_plan_survives_being_stored() {
308+ let original = Trace::Plan(vec![]);
309+ assert_eq!(Trace::from_text(&original.to_text()), Some(original));
310+ }
311+
312+ #[test]
313+ fn text_that_is_not_a_trace_is_not_read_as_one() {
314+ for text in [
315+ "",
316+ "hello",
317+ "tool",
318+ "tool\tnonsense\tc\tk\tt",
319+ "tool\tdone",
320+ "plan\textra",
321+ "plan\nno-tab-here",
322+ "plan\nwhoknows\tstep",
323+ ] {
324+ assert_eq!(Trace::from_text(text), None, "{text:?}");
325+ }
326+ }
327+
328+ #[test]
329+ fn long_output_is_cut_when_stored_and_says_so() {
330+ let stored = Trace::ToolCall(call(&"z".repeat(MAX_OUTPUT_CHARS + 10))).to_text();
331+ assert!(stored.ends_with("[output cut: 10 more character(s)]"));
332+ assert!(stored.matches('z').count() == MAX_OUTPUT_CHARS);
333+ }
334+
335+ #[test]
336+ fn output_exactly_at_the_limit_is_not_cut() {
337+ assert_eq!(
338+ shorten(&"é".repeat(MAX_OUTPUT_CHARS)).chars().count(),
339+ MAX_OUTPUT_CHARS
340+ );
341+ }
342+
343+ #[test]
344+ fn every_progress_has_a_word_that_reads_back() {
345+ for progress in [
346+ Progress::Pending,
347+ Progress::InProgress,
348+ Progress::Completed,
349+ Progress::Failed,
350+ ] {
351+ assert_eq!(Progress::from_word(progress.word()), Some(progress));
352+ }
353+ assert_eq!(Progress::from_word("done"), None);
354+ }
355+
356+ #[test]
357+ fn a_change_replaces_only_what_it_carries() {
358+ let mut tool = call("old output");
359+ let change = ToolCallChange {
360+ title: Some("New title".into()),
361+ output: Some("new output".into()),
362+ ..Default::default()
363+ };
364+ change.apply(&mut tool);
365+ assert_eq!(tool.title, "New title");
366+ assert_eq!(tool.output, "new output");
367+ assert_eq!(tool.kind, "execute");
368+ assert_eq!(tool.progress, Progress::InProgress);
369+ }
370+
371+ #[test]
372+ fn an_empty_change_changes_nothing() {
373+ let mut tool = call("out");
374+ let before = tool.clone();
375+ ToolCallChange::default().apply(&mut tool);
376+ assert_eq!(tool, before);
377+ }
378+
379+ #[test]
380+ fn an_empty_output_in_a_change_does_clear_the_output() {
381+ let mut tool = call("out");
382+ ToolCallChange {
383+ output: Some(String::new()),
384+ ..Default::default()
385+ }
386+ .apply(&mut tool);
387+ assert_eq!(tool.output, "");
388+ }
389+
390+ #[test]
391+ fn a_call_known_only_by_its_id_has_a_generic_title() {
392+ let tool = ToolCallTrace::unannounced("x9");
393+ assert_eq!((tool.id.as_str(), tool.title.as_str()), ("x9", "Tool call"));
394+ assert_eq!(tool.progress, Progress::Pending);
395+ }
396+
397+ #[test]
398+ fn a_trace_has_a_one_line_summary() {
399+ assert_eq!(
400+ Trace::ToolCall(call("")).to_string(),
401+ "Run the tests (running)"
402+ );
403+ assert_eq!(Trace::Plan(vec![]).to_string(), "Plan (0 steps)");
404+ }
405+}
modified crates/store/README.md +2 -2
@@ -15,8 +15,8 @@ repository.create_channel(&ChannelName::new("general").unwrap()).unwrap();
1515
1616 | Item | Contents |
1717 | --- | --- |
18-| `SqliteRepository` | `open(path)`, `open_in_memory()`, and every `Repository` operation |
19-| `migrations` | `apply`, `current_version`: the schema as an ordered list of migrations |
18+| `SqliteRepository` | `open(path)`, `open_in_memory()`, and every `Repository` operation, settings included |
19+| `migrations` | `apply`, `current_version`: the schema as an ordered list of migrations (version 3: the settings table, and traces as a kind of message author) |
2020 | `paths` | `data_dir`, `default_database_path`: where the file lives on each system |
2121
2222 The schema and the file location are in the [database reference](../../docs/en/reference/database.md). Run the tests with `cargo test -p synedrion-store`.
@@ -15,8 +15,8 @@ repository.create_channel(&ChannelName::new("general").unwrap()).unwrap();
15 15
16 | Item | Contents |16 | Item | Contents |
17 | --- | --- |17 | --- | --- |
18-| `SqliteRepository` | `open(path)`, `open_in_memory()`, and every `Repository` operation |18+| `SqliteRepository` | `open(path)`, `open_in_memory()`, and every `Repository` operation, settings included |
19-| `migrations` | `apply`, `current_version`: the schema as an ordered list of migrations |19+| `migrations` | `apply`, `current_version`: the schema as an ordered list of migrations (version 3: the settings table, and traces as a kind of message author) |
20 | `paths` | `data_dir`, `default_database_path`: where the file lives on each system |20 | `paths` | `data_dir`, `default_database_path`: where the file lives on each system |
21 21
22 The schema and the file location are in the [database reference](../../docs/en/reference/database.md). Run the tests with `cargo test -p synedrion-store`.22 The schema and the file location are in the [database reference](../../docs/en/reference/database.md). Run the tests with `cargo test -p synedrion-store`.
modified crates/store/src/migrations.rs +89 -4
@@ -42,7 +42,36 @@ const SCHEMA_V1: &str = "
4242 CREATE INDEX message_by_channel ON message (channel_id, id);
4343 ";
4444
45-const MIGRATIONS: &[&str] = &[SCHEMA_V1];
45+/// Version 2: the settings the user can change, one row each.
46+const SCHEMA_V2: &str = "
47+ CREATE TABLE setting (
48+ key TEXT PRIMARY KEY,
49+ value TEXT NOT NULL
50+ );
51+";
52+
53+/// Version 3: a message can be written by a `trace` (what an agent did: a tool call, a plan).
54+///
55+/// SQLite cannot change a `CHECK`, so the table is rebuilt and its rows copied.
56+const SCHEMA_V3: &str = "
57+ CREATE TABLE message_next (
58+ id INTEGER PRIMARY KEY AUTOINCREMENT,
59+ channel_id INTEGER NOT NULL REFERENCES channel(id) ON DELETE CASCADE,
60+ author_kind TEXT NOT NULL CHECK (author_kind IN ('user', 'agent', 'system', 'trace')),
61+ author_name TEXT,
62+ content TEXT NOT NULL,
63+ created_at_ms INTEGER NOT NULL
64+ );
65+
66+ INSERT INTO message_next (id, channel_id, author_kind, author_name, content, created_at_ms)
67+ SELECT id, channel_id, author_kind, author_name, content, created_at_ms FROM message;
68+
69+ DROP TABLE message;
70+ ALTER TABLE message_next RENAME TO message;
71+ CREATE INDEX message_by_channel ON message (channel_id, id);
72+";
73+
74+const MIGRATIONS: &[&str] = &[SCHEMA_V1, SCHEMA_V2, SCHEMA_V3];
4675
4776 /// Brings the database up to the latest schema.
4877 ///
@@ -111,17 +140,73 @@ mod tests {
111140 }
112141
113142 #[test]
114- fn schema_creates_the_four_tables() {
143+ fn a_database_of_version_one_keeps_its_messages_when_upgraded() {
144+ let mut connection = Connection::open_in_memory().unwrap();
145+ connection.execute_batch(SCHEMA_V1).unwrap();
146+ connection
147+ .pragma_update(None, "user_version", 1_i64)
148+ .unwrap();
149+ connection
150+ .execute("INSERT INTO channel (name) VALUES ('general')", [])
151+ .unwrap();
152+ connection
153+ .execute(
154+ "INSERT INTO message (channel_id, author_kind, content, created_at_ms)
155+ VALUES (1, 'user', 'kept', 5)",
156+ [],
157+ )
158+ .unwrap();
159+
160+ apply(&mut connection).unwrap();
161+
162+ let (id, content): (i64, String) = connection
163+ .query_row("SELECT id, content FROM message", [], |row| {
164+ Ok((row.get(0)?, row.get(1)?))
165+ })
166+ .unwrap();
167+ assert_eq!((id, content.as_str()), (1, "kept"));
168+ // The counter goes on after the rows that were copied.
169+ connection
170+ .execute(
171+ "INSERT INTO message (channel_id, author_kind, content, created_at_ms)
172+ VALUES (1, 'user', 'next', 6)",
173+ [],
174+ )
175+ .unwrap();
176+ assert_eq!(connection.last_insert_rowid(), 2);
177+ }
178+
179+ #[test]
180+ fn a_trace_can_be_stored_as_a_message_and_an_unknown_kind_cannot() {
181+ let mut connection = Connection::open_in_memory().unwrap();
182+ apply(&mut connection).unwrap();
183+ connection
184+ .execute("INSERT INTO channel (name) VALUES ('general')", [])
185+ .unwrap();
186+ let insert = |kind: &str| {
187+ connection.execute(
188+ "INSERT INTO message (channel_id, author_kind, author_name, content, created_at_ms)
189+ VALUES (1, ?1, 'bob', 'x', 1)",
190+ [kind],
191+ )
192+ };
193+ assert!(insert("trace").is_ok());
194+ assert!(insert("robot").is_err());
195+ }
196+
197+ #[test]
198+ fn schema_creates_the_five_tables() {
115199 let mut connection = Connection::open_in_memory().unwrap();
116200 apply(&mut connection).unwrap();
117201 let tables: i64 = connection
118202 .query_row(
119203 "SELECT COUNT(*) FROM sqlite_master
120- WHERE type = 'table' AND name IN ('user', 'agent', 'channel', 'message')",
204+ WHERE type = 'table'
205+ AND name IN ('user', 'agent', 'channel', 'message', 'setting')",
121206 [],
122207 |row| row.get(0),
123208 )
124209 .unwrap();
125- assert_eq!(tables, 4);
210+ assert_eq!(tables, 5);
126211 }
127212 }
@@ -42,7 +42,36 @@ const SCHEMA_V1: &str = "
42 CREATE INDEX message_by_channel ON message (channel_id, id);42 CREATE INDEX message_by_channel ON message (channel_id, id);
43 ";43 ";
44 44
45-const MIGRATIONS: &[&str] = &[SCHEMA_V1];45+/// Version 2: the settings the user can change, one row each.
46+const SCHEMA_V2: &str = "
47+ CREATE TABLE setting (
48+ key TEXT PRIMARY KEY,
49+ value TEXT NOT NULL
50+ );
51+";
52+
53+/// Version 3: a message can be written by a `trace` (what an agent did: a tool call, a plan).
54+///
55+/// SQLite cannot change a `CHECK`, so the table is rebuilt and its rows copied.
56+const SCHEMA_V3: &str = "
57+ CREATE TABLE message_next (
58+ id INTEGER PRIMARY KEY AUTOINCREMENT,
59+ channel_id INTEGER NOT NULL REFERENCES channel(id) ON DELETE CASCADE,
60+ author_kind TEXT NOT NULL CHECK (author_kind IN ('user', 'agent', 'system', 'trace')),
61+ author_name TEXT,
62+ content TEXT NOT NULL,
63+ created_at_ms INTEGER NOT NULL
64+ );
65+
66+ INSERT INTO message_next (id, channel_id, author_kind, author_name, content, created_at_ms)
67+ SELECT id, channel_id, author_kind, author_name, content, created_at_ms FROM message;
68+
69+ DROP TABLE message;
70+ ALTER TABLE message_next RENAME TO message;
71+ CREATE INDEX message_by_channel ON message (channel_id, id);
72+";
73+
74+const MIGRATIONS: &[&str] = &[SCHEMA_V1, SCHEMA_V2, SCHEMA_V3];
46 75
47 /// Brings the database up to the latest schema.76 /// Brings the database up to the latest schema.
48 ///77 ///
@@ -111,17 +140,73 @@ mod tests {
111 }140 }
112 141
113 #[test]142 #[test]
114- fn schema_creates_the_four_tables() {143+ fn a_database_of_version_one_keeps_its_messages_when_upgraded() {
144+ let mut connection = Connection::open_in_memory().unwrap();
145+ connection.execute_batch(SCHEMA_V1).unwrap();
146+ connection
147+ .pragma_update(None, "user_version", 1_i64)
148+ .unwrap();
149+ connection
150+ .execute("INSERT INTO channel (name) VALUES ('general')", [])
151+ .unwrap();
152+ connection
153+ .execute(
154+ "INSERT INTO message (channel_id, author_kind, content, created_at_ms)
155+ VALUES (1, 'user', 'kept', 5)",
156+ [],
157+ )
158+ .unwrap();
159+
160+ apply(&mut connection).unwrap();
161+
162+ let (id, content): (i64, String) = connection
163+ .query_row("SELECT id, content FROM message", [], |row| {
164+ Ok((row.get(0)?, row.get(1)?))
165+ })
166+ .unwrap();
167+ assert_eq!((id, content.as_str()), (1, "kept"));
168+ // The counter goes on after the rows that were copied.
169+ connection
170+ .execute(
171+ "INSERT INTO message (channel_id, author_kind, content, created_at_ms)
172+ VALUES (1, 'user', 'next', 6)",
173+ [],
174+ )
175+ .unwrap();
176+ assert_eq!(connection.last_insert_rowid(), 2);
177+ }
178+
179+ #[test]
180+ fn a_trace_can_be_stored_as_a_message_and_an_unknown_kind_cannot() {
181+ let mut connection = Connection::open_in_memory().unwrap();
182+ apply(&mut connection).unwrap();
183+ connection
184+ .execute("INSERT INTO channel (name) VALUES ('general')", [])
185+ .unwrap();
186+ let insert = |kind: &str| {
187+ connection.execute(
188+ "INSERT INTO message (channel_id, author_kind, author_name, content, created_at_ms)
189+ VALUES (1, ?1, 'bob', 'x', 1)",
190+ [kind],
191+ )
192+ };
193+ assert!(insert("trace").is_ok());
194+ assert!(insert("robot").is_err());
195+ }
196+
197+ #[test]
198+ fn schema_creates_the_five_tables() {
115 let mut connection = Connection::open_in_memory().unwrap();199 let mut connection = Connection::open_in_memory().unwrap();
116 apply(&mut connection).unwrap();200 apply(&mut connection).unwrap();
117 let tables: i64 = connection201 let tables: i64 = connection
118 .query_row(202 .query_row(
119 "SELECT COUNT(*) FROM sqlite_master203 "SELECT COUNT(*) FROM sqlite_master
120- WHERE type = 'table' AND name IN ('user', 'agent', 'channel', 'message')",204+ WHERE type = 'table'
205+ AND name IN ('user', 'agent', 'channel', 'message', 'setting')",
121 [],206 [],
122 |row| row.get(0),207 |row| row.get(0),
123 )208 )
124 .unwrap();209 .unwrap();
125- assert_eq!(tables, 4);210+ assert_eq!(tables, 5);
126 }211 }
127 }212 }
modified crates/store/src/sqlite.rs +106 -0
@@ -9,6 +9,7 @@ use synedrion_domain::agent::{AgentDeclaration, AgentName};
99 use synedrion_domain::channel::{Channel, ChannelId, ChannelName};
1010 use synedrion_domain::message::{Author, Message, MessageId, NewMessage};
1111 use synedrion_domain::repository::{Repository, RepositoryError, RepositoryResult};
12+use synedrion_domain::settings::ChatSettings;
1213 use synedrion_domain::user::{DisplayName, UserProfile};
1314
1415 use crate::migrations;
@@ -66,6 +67,32 @@ impl SqliteRepository {
6667 }
6768 }
6869
70+/// The names under which the settings are stored.
71+const CONTEXT_MESSAGES_KEY: &str = "context_messages";
72+const CHAIN_DEPTH_KEY: &str = "chain_depth";
73+
74+impl SqliteRepository {
75+ fn setting(&self, key: &str) -> RepositoryResult<Option<String>> {
76+ self.connection()
77+ .query_row("SELECT value FROM setting WHERE key = ?1", [key], |row| {
78+ row.get(0)
79+ })
80+ .optional()
81+ .map_err(storage_error)
82+ }
83+
84+ fn store_setting(&self, key: &str, value: usize) -> RepositoryResult<()> {
85+ self.connection()
86+ .execute(
87+ "INSERT INTO setting (key, value) VALUES (?1, ?2)
88+ ON CONFLICT (key) DO UPDATE SET value = excluded.value",
89+ params![key, value.to_string()],
90+ )
91+ .map_err(storage_error)?;
92+ Ok(())
93+ }
94+}
95+
6996 impl Repository for SqliteRepository {
7097 fn load_user(&self) -> RepositoryResult<Option<UserProfile>> {
7198 let stored: Option<String> = self
@@ -94,6 +121,22 @@ impl Repository for SqliteRepository {
94121 Ok(())
95122 }
96123
124+ fn load_settings(&self) -> RepositoryResult<ChatSettings> {
125+ let defaults = ChatSettings::default();
126+ let context = self
127+ .setting(CONTEXT_MESSAGES_KEY)?
128+ .unwrap_or_else(|| defaults.context_messages.to_string());
129+ let depth = self
130+ .setting(CHAIN_DEPTH_KEY)?
131+ .unwrap_or_else(|| defaults.chain_depth.to_string());
132+ ChatSettings::parse(&context, &depth).map_err(invalid_stored_value)
133+ }
134+
135+ fn save_settings(&self, settings: &ChatSettings) -> RepositoryResult<()> {
136+ self.store_setting(CONTEXT_MESSAGES_KEY, settings.context_messages)?;
137+ self.store_setting(CHAIN_DEPTH_KEY, settings.chain_depth)
138+ }
139+
97140 fn list_channels(&self) -> RepositoryResult<Vec<Channel>> {
98141 let connection = self.connection();
99142 let mut statement = connection
@@ -341,6 +384,7 @@ fn author_columns(author: &Author) -> (&'static str, Option<&str>) {
341384 Author::User => ("user", None),
342385 Author::Agent(name) => ("agent", Some(name.as_str())),
343386 Author::System => ("system", None),
387+ Author::Trace(name) => ("trace", Some(name.as_str())),
344388 }
345389 }
346390
@@ -351,6 +395,9 @@ fn author_from_columns(kind: &str, name: Option<&str>) -> RepositoryResult<Autho
351395 ("agent", Some(name)) => Ok(Author::Agent(
352396 AgentName::new(name).map_err(invalid_stored_value)?,
353397 )),
398+ ("trace", Some(name)) => Ok(Author::Trace(
399+ AgentName::new(name).map_err(invalid_stored_value)?,
400+ )),
354401 _ => Err(RepositoryError::Storage(format!(
355402 "unknown message author {kind:?}"
356403 ))),
@@ -605,6 +652,65 @@ mod tests {
605652 assert_eq!(authors, vec![Author::User, agent, Author::System]);
606653 }
607654
655+ #[test]
656+ fn a_trace_is_kept_with_the_agent_that_did_it() {
657+ let repository = repository();
658+ let channel = repository.create_channel(&channel_name("c")).unwrap();
659+ let author = Author::Trace(agent_name("bob"));
660+ repository
661+ .post_message(&new_message(
662+ channel.id,
663+ author.clone(),
664+ "tool\tcompleted\tc\tread\tRead",
665+ 1,
666+ ))
667+ .unwrap();
668+ let stored = repository.recent_messages(channel.id, 10).unwrap();
669+ assert_eq!(stored[0].author, author);
670+ }
671+
672+ #[test]
673+ fn settings_are_the_defaults_until_some_are_saved() {
674+ assert_eq!(
675+ repository().load_settings().unwrap(),
676+ ChatSettings::default()
677+ );
678+ }
679+
680+ #[test]
681+ fn saved_settings_are_read_back_and_replaced_by_the_next_save() {
682+ let repository = repository();
683+ let first = ChatSettings {
684+ context_messages: 7,
685+ chain_depth: 0,
686+ };
687+ repository.save_settings(&first).unwrap();
688+ assert_eq!(repository.load_settings().unwrap(), first);
689+
690+ let second = ChatSettings {
691+ context_messages: 0,
692+ chain_depth: 5,
693+ };
694+ repository.save_settings(&second).unwrap();
695+ assert_eq!(repository.load_settings().unwrap(), second);
696+ }
697+
698+ #[test]
699+ fn a_stored_setting_that_makes_no_sense_is_reported_not_hidden() {
700+ let repository = repository();
701+ repository
702+ .connection()
703+ .execute(
704+ "INSERT INTO setting (key, value) VALUES ('chain_depth', 'lots')",
705+ [],
706+ )
707+ .unwrap();
708+ assert!(matches!(
709+ repository.load_settings(),
710+ Err(RepositoryError::Storage(_))
711+ ));
712+ }
713+
608714 #[test]
609715 fn posting_in_a_missing_channel_is_not_found() {
610716 let error = repository()
@@ -9,6 +9,7 @@ use synedrion_domain::agent::{AgentDeclaration, AgentName};
9 use synedrion_domain::channel::{Channel, ChannelId, ChannelName};9 use synedrion_domain::channel::{Channel, ChannelId, ChannelName};
10 use synedrion_domain::message::{Author, Message, MessageId, NewMessage};10 use synedrion_domain::message::{Author, Message, MessageId, NewMessage};
11 use synedrion_domain::repository::{Repository, RepositoryError, RepositoryResult};11 use synedrion_domain::repository::{Repository, RepositoryError, RepositoryResult};
12+use synedrion_domain::settings::ChatSettings;
12 use synedrion_domain::user::{DisplayName, UserProfile};13 use synedrion_domain::user::{DisplayName, UserProfile};
13 14
14 use crate::migrations;15 use crate::migrations;
@@ -66,6 +67,32 @@ impl SqliteRepository {
66 }67 }
67 }68 }
68 69
70+/// The names under which the settings are stored.
71+const CONTEXT_MESSAGES_KEY: &str = "context_messages";
72+const CHAIN_DEPTH_KEY: &str = "chain_depth";
73+
74+impl SqliteRepository {
75+ fn setting(&self, key: &str) -> RepositoryResult<Option<String>> {
76+ self.connection()
77+ .query_row("SELECT value FROM setting WHERE key = ?1", [key], |row| {
78+ row.get(0)
79+ })
80+ .optional()
81+ .map_err(storage_error)
82+ }
83+
84+ fn store_setting(&self, key: &str, value: usize) -> RepositoryResult<()> {
85+ self.connection()
86+ .execute(
87+ "INSERT INTO setting (key, value) VALUES (?1, ?2)
88+ ON CONFLICT (key) DO UPDATE SET value = excluded.value",
89+ params![key, value.to_string()],
90+ )
91+ .map_err(storage_error)?;
92+ Ok(())
93+ }
94+}
95+
69 impl Repository for SqliteRepository {96 impl Repository for SqliteRepository {
70 fn load_user(&self) -> RepositoryResult<Option<UserProfile>> {97 fn load_user(&self) -> RepositoryResult<Option<UserProfile>> {
71 let stored: Option<String> = self98 let stored: Option<String> = self
@@ -94,6 +121,22 @@ impl Repository for SqliteRepository {
94 Ok(())121 Ok(())
95 }122 }
96 123
124+ fn load_settings(&self) -> RepositoryResult<ChatSettings> {
125+ let defaults = ChatSettings::default();
126+ let context = self
127+ .setting(CONTEXT_MESSAGES_KEY)?
128+ .unwrap_or_else(|| defaults.context_messages.to_string());
129+ let depth = self
130+ .setting(CHAIN_DEPTH_KEY)?
131+ .unwrap_or_else(|| defaults.chain_depth.to_string());
132+ ChatSettings::parse(&context, &depth).map_err(invalid_stored_value)
133+ }
134+
135+ fn save_settings(&self, settings: &ChatSettings) -> RepositoryResult<()> {
136+ self.store_setting(CONTEXT_MESSAGES_KEY, settings.context_messages)?;
137+ self.store_setting(CHAIN_DEPTH_KEY, settings.chain_depth)
138+ }
139+
97 fn list_channels(&self) -> RepositoryResult<Vec<Channel>> {140 fn list_channels(&self) -> RepositoryResult<Vec<Channel>> {
98 let connection = self.connection();141 let connection = self.connection();
99 let mut statement = connection142 let mut statement = connection
@@ -341,6 +384,7 @@ fn author_columns(author: &Author) -> (&'static str, Option<&str>) {
341 Author::User => ("user", None),384 Author::User => ("user", None),
342 Author::Agent(name) => ("agent", Some(name.as_str())),385 Author::Agent(name) => ("agent", Some(name.as_str())),
343 Author::System => ("system", None),386 Author::System => ("system", None),
387+ Author::Trace(name) => ("trace", Some(name.as_str())),
344 }388 }
345 }389 }
346 390
@@ -351,6 +395,9 @@ fn author_from_columns(kind: &str, name: Option<&str>) -> RepositoryResult<Autho
351 ("agent", Some(name)) => Ok(Author::Agent(395 ("agent", Some(name)) => Ok(Author::Agent(
352 AgentName::new(name).map_err(invalid_stored_value)?,396 AgentName::new(name).map_err(invalid_stored_value)?,
353 )),397 )),
398+ ("trace", Some(name)) => Ok(Author::Trace(
399+ AgentName::new(name).map_err(invalid_stored_value)?,
400+ )),
354 _ => Err(RepositoryError::Storage(format!(401 _ => Err(RepositoryError::Storage(format!(
355 "unknown message author {kind:?}"402 "unknown message author {kind:?}"
356 ))),403 ))),
@@ -605,6 +652,65 @@ mod tests {
605 assert_eq!(authors, vec![Author::User, agent, Author::System]);652 assert_eq!(authors, vec![Author::User, agent, Author::System]);
606 }653 }
607 654
655+ #[test]
656+ fn a_trace_is_kept_with_the_agent_that_did_it() {
657+ let repository = repository();
658+ let channel = repository.create_channel(&channel_name("c")).unwrap();
659+ let author = Author::Trace(agent_name("bob"));
660+ repository
661+ .post_message(&new_message(
662+ channel.id,
663+ author.clone(),
664+ "tool\tcompleted\tc\tread\tRead",
665+ 1,
666+ ))
667+ .unwrap();
668+ let stored = repository.recent_messages(channel.id, 10).unwrap();
669+ assert_eq!(stored[0].author, author);
670+ }
671+
672+ #[test]
673+ fn settings_are_the_defaults_until_some_are_saved() {
674+ assert_eq!(
675+ repository().load_settings().unwrap(),
676+ ChatSettings::default()
677+ );
678+ }
679+
680+ #[test]
681+ fn saved_settings_are_read_back_and_replaced_by_the_next_save() {
682+ let repository = repository();
683+ let first = ChatSettings {
684+ context_messages: 7,
685+ chain_depth: 0,
686+ };
687+ repository.save_settings(&first).unwrap();
688+ assert_eq!(repository.load_settings().unwrap(), first);
689+
690+ let second = ChatSettings {
691+ context_messages: 0,
692+ chain_depth: 5,
693+ };
694+ repository.save_settings(&second).unwrap();
695+ assert_eq!(repository.load_settings().unwrap(), second);
696+ }
697+
698+ #[test]
699+ fn a_stored_setting_that_makes_no_sense_is_reported_not_hidden() {
700+ let repository = repository();
701+ repository
702+ .connection()
703+ .execute(
704+ "INSERT INTO setting (key, value) VALUES ('chain_depth', 'lots')",
705+ [],
706+ )
707+ .unwrap();
708+ assert!(matches!(
709+ repository.load_settings(),
710+ Err(RepositoryError::Storage(_))
711+ ));
712+ }
713+
608 #[test]714 #[test]
609 fn posting_in_a_missing_channel_is_not_found() {715 fn posting_in_a_missing_channel_is_not_found() {
610 let error = repository()716 let error = repository()
modified crates/ui/README.md +4 -2
@@ -10,14 +10,16 @@ cargo run -p synedrion-ui --bin synedrion
1010
1111 | Module | Contents |
1212 | --- | --- |
13-| `controller` | `ChatController` (profile, channels, agents, sending a message, handling agent events, permissions, the activity of working agents), `Change`, `Sent`, `PendingPermission`, `Activity`, `Attachment`, `CommandSuggestion`, `ChatError` (it also gives the commands an agent announced and the recipients of a message) |
13+| `controller` | `ChatController` (profile, channels, agents, settings, sending a message with the context of the channel, handling agent events, agents calling agents and stopping them all, the tool calls and plans, permissions, the activity of working agents), `Change`, `Sent`, `PendingPermission`, `Activity`, `Attachment`, `CommandSuggestion`, `ChatError` (it also gives the commands an agent announced and the recipients of a message). Its parts are private submodules: what each agent is handed, agents calling agents, traces |
1414 | `gateway` | `AgentGateway`: the part of `AgentHub` the controller needs, as a trait, implemented for `AgentHub` |
1515 | `view` (private) | Draws agent messages as Markdown and the rest as plain text; see `docs/en/reference/message-rendering.md` |
1616 | `files` | `FileIndex`: the files under a folder, searched by words (for `/file`) |
17+| `folders` | `FolderListing`, `starting_folder`: the folders inside a folder, for the folder browser of the agent form |
1718 | `agent_form` | `AgentFormText`, `parse_agent_form`, `form_text_of`, `FormError`: the agent form as pure functions |
1819 | `format` | `clock_utc`, `status_label`, `tail_of` |
1920 | `app` | `SynedrionApp`, the root view, and `Screen`; it re-exports the types of `dock` and `Suggestion` |
2021 | `dock` | `Panel`, `OpenPanels` (which panels are open), the width rules `dock_width_for_pointer` and `dock_width_to_show` with their constants |
2122 | `suggestions` (private) | `Suggestion` (what the list above the message box offers) and the logic of that list and of attached files |
23+| `folder_browser`, `settings_panel`, `trace_view` (private) | The folder browser of the agent form, the settings panel, and the cards of tool calls and plans |
2224
23-The window tests are in `tests/window.rs` and use GPUI Kit's headless test windows. See [how to run the tests](../../docs/en/how-to/run-the-tests.md) and [how to build and run Synedrion](../../docs/en/how-to/build-and-run.md).
25+The window tests are in `tests/` (`window.rs`, `folder_browser.rs`, `settings_and_traces.rs`) and use GPUI Kit's headless test windows; `tests/conversation.rs` tests the controller alone, with a stand-in for the agents. See [how to run the tests](../../docs/en/how-to/run-the-tests.md) and [how to build and run Synedrion](../../docs/en/how-to/build-and-run.md).
@@ -10,14 +10,16 @@ cargo run -p synedrion-ui --bin synedrion
10 10
11 | Module | Contents |11 | Module | Contents |
12 | --- | --- |12 | --- | --- |
13-| `controller` | `ChatController` (profile, channels, agents, sending a message, handling agent events, permissions, the activity of working agents), `Change`, `Sent`, `PendingPermission`, `Activity`, `Attachment`, `CommandSuggestion`, `ChatError` (it also gives the commands an agent announced and the recipients of a message) |13+| `controller` | `ChatController` (profile, channels, agents, settings, sending a message with the context of the channel, handling agent events, agents calling agents and stopping them all, the tool calls and plans, permissions, the activity of working agents), `Change`, `Sent`, `PendingPermission`, `Activity`, `Attachment`, `CommandSuggestion`, `ChatError` (it also gives the commands an agent announced and the recipients of a message). Its parts are private submodules: what each agent is handed, agents calling agents, traces |
14 | `gateway` | `AgentGateway`: the part of `AgentHub` the controller needs, as a trait, implemented for `AgentHub` |14 | `gateway` | `AgentGateway`: the part of `AgentHub` the controller needs, as a trait, implemented for `AgentHub` |
15 | `view` (private) | Draws agent messages as Markdown and the rest as plain text; see `docs/en/reference/message-rendering.md` |15 | `view` (private) | Draws agent messages as Markdown and the rest as plain text; see `docs/en/reference/message-rendering.md` |
16 | `files` | `FileIndex`: the files under a folder, searched by words (for `/file`) |16 | `files` | `FileIndex`: the files under a folder, searched by words (for `/file`) |
17+| `folders` | `FolderListing`, `starting_folder`: the folders inside a folder, for the folder browser of the agent form |
17 | `agent_form` | `AgentFormText`, `parse_agent_form`, `form_text_of`, `FormError`: the agent form as pure functions |18 | `agent_form` | `AgentFormText`, `parse_agent_form`, `form_text_of`, `FormError`: the agent form as pure functions |
18 | `format` | `clock_utc`, `status_label`, `tail_of` |19 | `format` | `clock_utc`, `status_label`, `tail_of` |
19 | `app` | `SynedrionApp`, the root view, and `Screen`; it re-exports the types of `dock` and `Suggestion` |20 | `app` | `SynedrionApp`, the root view, and `Screen`; it re-exports the types of `dock` and `Suggestion` |
20 | `dock` | `Panel`, `OpenPanels` (which panels are open), the width rules `dock_width_for_pointer` and `dock_width_to_show` with their constants |21 | `dock` | `Panel`, `OpenPanels` (which panels are open), the width rules `dock_width_for_pointer` and `dock_width_to_show` with their constants |
21 | `suggestions` (private) | `Suggestion` (what the list above the message box offers) and the logic of that list and of attached files |22 | `suggestions` (private) | `Suggestion` (what the list above the message box offers) and the logic of that list and of attached files |
23+| `folder_browser`, `settings_panel`, `trace_view` (private) | The folder browser of the agent form, the settings panel, and the cards of tool calls and plans |
22 24
23-The window tests are in `tests/window.rs` and use GPUI Kit's headless test windows. See [how to run the tests](../../docs/en/how-to/run-the-tests.md) and [how to build and run Synedrion](../../docs/en/how-to/build-and-run.md).25+The window tests are in `tests/` (`window.rs`, `folder_browser.rs`, `settings_and_traces.rs`) and use GPUI Kit's headless test windows; `tests/conversation.rs` tests the controller alone, with a stand-in for the agents. See [how to run the tests](../../docs/en/how-to/run-the-tests.md) and [how to build and run Synedrion](../../docs/en/how-to/build-and-run.md).
modified crates/ui/src/app.rs +57 -14
@@ -5,6 +5,8 @@
55 use async_channel::Receiver;
66 use gpui_kit::component::input::{InputEvent, InputState, TextareaState};
77 use gpui_kit::component::message_scroller::MessageScrollerState;
8+use std::collections::HashSet;
9+
810 use gpui_kit::{AppContext, Context, Entity, Focusable as _, Pixels, Subscription, Window};
911 use synedrion_acp::events::{AgentEvent, PermissionChoice, PermissionRequestId};
1012 use synedrion_domain::agent::{AgentDeclaration, AgentName};
@@ -16,6 +18,7 @@ use synedrion_domain::user::UserProfile;
1618 use crate::agent_form::{AgentFormText, form_text_of, parse_agent_form};
1719 use crate::controller::{Attachment, Change, ChatController};
1820 use crate::files::FileIndex;
21+use crate::folders::FolderListing;
1922
2023 pub use crate::dock::{
2124 DEFAULT_DOCK_WIDTH, DOCK_BAR_WIDTH, MAX_DOCK_WIDTH, MIN_DOCK_WIDTH, OpenPanels, Panel,
@@ -48,6 +51,12 @@ pub(crate) struct AgentFormFields {
4851 pub working_dir: Entity<InputState>,
4952 }
5053
54+/// The text fields of the settings panel.
55+pub(crate) struct SettingsFields {
56+ pub context_messages: Entity<InputState>,
57+ pub chain_depth: Entity<InputState>,
58+}
59+
5160 /// The root view of the application.
5261 pub struct SynedrionApp {
5362 pub(crate) controller: ChatController,
@@ -61,22 +70,32 @@ pub struct SynedrionApp {
6170 pub(crate) notice: Option<String>,
6271 /// Agents proposed while the user types a mention.
6372 pub(crate) suggestions: Vec<Suggestion>,
64- /// True while the message starts with `/file`: the list then holds files, and an empty list
65- /// means that none matches.
73+ /// The row of the list that Tab takes: the first until the arrows move it.
74+ pub(crate) selected_suggestion: usize,
75+ /// True once the arrows moved the selection, which is when Enter takes the row instead of
76+ /// sending the message.
77+ pub(crate) suggestion_navigated: bool,
78+ /// True while the message starts with `/file` or ends with a `$` being typed: the list then
79+ /// holds files, and an empty list means that none matches.
6680 pub(crate) file_mode: bool,
6781 /// The files listed for `/file`, kept while the user filters them.
6882 pub(crate) file_index: Option<FileIndex>,
6983 /// The files that will be sent with the next message.
7084 pub(crate) attachments: Vec<Attachment>,
85+ /// The folder on show in the browser of the agent form, while it is open.
86+ pub(crate) folder_browser: Option<FolderListing>,
87+ /// The messages of tool calls that are unfolded: the others show their title and status only.
88+ pub(crate) expanded_traces: HashSet<i64>,
7189 pub(crate) profile_input: Entity<InputState>,
7290 pub(crate) new_channel_input: Entity<InputState>,
7391 pub(crate) composer: Entity<TextareaState>,
7492 pub(crate) scroller: Entity<MessageScrollerState>,
7593 pub(crate) agent_form: AgentFormFields,
94+ pub(crate) settings_form: SettingsFields,
7695 pub(crate) panels: OpenPanels,
7796 pub(crate) dock_width: Pixels,
78- /// Keeps the Tab interceptor alive: it is removed when this is dropped.
79- _tab_completion: Subscription,
97+ /// Keeps the key interceptor of the suggestion list alive: it is removed when this is dropped.
98+ _list_keys: Subscription,
8099 }
81100
82101 impl SynedrionApp {
@@ -112,6 +131,10 @@ impl SynedrionApp {
112131 working_dir: cx
113132 .new(|cx| InputState::new(window, cx).placeholder("Working folder (optional)")),
114133 };
134+ let settings_form = SettingsFields {
135+ context_messages: cx.new(|cx| InputState::new(window, cx).placeholder("Messages")),
136+ chain_depth: cx.new(|cx| InputState::new(window, cx).placeholder("Agents in a row")),
137+ };
115138 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
116139
117140 cx.subscribe_in(
@@ -128,17 +151,27 @@ impl SynedrionApp {
128151 )
129152 .detach();
130153
131- // Tab is bound to indentation in the text field, and key bindings are resolved before
132- // any key listener of an element, so only an interceptor can take it first.
154+ // Tab is bound to indentation in the text field, and the arrows and Enter to moving the
155+ // cursor and sending, and key bindings are resolved before any key listener of an element,
156+ // so only an interceptor can take these keys first.
133157 let this = cx.weak_entity();
134- let tab_completion = cx.intercept_keystrokes(move |event, window, cx| {
135- let plain_tab = event.keystroke.key == "tab" && !event.keystroke.modifiers.shift;
136- if !plain_tab {
158+ let list_keys = cx.intercept_keystrokes(move |event, window, cx| {
159+ let keystroke = &event.keystroke;
160+ if !matches!(
161+ keystroke.key.as_str(),
162+ "tab" | "up" | "down" | "enter" | "escape"
163+ ) {
137164 return;
138165 }
139166 this.update(cx, |app, cx| {
140167 if app.composer.read(cx).focus_handle(cx).is_focused(window)
141- && app.complete_with_first_suggestion(window, cx)
168+ && app.handle_list_key(
169+ &keystroke.key,
170+ keystroke.modifiers.modified(),
171+ keystroke.modifiers.shift,
172+ window,
173+ cx,
174+ )
142175 {
143176 cx.stop_propagation();
144177 }
@@ -156,19 +189,25 @@ impl SynedrionApp {
156189 agents: Vec::new(),
157190 notice: None,
158191 suggestions: Vec::new(),
192+ selected_suggestion: 0,
193+ suggestion_navigated: false,
159194 file_mode: false,
160195 file_index: None,
161196 attachments: Vec::new(),
197+ folder_browser: None,
198+ expanded_traces: HashSet::new(),
162199 profile_input,
163200 new_channel_input,
164201 composer,
165202 scroller,
166203 agent_form,
204+ settings_form,
167205 panels: OpenPanels::default(),
168206 dock_width: DEFAULT_DOCK_WIDTH,
169- _tab_completion: tab_completion,
207+ _list_keys: list_keys,
170208 };
171209 app.load(cx);
210+ app.fill_settings_form(window, cx);
172211 app.listen_to_agents(events, cx);
173212 app
174213 }
@@ -233,6 +272,12 @@ impl SynedrionApp {
233272 self.scroller.read(cx).item_count()
234273 }
235274
275+ /// The sentence shown to the user about what just happened or went wrong, if any. Public so
276+ /// that tests can read it.
277+ pub fn notice(&self) -> Option<&str> {
278+ self.notice.as_deref()
279+ }
280+
236281 /// How many messages of the active channel are loaded in the window.
237282 pub fn messages_loaded(&self) -> usize {
238283 self.messages.len()
@@ -401,9 +446,7 @@ impl SynedrionApp {
401446 let Some(channel) = self.active_channel else {
402447 return;
403448 };
404- for agent in self.controller.agents_working_in(channel) {
405- self.controller.cancel_turn(&agent, channel);
406- }
449+ self.controller.stop_all(channel);
407450 cx.notify();
408451 }
409452
@@ -5,6 +5,8 @@
5 use async_channel::Receiver;5 use async_channel::Receiver;
6 use gpui_kit::component::input::{InputEvent, InputState, TextareaState};6 use gpui_kit::component::input::{InputEvent, InputState, TextareaState};
7 use gpui_kit::component::message_scroller::MessageScrollerState;7 use gpui_kit::component::message_scroller::MessageScrollerState;
8+use std::collections::HashSet;
9+
8 use gpui_kit::{AppContext, Context, Entity, Focusable as _, Pixels, Subscription, Window};10 use gpui_kit::{AppContext, Context, Entity, Focusable as _, Pixels, Subscription, Window};
9 use synedrion_acp::events::{AgentEvent, PermissionChoice, PermissionRequestId};11 use synedrion_acp::events::{AgentEvent, PermissionChoice, PermissionRequestId};
10 use synedrion_domain::agent::{AgentDeclaration, AgentName};12 use synedrion_domain::agent::{AgentDeclaration, AgentName};
@@ -16,6 +18,7 @@ use synedrion_domain::user::UserProfile;
16 use crate::agent_form::{AgentFormText, form_text_of, parse_agent_form};18 use crate::agent_form::{AgentFormText, form_text_of, parse_agent_form};
17 use crate::controller::{Attachment, Change, ChatController};19 use crate::controller::{Attachment, Change, ChatController};
18 use crate::files::FileIndex;20 use crate::files::FileIndex;
21+use crate::folders::FolderListing;
19 22
20 pub use crate::dock::{23 pub use crate::dock::{
21 DEFAULT_DOCK_WIDTH, DOCK_BAR_WIDTH, MAX_DOCK_WIDTH, MIN_DOCK_WIDTH, OpenPanels, Panel,24 DEFAULT_DOCK_WIDTH, DOCK_BAR_WIDTH, MAX_DOCK_WIDTH, MIN_DOCK_WIDTH, OpenPanels, Panel,
@@ -48,6 +51,12 @@ pub(crate) struct AgentFormFields {
48 pub working_dir: Entity<InputState>,51 pub working_dir: Entity<InputState>,
49 }52 }
50 53
54+/// The text fields of the settings panel.
55+pub(crate) struct SettingsFields {
56+ pub context_messages: Entity<InputState>,
57+ pub chain_depth: Entity<InputState>,
58+}
59+
51 /// The root view of the application.60 /// The root view of the application.
52 pub struct SynedrionApp {61 pub struct SynedrionApp {
53 pub(crate) controller: ChatController,62 pub(crate) controller: ChatController,
@@ -61,22 +70,32 @@ pub struct SynedrionApp {
61 pub(crate) notice: Option<String>,70 pub(crate) notice: Option<String>,
62 /// Agents proposed while the user types a mention.71 /// Agents proposed while the user types a mention.
63 pub(crate) suggestions: Vec<Suggestion>,72 pub(crate) suggestions: Vec<Suggestion>,
64- /// True while the message starts with `/file`: the list then holds files, and an empty list73+ /// The row of the list that Tab takes: the first until the arrows move it.
65- /// means that none matches.74+ pub(crate) selected_suggestion: usize,
75+ /// True once the arrows moved the selection, which is when Enter takes the row instead of
76+ /// sending the message.
77+ pub(crate) suggestion_navigated: bool,
78+ /// True while the message starts with `/file` or ends with a `$` being typed: the list then
79+ /// holds files, and an empty list means that none matches.
66 pub(crate) file_mode: bool,80 pub(crate) file_mode: bool,
67 /// The files listed for `/file`, kept while the user filters them.81 /// The files listed for `/file`, kept while the user filters them.
68 pub(crate) file_index: Option<FileIndex>,82 pub(crate) file_index: Option<FileIndex>,
69 /// The files that will be sent with the next message.83 /// The files that will be sent with the next message.
70 pub(crate) attachments: Vec<Attachment>,84 pub(crate) attachments: Vec<Attachment>,
85+ /// The folder on show in the browser of the agent form, while it is open.
86+ pub(crate) folder_browser: Option<FolderListing>,
87+ /// The messages of tool calls that are unfolded: the others show their title and status only.
88+ pub(crate) expanded_traces: HashSet<i64>,
71 pub(crate) profile_input: Entity<InputState>,89 pub(crate) profile_input: Entity<InputState>,
72 pub(crate) new_channel_input: Entity<InputState>,90 pub(crate) new_channel_input: Entity<InputState>,
73 pub(crate) composer: Entity<TextareaState>,91 pub(crate) composer: Entity<TextareaState>,
74 pub(crate) scroller: Entity<MessageScrollerState>,92 pub(crate) scroller: Entity<MessageScrollerState>,
75 pub(crate) agent_form: AgentFormFields,93 pub(crate) agent_form: AgentFormFields,
94+ pub(crate) settings_form: SettingsFields,
76 pub(crate) panels: OpenPanels,95 pub(crate) panels: OpenPanels,
77 pub(crate) dock_width: Pixels,96 pub(crate) dock_width: Pixels,
78- /// Keeps the Tab interceptor alive: it is removed when this is dropped.97+ /// Keeps the key interceptor of the suggestion list alive: it is removed when this is dropped.
79- _tab_completion: Subscription,98+ _list_keys: Subscription,
80 }99 }
81 100
82 impl SynedrionApp {101 impl SynedrionApp {
@@ -112,6 +131,10 @@ impl SynedrionApp {
112 working_dir: cx131 working_dir: cx
113 .new(|cx| InputState::new(window, cx).placeholder("Working folder (optional)")),132 .new(|cx| InputState::new(window, cx).placeholder("Working folder (optional)")),
114 };133 };
134+ let settings_form = SettingsFields {
135+ context_messages: cx.new(|cx| InputState::new(window, cx).placeholder("Messages")),
136+ chain_depth: cx.new(|cx| InputState::new(window, cx).placeholder("Agents in a row")),
137+ };
115 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));138 let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
116 139
117 cx.subscribe_in(140 cx.subscribe_in(
@@ -128,17 +151,27 @@ impl SynedrionApp {
128 )151 )
129 .detach();152 .detach();
130 153
131- // Tab is bound to indentation in the text field, and key bindings are resolved before154+ // Tab is bound to indentation in the text field, and the arrows and Enter to moving the
132- // any key listener of an element, so only an interceptor can take it first.155+ // cursor and sending, and key bindings are resolved before any key listener of an element,
156+ // so only an interceptor can take these keys first.
133 let this = cx.weak_entity();157 let this = cx.weak_entity();
134- let tab_completion = cx.intercept_keystrokes(move |event, window, cx| {158+ let list_keys = cx.intercept_keystrokes(move |event, window, cx| {
135- let plain_tab = event.keystroke.key == "tab" && !event.keystroke.modifiers.shift;159+ let keystroke = &event.keystroke;
136- if !plain_tab {160+ if !matches!(
161+ keystroke.key.as_str(),
162+ "tab" | "up" | "down" | "enter" | "escape"
163+ ) {
137 return;164 return;
138 }165 }
139 this.update(cx, |app, cx| {166 this.update(cx, |app, cx| {
140 if app.composer.read(cx).focus_handle(cx).is_focused(window)167 if app.composer.read(cx).focus_handle(cx).is_focused(window)
141- && app.complete_with_first_suggestion(window, cx)168+ && app.handle_list_key(
169+ &keystroke.key,
170+ keystroke.modifiers.modified(),
171+ keystroke.modifiers.shift,
172+ window,
173+ cx,
174+ )
142 {175 {
143 cx.stop_propagation();176 cx.stop_propagation();
144 }177 }
@@ -156,19 +189,25 @@ impl SynedrionApp {
156 agents: Vec::new(),189 agents: Vec::new(),
157 notice: None,190 notice: None,
158 suggestions: Vec::new(),191 suggestions: Vec::new(),
192+ selected_suggestion: 0,
193+ suggestion_navigated: false,
159 file_mode: false,194 file_mode: false,
160 file_index: None,195 file_index: None,
161 attachments: Vec::new(),196 attachments: Vec::new(),
197+ folder_browser: None,
198+ expanded_traces: HashSet::new(),
162 profile_input,199 profile_input,
163 new_channel_input,200 new_channel_input,
164 composer,201 composer,
165 scroller,202 scroller,
166 agent_form,203 agent_form,
204+ settings_form,
167 panels: OpenPanels::default(),205 panels: OpenPanels::default(),
168 dock_width: DEFAULT_DOCK_WIDTH,206 dock_width: DEFAULT_DOCK_WIDTH,
169- _tab_completion: tab_completion,207+ _list_keys: list_keys,
170 };208 };
171 app.load(cx);209 app.load(cx);
210+ app.fill_settings_form(window, cx);
172 app.listen_to_agents(events, cx);211 app.listen_to_agents(events, cx);
173 app212 app
174 }213 }
@@ -233,6 +272,12 @@ impl SynedrionApp {
233 self.scroller.read(cx).item_count()272 self.scroller.read(cx).item_count()
234 }273 }
235 274
275+ /// The sentence shown to the user about what just happened or went wrong, if any. Public so
276+ /// that tests can read it.
277+ pub fn notice(&self) -> Option<&str> {
278+ self.notice.as_deref()
279+ }
280+
236 /// How many messages of the active channel are loaded in the window.281 /// How many messages of the active channel are loaded in the window.
237 pub fn messages_loaded(&self) -> usize {282 pub fn messages_loaded(&self) -> usize {
238 self.messages.len()283 self.messages.len()
@@ -401,9 +446,7 @@ impl SynedrionApp {
401 let Some(channel) = self.active_channel else {446 let Some(channel) = self.active_channel else {
402 return;447 return;
403 };448 };
404- for agent in self.controller.agents_working_in(channel) {449+ self.controller.stop_all(channel);
405- self.controller.cancel_turn(&agent, channel);
406- }
407 cx.notify();450 cx.notify();
408 }451 }
409 452
modified crates/ui/src/controller.rs +130 -54
@@ -3,7 +3,7 @@
33 //! The controller is the only place that knows both the database and the agents. The
44 //! windows call it, and it tells them what changed so they can redraw.
55
6-use std::collections::HashMap;
6+use std::collections::{HashMap, HashSet};
77 use std::fmt;
88 use std::path::PathBuf;
99 use std::sync::Arc;
@@ -13,15 +13,23 @@ use synedrion_acp::events::{
1313 };
1414 use synedrion_domain::agent::{AgentDeclaration, AgentName, AgentStatus};
1515 use synedrion_domain::channel::{Channel, ChannelId, ChannelName};
16-use synedrion_domain::command::{FILE_COMMAND, parse_slash, trailing_command_prefix};
16+use synedrion_domain::command::{FILE_COMMAND, trailing_command_prefix};
1717 use synedrion_domain::error::ValidationError;
1818 use synedrion_domain::mention::{extract_mentions, follow_up_recipients, resolve_mentions};
1919 use synedrion_domain::message::{Author, Message, MessageId, NewMessage};
2020 use synedrion_domain::repository::{Repository, RepositoryError};
21+use synedrion_domain::settings::ChatSettings;
22+use synedrion_domain::trace::ToolCallTrace;
2123 use synedrion_domain::user::{DisplayName, UserProfile};
2224
2325 use crate::gateway::AgentGateway;
2426
27+mod prompts;
28+mod relay;
29+mod traces;
30+
31+use prompts::Handover;
32+
2533 /// Why an action of the user was refused.
2634 #[derive(Debug, Clone, PartialEq, Eq)]
2735 pub enum ChatError {
@@ -128,6 +136,17 @@ struct Streaming {
128136 text: String,
129137 }
130138
139+/// What an agent has said during a turn. It is needed when the turn ends, to see whom the agent
140+/// called.
141+#[derive(Default)]
142+struct Turn {
143+ /// The first message the turn left in the channel, whatever it is: the context of an agent
144+ /// that is called stops right before it.
145+ first_message: Option<MessageId>,
146+ /// All the text of the answer, with its pieces put end to end.
147+ text: String,
148+}
149+
131150 /// The key of an answer being written: which agent, in which channel.
132151 type TurnKey = (String, ChannelId);
133152
@@ -142,15 +161,17 @@ fn recipients_of(text: &str, declared: &[AgentName], earlier: &[Message]) -> Vec
142161 }
143162 }
144163
145-/// The text of a message as stored: what the user typed, then one line per attached file.
164+/// The text of a message as stored: what the user typed, then one line per attached file that the
165+/// text does not already name (a file picked with `$` is written in the sentence).
146166 fn with_attachment_lines(text: &str, attachments: &[Attachment]) -> String {
147- if attachments.is_empty() {
148- return text.to_string();
149- }
150167 let lines: Vec<String> = attachments
151168 .iter()
169+ .filter(|attachment| !text.contains(&attachment.label))
152170 .map(|attachment| format!("[attached: {}]", attachment.label))
153171 .collect();
172+ if lines.is_empty() {
173+ return text.to_string();
174+ }
154175 format!("{text}\n\n{}", lines.join("\n"))
155176 }
156177
@@ -184,6 +205,20 @@ pub struct ChatController {
184205 /// The slash commands each agent announced, by agent.
185206 commands: HashMap<String, Vec<AgentCommand>>,
186207 pending_permissions: Vec<PendingPermission>,
208+ settings: ChatSettings,
209+ /// The last message of the channel that each agent was handed, so that it is never told the
210+ /// same thing twice.
211+ seen: HashMap<TurnKey, MessageId>,
212+ /// How many agents called one another to bring each running turn about: `0` for a turn the
213+ /// user started.
214+ depth: HashMap<TurnKey, usize>,
215+ /// The turns the user asked to stop. Their answer, if it still comes, calls nobody.
216+ stop_requested: HashSet<TurnKey>,
217+ turns: HashMap<TurnKey, Turn>,
218+ /// The tool calls of the running turns, with the message that shows each.
219+ tools: HashMap<(TurnKey, String), (MessageId, ToolCallTrace)>,
220+ /// The message that shows the plan of each running turn.
221+ plans: HashMap<TurnKey, MessageId>,
187222 }
188223
189224 impl ChatController {
@@ -211,12 +246,34 @@ impl ChatController {
211246 reasoning: HashMap::new(),
212247 commands: HashMap::new(),
213248 pending_permissions: Vec::new(),
249+ settings: ChatSettings::default(),
250+ seen: HashMap::new(),
251+ depth: HashMap::new(),
252+ stop_requested: HashSet::new(),
253+ turns: HashMap::new(),
254+ tools: HashMap::new(),
255+ plans: HashMap::new(),
214256 }
215257 }
216258
217- /// Prepares the database for use: makes sure there is a channel to talk in.
218- pub fn start(&self) -> Result<(), ChatError> {
219- Ok(self.repository.ensure_default_channel()?)
259+ /// Prepares the database for use: makes sure there is a channel to talk in, and reads the
260+ /// settings.
261+ pub fn start(&mut self) -> Result<(), ChatError> {
262+ self.repository.ensure_default_channel()?;
263+ self.settings = self.repository.load_settings()?;
264+ Ok(())
265+ }
266+
267+ /// The settings in force.
268+ pub fn settings(&self) -> ChatSettings {
269+ self.settings
270+ }
271+
272+ /// Stores new settings, which apply from the next message.
273+ pub fn save_settings(&mut self, settings: ChatSettings) -> Result<(), ChatError> {
274+ self.repository.save_settings(&settings)?;
275+ self.settings = settings;
276+ Ok(())
220277 }
221278
222279 /// The user's profile, or `None` the first time the application starts.
@@ -316,6 +373,7 @@ impl ChatController {
316373 Author::User,
317374 &with_attachment_lines(text, attachments),
318375 )?;
376+ let user_name = self.user_name()?;
319377
320378 let declarations = self.repository.list_agents()?;
321379 let names: Vec<AgentName> = declarations
@@ -335,20 +393,15 @@ impl ChatController {
335393 else {
336394 continue;
337395 };
338- let prompt = self.prompt_for(agent, text);
339- match self
340- .agents
341- .send_prompt(declaration, channel, &prompt, &files)
342- {
343- Ok(()) => {
344- self.working
345- .insert(turn_key(agent, channel), (agent.clone(), channel));
346- addressed.push(agent.clone());
347- }
348- Err(reason) => {
349- let notice = format!("Could not reach @{agent}: {reason}");
350- self.post(channel, Author::System, &notice)?;
351- }
396+ let prompt = self.prompt_for(agent, channel, text, &earlier, &user_name);
397+ let handover = Handover {
398+ prompt: &prompt,
399+ files: &files,
400+ depth: 0,
401+ up_to: message.id,
402+ };
403+ if self.deliver(declaration, channel, handover)? {
404+ addressed.push(agent.clone());
352405 }
353406 }
354407 Ok(Sent {
@@ -358,26 +411,6 @@ impl ChatController {
358411 })
359412 }
360413
361- /// What an agent receives for `text`: the bare command when the message is a command it
362- /// understands, the message as typed otherwise.
363- fn prompt_for(&self, agent: &AgentName, text: &str) -> String {
364- match parse_slash(text) {
365- Some(command) if self.understands(agent, command.name) => command.text.to_string(),
366- _ => text.to_string(),
367- }
368- }
369-
370- /// True when the agent announced the command, or announced no command at all yet (the
371- /// announcement comes with its first session, so the first message cannot wait for it).
372- fn understands(&self, agent: &AgentName, name: &str) -> bool {
373- match self.commands.get(&turn_key(agent, ChannelId(0)).0) {
374- Some(commands) if !commands.is_empty() => {
375- commands.iter().any(|command| command.name == name)
376- }
377- _ => true,
378- }
379- }
380-
381414 /// The agents a message typed in this channel would go to: the ones it mentions, or the ones
382415 /// the user addressed last when it mentions nobody.
383416 pub fn recipients_for(
@@ -485,11 +518,6 @@ impl ChatController {
485518 .collect()
486519 }
487520
488- /// Interrupts the agent's turn in this channel.
489- pub fn cancel_turn(&self, agent: &AgentName, channel: ChannelId) {
490- self.agents.cancel_turn(agent, channel);
491- }
492-
493521 /// The questions that agents asked and the user has not answered yet.
494522 pub fn pending_permissions(&self) -> &[PendingPermission] {
495523 &self.pending_permissions
@@ -504,6 +532,9 @@ impl ChatController {
504532
505533 /// Takes into account something an agent did, and says what the windows must redraw.
506534 pub fn handle_event(&mut self, event: AgentEvent) -> Vec<Change> {
535+ if let Some(changes) = self.handle_trace_event(&event) {
536+ return changes;
537+ }
507538 match event {
508539 AgentEvent::StatusChanged { agent, .. } => vec![Change::AgentStatus(agent)],
509540 AgentEvent::Text {
@@ -549,6 +580,11 @@ impl ChatController {
549580 .retain(|pending| pending.request.id != id);
550581 vec![Change::Permissions]
551582 }
583+ // Handled by `handle_trace_event`, which comes first.
584+ AgentEvent::ToolCall { .. }
585+ | AgentEvent::ToolCallUpdated { .. }
586+ | AgentEvent::Plan { .. }
587+ | AgentEvent::Notice { .. } => Vec::new(),
552588 }
553589 }
554590
@@ -560,6 +596,11 @@ impl ChatController {
560596 chunk: &str,
561597 ) -> Vec<Change> {
562598 let key = turn_key(agent, channel);
599+ self.turns
600+ .entry(key.clone())
601+ .or_default()
602+ .text
603+ .push_str(chunk);
563604 let result = match self.streaming.get_mut(&key) {
564605 Some(answer) => {
565606 answer.text.push_str(chunk);
@@ -571,6 +612,11 @@ impl ChatController {
571612 None => self
572613 .post(channel, Author::Agent(agent.clone()), chunk)
573614 .map(|message| {
615+ self.turns
616+ .entry(key.clone())
617+ .or_default()
618+ .first_message
619+ .get_or_insert(message.id);
574620 self.streaming.insert(
575621 key,
576622 Streaming {
@@ -595,9 +641,15 @@ impl ChatController {
595641 channel: ChannelId,
596642 outcome: &TurnOutcome,
597643 ) -> Vec<Change> {
598- self.streaming.remove(&turn_key(agent, channel));
599- self.working.remove(&turn_key(agent, channel));
600- self.reasoning.remove(&turn_key(agent, channel));
644+ let key = turn_key(agent, channel);
645+ self.streaming.remove(&key);
646+ self.working.remove(&key);
647+ self.reasoning.remove(&key);
648+ self.tools.retain(|(turn, _), _| *turn != key);
649+ self.plans.remove(&key);
650+ let turn = self.turns.remove(&key);
651+ let depth = self.depth.remove(&key).unwrap_or(0);
652+ let stopped = self.stop_requested.remove(&key);
601653 self.pending_permissions
602654 .retain(|pending| !(pending.agent == *agent && pending.channel == channel));
603655
@@ -609,6 +661,12 @@ impl ChatController {
609661 Err(error) => changes.push(Change::Problem(error.to_string())),
610662 }
611663 }
664+ if outcome.is_normal()
665+ && !stopped
666+ && let Some(turn) = turn
667+ {
668+ changes.extend(self.relay_answer(agent, channel, depth, &turn));
669+ }
612670 changes
613671 }
614672
@@ -706,7 +764,7 @@ mod tests {
706764 let repository = Arc::new(SqliteRepository::open_in_memory().unwrap());
707765 let agents = Arc::new(FakeAgents::default());
708766 let ticks = AtomicI64::new(0);
709- let controller = ChatController::with_clock(
767+ let mut controller = ChatController::with_clock(
710768 repository.clone(),
711769 agents.clone(),
712770 Box::new(move || ticks.fetch_add(1, Ordering::SeqCst)),
@@ -743,7 +801,7 @@ mod tests {
743801
744802 #[test]
745803 fn starting_creates_the_default_channel_once() {
746- let fixture = fixture();
804+ let mut fixture = fixture();
747805 fixture.controller.start().unwrap();
748806 assert_eq!(fixture.controller.channels().unwrap().len(), 1);
749807 }
@@ -1711,6 +1769,24 @@ mod tests {
17111769 );
17121770 }
17131771
1772+ #[test]
1773+ fn a_file_named_in_the_sentence_is_not_listed_again_in_the_stored_message() {
1774+ let mut fixture = fixture();
1775+ declare(&fixture, "bob");
1776+ fixture
1777+ .controller
1778+ .send_user_message_with_files(
1779+ fixture.channel,
1780+ "@bob read a.txt now",
1781+ &[attachment("a.txt"), attachment("b.txt")],
1782+ )
1783+ .unwrap();
1784+ assert_eq!(
1785+ contents(&fixture),
1786+ vec!["@bob read a.txt now\n\n[attached: b.txt]"]
1787+ );
1788+ }
1789+
17141790 #[test]
17151791 fn a_message_without_files_hands_over_no_file() {
17161792 let mut fixture = fixture();
@@ -1766,7 +1842,7 @@ mod tests {
17661842
17671843 #[test]
17681844 fn cancelling_goes_to_the_agent() {
1769- let fixture = fixture();
1845+ let mut fixture = fixture();
17701846 fixture
17711847 .controller
17721848 .cancel_turn(&name("bob"), fixture.channel);
@@ -3,7 +3,7 @@
3 //! The controller is the only place that knows both the database and the agents. The3 //! The controller is the only place that knows both the database and the agents. The
4 //! windows call it, and it tells them what changed so they can redraw.4 //! windows call it, and it tells them what changed so they can redraw.
5 5
6-use std::collections::HashMap;6+use std::collections::{HashMap, HashSet};
7 use std::fmt;7 use std::fmt;
8 use std::path::PathBuf;8 use std::path::PathBuf;
9 use std::sync::Arc;9 use std::sync::Arc;
@@ -13,15 +13,23 @@ use synedrion_acp::events::{
13 };13 };
14 use synedrion_domain::agent::{AgentDeclaration, AgentName, AgentStatus};14 use synedrion_domain::agent::{AgentDeclaration, AgentName, AgentStatus};
15 use synedrion_domain::channel::{Channel, ChannelId, ChannelName};15 use synedrion_domain::channel::{Channel, ChannelId, ChannelName};
16-use synedrion_domain::command::{FILE_COMMAND, parse_slash, trailing_command_prefix};16+use synedrion_domain::command::{FILE_COMMAND, trailing_command_prefix};
17 use synedrion_domain::error::ValidationError;17 use synedrion_domain::error::ValidationError;
18 use synedrion_domain::mention::{extract_mentions, follow_up_recipients, resolve_mentions};18 use synedrion_domain::mention::{extract_mentions, follow_up_recipients, resolve_mentions};
19 use synedrion_domain::message::{Author, Message, MessageId, NewMessage};19 use synedrion_domain::message::{Author, Message, MessageId, NewMessage};
20 use synedrion_domain::repository::{Repository, RepositoryError};20 use synedrion_domain::repository::{Repository, RepositoryError};
21+use synedrion_domain::settings::ChatSettings;
22+use synedrion_domain::trace::ToolCallTrace;
21 use synedrion_domain::user::{DisplayName, UserProfile};23 use synedrion_domain::user::{DisplayName, UserProfile};
22 24
23 use crate::gateway::AgentGateway;25 use crate::gateway::AgentGateway;
24 26
27+mod prompts;
28+mod relay;
29+mod traces;
30+
31+use prompts::Handover;
32+
25 /// Why an action of the user was refused.33 /// Why an action of the user was refused.
26 #[derive(Debug, Clone, PartialEq, Eq)]34 #[derive(Debug, Clone, PartialEq, Eq)]
27 pub enum ChatError {35 pub enum ChatError {
@@ -128,6 +136,17 @@ struct Streaming {
128 text: String,136 text: String,
129 }137 }
130 138
139+/// What an agent has said during a turn. It is needed when the turn ends, to see whom the agent
140+/// called.
141+#[derive(Default)]
142+struct Turn {
143+ /// The first message the turn left in the channel, whatever it is: the context of an agent
144+ /// that is called stops right before it.
145+ first_message: Option<MessageId>,
146+ /// All the text of the answer, with its pieces put end to end.
147+ text: String,
148+}
149+
131 /// The key of an answer being written: which agent, in which channel.150 /// The key of an answer being written: which agent, in which channel.
132 type TurnKey = (String, ChannelId);151 type TurnKey = (String, ChannelId);
133 152
@@ -142,15 +161,17 @@ fn recipients_of(text: &str, declared: &[AgentName], earlier: &[Message]) -> Vec
142 }161 }
143 }162 }
144 163
145-/// The text of a message as stored: what the user typed, then one line per attached file.164+/// The text of a message as stored: what the user typed, then one line per attached file that the
165+/// text does not already name (a file picked with `$` is written in the sentence).
146 fn with_attachment_lines(text: &str, attachments: &[Attachment]) -> String {166 fn with_attachment_lines(text: &str, attachments: &[Attachment]) -> String {
147- if attachments.is_empty() {
148- return text.to_string();
149- }
150 let lines: Vec<String> = attachments167 let lines: Vec<String> = attachments
151 .iter()168 .iter()
169+ .filter(|attachment| !text.contains(&attachment.label))
152 .map(|attachment| format!("[attached: {}]", attachment.label))170 .map(|attachment| format!("[attached: {}]", attachment.label))
153 .collect();171 .collect();
172+ if lines.is_empty() {
173+ return text.to_string();
174+ }
154 format!("{text}\n\n{}", lines.join("\n"))175 format!("{text}\n\n{}", lines.join("\n"))
155 }176 }
156 177
@@ -184,6 +205,20 @@ pub struct ChatController {
184 /// The slash commands each agent announced, by agent.205 /// The slash commands each agent announced, by agent.
185 commands: HashMap<String, Vec<AgentCommand>>,206 commands: HashMap<String, Vec<AgentCommand>>,
186 pending_permissions: Vec<PendingPermission>,207 pending_permissions: Vec<PendingPermission>,
208+ settings: ChatSettings,
209+ /// The last message of the channel that each agent was handed, so that it is never told the
210+ /// same thing twice.
211+ seen: HashMap<TurnKey, MessageId>,
212+ /// How many agents called one another to bring each running turn about: `0` for a turn the
213+ /// user started.
214+ depth: HashMap<TurnKey, usize>,
215+ /// The turns the user asked to stop. Their answer, if it still comes, calls nobody.
216+ stop_requested: HashSet<TurnKey>,
217+ turns: HashMap<TurnKey, Turn>,
218+ /// The tool calls of the running turns, with the message that shows each.
219+ tools: HashMap<(TurnKey, String), (MessageId, ToolCallTrace)>,
220+ /// The message that shows the plan of each running turn.
221+ plans: HashMap<TurnKey, MessageId>,
187 }222 }
188 223
189 impl ChatController {224 impl ChatController {
@@ -211,12 +246,34 @@ impl ChatController {
211 reasoning: HashMap::new(),246 reasoning: HashMap::new(),
212 commands: HashMap::new(),247 commands: HashMap::new(),
213 pending_permissions: Vec::new(),248 pending_permissions: Vec::new(),
249+ settings: ChatSettings::default(),
250+ seen: HashMap::new(),
251+ depth: HashMap::new(),
252+ stop_requested: HashSet::new(),
253+ turns: HashMap::new(),
254+ tools: HashMap::new(),
255+ plans: HashMap::new(),
214 }256 }
215 }257 }
216 258
217- /// Prepares the database for use: makes sure there is a channel to talk in.259+ /// Prepares the database for use: makes sure there is a channel to talk in, and reads the
218- pub fn start(&self) -> Result<(), ChatError> {260+ /// settings.
219- Ok(self.repository.ensure_default_channel()?)261+ pub fn start(&mut self) -> Result<(), ChatError> {
262+ self.repository.ensure_default_channel()?;
263+ self.settings = self.repository.load_settings()?;
264+ Ok(())
265+ }
266+
267+ /// The settings in force.
268+ pub fn settings(&self) -> ChatSettings {
269+ self.settings
270+ }
271+
272+ /// Stores new settings, which apply from the next message.
273+ pub fn save_settings(&mut self, settings: ChatSettings) -> Result<(), ChatError> {
274+ self.repository.save_settings(&settings)?;
275+ self.settings = settings;
276+ Ok(())
220 }277 }
221 278
222 /// The user's profile, or `None` the first time the application starts.279 /// The user's profile, or `None` the first time the application starts.
@@ -316,6 +373,7 @@ impl ChatController {
316 Author::User,373 Author::User,
317 &with_attachment_lines(text, attachments),374 &with_attachment_lines(text, attachments),
318 )?;375 )?;
376+ let user_name = self.user_name()?;
319 377
320 let declarations = self.repository.list_agents()?;378 let declarations = self.repository.list_agents()?;
321 let names: Vec<AgentName> = declarations379 let names: Vec<AgentName> = declarations
@@ -335,20 +393,15 @@ impl ChatController {
335 else {393 else {
336 continue;394 continue;
337 };395 };
338- let prompt = self.prompt_for(agent, text);396+ let prompt = self.prompt_for(agent, channel, text, &earlier, &user_name);
339- match self397+ let handover = Handover {
340- .agents398+ prompt: &prompt,
341- .send_prompt(declaration, channel, &prompt, &files)399+ files: &files,
342- {400+ depth: 0,
343- Ok(()) => {401+ up_to: message.id,
344- self.working402+ };
345- .insert(turn_key(agent, channel), (agent.clone(), channel));403+ if self.deliver(declaration, channel, handover)? {
346- addressed.push(agent.clone());404+ addressed.push(agent.clone());
347- }
348- Err(reason) => {
349- let notice = format!("Could not reach @{agent}: {reason}");
350- self.post(channel, Author::System, &notice)?;
351- }
352 }405 }
353 }406 }
354 Ok(Sent {407 Ok(Sent {
@@ -358,26 +411,6 @@ impl ChatController {
358 })411 })
359 }412 }
360 413
361- /// What an agent receives for `text`: the bare command when the message is a command it
362- /// understands, the message as typed otherwise.
363- fn prompt_for(&self, agent: &AgentName, text: &str) -> String {
364- match parse_slash(text) {
365- Some(command) if self.understands(agent, command.name) => command.text.to_string(),
366- _ => text.to_string(),
367- }
368- }
369-
370- /// True when the agent announced the command, or announced no command at all yet (the
371- /// announcement comes with its first session, so the first message cannot wait for it).
372- fn understands(&self, agent: &AgentName, name: &str) -> bool {
373- match self.commands.get(&turn_key(agent, ChannelId(0)).0) {
374- Some(commands) if !commands.is_empty() => {
375- commands.iter().any(|command| command.name == name)
376- }
377- _ => true,
378- }
379- }
380-
381 /// The agents a message typed in this channel would go to: the ones it mentions, or the ones414 /// The agents a message typed in this channel would go to: the ones it mentions, or the ones
382 /// the user addressed last when it mentions nobody.415 /// the user addressed last when it mentions nobody.
383 pub fn recipients_for(416 pub fn recipients_for(
@@ -485,11 +518,6 @@ impl ChatController {
485 .collect()518 .collect()
486 }519 }
487 520
488- /// Interrupts the agent's turn in this channel.
489- pub fn cancel_turn(&self, agent: &AgentName, channel: ChannelId) {
490- self.agents.cancel_turn(agent, channel);
491- }
492-
493 /// The questions that agents asked and the user has not answered yet.521 /// The questions that agents asked and the user has not answered yet.
494 pub fn pending_permissions(&self) -> &[PendingPermission] {522 pub fn pending_permissions(&self) -> &[PendingPermission] {
495 &self.pending_permissions523 &self.pending_permissions
@@ -504,6 +532,9 @@ impl ChatController {
504 532
505 /// Takes into account something an agent did, and says what the windows must redraw.533 /// Takes into account something an agent did, and says what the windows must redraw.
506 pub fn handle_event(&mut self, event: AgentEvent) -> Vec<Change> {534 pub fn handle_event(&mut self, event: AgentEvent) -> Vec<Change> {
535+ if let Some(changes) = self.handle_trace_event(&event) {
536+ return changes;
537+ }
507 match event {538 match event {
508 AgentEvent::StatusChanged { agent, .. } => vec![Change::AgentStatus(agent)],539 AgentEvent::StatusChanged { agent, .. } => vec![Change::AgentStatus(agent)],
509 AgentEvent::Text {540 AgentEvent::Text {
@@ -549,6 +580,11 @@ impl ChatController {
549 .retain(|pending| pending.request.id != id);580 .retain(|pending| pending.request.id != id);
550 vec![Change::Permissions]581 vec![Change::Permissions]
551 }582 }
583+ // Handled by `handle_trace_event`, which comes first.
584+ AgentEvent::ToolCall { .. }
585+ | AgentEvent::ToolCallUpdated { .. }
586+ | AgentEvent::Plan { .. }
587+ | AgentEvent::Notice { .. } => Vec::new(),
552 }588 }
553 }589 }
554 590
@@ -560,6 +596,11 @@ impl ChatController {
560 chunk: &str,596 chunk: &str,
561 ) -> Vec<Change> {597 ) -> Vec<Change> {
562 let key = turn_key(agent, channel);598 let key = turn_key(agent, channel);
599+ self.turns
600+ .entry(key.clone())
601+ .or_default()
602+ .text
603+ .push_str(chunk);
563 let result = match self.streaming.get_mut(&key) {604 let result = match self.streaming.get_mut(&key) {
564 Some(answer) => {605 Some(answer) => {
565 answer.text.push_str(chunk);606 answer.text.push_str(chunk);
@@ -571,6 +612,11 @@ impl ChatController {
571 None => self612 None => self
572 .post(channel, Author::Agent(agent.clone()), chunk)613 .post(channel, Author::Agent(agent.clone()), chunk)
573 .map(|message| {614 .map(|message| {
615+ self.turns
616+ .entry(key.clone())
617+ .or_default()
618+ .first_message
619+ .get_or_insert(message.id);
574 self.streaming.insert(620 self.streaming.insert(
575 key,621 key,
576 Streaming {622 Streaming {
@@ -595,9 +641,15 @@ impl ChatController {
595 channel: ChannelId,641 channel: ChannelId,
596 outcome: &TurnOutcome,642 outcome: &TurnOutcome,
597 ) -> Vec<Change> {643 ) -> Vec<Change> {
598- self.streaming.remove(&turn_key(agent, channel));644+ let key = turn_key(agent, channel);
599- self.working.remove(&turn_key(agent, channel));645+ self.streaming.remove(&key);
600- self.reasoning.remove(&turn_key(agent, channel));646+ self.working.remove(&key);
647+ self.reasoning.remove(&key);
648+ self.tools.retain(|(turn, _), _| *turn != key);
649+ self.plans.remove(&key);
650+ let turn = self.turns.remove(&key);
651+ let depth = self.depth.remove(&key).unwrap_or(0);
652+ let stopped = self.stop_requested.remove(&key);
601 self.pending_permissions653 self.pending_permissions
602 .retain(|pending| !(pending.agent == *agent && pending.channel == channel));654 .retain(|pending| !(pending.agent == *agent && pending.channel == channel));
603 655
@@ -609,6 +661,12 @@ impl ChatController {
609 Err(error) => changes.push(Change::Problem(error.to_string())),661 Err(error) => changes.push(Change::Problem(error.to_string())),
610 }662 }
611 }663 }
664+ if outcome.is_normal()
665+ && !stopped
666+ && let Some(turn) = turn
667+ {
668+ changes.extend(self.relay_answer(agent, channel, depth, &turn));
669+ }
612 changes670 changes
613 }671 }
614 672
@@ -706,7 +764,7 @@ mod tests {
706 let repository = Arc::new(SqliteRepository::open_in_memory().unwrap());764 let repository = Arc::new(SqliteRepository::open_in_memory().unwrap());
707 let agents = Arc::new(FakeAgents::default());765 let agents = Arc::new(FakeAgents::default());
708 let ticks = AtomicI64::new(0);766 let ticks = AtomicI64::new(0);
709- let controller = ChatController::with_clock(767+ let mut controller = ChatController::with_clock(
710 repository.clone(),768 repository.clone(),
711 agents.clone(),769 agents.clone(),
712 Box::new(move || ticks.fetch_add(1, Ordering::SeqCst)),770 Box::new(move || ticks.fetch_add(1, Ordering::SeqCst)),
@@ -743,7 +801,7 @@ mod tests {
743 801
744 #[test]802 #[test]
745 fn starting_creates_the_default_channel_once() {803 fn starting_creates_the_default_channel_once() {
746- let fixture = fixture();804+ let mut fixture = fixture();
747 fixture.controller.start().unwrap();805 fixture.controller.start().unwrap();
748 assert_eq!(fixture.controller.channels().unwrap().len(), 1);806 assert_eq!(fixture.controller.channels().unwrap().len(), 1);
749 }807 }
@@ -1711,6 +1769,24 @@ mod tests {
1711 );1769 );
1712 }1770 }
1713 1771
1772+ #[test]
1773+ fn a_file_named_in_the_sentence_is_not_listed_again_in_the_stored_message() {
1774+ let mut fixture = fixture();
1775+ declare(&fixture, "bob");
1776+ fixture
1777+ .controller
1778+ .send_user_message_with_files(
1779+ fixture.channel,
1780+ "@bob read a.txt now",
1781+ &[attachment("a.txt"), attachment("b.txt")],
1782+ )
1783+ .unwrap();
1784+ assert_eq!(
1785+ contents(&fixture),
1786+ vec!["@bob read a.txt now\n\n[attached: b.txt]"]
1787+ );
1788+ }
1789+
1714 #[test]1790 #[test]
1715 fn a_message_without_files_hands_over_no_file() {1791 fn a_message_without_files_hands_over_no_file() {
1716 let mut fixture = fixture();1792 let mut fixture = fixture();
@@ -1766,7 +1842,7 @@ mod tests {
1766 1842
1767 #[test]1843 #[test]
1768 fn cancelling_goes_to_the_agent() {1844 fn cancelling_goes_to_the_agent() {
1769- let fixture = fixture();1845+ let mut fixture = fixture();
1770 fixture1846 fixture
1771 .controller1847 .controller
1772 .cancel_turn(&name("bob"), fixture.channel);1848 .cancel_turn(&name("bob"), fixture.channel);
added crates/ui/src/controller/prompts.rs +120 -0
new file mode 100644
@@ -0,0 +1,120 @@
1+//! What each agent is handed: the message, preceded by what it has not seen of the channel, or a
2+//! bare slash command.
3+
4+use std::path::PathBuf;
5+
6+use synedrion_domain::agent::{AgentDeclaration, AgentName};
7+use synedrion_domain::channel::ChannelId;
8+use synedrion_domain::command::parse_slash;
9+use synedrion_domain::context::{Context, render_prompt, select_context};
10+use synedrion_domain::message::{Author, Message, MessageId};
11+
12+use super::{ChatController, ChatError, turn_key};
13+
14+/// What is handed to an agent, and where in the conversation that puts it.
15+pub(super) struct Handover<'a> {
16+ pub prompt: &'a str,
17+ /// Files that go with the prompt.
18+ pub files: &'a [PathBuf],
19+ /// How many agents called one another to bring this about: `0` for the user's own message.
20+ pub depth: usize,
21+ /// The last message of the channel that the agent is told about by this prompt.
22+ pub up_to: MessageId,
23+}
24+
25+impl ChatController {
26+ /// What an agent receives for the user's `text`: the bare command when the message is a
27+ /// command it understands (an agent recognises a command only at the very start, so no
28+ /// context goes in front of it); otherwise the message, preceded by what was said in the
29+ /// channel since the agent's last turn.
30+ ///
31+ /// `earlier` are the messages of the channel before this one.
32+ pub(super) fn prompt_for(
33+ &self,
34+ agent: &AgentName,
35+ channel: ChannelId,
36+ text: &str,
37+ earlier: &[Message],
38+ user_name: &str,
39+ ) -> String {
40+ if let Some(command) = parse_slash(text)
41+ && self.understands(agent, command.name)
42+ {
43+ return command.text.to_string();
44+ }
45+ let context = self.context_for(agent, channel, earlier, user_name);
46+ render_prompt(&context, None, text)
47+ }
48+
49+ /// What `agent` has not seen of `earlier`, within the limits of the settings.
50+ pub(super) fn context_for(
51+ &self,
52+ agent: &AgentName,
53+ channel: ChannelId,
54+ earlier: &[Message],
55+ user_name: &str,
56+ ) -> Context {
57+ let seen = self.seen.get(&turn_key(agent, channel)).copied();
58+ select_context(
59+ earlier,
60+ agent,
61+ seen,
62+ user_name,
63+ self.settings.context_messages,
64+ )
65+ }
66+
67+ /// True when the agent announced the command, or announced no command at all yet (the
68+ /// announcement comes with its first session, so the first message cannot wait for it).
69+ fn understands(&self, agent: &AgentName, name: &str) -> bool {
70+ match self.commands.get(&turn_key(agent, ChannelId(0)).0) {
71+ Some(commands) if !commands.is_empty() => {
72+ commands.iter().any(|command| command.name == name)
73+ }
74+ _ => true,
75+ }
76+ }
77+
78+ /// Hands the prompt to the agent. When it is handed over, the agent is marked as working, at
79+ /// the depth of the handover, and it counts as having seen the channel up to the message the
80+ /// handover names. When the agent cannot be reached, a system message says so and `false`
81+ /// comes back.
82+ pub(super) fn deliver(
83+ &mut self,
84+ declaration: &AgentDeclaration,
85+ channel: ChannelId,
86+ handover: Handover<'_>,
87+ ) -> Result<bool, ChatError> {
88+ let agent = &declaration.name;
89+ let Handover {
90+ prompt,
91+ files,
92+ depth,
93+ up_to,
94+ } = handover;
95+ match self.agents.send_prompt(declaration, channel, prompt, files) {
96+ Ok(()) => {
97+ let key = turn_key(agent, channel);
98+ self.working.insert(key.clone(), (agent.clone(), channel));
99+ self.depth.insert(key.clone(), depth);
100+ self.stop_requested.remove(&key);
101+ self.seen.insert(key, up_to);
102+ Ok(true)
103+ }
104+ Err(reason) => {
105+ let notice = format!("Could not reach @{agent}: {reason}");
106+ self.post(channel, Author::System, &notice)?;
107+ Ok(false)
108+ }
109+ }
110+ }
111+
112+ /// How the user's own messages are signed in the context given to agents.
113+ pub(super) fn user_name(&self) -> Result<String, ChatError> {
114+ Ok(self
115+ .repository
116+ .load_user()?
117+ .map(|profile| profile.display_name.as_str().to_string())
118+ .unwrap_or_else(|| "user".to_string()))
119+ }
120+}
new file mode 100644
@@ -0,0 +1,120 @@
1+//! What each agent is handed: the message, preceded by what it has not seen of the channel, or a
2+//! bare slash command.
3+
4+use std::path::PathBuf;
5+
6+use synedrion_domain::agent::{AgentDeclaration, AgentName};
7+use synedrion_domain::channel::ChannelId;
8+use synedrion_domain::command::parse_slash;
9+use synedrion_domain::context::{Context, render_prompt, select_context};
10+use synedrion_domain::message::{Author, Message, MessageId};
11+
12+use super::{ChatController, ChatError, turn_key};
13+
14+/// What is handed to an agent, and where in the conversation that puts it.
15+pub(super) struct Handover<'a> {
16+ pub prompt: &'a str,
17+ /// Files that go with the prompt.
18+ pub files: &'a [PathBuf],
19+ /// How many agents called one another to bring this about: `0` for the user's own message.
20+ pub depth: usize,
21+ /// The last message of the channel that the agent is told about by this prompt.
22+ pub up_to: MessageId,
23+}
24+
25+impl ChatController {
26+ /// What an agent receives for the user's `text`: the bare command when the message is a
27+ /// command it understands (an agent recognises a command only at the very start, so no
28+ /// context goes in front of it); otherwise the message, preceded by what was said in the
29+ /// channel since the agent's last turn.
30+ ///
31+ /// `earlier` are the messages of the channel before this one.
32+ pub(super) fn prompt_for(
33+ &self,
34+ agent: &AgentName,
35+ channel: ChannelId,
36+ text: &str,
37+ earlier: &[Message],
38+ user_name: &str,
39+ ) -> String {
40+ if let Some(command) = parse_slash(text)
41+ && self.understands(agent, command.name)
42+ {
43+ return command.text.to_string();
44+ }
45+ let context = self.context_for(agent, channel, earlier, user_name);
46+ render_prompt(&context, None, text)
47+ }
48+
49+ /// What `agent` has not seen of `earlier`, within the limits of the settings.
50+ pub(super) fn context_for(
51+ &self,
52+ agent: &AgentName,
53+ channel: ChannelId,
54+ earlier: &[Message],
55+ user_name: &str,
56+ ) -> Context {
57+ let seen = self.seen.get(&turn_key(agent, channel)).copied();
58+ select_context(
59+ earlier,
60+ agent,
61+ seen,
62+ user_name,
63+ self.settings.context_messages,
64+ )
65+ }
66+
67+ /// True when the agent announced the command, or announced no command at all yet (the
68+ /// announcement comes with its first session, so the first message cannot wait for it).
69+ fn understands(&self, agent: &AgentName, name: &str) -> bool {
70+ match self.commands.get(&turn_key(agent, ChannelId(0)).0) {
71+ Some(commands) if !commands.is_empty() => {
72+ commands.iter().any(|command| command.name == name)
73+ }
74+ _ => true,
75+ }
76+ }
77+
78+ /// Hands the prompt to the agent. When it is handed over, the agent is marked as working, at
79+ /// the depth of the handover, and it counts as having seen the channel up to the message the
80+ /// handover names. When the agent cannot be reached, a system message says so and `false`
81+ /// comes back.
82+ pub(super) fn deliver(
83+ &mut self,
84+ declaration: &AgentDeclaration,
85+ channel: ChannelId,
86+ handover: Handover<'_>,
87+ ) -> Result<bool, ChatError> {
88+ let agent = &declaration.name;
89+ let Handover {
90+ prompt,
91+ files,
92+ depth,
93+ up_to,
94+ } = handover;
95+ match self.agents.send_prompt(declaration, channel, prompt, files) {
96+ Ok(()) => {
97+ let key = turn_key(agent, channel);
98+ self.working.insert(key.clone(), (agent.clone(), channel));
99+ self.depth.insert(key.clone(), depth);
100+ self.stop_requested.remove(&key);
101+ self.seen.insert(key, up_to);
102+ Ok(true)
103+ }
104+ Err(reason) => {
105+ let notice = format!("Could not reach @{agent}: {reason}");
106+ self.post(channel, Author::System, &notice)?;
107+ Ok(false)
108+ }
109+ }
110+ }
111+
112+ /// How the user's own messages are signed in the context given to agents.
113+ pub(super) fn user_name(&self) -> Result<String, ChatError> {
114+ Ok(self
115+ .repository
116+ .load_user()?
117+ .map(|profile| profile.display_name.as_str().to_string())
118+ .unwrap_or_else(|| "user".to_string()))
119+ }
120+}
added crates/ui/src/controller/relay.rs +120 -0
new file mode 100644
@@ -0,0 +1,120 @@
1+//! Agents calling agents: when an answer mentions another agent, that agent is handed the
2+//! answer, within the limits that keep a conversation between agents from running away.
3+//!
4+//! The limit is the chain depth of the settings: the user's message starts a chain, the agent it
5+//! calls is at depth 0, the agent that one calls is at depth 1, and so on. A call that would go
6+//! beyond the limit is not made, and a message of the application in the channel says so.
7+//! The user can stop the whole chain at any time.
8+
9+use synedrion_domain::agent::AgentName;
10+use synedrion_domain::channel::ChannelId;
11+use synedrion_domain::context::render_prompt;
12+use synedrion_domain::mention::resolve_mentions;
13+use synedrion_domain::message::Author;
14+
15+use super::prompts::Handover;
16+use super::{Change, ChatController, FOLLOW_UP_LOOKBACK, Turn, turn_key};
17+
18+impl ChatController {
19+ /// Asks every agent to stop what it does in this channel, and makes sure that the answers
20+ /// still on their way call nobody: stopping one agent must not let its answer start another.
21+ pub fn stop_all(&mut self, channel: ChannelId) {
22+ for agent in self.agents_working_in(channel) {
23+ self.cancel_turn(&agent, channel);
24+ }
25+ }
26+
27+ /// Interrupts the agent's turn in this channel. Its answer, if one still comes, calls nobody.
28+ pub fn cancel_turn(&mut self, agent: &AgentName, channel: ChannelId) {
29+ self.stop_requested.insert(turn_key(agent, channel));
30+ self.agents.cancel_turn(agent, channel);
31+ }
32+
33+ /// Hands the answer of `agent` to the agents it mentions, one hop further in the chain.
34+ /// `depth` is the depth of the turn that ended.
35+ pub(super) fn relay_answer(
36+ &mut self,
37+ agent: &AgentName,
38+ channel: ChannelId,
39+ depth: usize,
40+ turn: &Turn,
41+ ) -> Vec<Change> {
42+ let Some(first_message) = turn.first_message else {
43+ return Vec::new();
44+ };
45+ if self.settings.chain_depth == 0 {
46+ return Vec::new();
47+ }
48+ match self.try_relay(agent, channel, depth, first_message, &turn.text) {
49+ Ok(changes) => changes,
50+ Err(error) => vec![Change::Problem(format!(
51+ "Could not hand @{agent}'s answer on: {error}"
52+ ))],
53+ }
54+ }
55+
56+ fn try_relay(
57+ &mut self,
58+ agent: &AgentName,
59+ channel: ChannelId,
60+ depth: usize,
61+ first_message: synedrion_domain::message::MessageId,
62+ answer: &str,
63+ ) -> Result<Vec<Change>, super::ChatError> {
64+ let declarations = self.repository.list_agents()?;
65+ let names: Vec<AgentName> = declarations.iter().map(|d| d.name.clone()).collect();
66+ let mut called: Vec<AgentName> = Vec::new();
67+ for target in resolve_mentions(answer, &names).agents {
68+ let is_self = agent.matches(target.as_str());
69+ if !is_self && !called.contains(&target) {
70+ called.push(target);
71+ }
72+ }
73+ if called.is_empty() {
74+ return Ok(Vec::new());
75+ }
76+
77+ if depth + 1 > self.settings.chain_depth {
78+ let who: Vec<String> = called.iter().map(|name| format!("@{name}")).collect();
79+ let notice = format!(
80+ "Chain stopped: @{agent} called {}, but the limit of {} agent(s) calling one \
81+ another in a row is reached. The limit is in the settings.",
82+ who.join(", "),
83+ self.settings.chain_depth
84+ );
85+ self.post(channel, Author::System, &notice)?;
86+ return Ok(vec![Change::Messages(channel)]);
87+ }
88+
89+ let everything = self
90+ .repository
91+ .recent_messages(channel, FOLLOW_UP_LOOKBACK)?;
92+ let Some(last) = everything.last().map(|message| message.id) else {
93+ return Ok(Vec::new());
94+ };
95+ // What the agent said in this turn is handed over as the message itself, so the context
96+ // stops right before it.
97+ let before_turn = everything
98+ .iter()
99+ .position(|message| message.id == first_message)
100+ .unwrap_or(everything.len());
101+ let earlier = &everything[..before_turn];
102+ let user_name = self.user_name()?;
103+
104+ for target in &called {
105+ let Some(declaration) = declarations.iter().find(|d| d.name == *target) else {
106+ continue;
107+ };
108+ let context = self.context_for(target, channel, earlier, &user_name);
109+ let prompt = render_prompt(&context, Some(agent.as_str()), answer);
110+ let handover = Handover {
111+ prompt: &prompt,
112+ files: &[],
113+ depth: depth + 1,
114+ up_to: last,
115+ };
116+ self.deliver(declaration, channel, handover)?;
117+ }
118+ Ok(vec![Change::Messages(channel)])
119+ }
120+}
new file mode 100644
@@ -0,0 +1,120 @@
1+//! Agents calling agents: when an answer mentions another agent, that agent is handed the
2+//! answer, within the limits that keep a conversation between agents from running away.
3+//!
4+//! The limit is the chain depth of the settings: the user's message starts a chain, the agent it
5+//! calls is at depth 0, the agent that one calls is at depth 1, and so on. A call that would go
6+//! beyond the limit is not made, and a message of the application in the channel says so.
7+//! The user can stop the whole chain at any time.
8+
9+use synedrion_domain::agent::AgentName;
10+use synedrion_domain::channel::ChannelId;
11+use synedrion_domain::context::render_prompt;
12+use synedrion_domain::mention::resolve_mentions;
13+use synedrion_domain::message::Author;
14+
15+use super::prompts::Handover;
16+use super::{Change, ChatController, FOLLOW_UP_LOOKBACK, Turn, turn_key};
17+
18+impl ChatController {
19+ /// Asks every agent to stop what it does in this channel, and makes sure that the answers
20+ /// still on their way call nobody: stopping one agent must not let its answer start another.
21+ pub fn stop_all(&mut self, channel: ChannelId) {
22+ for agent in self.agents_working_in(channel) {
23+ self.cancel_turn(&agent, channel);
24+ }
25+ }
26+
27+ /// Interrupts the agent's turn in this channel. Its answer, if one still comes, calls nobody.
28+ pub fn cancel_turn(&mut self, agent: &AgentName, channel: ChannelId) {
29+ self.stop_requested.insert(turn_key(agent, channel));
30+ self.agents.cancel_turn(agent, channel);
31+ }
32+
33+ /// Hands the answer of `agent` to the agents it mentions, one hop further in the chain.
34+ /// `depth` is the depth of the turn that ended.
35+ pub(super) fn relay_answer(
36+ &mut self,
37+ agent: &AgentName,
38+ channel: ChannelId,
39+ depth: usize,
40+ turn: &Turn,
41+ ) -> Vec<Change> {
42+ let Some(first_message) = turn.first_message else {
43+ return Vec::new();
44+ };
45+ if self.settings.chain_depth == 0 {
46+ return Vec::new();
47+ }
48+ match self.try_relay(agent, channel, depth, first_message, &turn.text) {
49+ Ok(changes) => changes,
50+ Err(error) => vec![Change::Problem(format!(
51+ "Could not hand @{agent}'s answer on: {error}"
52+ ))],
53+ }
54+ }
55+
56+ fn try_relay(
57+ &mut self,
58+ agent: &AgentName,
59+ channel: ChannelId,
60+ depth: usize,
61+ first_message: synedrion_domain::message::MessageId,
62+ answer: &str,
63+ ) -> Result<Vec<Change>, super::ChatError> {
64+ let declarations = self.repository.list_agents()?;
65+ let names: Vec<AgentName> = declarations.iter().map(|d| d.name.clone()).collect();
66+ let mut called: Vec<AgentName> = Vec::new();
67+ for target in resolve_mentions(answer, &names).agents {
68+ let is_self = agent.matches(target.as_str());
69+ if !is_self && !called.contains(&target) {
70+ called.push(target);
71+ }
72+ }
73+ if called.is_empty() {
74+ return Ok(Vec::new());
75+ }
76+
77+ if depth + 1 > self.settings.chain_depth {
78+ let who: Vec<String> = called.iter().map(|name| format!("@{name}")).collect();
79+ let notice = format!(
80+ "Chain stopped: @{agent} called {}, but the limit of {} agent(s) calling one \
81+ another in a row is reached. The limit is in the settings.",
82+ who.join(", "),
83+ self.settings.chain_depth
84+ );
85+ self.post(channel, Author::System, &notice)?;
86+ return Ok(vec![Change::Messages(channel)]);
87+ }
88+
89+ let everything = self
90+ .repository
91+ .recent_messages(channel, FOLLOW_UP_LOOKBACK)?;
92+ let Some(last) = everything.last().map(|message| message.id) else {
93+ return Ok(Vec::new());
94+ };
95+ // What the agent said in this turn is handed over as the message itself, so the context
96+ // stops right before it.
97+ let before_turn = everything
98+ .iter()
99+ .position(|message| message.id == first_message)
100+ .unwrap_or(everything.len());
101+ let earlier = &everything[..before_turn];
102+ let user_name = self.user_name()?;
103+
104+ for target in &called {
105+ let Some(declaration) = declarations.iter().find(|d| d.name == *target) else {
106+ continue;
107+ };
108+ let context = self.context_for(target, channel, earlier, &user_name);
109+ let prompt = render_prompt(&context, Some(agent.as_str()), answer);
110+ let handover = Handover {
111+ prompt: &prompt,
112+ files: &[],
113+ depth: depth + 1,
114+ up_to: last,
115+ };
116+ self.deliver(declaration, channel, handover)?;
117+ }
118+ Ok(vec![Change::Messages(channel)])
119+ }
120+}
added crates/ui/src/controller/traces.rs +162 -0
new file mode 100644
@@ -0,0 +1,162 @@
1+//! What an agent does besides writing: its tool calls and its plan, kept in the channel as
2+//! messages of a trace so that the history shows how an answer came about.
3+
4+use synedrion_acp::events::AgentEvent;
5+use synedrion_domain::agent::AgentName;
6+use synedrion_domain::channel::ChannelId;
7+use synedrion_domain::message::{Author, MessageId};
8+use synedrion_domain::trace::{PlanStep, ToolCallChange, ToolCallTrace, Trace};
9+
10+use super::{Change, ChatController, turn_key};
11+
12+impl ChatController {
13+ /// Takes into account an event about what an agent does besides writing. Returns `None` for
14+ /// any other kind of event.
15+ pub(super) fn handle_trace_event(&mut self, event: &AgentEvent) -> Option<Vec<Change>> {
16+ let changes = match event {
17+ AgentEvent::ToolCall {
18+ agent,
19+ channel,
20+ call,
21+ } => self.show_tool_call(agent, *channel, call.clone()),
22+ AgentEvent::ToolCallUpdated {
23+ agent,
24+ channel,
25+ id,
26+ change,
27+ } => self.update_tool_call(agent, *channel, id, change),
28+ AgentEvent::Plan {
29+ agent,
30+ channel,
31+ steps,
32+ } => self.show_plan(agent, *channel, steps.clone()),
33+ AgentEvent::Notice {
34+ agent,
35+ channel,
36+ text,
37+ } => self.show_notice(agent, *channel, text),
38+ _ => return None,
39+ };
40+ Some(changes)
41+ }
42+
43+ fn show_tool_call(
44+ &mut self,
45+ agent: &AgentName,
46+ channel: ChannelId,
47+ call: ToolCallTrace,
48+ ) -> Vec<Change> {
49+ let key = (turn_key(agent, channel), call.id.clone());
50+ let text = Trace::ToolCall(call.clone()).to_text();
51+ let result = match self.tools.get(&key) {
52+ // The agent announced it again: the message is the same call, brought up to date.
53+ Some((message, _)) => self
54+ .repository
55+ .update_message_content(*message, &text)
56+ .map(|()| *message)
57+ .map_err(Into::into),
58+ None => self.post_trace(agent, channel, &text),
59+ };
60+ self.after_trace(agent, channel, result.map(|message| (key, message, call)))
61+ }
62+
63+ fn update_tool_call(
64+ &mut self,
65+ agent: &AgentName,
66+ channel: ChannelId,
67+ id: &str,
68+ change: &ToolCallChange,
69+ ) -> Vec<Change> {
70+ let key = (turn_key(agent, channel), id.to_string());
71+ let mut call = match self.tools.get(&key) {
72+ Some((_, call)) => call.clone(),
73+ None => ToolCallTrace::unannounced(id),
74+ };
75+ change.apply(&mut call);
76+ let text = Trace::ToolCall(call.clone()).to_text();
77+ let result = match self.tools.get(&key) {
78+ Some((message, _)) => self
79+ .repository
80+ .update_message_content(*message, &text)
81+ .map(|()| *message)
82+ .map_err(Into::into),
83+ None => self.post_trace(agent, channel, &text),
84+ };
85+ self.after_trace(agent, channel, result.map(|message| (key, message, call)))
86+ }
87+
88+ fn show_plan(
89+ &mut self,
90+ agent: &AgentName,
91+ channel: ChannelId,
92+ steps: Vec<PlanStep>,
93+ ) -> Vec<Change> {
94+ let key = turn_key(agent, channel);
95+ let text = Trace::Plan(steps).to_text();
96+ let result = match self.plans.get(&key) {
97+ Some(message) => self
98+ .repository
99+ .update_message_content(*message, &text)
100+ .map(|()| *message)
101+ .map_err(Into::into),
102+ None => self.post_trace(agent, channel, &text),
103+ };
104+ match result {
105+ Ok(message) => {
106+ self.plans.insert(key.clone(), message);
107+ self.close_answer_segment(&key, message);
108+ vec![Change::Messages(channel)]
109+ }
110+ Err(error) => vec![Change::Problem(format!(
111+ "Could not store @{agent}'s plan: {error}"
112+ ))],
113+ }
114+ }
115+
116+ /// A notice of the agent, shown like the notices of the application, signed with its name.
117+ fn show_notice(&mut self, agent: &AgentName, channel: ChannelId, text: &str) -> Vec<Change> {
118+ match self.post(channel, Author::System, &format!("@{agent}: {text}")) {
119+ Ok(_) => vec![Change::Messages(channel)],
120+ Err(error) => vec![Change::Problem(error.to_string())],
121+ }
122+ }
123+
124+ fn post_trace(
125+ &self,
126+ agent: &AgentName,
127+ channel: ChannelId,
128+ text: &str,
129+ ) -> Result<MessageId, super::ChatError> {
130+ Ok(self.post(channel, Author::Trace(agent.clone()), text)?.id)
131+ }
132+
133+ /// Remembers the message of a tool call, and ends the piece of answer being written: what the
134+ /// agent writes next comes after the trace, as it happened.
135+ fn after_trace(
136+ &mut self,
137+ agent: &AgentName,
138+ channel: ChannelId,
139+ result: Result<((super::TurnKey, String), MessageId, ToolCallTrace), super::ChatError>,
140+ ) -> Vec<Change> {
141+ match result {
142+ Ok((key, message, call)) => {
143+ let turn = key.0.clone();
144+ self.tools.insert(key, (message, call));
145+ self.close_answer_segment(&turn, message);
146+ vec![Change::Messages(channel)]
147+ }
148+ Err(error) => vec![Change::Problem(format!(
149+ "Could not store what @{agent} did: {error}"
150+ ))],
151+ }
152+ }
153+
154+ fn close_answer_segment(&mut self, turn: &super::TurnKey, message: MessageId) {
155+ self.streaming.remove(turn);
156+ self.turns
157+ .entry(turn.clone())
158+ .or_default()
159+ .first_message
160+ .get_or_insert(message);
161+ }
162+}
new file mode 100644
@@ -0,0 +1,162 @@
1+//! What an agent does besides writing: its tool calls and its plan, kept in the channel as
2+//! messages of a trace so that the history shows how an answer came about.
3+
4+use synedrion_acp::events::AgentEvent;
5+use synedrion_domain::agent::AgentName;
6+use synedrion_domain::channel::ChannelId;
7+use synedrion_domain::message::{Author, MessageId};
8+use synedrion_domain::trace::{PlanStep, ToolCallChange, ToolCallTrace, Trace};
9+
10+use super::{Change, ChatController, turn_key};
11+
12+impl ChatController {
13+ /// Takes into account an event about what an agent does besides writing. Returns `None` for
14+ /// any other kind of event.
15+ pub(super) fn handle_trace_event(&mut self, event: &AgentEvent) -> Option<Vec<Change>> {
16+ let changes = match event {
17+ AgentEvent::ToolCall {
18+ agent,
19+ channel,
20+ call,
21+ } => self.show_tool_call(agent, *channel, call.clone()),
22+ AgentEvent::ToolCallUpdated {
23+ agent,
24+ channel,
25+ id,
26+ change,
27+ } => self.update_tool_call(agent, *channel, id, change),
28+ AgentEvent::Plan {
29+ agent,
30+ channel,
31+ steps,
32+ } => self.show_plan(agent, *channel, steps.clone()),
33+ AgentEvent::Notice {
34+ agent,
35+ channel,
36+ text,
37+ } => self.show_notice(agent, *channel, text),
38+ _ => return None,
39+ };
40+ Some(changes)
41+ }
42+
43+ fn show_tool_call(
44+ &mut self,
45+ agent: &AgentName,
46+ channel: ChannelId,
47+ call: ToolCallTrace,
48+ ) -> Vec<Change> {
49+ let key = (turn_key(agent, channel), call.id.clone());
50+ let text = Trace::ToolCall(call.clone()).to_text();
51+ let result = match self.tools.get(&key) {
52+ // The agent announced it again: the message is the same call, brought up to date.
53+ Some((message, _)) => self
54+ .repository
55+ .update_message_content(*message, &text)
56+ .map(|()| *message)
57+ .map_err(Into::into),
58+ None => self.post_trace(agent, channel, &text),
59+ };
60+ self.after_trace(agent, channel, result.map(|message| (key, message, call)))
61+ }
62+
63+ fn update_tool_call(
64+ &mut self,
65+ agent: &AgentName,
66+ channel: ChannelId,
67+ id: &str,
68+ change: &ToolCallChange,
69+ ) -> Vec<Change> {
70+ let key = (turn_key(agent, channel), id.to_string());
71+ let mut call = match self.tools.get(&key) {
72+ Some((_, call)) => call.clone(),
73+ None => ToolCallTrace::unannounced(id),
74+ };
75+ change.apply(&mut call);
76+ let text = Trace::ToolCall(call.clone()).to_text();
77+ let result = match self.tools.get(&key) {
78+ Some((message, _)) => self
79+ .repository
80+ .update_message_content(*message, &text)
81+ .map(|()| *message)
82+ .map_err(Into::into),
83+ None => self.post_trace(agent, channel, &text),
84+ };
85+ self.after_trace(agent, channel, result.map(|message| (key, message, call)))
86+ }
87+
88+ fn show_plan(
89+ &mut self,
90+ agent: &AgentName,
91+ channel: ChannelId,
92+ steps: Vec<PlanStep>,
93+ ) -> Vec<Change> {
94+ let key = turn_key(agent, channel);
95+ let text = Trace::Plan(steps).to_text();
96+ let result = match self.plans.get(&key) {
97+ Some(message) => self
98+ .repository
99+ .update_message_content(*message, &text)
100+ .map(|()| *message)
101+ .map_err(Into::into),
102+ None => self.post_trace(agent, channel, &text),
103+ };
104+ match result {
105+ Ok(message) => {
106+ self.plans.insert(key.clone(), message);
107+ self.close_answer_segment(&key, message);
108+ vec![Change::Messages(channel)]
109+ }
110+ Err(error) => vec![Change::Problem(format!(
111+ "Could not store @{agent}'s plan: {error}"
112+ ))],
113+ }
114+ }
115+
116+ /// A notice of the agent, shown like the notices of the application, signed with its name.
117+ fn show_notice(&mut self, agent: &AgentName, channel: ChannelId, text: &str) -> Vec<Change> {
118+ match self.post(channel, Author::System, &format!("@{agent}: {text}")) {
119+ Ok(_) => vec![Change::Messages(channel)],
120+ Err(error) => vec![Change::Problem(error.to_string())],
121+ }
122+ }
123+
124+ fn post_trace(
125+ &self,
126+ agent: &AgentName,
127+ channel: ChannelId,
128+ text: &str,
129+ ) -> Result<MessageId, super::ChatError> {
130+ Ok(self.post(channel, Author::Trace(agent.clone()), text)?.id)
131+ }
132+
133+ /// Remembers the message of a tool call, and ends the piece of answer being written: what the
134+ /// agent writes next comes after the trace, as it happened.
135+ fn after_trace(
136+ &mut self,
137+ agent: &AgentName,
138+ channel: ChannelId,
139+ result: Result<((super::TurnKey, String), MessageId, ToolCallTrace), super::ChatError>,
140+ ) -> Vec<Change> {
141+ match result {
142+ Ok((key, message, call)) => {
143+ let turn = key.0.clone();
144+ self.tools.insert(key, (message, call));
145+ self.close_answer_segment(&turn, message);
146+ vec![Change::Messages(channel)]
147+ }
148+ Err(error) => vec![Change::Problem(format!(
149+ "Could not store what @{agent} did: {error}"
150+ ))],
151+ }
152+ }
153+
154+ fn close_answer_segment(&mut self, turn: &super::TurnKey, message: MessageId) {
155+ self.streaming.remove(turn);
156+ self.turns
157+ .entry(turn.clone())
158+ .or_default()
159+ .first_message
160+ .get_or_insert(message);
161+ }
162+}
modified crates/ui/src/dock.rs +12 -1
@@ -12,11 +12,18 @@ pub enum Panel {
1212 ChannelSettings,
1313 /// The agents, their status, and the form that declares or edits one.
1414 Agents,
15+ /// How much of the channel an agent is told about, and how far agents may call one another.
16+ Settings,
1517 }
1618
1719 impl Panel {
1820 /// Every panel, in the order of the bar of buttons.
19- pub const ALL: [Panel; 3] = [Panel::Channels, Panel::ChannelSettings, Panel::Agents];
21+ pub const ALL: [Panel; 4] = [
22+ Panel::Channels,
23+ Panel::ChannelSettings,
24+ Panel::Agents,
25+ Panel::Settings,
26+ ];
2027 }
2128
2229 /// Which panels of the dock are open. Several can be open side by side.
@@ -35,6 +42,7 @@ pub struct OpenPanels {
3542 channels: bool,
3643 channel_settings: bool,
3744 agents: bool,
45+ settings: bool,
3846 }
3947
4048 impl Default for OpenPanels {
@@ -44,6 +52,7 @@ impl Default for OpenPanels {
4452 channels: true,
4553 channel_settings: false,
4654 agents: false,
55+ settings: false,
4756 }
4857 }
4958 }
@@ -72,6 +81,7 @@ impl OpenPanels {
7281 Panel::Channels => &self.channels,
7382 Panel::ChannelSettings => &self.channel_settings,
7483 Panel::Agents => &self.agents,
84+ Panel::Settings => &self.settings,
7585 }
7686 }
7787
@@ -80,6 +90,7 @@ impl OpenPanels {
8090 Panel::Channels => &mut self.channels,
8191 Panel::ChannelSettings => &mut self.channel_settings,
8292 Panel::Agents => &mut self.agents,
93+ Panel::Settings => &mut self.settings,
8394 }
8495 }
8596 }
@@ -12,11 +12,18 @@ pub enum Panel {
12 ChannelSettings,12 ChannelSettings,
13 /// The agents, their status, and the form that declares or edits one.13 /// The agents, their status, and the form that declares or edits one.
14 Agents,14 Agents,
15+ /// How much of the channel an agent is told about, and how far agents may call one another.
16+ Settings,
15 }17 }
16 18
17 impl Panel {19 impl Panel {
18 /// Every panel, in the order of the bar of buttons.20 /// Every panel, in the order of the bar of buttons.
19- pub const ALL: [Panel; 3] = [Panel::Channels, Panel::ChannelSettings, Panel::Agents];21+ pub const ALL: [Panel; 4] = [
22+ Panel::Channels,
23+ Panel::ChannelSettings,
24+ Panel::Agents,
25+ Panel::Settings,
26+ ];
20 }27 }
21 28
22 /// Which panels of the dock are open. Several can be open side by side.29 /// Which panels of the dock are open. Several can be open side by side.
@@ -35,6 +42,7 @@ pub struct OpenPanels {
35 channels: bool,42 channels: bool,
36 channel_settings: bool,43 channel_settings: bool,
37 agents: bool,44 agents: bool,
45+ settings: bool,
38 }46 }
39 47
40 impl Default for OpenPanels {48 impl Default for OpenPanels {
@@ -44,6 +52,7 @@ impl Default for OpenPanels {
44 channels: true,52 channels: true,
45 channel_settings: false,53 channel_settings: false,
46 agents: false,54 agents: false,
55+ settings: false,
47 }56 }
48 }57 }
49 }58 }
@@ -72,6 +81,7 @@ impl OpenPanels {
72 Panel::Channels => &self.channels,81 Panel::Channels => &self.channels,
73 Panel::ChannelSettings => &self.channel_settings,82 Panel::ChannelSettings => &self.channel_settings,
74 Panel::Agents => &self.agents,83 Panel::Agents => &self.agents,
84+ Panel::Settings => &self.settings,
75 }85 }
76 }86 }
77 87
@@ -80,6 +90,7 @@ impl OpenPanels {
80 Panel::Channels => &mut self.channels,90 Panel::Channels => &mut self.channels,
81 Panel::ChannelSettings => &mut self.channel_settings,91 Panel::ChannelSettings => &mut self.channel_settings,
82 Panel::Agents => &mut self.agents,92 Panel::Agents => &mut self.agents,
93+ Panel::Settings => &mut self.settings,
83 }94 }
84 }95 }
85 }96 }
added crates/ui/src/folder_browser.rs +199 -0
new file mode 100644
@@ -0,0 +1,199 @@
1+//! The folder browser of the agent form: a list of folders to walk through, in place of typing the
2+//! path of the agent's working folder.
3+//!
4+//! It is drawn by the application itself rather than by a dialog of the operating system, so
5+//! that it looks and behaves the same everywhere and can be tested without a screen.
6+
7+use std::path::PathBuf;
8+
9+use gpui_kit::assets::IconName;
10+use gpui_kit::component::button::{Button, ButtonVariants as _};
11+use gpui_kit::component::{ActiveTheme as _, Icon, Sizable as _, h_flex, v_flex};
12+use gpui_kit::{
13+ AnyElement, Context, SharedString, TestSupportExt as _, Window, div, prelude::*, px,
14+};
15+
16+use crate::app::SynedrionApp;
17+use crate::folders::{FolderListing, starting_folder};
18+
19+impl SynedrionApp {
20+ /// Opens the browser on the folder typed in the field, or on a sensible one.
21+ pub(crate) fn open_folder_browser(&mut self, cx: &mut Context<Self>) {
22+ let typed = self.agent_form.working_dir.read(cx).value().to_string();
23+ self.folder_browser = Some(FolderListing::of(&starting_folder(&typed)));
24+ cx.notify();
25+ }
26+
27+ /// Shows the content of another folder.
28+ pub(crate) fn browse_to(&mut self, path: PathBuf, cx: &mut Context<Self>) {
29+ self.folder_browser = Some(FolderListing::of(&path));
30+ cx.notify();
31+ }
32+
33+ /// Puts the folder on show in the working folder field and closes the browser.
34+ pub(crate) fn choose_browsed_folder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
35+ if let Some(listing) = self.folder_browser.take() {
36+ let path = listing.path.to_string_lossy().into_owned();
37+ self.agent_form
38+ .working_dir
39+ .update(cx, |input, cx| input.set_value(path, window, cx));
40+ }
41+ cx.notify();
42+ }
43+
44+ /// The text of the working folder field of the agent form. Public so that tests can read it.
45+ pub fn working_folder_text(&self, cx: &gpui_kit::App) -> String {
46+ self.agent_form.working_dir.read(cx).value().to_string()
47+ }
48+
49+ /// The folder on show in the browser, `None` while it is closed. Public for the tests.
50+ pub fn browsed_folder(&self) -> Option<&std::path::Path> {
51+ self.folder_browser
52+ .as_ref()
53+ .map(|listing| listing.path.as_path())
54+ }
55+
56+ pub(crate) fn close_folder_browser(&mut self, cx: &mut Context<Self>) {
57+ self.folder_browser = None;
58+ cx.notify();
59+ }
60+
61+ /// The button that opens the browser, and the browser itself while it is open.
62+ pub(crate) fn render_folder_browser(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
63+ let Some(listing) = &self.folder_browser else {
64+ return vec![
65+ Button::new("browse-folders")
66+ .label("Browse\u{2026}")
67+ .compact()
68+ .outline()
69+ .on_click(cx.listener(|this, _, _, cx| this.open_folder_browser(cx)))
70+ .into_any_element(),
71+ ];
72+ };
73+ let border = cx.theme().border;
74+ let muted = cx.theme().muted_foreground;
75+ let hover = cx.theme().list_hover;
76+
77+ let up = listing.parent().map(|parent| {
78+ folder_row(
79+ "folder-up",
80+ "..",
81+ IconName::ArrowUp,
82+ hover,
83+ cx.listener(move |this, _, _, cx| this.browse_to(parent.clone(), cx)),
84+ )
85+ });
86+ let rows = listing.folders.iter().enumerate().map(|(index, name)| {
87+ let path = listing.child(name);
88+ folder_row(
89+ SharedString::from(format!("folder-row-{index}")),
90+ name,
91+ IconName::Folder,
92+ hover,
93+ cx.listener(move |this, _, _, cx| this.browse_to(path.clone(), cx)),
94+ )
95+ });
96+
97+ let list = v_flex()
98+ .id("folder-list")
99+ .test_support()
100+ .max_h(px(220.))
101+ .overflow_y_scroll()
102+ .children(up)
103+ .children(rows)
104+ .when(listing.folders.is_empty(), |list| {
105+ list.child(
106+ div()
107+ .id("no-folders")
108+ .test_support()
109+ .px_2()
110+ .py_1()
111+ .text_xs()
112+ .text_color(muted)
113+ .child("No folder inside this one."),
114+ )
115+ })
116+ .when(listing.truncated, |list| {
117+ list.child(
118+ div()
119+ .id("folders-truncated")
120+ .test_support()
121+ .px_2()
122+ .py_1()
123+ .text_xs()
124+ .text_color(muted)
125+ .child("Only the first folders are listed. Type the path to go further."),
126+ )
127+ });
128+
129+ vec![
130+ v_flex()
131+ .id("folder-browser")
132+ .test_support()
133+ .gap_1()
134+ .p_1()
135+ .border_1()
136+ .border_color(border)
137+ .rounded_md()
138+ .child(
139+ div()
140+ .id("folder-browser-path")
141+ .test_support()
142+ .px_2()
143+ .text_xs()
144+ .text_color(muted)
145+ .child(listing.path.display().to_string()),
146+ )
147+ .child(list)
148+ .child(
149+ h_flex()
150+ .gap_1()
151+ .child(
152+ Button::new("folder-choose")
153+ .label("Use this folder")
154+ .compact()
155+ .primary()
156+ .on_click(cx.listener(|this, _, window, cx| {
157+ this.choose_browsed_folder(window, cx)
158+ })),
159+ )
160+ .child(
161+ Button::new("folder-cancel")
162+ .label("Cancel")
163+ .compact()
164+ .outline()
165+ .on_click(
166+ cx.listener(|this, _, _, cx| this.close_folder_browser(cx)),
167+ ),
168+ ),
169+ )
170+ .into_any_element(),
171+ ]
172+ }
173+}
174+
175+/// One row of the list of folders: an icon and a name, with a highlight under the pointer.
176+fn folder_row(
177+ id: impl Into<SharedString>,
178+ name: &str,
179+ icon: IconName,
180+ hover: gpui_kit::Hsla,
181+ on_click: impl Fn(&gpui_kit::ClickEvent, &mut Window, &mut gpui_kit::App) + 'static,
182+) -> AnyElement {
183+ h_flex()
184+ .id(id.into())
185+ .test_support()
186+ .w_full()
187+ .gap_2()
188+ .items_center()
189+ .px_2()
190+ .py_1()
191+ .rounded_md()
192+ .cursor_pointer()
193+ .text_sm()
194+ .hover(move |style| style.bg(hover))
195+ .on_click(on_click)
196+ .child(Icon::new(icon).small())
197+ .child(name.to_string())
198+ .into_any_element()
199+}
new file mode 100644
@@ -0,0 +1,199 @@
1+//! The folder browser of the agent form: a list of folders to walk through, in place of typing the
2+//! path of the agent's working folder.
3+//!
4+//! It is drawn by the application itself rather than by a dialog of the operating system, so
5+//! that it looks and behaves the same everywhere and can be tested without a screen.
6+
7+use std::path::PathBuf;
8+
9+use gpui_kit::assets::IconName;
10+use gpui_kit::component::button::{Button, ButtonVariants as _};
11+use gpui_kit::component::{ActiveTheme as _, Icon, Sizable as _, h_flex, v_flex};
12+use gpui_kit::{
13+ AnyElement, Context, SharedString, TestSupportExt as _, Window, div, prelude::*, px,
14+};
15+
16+use crate::app::SynedrionApp;
17+use crate::folders::{FolderListing, starting_folder};
18+
19+impl SynedrionApp {
20+ /// Opens the browser on the folder typed in the field, or on a sensible one.
21+ pub(crate) fn open_folder_browser(&mut self, cx: &mut Context<Self>) {
22+ let typed = self.agent_form.working_dir.read(cx).value().to_string();
23+ self.folder_browser = Some(FolderListing::of(&starting_folder(&typed)));
24+ cx.notify();
25+ }
26+
27+ /// Shows the content of another folder.
28+ pub(crate) fn browse_to(&mut self, path: PathBuf, cx: &mut Context<Self>) {
29+ self.folder_browser = Some(FolderListing::of(&path));
30+ cx.notify();
31+ }
32+
33+ /// Puts the folder on show in the working folder field and closes the browser.
34+ pub(crate) fn choose_browsed_folder(&mut self, window: &mut Window, cx: &mut Context<Self>) {
35+ if let Some(listing) = self.folder_browser.take() {
36+ let path = listing.path.to_string_lossy().into_owned();
37+ self.agent_form
38+ .working_dir
39+ .update(cx, |input, cx| input.set_value(path, window, cx));
40+ }
41+ cx.notify();
42+ }
43+
44+ /// The text of the working folder field of the agent form. Public so that tests can read it.
45+ pub fn working_folder_text(&self, cx: &gpui_kit::App) -> String {
46+ self.agent_form.working_dir.read(cx).value().to_string()
47+ }
48+
49+ /// The folder on show in the browser, `None` while it is closed. Public for the tests.
50+ pub fn browsed_folder(&self) -> Option<&std::path::Path> {
51+ self.folder_browser
52+ .as_ref()
53+ .map(|listing| listing.path.as_path())
54+ }
55+
56+ pub(crate) fn close_folder_browser(&mut self, cx: &mut Context<Self>) {
57+ self.folder_browser = None;
58+ cx.notify();
59+ }
60+
61+ /// The button that opens the browser, and the browser itself while it is open.
62+ pub(crate) fn render_folder_browser(&self, cx: &mut Context<Self>) -> Vec<AnyElement> {
63+ let Some(listing) = &self.folder_browser else {
64+ return vec![
65+ Button::new("browse-folders")
66+ .label("Browse\u{2026}")
67+ .compact()
68+ .outline()
69+ .on_click(cx.listener(|this, _, _, cx| this.open_folder_browser(cx)))
70+ .into_any_element(),
71+ ];
72+ };
73+ let border = cx.theme().border;
74+ let muted = cx.theme().muted_foreground;
75+ let hover = cx.theme().list_hover;
76+
77+ let up = listing.parent().map(|parent| {
78+ folder_row(
79+ "folder-up",
80+ "..",
81+ IconName::ArrowUp,
82+ hover,
83+ cx.listener(move |this, _, _, cx| this.browse_to(parent.clone(), cx)),
84+ )
85+ });
86+ let rows = listing.folders.iter().enumerate().map(|(index, name)| {
87+ let path = listing.child(name);
88+ folder_row(
89+ SharedString::from(format!("folder-row-{index}")),
90+ name,
91+ IconName::Folder,
92+ hover,
93+ cx.listener(move |this, _, _, cx| this.browse_to(path.clone(), cx)),
94+ )
95+ });
96+
97+ let list = v_flex()
98+ .id("folder-list")
99+ .test_support()
100+ .max_h(px(220.))
101+ .overflow_y_scroll()
102+ .children(up)
103+ .children(rows)
104+ .when(listing.folders.is_empty(), |list| {
105+ list.child(
106+ div()
107+ .id("no-folders")
108+ .test_support()
109+ .px_2()
110+ .py_1()
111+ .text_xs()
112+ .text_color(muted)
113+ .child("No folder inside this one."),
114+ )
115+ })
116+ .when(listing.truncated, |list| {
117+ list.child(
118+ div()
119+ .id("folders-truncated")
120+ .test_support()
121+ .px_2()
122+ .py_1()
123+ .text_xs()
124+ .text_color(muted)
125+ .child("Only the first folders are listed. Type the path to go further."),
126+ )
127+ });
128+
129+ vec![
130+ v_flex()
131+ .id("folder-browser")
132+ .test_support()
133+ .gap_1()
134+ .p_1()
135+ .border_1()
136+ .border_color(border)
137+ .rounded_md()
138+ .child(
139+ div()
140+ .id("folder-browser-path")
141+ .test_support()
142+ .px_2()
143+ .text_xs()
144+ .text_color(muted)
145+ .child(listing.path.display().to_string()),
146+ )
147+ .child(list)
148+ .child(
149+ h_flex()
150+ .gap_1()
151+ .child(
152+ Button::new("folder-choose")
153+ .label("Use this folder")
154+ .compact()
155+ .primary()
156+ .on_click(cx.listener(|this, _, window, cx| {
157+ this.choose_browsed_folder(window, cx)
158+ })),
159+ )
160+ .child(
161+ Button::new("folder-cancel")
162+ .label("Cancel")
163+ .compact()
164+ .outline()
165+ .on_click(
166+ cx.listener(|this, _, _, cx| this.close_folder_browser(cx)),
167+ ),
168+ ),
169+ )
170+ .into_any_element(),
171+ ]
172+ }
173+}
174+
175+/// One row of the list of folders: an icon and a name, with a highlight under the pointer.
176+fn folder_row(
177+ id: impl Into<SharedString>,
178+ name: &str,
179+ icon: IconName,
180+ hover: gpui_kit::Hsla,
181+ on_click: impl Fn(&gpui_kit::ClickEvent, &mut Window, &mut gpui_kit::App) + 'static,
182+) -> AnyElement {
183+ h_flex()
184+ .id(id.into())
185+ .test_support()
186+ .w_full()
187+ .gap_2()
188+ .items_center()
189+ .px_2()
190+ .py_1()
191+ .rounded_md()
192+ .cursor_pointer()
193+ .text_sm()
194+ .hover(move |style| style.bg(hover))
195+ .on_click(on_click)
196+ .child(Icon::new(icon).small())
197+ .child(name.to_string())
198+ .into_any_element()
199+}
added crates/ui/src/folders.rs +187 -0
new file mode 100644
@@ -0,0 +1,187 @@
1+//! The folders a user can walk through to choose the folder an agent works in.
2+//!
3+//! A [`FolderListing`] is one folder seen from the inside: the folders it holds, and the way up.
4+//! The window shows one listing at a time and replaces it when the user goes into a folder or up.
5+
6+use std::path::{Path, PathBuf};
7+
8+/// How many sub-folders of one folder are listed at most, so that a folder holding thousands of
9+/// them cannot stall the window.
10+pub const MAX_FOLDERS: usize = 200;
11+
12+/// A folder and the folders directly inside it.
13+///
14+/// ```no_run
15+/// use std::path::Path;
16+/// use synedrion_ui::folders::FolderListing;
17+///
18+/// let listing = FolderListing::of(Path::new("/home"));
19+/// for folder in &listing.folders {
20+/// println!("{folder}");
21+/// }
22+/// ```
23+#[derive(Debug, Clone, PartialEq, Eq)]
24+pub struct FolderListing {
25+ /// The folder that is listed.
26+ pub path: PathBuf,
27+ /// The names of the folders inside it, sorted without regard to case. Hidden folders (the
28+ /// name starts with a dot) are left out. At most [`MAX_FOLDERS`].
29+ pub folders: Vec<String>,
30+ /// True when there were more folders than [`MAX_FOLDERS`].
31+ pub truncated: bool,
32+}
33+
34+impl FolderListing {
35+ /// Lists the folders inside `path`. A folder that cannot be read gives an empty listing.
36+ pub fn of(path: &Path) -> Self {
37+ let mut folders: Vec<String> = std::fs::read_dir(path)
38+ .into_iter()
39+ .flatten()
40+ .flatten()
41+ .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))
42+ .map(|entry| entry.file_name().to_string_lossy().into_owned())
43+ .filter(|name| !name.starts_with('.'))
44+ .collect();
45+ folders.sort_by_key(|name| name.to_lowercase());
46+ let truncated = folders.len() > MAX_FOLDERS;
47+ folders.truncate(MAX_FOLDERS);
48+ Self {
49+ path: path.to_path_buf(),
50+ folders,
51+ truncated,
52+ }
53+ }
54+
55+ /// The folder above this one, or `None` at the top of the file system.
56+ pub fn parent(&self) -> Option<PathBuf> {
57+ self.path.parent().map(Path::to_path_buf)
58+ }
59+
60+ /// The path of a folder listed here.
61+ pub fn child(&self, name: &str) -> PathBuf {
62+ self.path.join(name)
63+ }
64+}
65+
66+/// The folder a browser opens on when the field holds `typed`: that folder if it exists, else the
67+/// folder of the user (`HOME`), else the folder Synedrion runs in.
68+///
69+/// ```
70+/// use std::path::Path;
71+/// use synedrion_ui::folders::starting_folder;
72+///
73+/// assert!(starting_folder("/definitely/not/a/folder").is_dir());
74+/// assert_eq!(starting_folder("/"), Path::new("/"));
75+/// ```
76+pub fn starting_folder(typed: &str) -> PathBuf {
77+ let typed = typed.trim();
78+ if !typed.is_empty() && Path::new(typed).is_dir() {
79+ return PathBuf::from(typed);
80+ }
81+ std::env::var_os("HOME")
82+ .map(PathBuf::from)
83+ .filter(|home| home.is_dir())
84+ .or_else(|| std::env::current_dir().ok())
85+ .unwrap_or_else(|| PathBuf::from("/"))
86+}
87+
88+#[cfg(test)]
89+mod tests {
90+ use super::*;
91+
92+ /// A folder of folders that is removed when the test ends.
93+ struct Tree(PathBuf);
94+
95+ impl Tree {
96+ fn new(name: &str, folders: &[&str], files: &[&str]) -> Self {
97+ let root = std::env::temp_dir()
98+ .join(format!("synedrion-folders-{name}-{}", std::process::id()));
99+ let _ = std::fs::remove_dir_all(&root);
100+ std::fs::create_dir_all(&root).unwrap();
101+ for folder in folders {
102+ std::fs::create_dir_all(root.join(folder)).unwrap();
103+ }
104+ for file in files {
105+ std::fs::write(root.join(file), "x").unwrap();
106+ }
107+ Tree(root)
108+ }
109+ }
110+
111+ impl Drop for Tree {
112+ fn drop(&mut self) {
113+ let _ = std::fs::remove_dir_all(&self.0);
114+ }
115+ }
116+
117+ #[test]
118+ fn only_folders_are_listed_and_files_are_not() {
119+ let tree = Tree::new("only", &["src", "docs"], &["notes.txt"]);
120+ let listing = FolderListing::of(&tree.0);
121+ assert_eq!(listing.folders, vec!["docs", "src"]);
122+ }
123+
124+ #[test]
125+ fn hidden_folders_are_left_out() {
126+ let tree = Tree::new("hidden", &[".git", "visible"], &[]);
127+ assert_eq!(FolderListing::of(&tree.0).folders, vec!["visible"]);
128+ }
129+
130+ #[test]
131+ fn folders_are_sorted_without_regard_to_case() {
132+ let tree = Tree::new("case", &["beta", "Alpha", "gamma"], &[]);
133+ assert_eq!(
134+ FolderListing::of(&tree.0).folders,
135+ vec!["Alpha", "beta", "gamma"]
136+ );
137+ }
138+
139+ #[test]
140+ fn a_folder_that_cannot_be_read_gives_an_empty_listing() {
141+ let listing = FolderListing::of(Path::new("/definitely/not/a/folder"));
142+ assert!(listing.folders.is_empty());
143+ assert!(!listing.truncated);
144+ }
145+
146+ #[test]
147+ fn the_listing_is_cut_at_the_limit_and_says_so() {
148+ let names: Vec<String> = (0..MAX_FOLDERS + 5).map(|n| format!("d{n:04}")).collect();
149+ let refs: Vec<&str> = names.iter().map(String::as_str).collect();
150+ let tree = Tree::new("many", &refs, &[]);
151+ let listing = FolderListing::of(&tree.0);
152+ assert_eq!(listing.folders.len(), MAX_FOLDERS);
153+ assert!(listing.truncated);
154+ }
155+
156+ #[test]
157+ fn a_listing_under_the_limit_is_not_truncated() {
158+ let tree = Tree::new("few", &["a"], &[]);
159+ assert!(!FolderListing::of(&tree.0).truncated);
160+ }
161+
162+ #[test]
163+ fn the_parent_and_a_child_are_paths_around_the_folder() {
164+ let tree = Tree::new("walk", &["inner"], &[]);
165+ let listing = FolderListing::of(&tree.0);
166+ assert_eq!(listing.child("inner"), tree.0.join("inner"));
167+ assert_eq!(listing.parent(), tree.0.parent().map(Path::to_path_buf));
168+ }
169+
170+ #[test]
171+ fn the_top_of_the_file_system_has_no_parent() {
172+ assert_eq!(FolderListing::of(Path::new("/")).parent(), None);
173+ }
174+
175+ #[test]
176+ fn a_typed_folder_that_exists_is_where_the_browser_opens() {
177+ let tree = Tree::new("start", &[], &[]);
178+ let typed = format!(" {} ", tree.0.display());
179+ assert_eq!(starting_folder(&typed), tree.0);
180+ }
181+
182+ #[test]
183+ fn a_typed_folder_that_does_not_exist_opens_on_an_existing_folder() {
184+ assert!(starting_folder("/definitely/not/a/folder").is_dir());
185+ assert!(starting_folder("").is_dir());
186+ }
187+}
new file mode 100644
@@ -0,0 +1,187 @@
1+//! The folders a user can walk through to choose the folder an agent works in.
2+//!
3+//! A [`FolderListing`] is one folder seen from the inside: the folders it holds, and the way up.
4+//! The window shows one listing at a time and replaces it when the user goes into a folder or up.
5+
6+use std::path::{Path, PathBuf};
7+
8+/// How many sub-folders of one folder are listed at most, so that a folder holding thousands of
9+/// them cannot stall the window.
10+pub const MAX_FOLDERS: usize = 200;
11+
12+/// A folder and the folders directly inside it.
13+///
14+/// ```no_run
15+/// use std::path::Path;
16+/// use synedrion_ui::folders::FolderListing;
17+///
18+/// let listing = FolderListing::of(Path::new("/home"));
19+/// for folder in &listing.folders {
20+/// println!("{folder}");
21+/// }
22+/// ```
23+#[derive(Debug, Clone, PartialEq, Eq)]
24+pub struct FolderListing {
25+ /// The folder that is listed.
26+ pub path: PathBuf,
27+ /// The names of the folders inside it, sorted without regard to case. Hidden folders (the
28+ /// name starts with a dot) are left out. At most [`MAX_FOLDERS`].
29+ pub folders: Vec<String>,
30+ /// True when there were more folders than [`MAX_FOLDERS`].
31+ pub truncated: bool,
32+}
33+
34+impl FolderListing {
35+ /// Lists the folders inside `path`. A folder that cannot be read gives an empty listing.
36+ pub fn of(path: &Path) -> Self {
37+ let mut folders: Vec<String> = std::fs::read_dir(path)
38+ .into_iter()
39+ .flatten()
40+ .flatten()
41+ .filter(|entry| entry.file_type().is_ok_and(|kind| kind.is_dir()))
42+ .map(|entry| entry.file_name().to_string_lossy().into_owned())
43+ .filter(|name| !name.starts_with('.'))
44+ .collect();
45+ folders.sort_by_key(|name| name.to_lowercase());
46+ let truncated = folders.len() > MAX_FOLDERS;
47+ folders.truncate(MAX_FOLDERS);
48+ Self {
49+ path: path.to_path_buf(),
50+ folders,
51+ truncated,
52+ }
53+ }
54+
55+ /// The folder above this one, or `None` at the top of the file system.
56+ pub fn parent(&self) -> Option<PathBuf> {
57+ self.path.parent().map(Path::to_path_buf)
58+ }
59+
60+ /// The path of a folder listed here.
61+ pub fn child(&self, name: &str) -> PathBuf {
62+ self.path.join(name)
63+ }
64+}
65+
66+/// The folder a browser opens on when the field holds `typed`: that folder if it exists, else the
67+/// folder of the user (`HOME`), else the folder Synedrion runs in.
68+///
69+/// ```
70+/// use std::path::Path;
71+/// use synedrion_ui::folders::starting_folder;
72+///
73+/// assert!(starting_folder("/definitely/not/a/folder").is_dir());
74+/// assert_eq!(starting_folder("/"), Path::new("/"));
75+/// ```
76+pub fn starting_folder(typed: &str) -> PathBuf {
77+ let typed = typed.trim();
78+ if !typed.is_empty() && Path::new(typed).is_dir() {
79+ return PathBuf::from(typed);
80+ }
81+ std::env::var_os("HOME")
82+ .map(PathBuf::from)
83+ .filter(|home| home.is_dir())
84+ .or_else(|| std::env::current_dir().ok())
85+ .unwrap_or_else(|| PathBuf::from("/"))
86+}
87+
88+#[cfg(test)]
89+mod tests {
90+ use super::*;
91+
92+ /// A folder of folders that is removed when the test ends.
93+ struct Tree(PathBuf);
94+
95+ impl Tree {
96+ fn new(name: &str, folders: &[&str], files: &[&str]) -> Self {
97+ let root = std::env::temp_dir()
98+ .join(format!("synedrion-folders-{name}-{}", std::process::id()));
99+ let _ = std::fs::remove_dir_all(&root);
100+ std::fs::create_dir_all(&root).unwrap();
101+ for folder in folders {
102+ std::fs::create_dir_all(root.join(folder)).unwrap();
103+ }
104+ for file in files {
105+ std::fs::write(root.join(file), "x").unwrap();
106+ }
107+ Tree(root)
108+ }
109+ }
110+
111+ impl Drop for Tree {
112+ fn drop(&mut self) {
113+ let _ = std::fs::remove_dir_all(&self.0);
114+ }
115+ }
116+
117+ #[test]
118+ fn only_folders_are_listed_and_files_are_not() {
119+ let tree = Tree::new("only", &["src", "docs"], &["notes.txt"]);
120+ let listing = FolderListing::of(&tree.0);
121+ assert_eq!(listing.folders, vec!["docs", "src"]);
122+ }
123+
124+ #[test]
125+ fn hidden_folders_are_left_out() {
126+ let tree = Tree::new("hidden", &[".git", "visible"], &[]);
127+ assert_eq!(FolderListing::of(&tree.0).folders, vec!["visible"]);
128+ }
129+
130+ #[test]
131+ fn folders_are_sorted_without_regard_to_case() {
132+ let tree = Tree::new("case", &["beta", "Alpha", "gamma"], &[]);
133+ assert_eq!(
134+ FolderListing::of(&tree.0).folders,
135+ vec!["Alpha", "beta", "gamma"]
136+ );
137+ }
138+
139+ #[test]
140+ fn a_folder_that_cannot_be_read_gives_an_empty_listing() {
141+ let listing = FolderListing::of(Path::new("/definitely/not/a/folder"));
142+ assert!(listing.folders.is_empty());
143+ assert!(!listing.truncated);
144+ }
145+
146+ #[test]
147+ fn the_listing_is_cut_at_the_limit_and_says_so() {
148+ let names: Vec<String> = (0..MAX_FOLDERS + 5).map(|n| format!("d{n:04}")).collect();
149+ let refs: Vec<&str> = names.iter().map(String::as_str).collect();
150+ let tree = Tree::new("many", &refs, &[]);
151+ let listing = FolderListing::of(&tree.0);
152+ assert_eq!(listing.folders.len(), MAX_FOLDERS);
153+ assert!(listing.truncated);
154+ }
155+
156+ #[test]
157+ fn a_listing_under_the_limit_is_not_truncated() {
158+ let tree = Tree::new("few", &["a"], &[]);
159+ assert!(!FolderListing::of(&tree.0).truncated);
160+ }
161+
162+ #[test]
163+ fn the_parent_and_a_child_are_paths_around_the_folder() {
164+ let tree = Tree::new("walk", &["inner"], &[]);
165+ let listing = FolderListing::of(&tree.0);
166+ assert_eq!(listing.child("inner"), tree.0.join("inner"));
167+ assert_eq!(listing.parent(), tree.0.parent().map(Path::to_path_buf));
168+ }
169+
170+ #[test]
171+ fn the_top_of_the_file_system_has_no_parent() {
172+ assert_eq!(FolderListing::of(Path::new("/")).parent(), None);
173+ }
174+
175+ #[test]
176+ fn a_typed_folder_that_exists_is_where_the_browser_opens() {
177+ let tree = Tree::new("start", &[], &[]);
178+ let typed = format!(" {} ", tree.0.display());
179+ assert_eq!(starting_folder(&typed), tree.0);
180+ }
181+
182+ #[test]
183+ fn a_typed_folder_that_does_not_exist_opens_on_an_existing_folder() {
184+ assert!(starting_folder("/definitely/not/a/folder").is_dir());
185+ assert!(starting_folder("").is_dir());
186+ }
187+}
modified crates/ui/src/lib.rs +5 -1
@@ -13,7 +13,7 @@
1313 //!
1414 //! let repository = Arc::new(SqliteRepository::open_in_memory().unwrap());
1515 //! let hub = Arc::new(AgentHub::new(Arc::new(|_event| {})));
16-//! let controller = ChatController::new(repository, hub);
16+//! let mut controller = ChatController::new(repository, hub);
1717 //! controller.start().unwrap();
1818 //! assert_eq!(controller.channels().unwrap().len(), 1);
1919 //! ```
@@ -36,7 +36,11 @@ pub mod app;
3636 pub mod controller;
3737 pub mod dock;
3838 pub mod files;
39+mod folder_browser;
40+pub mod folders;
3941 pub mod format;
4042 pub mod gateway;
43+mod settings_panel;
4144 mod suggestions;
45+mod trace_view;
4246 mod view;
@@ -13,7 +13,7 @@
13 //!13 //!
14 //! let repository = Arc::new(SqliteRepository::open_in_memory().unwrap());14 //! let repository = Arc::new(SqliteRepository::open_in_memory().unwrap());
15 //! let hub = Arc::new(AgentHub::new(Arc::new(|_event| {})));15 //! let hub = Arc::new(AgentHub::new(Arc::new(|_event| {})));
16-//! let controller = ChatController::new(repository, hub);16+//! let mut controller = ChatController::new(repository, hub);
17 //! controller.start().unwrap();17 //! controller.start().unwrap();
18 //! assert_eq!(controller.channels().unwrap().len(), 1);18 //! assert_eq!(controller.channels().unwrap().len(), 1);
19 //! ```19 //! ```
@@ -36,7 +36,11 @@ pub mod app;
36 pub mod controller;36 pub mod controller;
37 pub mod dock;37 pub mod dock;
38 pub mod files;38 pub mod files;
39+mod folder_browser;
40+pub mod folders;
39 pub mod format;41 pub mod format;
40 pub mod gateway;42 pub mod gateway;
43+mod settings_panel;
41 mod suggestions;44 mod suggestions;
45+mod trace_view;
42 mod view;46 mod view;
added crates/ui/src/settings_panel.rs +89 -0
new file mode 100644
@@ -0,0 +1,89 @@
1+//! The panel of settings: how much of the channel an agent is told about, and how far agents may
2+//! call one another.
3+
4+use gpui_kit::component::ActiveTheme as _;
5+use gpui_kit::component::button::{Button, ButtonVariants as _};
6+use gpui_kit::component::input::Input;
7+use gpui_kit::{AnyElement, Context, Window, div, prelude::*};
8+use synedrion_domain::settings::{ChatSettings, MAX_CHAIN_DEPTH, MAX_CONTEXT_MESSAGES};
9+
10+use crate::app::{Panel, SynedrionApp};
11+
12+impl SynedrionApp {
13+ /// Puts the settings in force into the two fields.
14+ pub(crate) fn fill_settings_form(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15+ let settings = self.controller.settings();
16+ self.settings_form.context_messages.update(cx, |input, cx| {
17+ input.set_value(settings.context_messages.to_string(), window, cx)
18+ });
19+ self.settings_form.chain_depth.update(cx, |input, cx| {
20+ input.set_value(settings.chain_depth.to_string(), window, cx)
21+ });
22+ }
23+
24+ /// Reads the two fields, and keeps the settings if they are acceptable.
25+ pub(crate) fn save_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
26+ let context = self
27+ .settings_form
28+ .context_messages
29+ .read(cx)
30+ .value()
31+ .to_string();
32+ let depth = self.settings_form.chain_depth.read(cx).value().to_string();
33+ let saved = ChatSettings::parse(&context, &depth)
34+ .map_err(|error| error.to_string())
35+ .and_then(|settings| {
36+ self.controller
37+ .save_settings(settings)
38+ .map_err(|error| error.to_string())
39+ });
40+ match saved {
41+ Ok(()) => {
42+ self.notice = Some("Settings saved. They apply from the next message.".to_string());
43+ self.fill_settings_form(window, cx);
44+ }
45+ Err(message) => self.notice = Some(message),
46+ }
47+ cx.notify();
48+ }
49+
50+ pub(crate) fn render_settings_panel(&self, cx: &mut Context<Self>) -> AnyElement {
51+ let muted = cx.theme().muted_foreground;
52+ let form = &self.settings_form;
53+ let content = vec![
54+ div()
55+ .text_sm()
56+ .child("Messages of context")
57+ .into_any_element(),
58+ Input::new(&form.context_messages)
59+ .id("settings-context")
60+ .aria_label("Messages of context")
61+ .into_any_element(),
62+ div()
63+ .text_xs()
64+ .text_color(muted)
65+ .child(format!(
66+ "How many messages sent since its last turn an agent is told about, besides the one that calls it. 0 to tell it nothing more. At most {MAX_CONTEXT_MESSAGES}."
67+ ))
68+ .into_any_element(),
69+ div().text_sm().child("Chain depth").into_any_element(),
70+ Input::new(&form.chain_depth)
71+ .id("settings-depth")
72+ .aria_label("Chain depth")
73+ .into_any_element(),
74+ div()
75+ .text_xs()
76+ .text_color(muted)
77+ .child(format!(
78+ "How many agents may call one another in a row, when an answer mentions another agent. 0 to forbid it. At most {MAX_CHAIN_DEPTH}."
79+ ))
80+ .into_any_element(),
81+ Button::new("save-settings")
82+ .label("Save settings")
83+ .primary()
84+ .on_click(cx.listener(|this, _, window, cx| this.save_settings(window, cx)))
85+ .into_any_element(),
86+ ];
87+ self.render_dock_panel(Panel::Settings, content, cx)
88+ }
89+}
new file mode 100644
@@ -0,0 +1,89 @@
1+//! The panel of settings: how much of the channel an agent is told about, and how far agents may
2+//! call one another.
3+
4+use gpui_kit::component::ActiveTheme as _;
5+use gpui_kit::component::button::{Button, ButtonVariants as _};
6+use gpui_kit::component::input::Input;
7+use gpui_kit::{AnyElement, Context, Window, div, prelude::*};
8+use synedrion_domain::settings::{ChatSettings, MAX_CHAIN_DEPTH, MAX_CONTEXT_MESSAGES};
9+
10+use crate::app::{Panel, SynedrionApp};
11+
12+impl SynedrionApp {
13+ /// Puts the settings in force into the two fields.
14+ pub(crate) fn fill_settings_form(&mut self, window: &mut Window, cx: &mut Context<Self>) {
15+ let settings = self.controller.settings();
16+ self.settings_form.context_messages.update(cx, |input, cx| {
17+ input.set_value(settings.context_messages.to_string(), window, cx)
18+ });
19+ self.settings_form.chain_depth.update(cx, |input, cx| {
20+ input.set_value(settings.chain_depth.to_string(), window, cx)
21+ });
22+ }
23+
24+ /// Reads the two fields, and keeps the settings if they are acceptable.
25+ pub(crate) fn save_settings(&mut self, window: &mut Window, cx: &mut Context<Self>) {
26+ let context = self
27+ .settings_form
28+ .context_messages
29+ .read(cx)
30+ .value()
31+ .to_string();
32+ let depth = self.settings_form.chain_depth.read(cx).value().to_string();
33+ let saved = ChatSettings::parse(&context, &depth)
34+ .map_err(|error| error.to_string())
35+ .and_then(|settings| {
36+ self.controller
37+ .save_settings(settings)
38+ .map_err(|error| error.to_string())
39+ });
40+ match saved {
41+ Ok(()) => {
42+ self.notice = Some("Settings saved. They apply from the next message.".to_string());
43+ self.fill_settings_form(window, cx);
44+ }
45+ Err(message) => self.notice = Some(message),
46+ }
47+ cx.notify();
48+ }
49+
50+ pub(crate) fn render_settings_panel(&self, cx: &mut Context<Self>) -> AnyElement {
51+ let muted = cx.theme().muted_foreground;
52+ let form = &self.settings_form;
53+ let content = vec![
54+ div()
55+ .text_sm()
56+ .child("Messages of context")
57+ .into_any_element(),
58+ Input::new(&form.context_messages)
59+ .id("settings-context")
60+ .aria_label("Messages of context")
61+ .into_any_element(),
62+ div()
63+ .text_xs()
64+ .text_color(muted)
65+ .child(format!(
66+ "How many messages sent since its last turn an agent is told about, besides the one that calls it. 0 to tell it nothing more. At most {MAX_CONTEXT_MESSAGES}."
67+ ))
68+ .into_any_element(),
69+ div().text_sm().child("Chain depth").into_any_element(),
70+ Input::new(&form.chain_depth)
71+ .id("settings-depth")
72+ .aria_label("Chain depth")
73+ .into_any_element(),
74+ div()
75+ .text_xs()
76+ .text_color(muted)
77+ .child(format!(
78+ "How many agents may call one another in a row, when an answer mentions another agent. 0 to forbid it. At most {MAX_CHAIN_DEPTH}."
79+ ))
80+ .into_any_element(),
81+ Button::new("save-settings")
82+ .label("Save settings")
83+ .primary()
84+ .on_click(cx.listener(|this, _, window, cx| this.save_settings(window, cx)))
85+ .into_any_element(),
86+ ];
87+ self.render_dock_panel(Panel::Settings, content, cx)
88+ }
89+}
modified crates/ui/src/suggestions.rs +117 -17
@@ -1,5 +1,6 @@
11 //! The list that opens above the message box while the user types: agents after an `@`, commands
2-//! after a `/`, and files after `/file`, together with the files attached to the next message.
2+//! after a `/`, and files after `/file` or after a `$` in the middle of a sentence, together with
3+//! the files attached to the next message.
34
45 use std::path::PathBuf;
56
@@ -9,6 +10,7 @@ use synedrion_domain::channel::ChannelId;
910 use synedrion_domain::command::{
1011 complete_command, file_query, trailing_command_prefix, without_file_command,
1112 };
13+use synedrion_domain::file_reference::{complete_file_reference, trailing_file_query};
1214 use synedrion_domain::mention::{
1315 agents_starting_with, complete_trailing_mention, trailing_mention_prefix,
1416 };
@@ -73,14 +75,87 @@ impl Suggestion {
7375 }
7476 }
7577
78+/// Which way an arrow key moves the selection in the list.
79+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80+pub(crate) enum Step {
81+ Up,
82+ Down,
83+}
84+
85+/// The row selected after an arrow key, among `count` rows: one row up or down, going round at
86+/// both ends. With no row, the selection stays at `0`.
87+pub(crate) fn moved_selection(current: usize, count: usize, step: Step) -> usize {
88+ if count == 0 {
89+ return 0;
90+ }
91+ match step {
92+ Step::Down => (current + 1) % count,
93+ Step::Up => (current + count - 1) % count,
94+ }
95+}
96+
7697 impl SynedrionApp {
98+ /// Takes a key that the list above the message box uses, while the message box has the focus
99+ /// and the list is open. Returns `true` when the key was used, so that it goes no further.
100+ ///
101+ /// Up and Down move the selection, Tab takes the selected row, Enter takes it too once the
102+ /// selection was moved with the arrows (before that, Enter sends the message as it always
103+ /// did), and Escape closes the list. Any other key, or a key with a modifier (but Tab, which
104+ /// only gives way to Shift), is left alone.
105+ pub(crate) fn handle_list_key(
106+ &mut self,
107+ key: &str,
108+ modified: bool,
109+ shift: bool,
110+ window: &mut Window,
111+ cx: &mut Context<Self>,
112+ ) -> bool {
113+ if self.suggestions.is_empty() {
114+ return false;
115+ }
116+ match key {
117+ "tab" if !shift => self.pick_selected(window, cx),
118+ "down" | "up" if !modified => {
119+ let step = if key == "down" { Step::Down } else { Step::Up };
120+ self.selected_suggestion =
121+ moved_selection(self.selected_suggestion, self.suggestions.len(), step);
122+ self.suggestion_navigated = true;
123+ cx.notify();
124+ true
125+ }
126+ "enter" if !modified && self.suggestion_navigated => self.pick_selected(window, cx),
127+ "escape" if !modified => {
128+ self.suggestions.clear();
129+ self.file_mode = false;
130+ cx.notify();
131+ true
132+ }
133+ _ => false,
134+ }
135+ }
136+
137+ /// The row that Tab, and Enter after the arrows, would take. Public so that tests can read it.
138+ pub fn selected_suggestion(&self) -> usize {
139+ self.selected_suggestion
140+ }
141+
142+ /// Takes the selected row. Returns `false`, and does nothing, when the list is empty.
143+ fn pick_selected(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
144+ let Some(selected) = self.suggestions.get(self.selected_suggestion).cloned() else {
145+ return false;
146+ };
147+ self.pick_suggestion(&selected, window, cx);
148+ true
149+ }
150+
77151 /// Updates the list of agents proposed for the mention being typed.
78152 pub(crate) fn refresh_suggestions(&mut self, cx: &mut Context<Self>) {
79153 let text = self.composer.read(cx).value().to_string();
80154 let Some(channel) = self.active_channel else {
81155 return;
82156 };
83- let file_words = file_query(&text);
157+ // `/file` at the start, or a `$` being typed anywhere: both list files.
158+ let file_words = file_query(&text).or_else(|| trailing_file_query(&text));
84159 self.file_mode = file_words.is_some();
85160
86161 let mut suggestions: Vec<Suggestion> = if let Some(words) = file_words {
@@ -109,23 +184,11 @@ impl SynedrionApp {
109184 };
110185 suggestions.truncate(MAX_SUGGESTIONS);
111186 self.suggestions = suggestions;
187+ self.selected_suggestion = 0;
188+ self.suggestion_navigated = false;
112189 cx.notify();
113190 }
114191
115- /// Completes the mention being typed with the first proposed agent. Returns `false`, and
116- /// does nothing, when no agent is proposed.
117- pub(crate) fn complete_with_first_suggestion(
118- &mut self,
119- window: &mut Window,
120- cx: &mut Context<Self>,
121- ) -> bool {
122- let Some(first) = self.suggestions.first().cloned() else {
123- return false;
124- };
125- self.pick_suggestion(&first, window, cx);
126- true
127- }
128-
129192 pub(crate) fn pick_suggestion(
130193 &mut self,
131194 suggestion: &Suggestion,
@@ -145,7 +208,13 @@ impl SynedrionApp {
145208 }
146209 Suggestion::File(relative) => {
147210 self.attach(relative);
148- self.set_composer_text(without_file_command(&text), window, cx);
211+ // `/file` is removed; a `$name` typed in a sentence becomes the path of the file.
212+ let next = if file_query(&text).is_some() {
213+ without_file_command(&text)
214+ } else {
215+ complete_file_reference(&text, &relative.display().to_string())
216+ };
217+ self.set_composer_text(next, window, cx);
149218 self.suggestions.clear();
150219 self.file_mode = false;
151220 self.file_index = None;
@@ -216,3 +285,34 @@ impl SynedrionApp {
216285 }
217286 }
218287 }
288+
289+#[cfg(test)]
290+mod tests {
291+ use super::*;
292+
293+ #[test]
294+ fn down_goes_to_the_next_row_and_round_to_the_first_after_the_last() {
295+ assert_eq!(moved_selection(0, 3, Step::Down), 1);
296+ assert_eq!(moved_selection(1, 3, Step::Down), 2);
297+ assert_eq!(moved_selection(2, 3, Step::Down), 0);
298+ }
299+
300+ #[test]
301+ fn up_goes_to_the_previous_row_and_round_to_the_last_before_the_first() {
302+ assert_eq!(moved_selection(2, 3, Step::Up), 1);
303+ assert_eq!(moved_selection(1, 3, Step::Up), 0);
304+ assert_eq!(moved_selection(0, 3, Step::Up), 2);
305+ }
306+
307+ #[test]
308+ fn a_single_row_stays_selected_whichever_way_the_arrow_goes() {
309+ assert_eq!(moved_selection(0, 1, Step::Down), 0);
310+ assert_eq!(moved_selection(0, 1, Step::Up), 0);
311+ }
312+
313+ #[test]
314+ fn with_no_row_the_selection_stays_at_zero() {
315+ assert_eq!(moved_selection(0, 0, Step::Down), 0);
316+ assert_eq!(moved_selection(0, 0, Step::Up), 0);
317+ }
318+}
@@ -1,5 +1,6 @@
1 //! The list that opens above the message box while the user types: agents after an `@`, commands1 //! The list that opens above the message box while the user types: agents after an `@`, commands
2-//! after a `/`, and files after `/file`, together with the files attached to the next message.2+//! after a `/`, and files after `/file` or after a `$` in the middle of a sentence, together with
3+//! the files attached to the next message.
3 4
4 use std::path::PathBuf;5 use std::path::PathBuf;
5 6
@@ -9,6 +10,7 @@ use synedrion_domain::channel::ChannelId;
9 use synedrion_domain::command::{10 use synedrion_domain::command::{
10 complete_command, file_query, trailing_command_prefix, without_file_command,11 complete_command, file_query, trailing_command_prefix, without_file_command,
11 };12 };
13+use synedrion_domain::file_reference::{complete_file_reference, trailing_file_query};
12 use synedrion_domain::mention::{14 use synedrion_domain::mention::{
13 agents_starting_with, complete_trailing_mention, trailing_mention_prefix,15 agents_starting_with, complete_trailing_mention, trailing_mention_prefix,
14 };16 };
@@ -73,14 +75,87 @@ impl Suggestion {
73 }75 }
74 }76 }
75 77
78+/// Which way an arrow key moves the selection in the list.
79+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
80+pub(crate) enum Step {
81+ Up,
82+ Down,
83+}
84+
85+/// The row selected after an arrow key, among `count` rows: one row up or down, going round at
86+/// both ends. With no row, the selection stays at `0`.
87+pub(crate) fn moved_selection(current: usize, count: usize, step: Step) -> usize {
88+ if count == 0 {
89+ return 0;
90+ }
91+ match step {
92+ Step::Down => (current + 1) % count,
93+ Step::Up => (current + count - 1) % count,
94+ }
95+}
96+
76 impl SynedrionApp {97 impl SynedrionApp {
98+ /// Takes a key that the list above the message box uses, while the message box has the focus
99+ /// and the list is open. Returns `true` when the key was used, so that it goes no further.
100+ ///
101+ /// Up and Down move the selection, Tab takes the selected row, Enter takes it too once the
102+ /// selection was moved with the arrows (before that, Enter sends the message as it always
103+ /// did), and Escape closes the list. Any other key, or a key with a modifier (but Tab, which
104+ /// only gives way to Shift), is left alone.
105+ pub(crate) fn handle_list_key(
106+ &mut self,
107+ key: &str,
108+ modified: bool,
109+ shift: bool,
110+ window: &mut Window,
111+ cx: &mut Context<Self>,
112+ ) -> bool {
113+ if self.suggestions.is_empty() {
114+ return false;
115+ }
116+ match key {
117+ "tab" if !shift => self.pick_selected(window, cx),
118+ "down" | "up" if !modified => {
119+ let step = if key == "down" { Step::Down } else { Step::Up };
120+ self.selected_suggestion =
121+ moved_selection(self.selected_suggestion, self.suggestions.len(), step);
122+ self.suggestion_navigated = true;
123+ cx.notify();
124+ true
125+ }
126+ "enter" if !modified && self.suggestion_navigated => self.pick_selected(window, cx),
127+ "escape" if !modified => {
128+ self.suggestions.clear();
129+ self.file_mode = false;
130+ cx.notify();
131+ true
132+ }
133+ _ => false,
134+ }
135+ }
136+
137+ /// The row that Tab, and Enter after the arrows, would take. Public so that tests can read it.
138+ pub fn selected_suggestion(&self) -> usize {
139+ self.selected_suggestion
140+ }
141+
142+ /// Takes the selected row. Returns `false`, and does nothing, when the list is empty.
143+ fn pick_selected(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
144+ let Some(selected) = self.suggestions.get(self.selected_suggestion).cloned() else {
145+ return false;
146+ };
147+ self.pick_suggestion(&selected, window, cx);
148+ true
149+ }
150+
77 /// Updates the list of agents proposed for the mention being typed.151 /// Updates the list of agents proposed for the mention being typed.
78 pub(crate) fn refresh_suggestions(&mut self, cx: &mut Context<Self>) {152 pub(crate) fn refresh_suggestions(&mut self, cx: &mut Context<Self>) {
79 let text = self.composer.read(cx).value().to_string();153 let text = self.composer.read(cx).value().to_string();
80 let Some(channel) = self.active_channel else {154 let Some(channel) = self.active_channel else {
81 return;155 return;
82 };156 };
83- let file_words = file_query(&text);157+ // `/file` at the start, or a `$` being typed anywhere: both list files.
158+ let file_words = file_query(&text).or_else(|| trailing_file_query(&text));
84 self.file_mode = file_words.is_some();159 self.file_mode = file_words.is_some();
85 160
86 let mut suggestions: Vec<Suggestion> = if let Some(words) = file_words {161 let mut suggestions: Vec<Suggestion> = if let Some(words) = file_words {
@@ -109,23 +184,11 @@ impl SynedrionApp {
109 };184 };
110 suggestions.truncate(MAX_SUGGESTIONS);185 suggestions.truncate(MAX_SUGGESTIONS);
111 self.suggestions = suggestions;186 self.suggestions = suggestions;
187+ self.selected_suggestion = 0;
188+ self.suggestion_navigated = false;
112 cx.notify();189 cx.notify();
113 }190 }
114 191
115- /// Completes the mention being typed with the first proposed agent. Returns `false`, and
116- /// does nothing, when no agent is proposed.
117- pub(crate) fn complete_with_first_suggestion(
118- &mut self,
119- window: &mut Window,
120- cx: &mut Context<Self>,
121- ) -> bool {
122- let Some(first) = self.suggestions.first().cloned() else {
123- return false;
124- };
125- self.pick_suggestion(&first, window, cx);
126- true
127- }
128-
129 pub(crate) fn pick_suggestion(192 pub(crate) fn pick_suggestion(
130 &mut self,193 &mut self,
131 suggestion: &Suggestion,194 suggestion: &Suggestion,
@@ -145,7 +208,13 @@ impl SynedrionApp {
145 }208 }
146 Suggestion::File(relative) => {209 Suggestion::File(relative) => {
147 self.attach(relative);210 self.attach(relative);
148- self.set_composer_text(without_file_command(&text), window, cx);211+ // `/file` is removed; a `$name` typed in a sentence becomes the path of the file.
212+ let next = if file_query(&text).is_some() {
213+ without_file_command(&text)
214+ } else {
215+ complete_file_reference(&text, &relative.display().to_string())
216+ };
217+ self.set_composer_text(next, window, cx);
149 self.suggestions.clear();218 self.suggestions.clear();
150 self.file_mode = false;219 self.file_mode = false;
151 self.file_index = None;220 self.file_index = None;
@@ -216,3 +285,34 @@ impl SynedrionApp {
216 }285 }
217 }286 }
218 }287 }
288+
289+#[cfg(test)]
290+mod tests {
291+ use super::*;
292+
293+ #[test]
294+ fn down_goes_to_the_next_row_and_round_to_the_first_after_the_last() {
295+ assert_eq!(moved_selection(0, 3, Step::Down), 1);
296+ assert_eq!(moved_selection(1, 3, Step::Down), 2);
297+ assert_eq!(moved_selection(2, 3, Step::Down), 0);
298+ }
299+
300+ #[test]
301+ fn up_goes_to_the_previous_row_and_round_to_the_last_before_the_first() {
302+ assert_eq!(moved_selection(2, 3, Step::Up), 1);
303+ assert_eq!(moved_selection(1, 3, Step::Up), 0);
304+ assert_eq!(moved_selection(0, 3, Step::Up), 2);
305+ }
306+
307+ #[test]
308+ fn a_single_row_stays_selected_whichever_way_the_arrow_goes() {
309+ assert_eq!(moved_selection(0, 1, Step::Down), 0);
310+ assert_eq!(moved_selection(0, 1, Step::Up), 0);
311+ }
312+
313+ #[test]
314+ fn with_no_row_the_selection_stays_at_zero() {
315+ assert_eq!(moved_selection(0, 0, Step::Down), 0);
316+ assert_eq!(moved_selection(0, 0, Step::Up), 0);
317+ }
318+}
added crates/ui/src/trace_view.rs +199 -0
new file mode 100644
@@ -0,0 +1,199 @@
1+//! How what an agent did besides writing is drawn: a tool call that folds and unfolds, and a plan.
2+
3+use gpui_kit::component::button::{Button, ButtonVariants as _};
4+use gpui_kit::component::{ActiveTheme as _, h_flex, v_flex};
5+use gpui_kit::{
6+ AnyElement, App, Context, Hsla, SharedString, TestSupportExt as _, WeakEntity, div, prelude::*,
7+};
8+use synedrion_domain::trace::{PlanStep, Progress, ToolCallTrace, Trace};
9+
10+use crate::app::SynedrionApp;
11+
12+impl SynedrionApp {
13+ /// Unfolds a tool call that is folded, and folds one that is unfolded.
14+ pub(crate) fn toggle_trace(&mut self, message: i64, cx: &mut Context<Self>) {
15+ if !self.expanded_traces.remove(&message) {
16+ self.expanded_traces.insert(message);
17+ }
18+ // The row changes height, so the list must measure it again.
19+ if let Some(index) = self
20+ .messages
21+ .iter()
22+ .position(|candidate| candidate.id.0 == message)
23+ {
24+ self.scroller.update(cx, |scroller, cx| {
25+ scroller.remeasure_items(index..index + 1, cx)
26+ });
27+ }
28+ cx.notify();
29+ }
30+
31+ /// Whether the tool call shown by this message is unfolded. Public so that tests can read it.
32+ pub fn trace_is_expanded(&self, message: i64) -> bool {
33+ self.expanded_traces.contains(&message)
34+ }
35+}
36+
37+/// The body of a message written by a trace. Anything that is not a readable trace is shown as
38+/// the text it holds, so that nothing is lost.
39+pub(crate) fn trace_body(
40+ message: i64,
41+ text: &str,
42+ expanded: bool,
43+ app: WeakEntity<SynedrionApp>,
44+ cx: &App,
45+) -> AnyElement {
46+ let colours = Colours {
47+ muted: cx.theme().muted_foreground,
48+ border: cx.theme().border,
49+ failed: cx.theme().danger,
50+ };
51+ match Trace::from_text(text) {
52+ Some(Trace::ToolCall(call)) => tool_call(message, &call, expanded, app, colours),
53+ Some(Trace::Plan(steps)) => plan(message, &steps, colours),
54+ None => div()
55+ .id(SharedString::from(format!("trace-{message}")))
56+ .test_support()
57+ .text_sm()
58+ .text_color(colours.muted)
59+ .child(text.to_string())
60+ .into_any_element(),
61+ }
62+}
63+
64+/// The colours a trace is drawn with, taken from the theme once.
65+#[derive(Clone, Copy)]
66+struct Colours {
67+ muted: Hsla,
68+ border: Hsla,
69+ /// The colour of the status of a call that failed.
70+ failed: Hsla,
71+}
72+
73+fn tool_call(
74+ message: i64,
75+ call: &ToolCallTrace,
76+ expanded: bool,
77+ app: WeakEntity<SynedrionApp>,
78+ colours: Colours,
79+) -> AnyElement {
80+ let Colours {
81+ muted,
82+ border,
83+ failed,
84+ } = colours;
85+ let has_output = !call.output.is_empty();
86+ let status_colour = if call.progress == Progress::Failed {
87+ failed
88+ } else {
89+ muted
90+ };
91+ v_flex()
92+ .id(SharedString::from(format!("trace-{message}")))
93+ .test_support()
94+ .gap_1()
95+ .p_2()
96+ .border_1()
97+ .border_color(border)
98+ .rounded_md()
99+ .text_sm()
100+ .child(
101+ h_flex()
102+ .gap_2()
103+ .items_center()
104+ .child(call.title.clone())
105+ .child(div().text_xs().text_color(muted).child(call.kind.clone()))
106+ .child(
107+ div()
108+ .id(SharedString::from(format!("trace-status-{message}")))
109+ .test_support()
110+ .text_xs()
111+ .text_color(status_colour)
112+ .child(call.progress.label()),
113+ )
114+ .when(has_output, |header| {
115+ header.child(
116+ Button::new(SharedString::from(format!("trace-toggle-{message}")))
117+ .label(if expanded {
118+ "Hide output"
119+ } else {
120+ "Show output"
121+ })
122+ .ghost()
123+ .compact()
124+ .on_click(move |_, _, cx| {
125+ app.update(cx, |app, cx| app.toggle_trace(message, cx)).ok();
126+ }),
127+ )
128+ }),
129+ )
130+ .when(has_output && expanded, |card| {
131+ card.child(
132+ div()
133+ .id(SharedString::from(format!("trace-output-{message}")))
134+ .test_support()
135+ .px_2()
136+ .py_1()
137+ .rounded_md()
138+ .border_1()
139+ .border_color(border)
140+ .text_xs()
141+ .font_family("monospace")
142+ .child(call.output.clone()),
143+ )
144+ })
145+ .into_any_element()
146+}
147+
148+fn plan(message: i64, steps: &[PlanStep], colours: Colours) -> AnyElement {
149+ let Colours { muted, border, .. } = colours;
150+ v_flex()
151+ .id(SharedString::from(format!("trace-{message}")))
152+ .test_support()
153+ .gap_1()
154+ .p_2()
155+ .border_1()
156+ .border_color(border)
157+ .rounded_md()
158+ .text_sm()
159+ .child(div().text_xs().text_color(muted).child("Plan"))
160+ .children(steps.iter().enumerate().map(|(index, step)| {
161+ div()
162+ .id(SharedString::from(format!("plan-step-{message}-{index}")))
163+ .test_support()
164+ .child(format!("{} {}", marker(step.progress), step.text))
165+ }))
166+ .into_any_element()
167+}
168+
169+/// The sign in front of a step of a plan.
170+fn marker(progress: Progress) -> &'static str {
171+ match progress {
172+ Progress::Pending => "[ ]",
173+ Progress::InProgress => "[~]",
174+ Progress::Completed => "[x]",
175+ Progress::Failed => "[!]",
176+ }
177+}
178+
179+#[cfg(test)]
180+mod tests {
181+ use super::*;
182+
183+ #[test]
184+ fn every_step_progress_has_its_own_marker() {
185+ let markers: Vec<&str> = [
186+ Progress::Pending,
187+ Progress::InProgress,
188+ Progress::Completed,
189+ Progress::Failed,
190+ ]
191+ .into_iter()
192+ .map(marker)
193+ .collect();
194+ let mut unique = markers.clone();
195+ unique.sort();
196+ unique.dedup();
197+ assert_eq!(unique.len(), markers.len());
198+ }
199+}
new file mode 100644
@@ -0,0 +1,199 @@
1+//! How what an agent did besides writing is drawn: a tool call that folds and unfolds, and a plan.
2+
3+use gpui_kit::component::button::{Button, ButtonVariants as _};
4+use gpui_kit::component::{ActiveTheme as _, h_flex, v_flex};
5+use gpui_kit::{
6+ AnyElement, App, Context, Hsla, SharedString, TestSupportExt as _, WeakEntity, div, prelude::*,
7+};
8+use synedrion_domain::trace::{PlanStep, Progress, ToolCallTrace, Trace};
9+
10+use crate::app::SynedrionApp;
11+
12+impl SynedrionApp {
13+ /// Unfolds a tool call that is folded, and folds one that is unfolded.
14+ pub(crate) fn toggle_trace(&mut self, message: i64, cx: &mut Context<Self>) {
15+ if !self.expanded_traces.remove(&message) {
16+ self.expanded_traces.insert(message);
17+ }
18+ // The row changes height, so the list must measure it again.
19+ if let Some(index) = self
20+ .messages
21+ .iter()
22+ .position(|candidate| candidate.id.0 == message)
23+ {
24+ self.scroller.update(cx, |scroller, cx| {
25+ scroller.remeasure_items(index..index + 1, cx)
26+ });
27+ }
28+ cx.notify();
29+ }
30+
31+ /// Whether the tool call shown by this message is unfolded. Public so that tests can read it.
32+ pub fn trace_is_expanded(&self, message: i64) -> bool {
33+ self.expanded_traces.contains(&message)
34+ }
35+}
36+
37+/// The body of a message written by a trace. Anything that is not a readable trace is shown as
38+/// the text it holds, so that nothing is lost.
39+pub(crate) fn trace_body(
40+ message: i64,
41+ text: &str,
42+ expanded: bool,
43+ app: WeakEntity<SynedrionApp>,
44+ cx: &App,
45+) -> AnyElement {
46+ let colours = Colours {
47+ muted: cx.theme().muted_foreground,
48+ border: cx.theme().border,
49+ failed: cx.theme().danger,
50+ };
51+ match Trace::from_text(text) {
52+ Some(Trace::ToolCall(call)) => tool_call(message, &call, expanded, app, colours),
53+ Some(Trace::Plan(steps)) => plan(message, &steps, colours),
54+ None => div()
55+ .id(SharedString::from(format!("trace-{message}")))
56+ .test_support()
57+ .text_sm()
58+ .text_color(colours.muted)
59+ .child(text.to_string())
60+ .into_any_element(),
61+ }
62+}
63+
64+/// The colours a trace is drawn with, taken from the theme once.
65+#[derive(Clone, Copy)]
66+struct Colours {
67+ muted: Hsla,
68+ border: Hsla,
69+ /// The colour of the status of a call that failed.
70+ failed: Hsla,
71+}
72+
73+fn tool_call(
74+ message: i64,
75+ call: &ToolCallTrace,
76+ expanded: bool,
77+ app: WeakEntity<SynedrionApp>,
78+ colours: Colours,
79+) -> AnyElement {
80+ let Colours {
81+ muted,
82+ border,
83+ failed,
84+ } = colours;
85+ let has_output = !call.output.is_empty();
86+ let status_colour = if call.progress == Progress::Failed {
87+ failed
88+ } else {
89+ muted
90+ };
91+ v_flex()
92+ .id(SharedString::from(format!("trace-{message}")))
93+ .test_support()
94+ .gap_1()
95+ .p_2()
96+ .border_1()
97+ .border_color(border)
98+ .rounded_md()
99+ .text_sm()
100+ .child(
101+ h_flex()
102+ .gap_2()
103+ .items_center()
104+ .child(call.title.clone())
105+ .child(div().text_xs().text_color(muted).child(call.kind.clone()))
106+ .child(
107+ div()
108+ .id(SharedString::from(format!("trace-status-{message}")))
109+ .test_support()
110+ .text_xs()
111+ .text_color(status_colour)
112+ .child(call.progress.label()),
113+ )
114+ .when(has_output, |header| {
115+ header.child(
116+ Button::new(SharedString::from(format!("trace-toggle-{message}")))
117+ .label(if expanded {
118+ "Hide output"
119+ } else {
120+ "Show output"
121+ })
122+ .ghost()
123+ .compact()
124+ .on_click(move |_, _, cx| {
125+ app.update(cx, |app, cx| app.toggle_trace(message, cx)).ok();
126+ }),
127+ )
128+ }),
129+ )
130+ .when(has_output && expanded, |card| {
131+ card.child(
132+ div()
133+ .id(SharedString::from(format!("trace-output-{message}")))
134+ .test_support()
135+ .px_2()
136+ .py_1()
137+ .rounded_md()
138+ .border_1()
139+ .border_color(border)
140+ .text_xs()
141+ .font_family("monospace")
142+ .child(call.output.clone()),
143+ )
144+ })
145+ .into_any_element()
146+}
147+
148+fn plan(message: i64, steps: &[PlanStep], colours: Colours) -> AnyElement {
149+ let Colours { muted, border, .. } = colours;
150+ v_flex()
151+ .id(SharedString::from(format!("trace-{message}")))
152+ .test_support()
153+ .gap_1()
154+ .p_2()
155+ .border_1()
156+ .border_color(border)
157+ .rounded_md()
158+ .text_sm()
159+ .child(div().text_xs().text_color(muted).child("Plan"))
160+ .children(steps.iter().enumerate().map(|(index, step)| {
161+ div()
162+ .id(SharedString::from(format!("plan-step-{message}-{index}")))
163+ .test_support()
164+ .child(format!("{} {}", marker(step.progress), step.text))
165+ }))
166+ .into_any_element()
167+}
168+
169+/// The sign in front of a step of a plan.
170+fn marker(progress: Progress) -> &'static str {
171+ match progress {
172+ Progress::Pending => "[ ]",
173+ Progress::InProgress => "[~]",
174+ Progress::Completed => "[x]",
175+ Progress::Failed => "[!]",
176+ }
177+}
178+
179+#[cfg(test)]
180+mod tests {
181+ use super::*;
182+
183+ #[test]
184+ fn every_step_progress_has_its_own_marker() {
185+ let markers: Vec<&str> = [
186+ Progress::Pending,
187+ Progress::InProgress,
188+ Progress::Completed,
189+ Progress::Failed,
190+ ]
191+ .into_iter()
192+ .map(marker)
193+ .collect();
194+ let mut unique = markers.clone();
195+ unique.sort();
196+ unique.dedup();
197+ assert_eq!(unique.len(), markers.len());
198+ }
199+}
modified crates/ui/src/view.rs +51 -11
@@ -26,6 +26,7 @@ use synedrion_domain::message::{Author, Message};
2626
2727 use crate::app::{DOCK_BAR_WIDTH, Panel, Screen, SynedrionApp, dock_width_to_show};
2828 use crate::format::{clock_utc, status_label, tail_of};
29+use crate::trace_view::trace_body;
2930
3031 /// How many characters of an agent's reasoning are shown at most: the latest ones.
3132 const REASONING_SHOWN: usize = 700;
@@ -40,6 +41,10 @@ struct Row {
4041 text: SharedString,
4142 from_user: bool,
4243 from_system: bool,
44+ /// What an agent did besides writing: drawn as a tool call or a plan, not as text.
45+ from_trace: bool,
46+ /// For a tool call, whether its output is unfolded.
47+ expanded: bool,
4348 /// Agents write Markdown (emphasis, lists, code blocks), so their messages are rendered as
4449 /// such. The user's own text and the application's notices are shown as typed.
4550 markdown: bool,
@@ -50,6 +55,7 @@ fn row_of(message: &Message, user_name: &str) -> Row {
5055 Author::User => user_name.to_string(),
5156 Author::Agent(name) => format!("@{name}"),
5257 Author::System => "Synedrion".to_string(),
58+ Author::Trace(name) => format!("@{name}"),
5359 };
5460 Row {
5561 id: message.id.0,
@@ -58,6 +64,8 @@ fn row_of(message: &Message, user_name: &str) -> Row {
5864 text: message.content.clone().into(),
5965 from_user: message.author == Author::User,
6066 from_system: message.author == Author::System,
67+ from_trace: matches!(message.author, Author::Trace(_)),
68+ expanded: false,
6169 markdown: message.author.is_agent(),
6270 }
6371 }
@@ -92,6 +100,7 @@ fn icons_used() -> Vec<IconName> {
92100 .map(|panel| panel_look(panel).2)
93101 .collect();
94102 icons.push(CLOSE_ICON);
103+ icons.extend([IconName::Folder, IconName::ArrowUp]);
95104 icons
96105 }
97106
@@ -101,6 +110,7 @@ fn panel_look(panel: Panel) -> (&'static str, &'static str, IconName) {
101110 Panel::Channels => ("dock-channels", "Channels", IconName::Hash),
102111 Panel::ChannelSettings => ("dock-settings", "Channel settings", IconName::Settings),
103112 Panel::Agents => ("dock-agents", "Agents", IconName::Bot),
113+ Panel::Settings => ("dock-app-settings", "Settings", IconName::SlidersHorizontal),
104114 }
105115 }
106116
@@ -225,6 +235,7 @@ impl SynedrionApp {
225235 Panel::Channels => self.render_channels_panel(cx),
226236 Panel::ChannelSettings => self.render_channel_settings_panel(cx),
227237 Panel::Agents => self.render_agents_panel(cx),
238+ Panel::Settings => self.render_settings_panel(cx),
228239 })
229240 .collect();
230241
@@ -245,7 +256,7 @@ impl SynedrionApp {
245256 }
246257
247258 /// The frame every panel shares: a title, and a body that scrolls.
248- fn render_dock_panel(
259+ pub(crate) fn render_dock_panel(
249260 &self,
250261 panel: Panel,
251262 content: Vec<AnyElement>,
@@ -461,12 +472,13 @@ impl SynedrionApp {
461472 .id("agent-form-dir")
462473 .aria_label("Working folder")
463474 .into_any_element(),
464- Button::new("save-agent")
465- .label("Save agent")
466- .primary()
467- .on_click(cx.listener(|this, _, window, cx| this.save_agent(window, cx)))
468- .into_any_element(),
469475 ]);
476+ content.extend(self.render_folder_browser(cx));
477+ content.extend([Button::new("save-agent")
478+ .label("Save agent")
479+ .primary()
480+ .on_click(cx.listener(|this, _, window, cx| this.save_agent(window, cx)))
481+ .into_any_element()]);
470482 self.render_dock_panel(Panel::Agents, content, cx)
471483 }
472484
@@ -509,19 +521,44 @@ impl SynedrionApp {
509521 let rows: Rc<Vec<Row>> = Rc::new(
510522 self.messages
511523 .iter()
512- .map(|message| row_of(message, &user_name))
524+ .map(|message| Row {
525+ expanded: self.expanded_traces.contains(&message.id.0),
526+ ..row_of(message, &user_name)
527+ })
513528 .collect(),
514529 );
530+ let app = cx.weak_entity();
515531 let muted = cx.theme().muted_foreground;
516532 let own_background = cx.theme().secondary;
517533
518534 div().flex_1().min_h_0().child(MessageScroller::new(
519535 "messages",
520536 self.scroller.clone(),
521- move |index, _window, _cx| {
537+ move |index, _window, cx| {
522538 let row = rows[index].clone();
523539 let raw_text = row.text.clone();
524540 let message_id = row.id;
541+ if row.from_trace {
542+ return v_flex()
543+ .px_3()
544+ .py_1()
545+ .gap_1()
546+ .child(
547+ h_flex()
548+ .gap_2()
549+ .text_xs()
550+ .text_color(muted)
551+ .child(row.who)
552+ .child(row.when),
553+ )
554+ .child(trace_body(
555+ message_id,
556+ &row.text,
557+ row.expanded,
558+ app.clone(),
559+ cx,
560+ ));
561+ }
525562 v_flex()
526563 .px_3()
527564 .py_1()
@@ -711,7 +748,8 @@ impl SynedrionApp {
711748 .map(|agent| format!("@{agent}"))
712749 .collect();
713750
714- // The first proposal is the one Tab picks, so it is the one that stands out.
751+ // The selected proposal is the one Tab picks, so it is the one that stands out.
752+ let selected = self.selected_suggestion;
715753 let active_background = cx.theme().list_active;
716754 let hover = cx.theme().list_hover;
717755 let suggestions: Vec<AnyElement> = self
@@ -730,8 +768,10 @@ impl SynedrionApp {
730768 .rounded_md()
731769 .cursor_pointer()
732770 .text_sm()
733- .when(index == 0, |row| row.bg(active_background))
734- .when(index != 0, |row| row.hover(move |style| style.bg(hover)))
771+ .when(index == selected, |row| row.bg(active_background))
772+ .when(index != selected, |row| {
773+ row.hover(move |style| style.bg(hover))
774+ })
735775 .on_click(cx.listener(move |this, _, window, cx| {
736776 this.pick_suggestion(&picked, window, cx)
737777 }))
@@ -26,6 +26,7 @@ use synedrion_domain::message::{Author, Message};
26 26
27 use crate::app::{DOCK_BAR_WIDTH, Panel, Screen, SynedrionApp, dock_width_to_show};27 use crate::app::{DOCK_BAR_WIDTH, Panel, Screen, SynedrionApp, dock_width_to_show};
28 use crate::format::{clock_utc, status_label, tail_of};28 use crate::format::{clock_utc, status_label, tail_of};
29+use crate::trace_view::trace_body;
29 30
30 /// How many characters of an agent's reasoning are shown at most: the latest ones.31 /// How many characters of an agent's reasoning are shown at most: the latest ones.
31 const REASONING_SHOWN: usize = 700;32 const REASONING_SHOWN: usize = 700;
@@ -40,6 +41,10 @@ struct Row {
40 text: SharedString,41 text: SharedString,
41 from_user: bool,42 from_user: bool,
42 from_system: bool,43 from_system: bool,
44+ /// What an agent did besides writing: drawn as a tool call or a plan, not as text.
45+ from_trace: bool,
46+ /// For a tool call, whether its output is unfolded.
47+ expanded: bool,
43 /// Agents write Markdown (emphasis, lists, code blocks), so their messages are rendered as48 /// Agents write Markdown (emphasis, lists, code blocks), so their messages are rendered as
44 /// such. The user's own text and the application's notices are shown as typed.49 /// such. The user's own text and the application's notices are shown as typed.
45 markdown: bool,50 markdown: bool,
@@ -50,6 +55,7 @@ fn row_of(message: &Message, user_name: &str) -> Row {
50 Author::User => user_name.to_string(),55 Author::User => user_name.to_string(),
51 Author::Agent(name) => format!("@{name}"),56 Author::Agent(name) => format!("@{name}"),
52 Author::System => "Synedrion".to_string(),57 Author::System => "Synedrion".to_string(),
58+ Author::Trace(name) => format!("@{name}"),
53 };59 };
54 Row {60 Row {
55 id: message.id.0,61 id: message.id.0,
@@ -58,6 +64,8 @@ fn row_of(message: &Message, user_name: &str) -> Row {
58 text: message.content.clone().into(),64 text: message.content.clone().into(),
59 from_user: message.author == Author::User,65 from_user: message.author == Author::User,
60 from_system: message.author == Author::System,66 from_system: message.author == Author::System,
67+ from_trace: matches!(message.author, Author::Trace(_)),
68+ expanded: false,
61 markdown: message.author.is_agent(),69 markdown: message.author.is_agent(),
62 }70 }
63 }71 }
@@ -92,6 +100,7 @@ fn icons_used() -> Vec<IconName> {
92 .map(|panel| panel_look(panel).2)100 .map(|panel| panel_look(panel).2)
93 .collect();101 .collect();
94 icons.push(CLOSE_ICON);102 icons.push(CLOSE_ICON);
103+ icons.extend([IconName::Folder, IconName::ArrowUp]);
95 icons104 icons
96 }105 }
97 106
@@ -101,6 +110,7 @@ fn panel_look(panel: Panel) -> (&'static str, &'static str, IconName) {
101 Panel::Channels => ("dock-channels", "Channels", IconName::Hash),110 Panel::Channels => ("dock-channels", "Channels", IconName::Hash),
102 Panel::ChannelSettings => ("dock-settings", "Channel settings", IconName::Settings),111 Panel::ChannelSettings => ("dock-settings", "Channel settings", IconName::Settings),
103 Panel::Agents => ("dock-agents", "Agents", IconName::Bot),112 Panel::Agents => ("dock-agents", "Agents", IconName::Bot),
113+ Panel::Settings => ("dock-app-settings", "Settings", IconName::SlidersHorizontal),
104 }114 }
105 }115 }
106 116
@@ -225,6 +235,7 @@ impl SynedrionApp {
225 Panel::Channels => self.render_channels_panel(cx),235 Panel::Channels => self.render_channels_panel(cx),
226 Panel::ChannelSettings => self.render_channel_settings_panel(cx),236 Panel::ChannelSettings => self.render_channel_settings_panel(cx),
227 Panel::Agents => self.render_agents_panel(cx),237 Panel::Agents => self.render_agents_panel(cx),
238+ Panel::Settings => self.render_settings_panel(cx),
228 })239 })
229 .collect();240 .collect();
230 241
@@ -245,7 +256,7 @@ impl SynedrionApp {
245 }256 }
246 257
247 /// The frame every panel shares: a title, and a body that scrolls.258 /// The frame every panel shares: a title, and a body that scrolls.
248- fn render_dock_panel(259+ pub(crate) fn render_dock_panel(
249 &self,260 &self,
250 panel: Panel,261 panel: Panel,
251 content: Vec<AnyElement>,262 content: Vec<AnyElement>,
@@ -461,12 +472,13 @@ impl SynedrionApp {
461 .id("agent-form-dir")472 .id("agent-form-dir")
462 .aria_label("Working folder")473 .aria_label("Working folder")
463 .into_any_element(),474 .into_any_element(),
464- Button::new("save-agent")
465- .label("Save agent")
466- .primary()
467- .on_click(cx.listener(|this, _, window, cx| this.save_agent(window, cx)))
468- .into_any_element(),
469 ]);475 ]);
476+ content.extend(self.render_folder_browser(cx));
477+ content.extend([Button::new("save-agent")
478+ .label("Save agent")
479+ .primary()
480+ .on_click(cx.listener(|this, _, window, cx| this.save_agent(window, cx)))
481+ .into_any_element()]);
470 self.render_dock_panel(Panel::Agents, content, cx)482 self.render_dock_panel(Panel::Agents, content, cx)
471 }483 }
472 484
@@ -509,19 +521,44 @@ impl SynedrionApp {
509 let rows: Rc<Vec<Row>> = Rc::new(521 let rows: Rc<Vec<Row>> = Rc::new(
510 self.messages522 self.messages
511 .iter()523 .iter()
512- .map(|message| row_of(message, &user_name))524+ .map(|message| Row {
525+ expanded: self.expanded_traces.contains(&message.id.0),
526+ ..row_of(message, &user_name)
527+ })
513 .collect(),528 .collect(),
514 );529 );
530+ let app = cx.weak_entity();
515 let muted = cx.theme().muted_foreground;531 let muted = cx.theme().muted_foreground;
516 let own_background = cx.theme().secondary;532 let own_background = cx.theme().secondary;
517 533
518 div().flex_1().min_h_0().child(MessageScroller::new(534 div().flex_1().min_h_0().child(MessageScroller::new(
519 "messages",535 "messages",
520 self.scroller.clone(),536 self.scroller.clone(),
521- move |index, _window, _cx| {537+ move |index, _window, cx| {
522 let row = rows[index].clone();538 let row = rows[index].clone();
523 let raw_text = row.text.clone();539 let raw_text = row.text.clone();
524 let message_id = row.id;540 let message_id = row.id;
541+ if row.from_trace {
542+ return v_flex()
543+ .px_3()
544+ .py_1()
545+ .gap_1()
546+ .child(
547+ h_flex()
548+ .gap_2()
549+ .text_xs()
550+ .text_color(muted)
551+ .child(row.who)
552+ .child(row.when),
553+ )
554+ .child(trace_body(
555+ message_id,
556+ &row.text,
557+ row.expanded,
558+ app.clone(),
559+ cx,
560+ ));
561+ }
525 v_flex()562 v_flex()
526 .px_3()563 .px_3()
527 .py_1()564 .py_1()
@@ -711,7 +748,8 @@ impl SynedrionApp {
711 .map(|agent| format!("@{agent}"))748 .map(|agent| format!("@{agent}"))
712 .collect();749 .collect();
713 750
714- // The first proposal is the one Tab picks, so it is the one that stands out.751+ // The selected proposal is the one Tab picks, so it is the one that stands out.
752+ let selected = self.selected_suggestion;
715 let active_background = cx.theme().list_active;753 let active_background = cx.theme().list_active;
716 let hover = cx.theme().list_hover;754 let hover = cx.theme().list_hover;
717 let suggestions: Vec<AnyElement> = self755 let suggestions: Vec<AnyElement> = self
@@ -730,8 +768,10 @@ impl SynedrionApp {
730 .rounded_md()768 .rounded_md()
731 .cursor_pointer()769 .cursor_pointer()
732 .text_sm()770 .text_sm()
733- .when(index == 0, |row| row.bg(active_background))771+ .when(index == selected, |row| row.bg(active_background))
734- .when(index != 0, |row| row.hover(move |style| style.bg(hover)))772+ .when(index != selected, |row| {
773+ row.hover(move |style| style.bg(hover))
774+ })
735 .on_click(cx.listener(move |this, _, window, cx| {775 .on_click(cx.listener(move |this, _, window, cx| {
736 this.pick_suggestion(&picked, window, cx)776 this.pick_suggestion(&picked, window, cx)
737 }))777 }))
added crates/ui/tests/conversation.rs +781 -0
new file mode 100644
@@ -0,0 +1,781 @@
1+//! What the controller hands to agents, and what it does with their answers: the context of the
2+//! channel, agents calling agents, and the tool calls and plans that show up in the channel.
3+//!
4+//! No window is involved: the agents are a stand-in that records the prompts it receives.
5+
6+mod support;
7+
8+use std::sync::Arc;
9+
10+use support::FakeAgents;
11+use synedrion_acp::events::{AgentEvent, TurnOutcome};
12+use synedrion_domain::agent::{AgentDeclaration, AgentName};
13+use synedrion_domain::channel::ChannelId;
14+use synedrion_domain::message::Author;
15+use synedrion_domain::repository::Repository;
16+use synedrion_domain::settings::ChatSettings;
17+use synedrion_domain::trace::{PlanStep, Progress, ToolCallChange, ToolCallTrace, Trace};
18+use synedrion_domain::user::{DisplayName, UserProfile};
19+use synedrion_store::SqliteRepository;
20+use synedrion_ui::controller::ChatController;
21+
22+struct World {
23+ controller: ChatController,
24+ repository: Arc<SqliteRepository>,
25+ agents: Arc<FakeAgents>,
26+ channel: ChannelId,
27+}
28+
29+fn name(text: &str) -> AgentName {
30+ AgentName::new(text).unwrap()
31+}
32+
33+/// A controller for the user Ada, with these agents declared, on a fresh database.
34+fn world(agent_names: &[&str]) -> World {
35+ let repository = Arc::new(SqliteRepository::open_in_memory().unwrap());
36+ repository
37+ .save_user(&UserProfile {
38+ display_name: DisplayName::new("Ada").unwrap(),
39+ })
40+ .unwrap();
41+ for agent in agent_names {
42+ let declaration = AgentDeclaration::new(
43+ name(agent),
44+ "cmd",
45+ vec![],
46+ std::collections::BTreeMap::new(),
47+ None,
48+ )
49+ .unwrap();
50+ repository.save_agent(&declaration).unwrap();
51+ }
52+ let agents = Arc::new(FakeAgents::default());
53+ let mut controller = ChatController::new(repository.clone(), agents.clone());
54+ controller.start().unwrap();
55+ let channel = controller.channels().unwrap()[0].id;
56+ World {
57+ controller,
58+ repository,
59+ agents,
60+ channel,
61+ }
62+}
63+
64+impl World {
65+ fn say(&mut self, text: &str) {
66+ self.controller
67+ .send_user_message(self.channel, text)
68+ .unwrap();
69+ }
70+
71+ /// The prompts handed to the agents so far: who, and what.
72+ fn prompts(&self) -> Vec<(String, String)> {
73+ self.agents
74+ .prompts
75+ .lock()
76+ .unwrap()
77+ .iter()
78+ .map(|(agent, _, text)| (agent.clone(), text.clone()))
79+ .collect()
80+ }
81+
82+ fn last_prompt_of(&self, agent: &str) -> String {
83+ self.prompts()
84+ .into_iter()
85+ .rev()
86+ .find(|(who, _)| who == agent)
87+ .unwrap_or_else(|| panic!("{agent} was handed no prompt"))
88+ .1
89+ }
90+
91+ fn agent_says(&mut self, agent: &str, text: &str) {
92+ self.controller.handle_event(AgentEvent::Text {
93+ agent: name(agent),
94+ channel: self.channel,
95+ chunk: text.to_string(),
96+ });
97+ }
98+
99+ fn finish(&mut self, agent: &str) {
100+ self.finish_with(agent, TurnOutcome::Completed);
101+ }
102+
103+ fn finish_with(&mut self, agent: &str, outcome: TurnOutcome) {
104+ self.controller.handle_event(AgentEvent::TurnFinished {
105+ agent: name(agent),
106+ channel: self.channel,
107+ outcome,
108+ });
109+ }
110+
111+ /// An agent answers `text` in one piece and ends its turn.
112+ fn answer(&mut self, agent: &str, text: &str) {
113+ self.agent_says(agent, text);
114+ self.finish(agent);
115+ }
116+
117+ fn messages(&self) -> Vec<(Author, String)> {
118+ self.repository
119+ .recent_messages(self.channel, 100)
120+ .unwrap()
121+ .into_iter()
122+ .map(|message| (message.author, message.content))
123+ .collect()
124+ }
125+
126+ fn system_notices(&self) -> Vec<String> {
127+ self.messages()
128+ .into_iter()
129+ .filter(|(author, _)| *author == Author::System)
130+ .map(|(_, text)| text)
131+ .collect()
132+ }
133+
134+ fn settings(&mut self, context_messages: usize, chain_depth: usize) {
135+ self.controller
136+ .save_settings(ChatSettings {
137+ context_messages,
138+ chain_depth,
139+ })
140+ .unwrap();
141+ }
142+}
143+
144+// ---------------------------------------------------------------- the context of the channel
145+
146+#[test]
147+fn an_agent_called_for_the_first_time_is_told_what_was_said_before() {
148+ let mut world = world(&["bob"]);
149+ world.say("hello everyone");
150+ world.say("@bob what do you think?");
151+
152+ let prompt = world.last_prompt_of("bob");
153+ assert!(prompt.contains("Ada: hello everyone"), "{prompt}");
154+ assert!(prompt.ends_with("@bob what do you think?"), "{prompt}");
155+}
156+
157+#[test]
158+fn a_message_with_nothing_to_add_is_handed_over_exactly_as_typed() {
159+ let mut world = world(&["bob"]);
160+ world.say("@bob hello");
161+ assert_eq!(
162+ world.prompts(),
163+ vec![("bob".to_string(), "@bob hello".to_string())]
164+ );
165+}
166+
167+#[test]
168+fn what_an_agent_was_handed_is_not_repeated_on_its_next_turn() {
169+ let mut world = world(&["bob"]);
170+ world.say("one");
171+ world.say("@bob two");
172+ world.answer("bob", "answer");
173+ world.say("three");
174+
175+ // "one" went with the first prompt; the second prompt carries only "three".
176+ assert!(world.prompts()[0].1.contains("Ada: one"));
177+ assert_eq!(world.prompts()[1].1, "three");
178+}
179+
180+#[test]
181+fn what_other_agents_said_in_between_is_told_but_not_what_the_agent_said_itself() {
182+ let mut world = world(&["bob", "amy"]);
183+ world.say("@bob hi");
184+ world.answer("bob", "bob's own answer");
185+ world.say("@amy and you?");
186+ world.answer("amy", "amy's answer");
187+ world.say("@bob again");
188+
189+ let amy = world.last_prompt_of("amy");
190+ assert!(
191+ amy.contains("Ada: @bob hi") && amy.contains("bob: bob's own answer"),
192+ "{amy}"
193+ );
194+
195+ let bob = world.last_prompt_of("bob");
196+ assert!(bob.contains("Ada: @amy and you?"), "{bob}");
197+ assert!(bob.contains("amy: amy's answer"), "{bob}");
198+ assert!(!bob.contains("bob's own answer"), "{bob}");
199+}
200+
201+#[test]
202+fn the_notices_of_the_application_are_not_part_of_the_context() {
203+ let mut world = world(&["bob", "amy"]);
204+ world.say("@bob hi");
205+ world.finish_with("bob", TurnOutcome::Refused);
206+ world.say("@amy hello");
207+
208+ assert!(!world.last_prompt_of("amy").contains("refused"));
209+ assert!(
210+ !world.system_notices().is_empty(),
211+ "the notice is in the channel"
212+ );
213+}
214+
215+#[test]
216+fn only_the_latest_messages_are_told_and_the_others_are_counted() {
217+ let mut world = world(&["bob"]);
218+ world.settings(2, 3);
219+ for number in 1..=5 {
220+ world.say(&format!("note {number}"));
221+ }
222+ world.say("@bob now");
223+
224+ let prompt = world.last_prompt_of("bob");
225+ assert!(
226+ prompt.contains("note 4") && prompt.contains("note 5"),
227+ "{prompt}"
228+ );
229+ assert!(!prompt.contains("note 3"), "{prompt}");
230+ assert!(
231+ prompt.contains("[3 earlier message(s) not shown]"),
232+ "{prompt}"
233+ );
234+}
235+
236+#[test]
237+fn a_context_of_zero_messages_tells_the_agent_nothing_more() {
238+ let mut world = world(&["bob"]);
239+ world.settings(0, 3);
240+ world.say("secret talk");
241+ world.say("@bob now");
242+ assert_eq!(world.last_prompt_of("bob"), "@bob now");
243+}
244+
245+#[test]
246+fn a_very_long_earlier_message_is_cut_and_marked() {
247+ let mut world = world(&["bob"]);
248+ world.say(&"x".repeat(5_000));
249+ world.say("@bob now");
250+ assert!(
251+ world
252+ .last_prompt_of("bob")
253+ .contains("[message cut: 3000 more character(s)]")
254+ );
255+}
256+
257+#[test]
258+fn a_command_is_handed_over_bare_even_when_there_is_context() {
259+ let mut world = world(&["bob"]);
260+ world.say("something first");
261+ world.say("@bob /new");
262+ assert_eq!(world.last_prompt_of("bob"), "/new");
263+}
264+
265+#[test]
266+fn the_settings_are_kept_and_found_again_when_the_application_restarts() {
267+ let mut world = world(&["bob"]);
268+ world.settings(7, 1);
269+
270+ let mut restarted = ChatController::new(world.repository.clone(), world.agents.clone());
271+ restarted.start().unwrap();
272+ assert_eq!(
273+ restarted.settings(),
274+ ChatSettings {
275+ context_messages: 7,
276+ chain_depth: 1
277+ }
278+ );
279+}
280+
281+#[test]
282+fn the_defaults_apply_until_the_user_chooses() {
283+ let world = world(&[]);
284+ assert_eq!(world.controller.settings(), ChatSettings::default());
285+}
286+
287+// ------------------------------------------------------------------- agents calling agents
288+
289+#[test]
290+fn an_answer_that_mentions_another_agent_hands_it_the_answer() {
291+ let mut world = world(&["amy", "bob"]);
292+ world.say("@amy ask bob");
293+ world.answer("amy", "@bob can you check the build?");
294+
295+ let bob = world.last_prompt_of("bob");
296+ assert!(
297+ bob.ends_with("[Message from @amy]\n@bob can you check the build?"),
298+ "{bob}"
299+ );
300+ assert!(
301+ world
302+ .controller
303+ .agents_working_in(world.channel)
304+ .contains(&name("bob"))
305+ );
306+}
307+
308+#[test]
309+fn the_agent_called_is_also_told_what_the_user_said_before() {
310+ let mut world = world(&["amy", "bob"]);
311+ world.say("the build is red");
312+ world.say("@amy ask bob");
313+ world.answer("amy", "@bob can you check?");
314+
315+ let bob = world.last_prompt_of("bob");
316+ assert!(bob.contains("Ada: the build is red"), "{bob}");
317+ assert!(bob.contains("Ada: @amy ask bob"), "{bob}");
318+ assert_eq!(
319+ bob.matches("can you check?").count(),
320+ 1,
321+ "the answer is the message, not context: {bob}"
322+ );
323+}
324+
325+#[test]
326+fn a_chain_of_agents_stops_at_the_limit_and_the_channel_says_so() {
327+ let mut world = world(&["amy", "bob"]);
328+ world.settings(20, 2);
329+ world.say("@amy start");
330+ world.answer("amy", "@bob your turn"); // hop 1
331+ world.answer("bob", "@amy back to you"); // hop 2
332+ world.answer("amy", "@bob again"); // would be hop 3
333+
334+ let called: Vec<String> = world
335+ .prompts()
336+ .into_iter()
337+ .map(|(agent, _)| agent)
338+ .collect();
339+ assert_eq!(
340+ called,
341+ vec!["amy", "bob", "amy"],
342+ "the third hop was not made"
343+ );
344+ let notices = world.system_notices();
345+ assert_eq!(notices.len(), 1);
346+ assert!(
347+ notices[0].contains("Chain stopped") && notices[0].contains("@bob"),
348+ "{notices:?}"
349+ );
350+ assert!(notices[0].contains("limit of 2"), "{notices:?}");
351+}
352+
353+#[test]
354+fn the_default_limit_allows_three_hops() {
355+ let mut world = world(&["amy", "bob"]);
356+ world.say("@amy start");
357+ world.answer("amy", "@bob 1");
358+ world.answer("bob", "@amy 2");
359+ world.answer("amy", "@bob 3");
360+ world.answer("bob", "@amy 4");
361+
362+ assert_eq!(world.prompts().len(), 4);
363+ assert_eq!(world.system_notices().len(), 1);
364+}
365+
366+#[test]
367+fn a_new_message_of_the_user_starts_a_new_chain() {
368+ let mut world = world(&["amy", "bob"]);
369+ world.settings(20, 1);
370+ world.say("@amy first");
371+ world.answer("amy", "@bob 1");
372+ world.answer("bob", "@amy 2"); // stopped
373+ world.say("@amy second");
374+ world.answer("amy", "@bob 1 again");
375+
376+ assert_eq!(world.prompts().len(), 4, "the second chain got its hop");
377+}
378+
379+#[test]
380+fn stopping_interrupts_every_running_turn_and_their_answers_call_nobody() {
381+ let mut world = world(&["amy", "bob", "cat"]);
382+ world.say("@amy go");
383+ world.answer("amy", "@bob please");
384+ world.agent_says("bob", "@cat over to you");
385+ assert_eq!(world.prompts().len(), 2);
386+
387+ world.controller.stop_all(world.channel);
388+ assert_eq!(
389+ world.agents.cancelled.lock().unwrap().len(),
390+ 1,
391+ "only bob was working"
392+ );
393+
394+ // bob's answer arrives anyway, as if it had completed just before the stop.
395+ world.finish("bob");
396+ assert_eq!(world.prompts().len(), 2, "cat was not called");
397+}
398+
399+#[test]
400+fn a_turn_that_was_cancelled_or_failed_calls_nobody() {
401+ for outcome in [
402+ TurnOutcome::Cancelled,
403+ TurnOutcome::Failed("died".to_string()),
404+ TurnOutcome::Refused,
405+ ] {
406+ let mut world = world(&["amy", "bob"]);
407+ world.say("@amy go");
408+ world.agent_says("amy", "@bob please");
409+ world.finish_with("amy", outcome.clone());
410+ assert_eq!(world.prompts().len(), 1, "{outcome:?}");
411+ }
412+}
413+
414+#[test]
415+fn an_agent_that_mentions_itself_calls_nobody() {
416+ let mut world = world(&["amy"]);
417+ world.say("@amy go");
418+ world.answer("amy", "I am @amy and I will do it myself");
419+ assert_eq!(world.prompts().len(), 1);
420+ assert!(world.system_notices().is_empty());
421+}
422+
423+#[test]
424+fn a_mention_of_a_name_nobody_carries_calls_nobody() {
425+ let mut world = world(&["amy"]);
426+ world.say("@amy go");
427+ world.answer("amy", "ask @ghost about it");
428+ assert_eq!(world.prompts().len(), 1);
429+}
430+
431+#[test]
432+fn a_chain_depth_of_zero_forbids_agents_from_calling_one_another() {
433+ let mut world = world(&["amy", "bob"]);
434+ world.settings(20, 0);
435+ world.say("@amy go");
436+ world.answer("amy", "@bob please");
437+ assert_eq!(world.prompts().len(), 1);
438+ assert!(
439+ world.system_notices().is_empty(),
440+ "nothing was refused, it was off"
441+ );
442+}
443+
444+#[test]
445+fn every_agent_mentioned_is_called_once_even_when_mentioned_twice() {
446+ let mut world = world(&["amy", "bob", "cat"]);
447+ world.say("@amy go");
448+ world.answer("amy", "please ask @bob and @cat, yes @bob you too");
449+
450+ let called: Vec<String> = world
451+ .prompts()
452+ .into_iter()
453+ .map(|(agent, _)| agent)
454+ .collect();
455+ assert_eq!(called.iter().filter(|who| *who == "bob").count(), 1);
456+ assert_eq!(called.iter().filter(|who| *who == "cat").count(), 1);
457+}
458+
459+#[test]
460+fn a_message_that_starts_with_a_mention_calls_only_that_agent() {
461+ let mut world = world(&["bob", "mouse"]);
462+ world.say("@bob greet @mouse");
463+
464+ let called: Vec<String> = world
465+ .prompts()
466+ .into_iter()
467+ .map(|(agent, _)| agent)
468+ .collect();
469+ assert_eq!(called, vec!["bob"], "mouse is only talked about");
470+}
471+
472+#[test]
473+fn a_message_with_several_leading_mentions_calls_each_of_them() {
474+ let mut world = world(&["bob", "mouse", "cat"]);
475+ world.say("@bob @mouse discuss it, @cat is only mentioned");
476+
477+ let called: Vec<String> = world
478+ .prompts()
479+ .into_iter()
480+ .map(|(agent, _)| agent)
481+ .collect();
482+ assert_eq!(called, vec!["bob", "mouse"]);
483+}
484+
485+#[test]
486+fn a_name_nobody_carries_after_the_leading_mentions_raises_no_notice() {
487+ let mut world = world(&["bob"]);
488+ let sent = world
489+ .controller
490+ .send_user_message(world.channel, "@bob greet @ghost")
491+ .unwrap();
492+ assert!(sent.unknown_mentions.is_empty());
493+}
494+
495+#[test]
496+fn an_answer_that_starts_with_a_mention_calls_only_that_agent() {
497+ let mut world = world(&["amy", "bob", "cat"]);
498+ world.say("@amy go");
499+ world.answer("amy", "@bob greet @cat");
500+
501+ let called: Vec<String> = world
502+ .prompts()
503+ .into_iter()
504+ .map(|(agent, _)| agent)
505+ .collect();
506+ assert_eq!(called, vec!["amy", "bob"]);
507+}
508+
509+#[test]
510+fn a_mention_split_between_two_pieces_of_the_answer_is_still_a_mention() {
511+ let mut world = world(&["amy", "bob"]);
512+ world.say("@amy go");
513+ world.agent_says("amy", "please @");
514+ world.agent_says("amy", "bob check");
515+ world.finish("amy");
516+ assert_eq!(world.prompts().len(), 2);
517+}
518+
519+#[test]
520+fn a_mention_before_a_tool_call_counts_as_much_as_one_after() {
521+ let mut world = world(&["amy", "bob"]);
522+ world.say("@amy go");
523+ world.agent_says("amy", "asking @bob; ");
524+ world.tool_call("amy", "t1", "Look");
525+ world.agent_says("amy", "done");
526+ world.finish("amy");
527+
528+ let bob = world.last_prompt_of("bob");
529+ assert!(bob.ends_with("asking @bob; done"), "{bob}");
530+}
531+
532+#[test]
533+fn an_agent_that_cannot_be_reached_in_a_chain_is_reported_not_hidden() {
534+ let mut world = world(&["amy", "bob"]);
535+ world.agents.fail_for("bob");
536+ world.say("@amy go");
537+ world.answer("amy", "@bob please");
538+ assert!(
539+ world
540+ .system_notices()
541+ .iter()
542+ .any(|notice| notice.contains("Could not reach @bob"))
543+ );
544+}
545+
546+// ------------------------------------------------------------- tool calls and plans
547+
548+impl World {
549+ fn tool_call(&mut self, agent: &str, id: &str, title: &str) {
550+ self.controller.handle_event(AgentEvent::ToolCall {
551+ agent: name(agent),
552+ channel: self.channel,
553+ call: ToolCallTrace {
554+ id: id.to_string(),
555+ title: title.to_string(),
556+ kind: "read".to_string(),
557+ progress: Progress::InProgress,
558+ output: String::new(),
559+ },
560+ });
561+ }
562+
563+ fn tool_update(&mut self, agent: &str, id: &str, change: ToolCallChange) {
564+ self.controller.handle_event(AgentEvent::ToolCallUpdated {
565+ agent: name(agent),
566+ channel: self.channel,
567+ id: id.to_string(),
568+ change,
569+ });
570+ }
571+
572+ fn plan(&mut self, agent: &str, steps: &[(&str, Progress)]) {
573+ self.controller.handle_event(AgentEvent::Plan {
574+ agent: name(agent),
575+ channel: self.channel,
576+ steps: steps
577+ .iter()
578+ .map(|(text, progress)| PlanStep {
579+ text: text.to_string(),
580+ progress: *progress,
581+ })
582+ .collect(),
583+ });
584+ }
585+
586+ /// The traces in the channel, in order.
587+ fn traces(&self) -> Vec<Trace> {
588+ self.messages()
589+ .into_iter()
590+ .filter(|(author, _)| matches!(author, Author::Trace(_)))
591+ .map(|(_, text)| Trace::from_text(&text).expect("a readable trace"))
592+ .collect()
593+ }
594+}
595+
596+fn completed_with(output: &str) -> ToolCallChange {
597+ ToolCallChange {
598+ progress: Some(Progress::Completed),
599+ output: Some(output.to_string()),
600+ ..Default::default()
601+ }
602+}
603+
604+#[test]
605+fn a_tool_call_shows_up_in_the_channel_as_a_message_of_a_trace() {
606+ let mut world = world(&["amy"]);
607+ world.say("@amy read it");
608+ world.tool_call("amy", "t1", "Read notes.md");
609+
610+ let messages = world.messages();
611+ let (author, _) = messages.last().unwrap();
612+ assert_eq!(*author, Author::Trace(name("amy")));
613+ assert!(matches!(&world.traces()[0], Trace::ToolCall(call) if call.title == "Read notes.md"));
614+}
615+
616+#[test]
617+fn an_update_changes_the_same_message_instead_of_adding_one() {
618+ let mut world = world(&["amy"]);
619+ world.say("@amy read it");
620+ world.tool_call("amy", "t1", "Read notes.md");
621+ let count = world.messages().len();
622+ world.tool_update("amy", "t1", completed_with("the notes"));
623+
624+ assert_eq!(world.messages().len(), count);
625+ let Trace::ToolCall(call) = &world.traces()[0] else {
626+ panic!("expected a tool call");
627+ };
628+ assert_eq!(call.progress, Progress::Completed);
629+ assert_eq!(call.output, "the notes");
630+ assert_eq!(
631+ call.title, "Read notes.md",
632+ "what the update did not carry is kept"
633+ );
634+}
635+
636+#[test]
637+fn an_update_for_a_call_never_announced_is_shown_not_lost() {
638+ let mut world = world(&["amy"]);
639+ world.say("@amy go");
640+ world.tool_update("amy", "ghost", completed_with("out"));
641+
642+ let Trace::ToolCall(call) = &world.traces()[0] else {
643+ panic!("expected a tool call");
644+ };
645+ assert_eq!(
646+ (call.title.as_str(), call.output.as_str()),
647+ ("Tool call", "out")
648+ );
649+}
650+
651+#[test]
652+fn two_tool_calls_of_a_turn_are_two_messages_updated_apart() {
653+ let mut world = world(&["amy"]);
654+ world.say("@amy go");
655+ world.tool_call("amy", "a", "First");
656+ world.tool_call("amy", "b", "Second");
657+ world.tool_update("amy", "a", completed_with("one"));
658+
659+ let traces = world.traces();
660+ assert_eq!(traces.len(), 2);
661+ assert!(matches!(&traces[0], Trace::ToolCall(c) if c.output == "one"));
662+ assert!(matches!(&traces[1], Trace::ToolCall(c) if c.output.is_empty()));
663+}
664+
665+#[test]
666+fn the_same_call_announced_twice_is_one_message() {
667+ let mut world = world(&["amy"]);
668+ world.say("@amy go");
669+ world.tool_call("amy", "a", "First");
670+ world.tool_call("amy", "a", "First again");
671+ assert_eq!(world.traces().len(), 1);
672+}
673+
674+#[test]
675+fn a_plan_is_one_message_that_is_replaced_each_time_it_changes() {
676+ let mut world = world(&["amy"]);
677+ world.say("@amy go");
678+ world.plan(
679+ "amy",
680+ &[("read", Progress::InProgress), ("write", Progress::Pending)],
681+ );
682+ world.plan(
683+ "amy",
684+ &[
685+ ("read", Progress::Completed),
686+ ("write", Progress::InProgress),
687+ ],
688+ );
689+
690+ let traces = world.traces();
691+ assert_eq!(traces.len(), 1);
692+ let Trace::Plan(steps) = &traces[0] else {
693+ panic!("expected a plan");
694+ };
695+ assert_eq!(steps[0].progress, Progress::Completed);
696+ assert_eq!(steps[1].progress, Progress::InProgress);
697+}
698+
699+#[test]
700+fn the_text_written_after_a_tool_call_comes_after_it_in_the_channel() {
701+ let mut world = world(&["amy"]);
702+ world.say("@amy go");
703+ world.agent_says("amy", "Let me look. ");
704+ world.tool_call("amy", "t1", "Look");
705+ world.agent_says("amy", "Found it.");
706+
707+ let kinds: Vec<String> = world
708+ .messages()
709+ .into_iter()
710+ .skip(1)
711+ .map(|(author, text)| match author {
712+ Author::Agent(_) => format!("text: {text}"),
713+ Author::Trace(_) => "trace".to_string(),
714+ other => format!("{other:?}"),
715+ })
716+ .collect();
717+ assert_eq!(
718+ kinds,
719+ vec!["text: Let me look. ", "trace", "text: Found it."]
720+ );
721+}
722+
723+#[test]
724+fn a_call_of_one_turn_does_not_get_updated_by_the_next_turn() {
725+ let mut world = world(&["amy"]);
726+ world.say("@amy go");
727+ world.tool_call("amy", "t1", "First turn");
728+ world.finish("amy");
729+ world.say("again");
730+ world.tool_call("amy", "t1", "Second turn");
731+
732+ assert_eq!(world.traces().len(), 2);
733+}
734+
735+#[test]
736+fn traces_are_not_told_to_other_agents_as_context() {
737+ let mut world = world(&["amy", "bob"]);
738+ world.say("@amy go");
739+ world.tool_call("amy", "t1", "Secret tool title");
740+ world.plan("amy", &[("a secret step", Progress::Pending)]);
741+ world.answer("amy", "all done");
742+ world.say("@bob your view?");
743+
744+ let bob = world.last_prompt_of("bob");
745+ assert!(bob.contains("amy: all done"), "{bob}");
746+ assert!(
747+ !bob.contains("Secret tool title") && !bob.contains("a secret step"),
748+ "{bob}"
749+ );
750+}
751+
752+#[test]
753+fn a_trace_does_not_change_who_a_message_without_mention_goes_to() {
754+ let mut world = world(&["amy", "bob"]);
755+ world.say("@amy go");
756+ world.tool_call("amy", "t1", "Look");
757+ world.answer("amy", "done");
758+ world.say("and then?");
759+
760+ assert_eq!(world.last_prompt_of("amy"), "and then?");
761+ assert_eq!(
762+ world
763+ .prompts()
764+ .iter()
765+ .filter(|(who, _)| who == "bob")
766+ .count(),
767+ 0
768+ );
769+}
770+
771+#[test]
772+fn a_notice_of_an_agent_is_shown_with_its_name() {
773+ let mut world = world(&["amy"]);
774+ world.say("@amy go");
775+ world.controller.handle_event(AgentEvent::Notice {
776+ agent: name("amy"),
777+ channel: world.channel,
778+ text: "Context nearly full".to_string(),
779+ });
780+ assert_eq!(world.system_notices(), vec!["@amy: Context nearly full"]);
781+}
new file mode 100644
@@ -0,0 +1,781 @@
1+//! What the controller hands to agents, and what it does with their answers: the context of the
2+//! channel, agents calling agents, and the tool calls and plans that show up in the channel.
3+//!
4+//! No window is involved: the agents are a stand-in that records the prompts it receives.
5+
6+mod support;
7+
8+use std::sync::Arc;
9+
10+use support::FakeAgents;
11+use synedrion_acp::events::{AgentEvent, TurnOutcome};
12+use synedrion_domain::agent::{AgentDeclaration, AgentName};
13+use synedrion_domain::channel::ChannelId;
14+use synedrion_domain::message::Author;
15+use synedrion_domain::repository::Repository;
16+use synedrion_domain::settings::ChatSettings;
17+use synedrion_domain::trace::{PlanStep, Progress, ToolCallChange, ToolCallTrace, Trace};
18+use synedrion_domain::user::{DisplayName, UserProfile};
19+use synedrion_store::SqliteRepository;
20+use synedrion_ui::controller::ChatController;
21+
22+struct World {
23+ controller: ChatController,
24+ repository: Arc<SqliteRepository>,
25+ agents: Arc<FakeAgents>,
26+ channel: ChannelId,
27+}
28+
29+fn name(text: &str) -> AgentName {
30+ AgentName::new(text).unwrap()
31+}
32+
33+/// A controller for the user Ada, with these agents declared, on a fresh database.
34+fn world(agent_names: &[&str]) -> World {
35+ let repository = Arc::new(SqliteRepository::open_in_memory().unwrap());
36+ repository
37+ .save_user(&UserProfile {
38+ display_name: DisplayName::new("Ada").unwrap(),
39+ })
40+ .unwrap();
41+ for agent in agent_names {
42+ let declaration = AgentDeclaration::new(
43+ name(agent),
44+ "cmd",
45+ vec![],
46+ std::collections::BTreeMap::new(),
47+ None,
48+ )
49+ .unwrap();
50+ repository.save_agent(&declaration).unwrap();
51+ }
52+ let agents = Arc::new(FakeAgents::default());
53+ let mut controller = ChatController::new(repository.clone(), agents.clone());
54+ controller.start().unwrap();
55+ let channel = controller.channels().unwrap()[0].id;
56+ World {
57+ controller,
58+ repository,
59+ agents,
60+ channel,
61+ }
62+}
63+
64+impl World {
65+ fn say(&mut self, text: &str) {
66+ self.controller
67+ .send_user_message(self.channel, text)
68+ .unwrap();
69+ }
70+
71+ /// The prompts handed to the agents so far: who, and what.
72+ fn prompts(&self) -> Vec<(String, String)> {
73+ self.agents
74+ .prompts
75+ .lock()
76+ .unwrap()
77+ .iter()
78+ .map(|(agent, _, text)| (agent.clone(), text.clone()))
79+ .collect()
80+ }
81+
82+ fn last_prompt_of(&self, agent: &str) -> String {
83+ self.prompts()
84+ .into_iter()
85+ .rev()
86+ .find(|(who, _)| who == agent)
87+ .unwrap_or_else(|| panic!("{agent} was handed no prompt"))
88+ .1
89+ }
90+
91+ fn agent_says(&mut self, agent: &str, text: &str) {
92+ self.controller.handle_event(AgentEvent::Text {
93+ agent: name(agent),
94+ channel: self.channel,
95+ chunk: text.to_string(),
96+ });
97+ }
98+
99+ fn finish(&mut self, agent: &str) {
100+ self.finish_with(agent, TurnOutcome::Completed);
101+ }
102+
103+ fn finish_with(&mut self, agent: &str, outcome: TurnOutcome) {
104+ self.controller.handle_event(AgentEvent::TurnFinished {
105+ agent: name(agent),
106+ channel: self.channel,
107+ outcome,
108+ });
109+ }
110+
111+ /// An agent answers `text` in one piece and ends its turn.
112+ fn answer(&mut self, agent: &str, text: &str) {
113+ self.agent_says(agent, text);
114+ self.finish(agent);
115+ }
116+
117+ fn messages(&self) -> Vec<(Author, String)> {
118+ self.repository
119+ .recent_messages(self.channel, 100)
120+ .unwrap()
121+ .into_iter()
122+ .map(|message| (message.author, message.content))
123+ .collect()
124+ }
125+
126+ fn system_notices(&self) -> Vec<String> {
127+ self.messages()
128+ .into_iter()
129+ .filter(|(author, _)| *author == Author::System)
130+ .map(|(_, text)| text)
131+ .collect()
132+ }
133+
134+ fn settings(&mut self, context_messages: usize, chain_depth: usize) {
135+ self.controller
136+ .save_settings(ChatSettings {
137+ context_messages,
138+ chain_depth,
139+ })
140+ .unwrap();
141+ }
142+}
143+
144+// ---------------------------------------------------------------- the context of the channel
145+
146+#[test]
147+fn an_agent_called_for_the_first_time_is_told_what_was_said_before() {
148+ let mut world = world(&["bob"]);
149+ world.say("hello everyone");
150+ world.say("@bob what do you think?");
151+
152+ let prompt = world.last_prompt_of("bob");
153+ assert!(prompt.contains("Ada: hello everyone"), "{prompt}");
154+ assert!(prompt.ends_with("@bob what do you think?"), "{prompt}");
155+}
156+
157+#[test]
158+fn a_message_with_nothing_to_add_is_handed_over_exactly_as_typed() {
159+ let mut world = world(&["bob"]);
160+ world.say("@bob hello");
161+ assert_eq!(
162+ world.prompts(),
163+ vec![("bob".to_string(), "@bob hello".to_string())]
164+ );
165+}
166+
167+#[test]
168+fn what_an_agent_was_handed_is_not_repeated_on_its_next_turn() {
169+ let mut world = world(&["bob"]);
170+ world.say("one");
171+ world.say("@bob two");
172+ world.answer("bob", "answer");
173+ world.say("three");
174+
175+ // "one" went with the first prompt; the second prompt carries only "three".
176+ assert!(world.prompts()[0].1.contains("Ada: one"));
177+ assert_eq!(world.prompts()[1].1, "three");
178+}
179+
180+#[test]
181+fn what_other_agents_said_in_between_is_told_but_not_what_the_agent_said_itself() {
182+ let mut world = world(&["bob", "amy"]);
183+ world.say("@bob hi");
184+ world.answer("bob", "bob's own answer");
185+ world.say("@amy and you?");
186+ world.answer("amy", "amy's answer");
187+ world.say("@bob again");
188+
189+ let amy = world.last_prompt_of("amy");
190+ assert!(
191+ amy.contains("Ada: @bob hi") && amy.contains("bob: bob's own answer"),
192+ "{amy}"
193+ );
194+
195+ let bob = world.last_prompt_of("bob");
196+ assert!(bob.contains("Ada: @amy and you?"), "{bob}");
197+ assert!(bob.contains("amy: amy's answer"), "{bob}");
198+ assert!(!bob.contains("bob's own answer"), "{bob}");
199+}
200+
201+#[test]
202+fn the_notices_of_the_application_are_not_part_of_the_context() {
203+ let mut world = world(&["bob", "amy"]);
204+ world.say("@bob hi");
205+ world.finish_with("bob", TurnOutcome::Refused);
206+ world.say("@amy hello");
207+
208+ assert!(!world.last_prompt_of("amy").contains("refused"));
209+ assert!(
210+ !world.system_notices().is_empty(),
211+ "the notice is in the channel"
212+ );
213+}
214+
215+#[test]
216+fn only_the_latest_messages_are_told_and_the_others_are_counted() {
217+ let mut world = world(&["bob"]);
218+ world.settings(2, 3);
219+ for number in 1..=5 {
220+ world.say(&format!("note {number}"));
221+ }
222+ world.say("@bob now");
223+
224+ let prompt = world.last_prompt_of("bob");
225+ assert!(
226+ prompt.contains("note 4") && prompt.contains("note 5"),
227+ "{prompt}"
228+ );
229+ assert!(!prompt.contains("note 3"), "{prompt}");
230+ assert!(
231+ prompt.contains("[3 earlier message(s) not shown]"),
232+ "{prompt}"
233+ );
234+}
235+
236+#[test]
237+fn a_context_of_zero_messages_tells_the_agent_nothing_more() {
238+ let mut world = world(&["bob"]);
239+ world.settings(0, 3);
240+ world.say("secret talk");
241+ world.say("@bob now");
242+ assert_eq!(world.last_prompt_of("bob"), "@bob now");
243+}
244+
245+#[test]
246+fn a_very_long_earlier_message_is_cut_and_marked() {
247+ let mut world = world(&["bob"]);
248+ world.say(&"x".repeat(5_000));
249+ world.say("@bob now");
250+ assert!(
251+ world
252+ .last_prompt_of("bob")
253+ .contains("[message cut: 3000 more character(s)]")
254+ );
255+}
256+
257+#[test]
258+fn a_command_is_handed_over_bare_even_when_there_is_context() {
259+ let mut world = world(&["bob"]);
260+ world.say("something first");
261+ world.say("@bob /new");
262+ assert_eq!(world.last_prompt_of("bob"), "/new");
263+}
264+
265+#[test]
266+fn the_settings_are_kept_and_found_again_when_the_application_restarts() {
267+ let mut world = world(&["bob"]);
268+ world.settings(7, 1);
269+
270+ let mut restarted = ChatController::new(world.repository.clone(), world.agents.clone());
271+ restarted.start().unwrap();
272+ assert_eq!(
273+ restarted.settings(),
274+ ChatSettings {
275+ context_messages: 7,
276+ chain_depth: 1
277+ }
278+ );
279+}
280+
281+#[test]
282+fn the_defaults_apply_until_the_user_chooses() {
283+ let world = world(&[]);
284+ assert_eq!(world.controller.settings(), ChatSettings::default());
285+}
286+
287+// ------------------------------------------------------------------- agents calling agents
288+
289+#[test]
290+fn an_answer_that_mentions_another_agent_hands_it_the_answer() {
291+ let mut world = world(&["amy", "bob"]);
292+ world.say("@amy ask bob");
293+ world.answer("amy", "@bob can you check the build?");
294+
295+ let bob = world.last_prompt_of("bob");
296+ assert!(
297+ bob.ends_with("[Message from @amy]\n@bob can you check the build?"),
298+ "{bob}"
299+ );
300+ assert!(
301+ world
302+ .controller
303+ .agents_working_in(world.channel)
304+ .contains(&name("bob"))
305+ );
306+}
307+
308+#[test]
309+fn the_agent_called_is_also_told_what_the_user_said_before() {
310+ let mut world = world(&["amy", "bob"]);
311+ world.say("the build is red");
312+ world.say("@amy ask bob");
313+ world.answer("amy", "@bob can you check?");
314+
315+ let bob = world.last_prompt_of("bob");
316+ assert!(bob.contains("Ada: the build is red"), "{bob}");
317+ assert!(bob.contains("Ada: @amy ask bob"), "{bob}");
318+ assert_eq!(
319+ bob.matches("can you check?").count(),
320+ 1,
321+ "the answer is the message, not context: {bob}"
322+ );
323+}
324+
325+#[test]
326+fn a_chain_of_agents_stops_at_the_limit_and_the_channel_says_so() {
327+ let mut world = world(&["amy", "bob"]);
328+ world.settings(20, 2);
329+ world.say("@amy start");
330+ world.answer("amy", "@bob your turn"); // hop 1
331+ world.answer("bob", "@amy back to you"); // hop 2
332+ world.answer("amy", "@bob again"); // would be hop 3
333+
334+ let called: Vec<String> = world
335+ .prompts()
336+ .into_iter()
337+ .map(|(agent, _)| agent)
338+ .collect();
339+ assert_eq!(
340+ called,
341+ vec!["amy", "bob", "amy"],
342+ "the third hop was not made"
343+ );
344+ let notices = world.system_notices();
345+ assert_eq!(notices.len(), 1);
346+ assert!(
347+ notices[0].contains("Chain stopped") && notices[0].contains("@bob"),
348+ "{notices:?}"
349+ );
350+ assert!(notices[0].contains("limit of 2"), "{notices:?}");
351+}
352+
353+#[test]
354+fn the_default_limit_allows_three_hops() {
355+ let mut world = world(&["amy", "bob"]);
356+ world.say("@amy start");
357+ world.answer("amy", "@bob 1");
358+ world.answer("bob", "@amy 2");
359+ world.answer("amy", "@bob 3");
360+ world.answer("bob", "@amy 4");
361+
362+ assert_eq!(world.prompts().len(), 4);
363+ assert_eq!(world.system_notices().len(), 1);
364+}
365+
366+#[test]
367+fn a_new_message_of_the_user_starts_a_new_chain() {
368+ let mut world = world(&["amy", "bob"]);
369+ world.settings(20, 1);
370+ world.say("@amy first");
371+ world.answer("amy", "@bob 1");
372+ world.answer("bob", "@amy 2"); // stopped
373+ world.say("@amy second");
374+ world.answer("amy", "@bob 1 again");
375+
376+ assert_eq!(world.prompts().len(), 4, "the second chain got its hop");
377+}
378+
379+#[test]
380+fn stopping_interrupts_every_running_turn_and_their_answers_call_nobody() {
381+ let mut world = world(&["amy", "bob", "cat"]);
382+ world.say("@amy go");
383+ world.answer("amy", "@bob please");
384+ world.agent_says("bob", "@cat over to you");
385+ assert_eq!(world.prompts().len(), 2);
386+
387+ world.controller.stop_all(world.channel);
388+ assert_eq!(
389+ world.agents.cancelled.lock().unwrap().len(),
390+ 1,
391+ "only bob was working"
392+ );
393+
394+ // bob's answer arrives anyway, as if it had completed just before the stop.
395+ world.finish("bob");
396+ assert_eq!(world.prompts().len(), 2, "cat was not called");
397+}
398+
399+#[test]
400+fn a_turn_that_was_cancelled_or_failed_calls_nobody() {
401+ for outcome in [
402+ TurnOutcome::Cancelled,
403+ TurnOutcome::Failed("died".to_string()),
404+ TurnOutcome::Refused,
405+ ] {
406+ let mut world = world(&["amy", "bob"]);
407+ world.say("@amy go");
408+ world.agent_says("amy", "@bob please");
409+ world.finish_with("amy", outcome.clone());
410+ assert_eq!(world.prompts().len(), 1, "{outcome:?}");
411+ }
412+}
413+
414+#[test]
415+fn an_agent_that_mentions_itself_calls_nobody() {
416+ let mut world = world(&["amy"]);
417+ world.say("@amy go");
418+ world.answer("amy", "I am @amy and I will do it myself");
419+ assert_eq!(world.prompts().len(), 1);
420+ assert!(world.system_notices().is_empty());
421+}
422+
423+#[test]
424+fn a_mention_of_a_name_nobody_carries_calls_nobody() {
425+ let mut world = world(&["amy"]);
426+ world.say("@amy go");
427+ world.answer("amy", "ask @ghost about it");
428+ assert_eq!(world.prompts().len(), 1);
429+}
430+
431+#[test]
432+fn a_chain_depth_of_zero_forbids_agents_from_calling_one_another() {
433+ let mut world = world(&["amy", "bob"]);
434+ world.settings(20, 0);
435+ world.say("@amy go");
436+ world.answer("amy", "@bob please");
437+ assert_eq!(world.prompts().len(), 1);
438+ assert!(
439+ world.system_notices().is_empty(),
440+ "nothing was refused, it was off"
441+ );
442+}
443+
444+#[test]
445+fn every_agent_mentioned_is_called_once_even_when_mentioned_twice() {
446+ let mut world = world(&["amy", "bob", "cat"]);
447+ world.say("@amy go");
448+ world.answer("amy", "please ask @bob and @cat, yes @bob you too");
449+
450+ let called: Vec<String> = world
451+ .prompts()
452+ .into_iter()
453+ .map(|(agent, _)| agent)
454+ .collect();
455+ assert_eq!(called.iter().filter(|who| *who == "bob").count(), 1);
456+ assert_eq!(called.iter().filter(|who| *who == "cat").count(), 1);
457+}
458+
459+#[test]
460+fn a_message_that_starts_with_a_mention_calls_only_that_agent() {
461+ let mut world = world(&["bob", "mouse"]);
462+ world.say("@bob greet @mouse");
463+
464+ let called: Vec<String> = world
465+ .prompts()
466+ .into_iter()
467+ .map(|(agent, _)| agent)
468+ .collect();
469+ assert_eq!(called, vec!["bob"], "mouse is only talked about");
470+}
471+
472+#[test]
473+fn a_message_with_several_leading_mentions_calls_each_of_them() {
474+ let mut world = world(&["bob", "mouse", "cat"]);
475+ world.say("@bob @mouse discuss it, @cat is only mentioned");
476+
477+ let called: Vec<String> = world
478+ .prompts()
479+ .into_iter()
480+ .map(|(agent, _)| agent)
481+ .collect();
482+ assert_eq!(called, vec!["bob", "mouse"]);
483+}
484+
485+#[test]
486+fn a_name_nobody_carries_after_the_leading_mentions_raises_no_notice() {
487+ let mut world = world(&["bob"]);
488+ let sent = world
489+ .controller
490+ .send_user_message(world.channel, "@bob greet @ghost")
491+ .unwrap();
492+ assert!(sent.unknown_mentions.is_empty());
493+}
494+
495+#[test]
496+fn an_answer_that_starts_with_a_mention_calls_only_that_agent() {
497+ let mut world = world(&["amy", "bob", "cat"]);
498+ world.say("@amy go");
499+ world.answer("amy", "@bob greet @cat");
500+
501+ let called: Vec<String> = world
502+ .prompts()
503+ .into_iter()
504+ .map(|(agent, _)| agent)
505+ .collect();
506+ assert_eq!(called, vec!["amy", "bob"]);
507+}
508+
509+#[test]
510+fn a_mention_split_between_two_pieces_of_the_answer_is_still_a_mention() {
511+ let mut world = world(&["amy", "bob"]);
512+ world.say("@amy go");
513+ world.agent_says("amy", "please @");
514+ world.agent_says("amy", "bob check");
515+ world.finish("amy");
516+ assert_eq!(world.prompts().len(), 2);
517+}
518+
519+#[test]
520+fn a_mention_before_a_tool_call_counts_as_much_as_one_after() {
521+ let mut world = world(&["amy", "bob"]);
522+ world.say("@amy go");
523+ world.agent_says("amy", "asking @bob; ");
524+ world.tool_call("amy", "t1", "Look");
525+ world.agent_says("amy", "done");
526+ world.finish("amy");
527+
528+ let bob = world.last_prompt_of("bob");
529+ assert!(bob.ends_with("asking @bob; done"), "{bob}");
530+}
531+
532+#[test]
533+fn an_agent_that_cannot_be_reached_in_a_chain_is_reported_not_hidden() {
534+ let mut world = world(&["amy", "bob"]);
535+ world.agents.fail_for("bob");
536+ world.say("@amy go");
537+ world.answer("amy", "@bob please");
538+ assert!(
539+ world
540+ .system_notices()
541+ .iter()
542+ .any(|notice| notice.contains("Could not reach @bob"))
543+ );
544+}
545+
546+// ------------------------------------------------------------- tool calls and plans
547+
548+impl World {
549+ fn tool_call(&mut self, agent: &str, id: &str, title: &str) {
550+ self.controller.handle_event(AgentEvent::ToolCall {
551+ agent: name(agent),
552+ channel: self.channel,
553+ call: ToolCallTrace {
554+ id: id.to_string(),
555+ title: title.to_string(),
556+ kind: "read".to_string(),
557+ progress: Progress::InProgress,
558+ output: String::new(),
559+ },
560+ });
561+ }
562+
563+ fn tool_update(&mut self, agent: &str, id: &str, change: ToolCallChange) {
564+ self.controller.handle_event(AgentEvent::ToolCallUpdated {
565+ agent: name(agent),
566+ channel: self.channel,
567+ id: id.to_string(),
568+ change,
569+ });
570+ }
571+
572+ fn plan(&mut self, agent: &str, steps: &[(&str, Progress)]) {
573+ self.controller.handle_event(AgentEvent::Plan {
574+ agent: name(agent),
575+ channel: self.channel,
576+ steps: steps
577+ .iter()
578+ .map(|(text, progress)| PlanStep {
579+ text: text.to_string(),
580+ progress: *progress,
581+ })
582+ .collect(),
583+ });
584+ }
585+
586+ /// The traces in the channel, in order.
587+ fn traces(&self) -> Vec<Trace> {
588+ self.messages()
589+ .into_iter()
590+ .filter(|(author, _)| matches!(author, Author::Trace(_)))
591+ .map(|(_, text)| Trace::from_text(&text).expect("a readable trace"))
592+ .collect()
593+ }
594+}
595+
596+fn completed_with(output: &str) -> ToolCallChange {
597+ ToolCallChange {
598+ progress: Some(Progress::Completed),
599+ output: Some(output.to_string()),
600+ ..Default::default()
601+ }
602+}
603+
604+#[test]
605+fn a_tool_call_shows_up_in_the_channel_as_a_message_of_a_trace() {
606+ let mut world = world(&["amy"]);
607+ world.say("@amy read it");
608+ world.tool_call("amy", "t1", "Read notes.md");
609+
610+ let messages = world.messages();
611+ let (author, _) = messages.last().unwrap();
612+ assert_eq!(*author, Author::Trace(name("amy")));
613+ assert!(matches!(&world.traces()[0], Trace::ToolCall(call) if call.title == "Read notes.md"));
614+}
615+
616+#[test]
617+fn an_update_changes_the_same_message_instead_of_adding_one() {
618+ let mut world = world(&["amy"]);
619+ world.say("@amy read it");
620+ world.tool_call("amy", "t1", "Read notes.md");
621+ let count = world.messages().len();
622+ world.tool_update("amy", "t1", completed_with("the notes"));
623+
624+ assert_eq!(world.messages().len(), count);
625+ let Trace::ToolCall(call) = &world.traces()[0] else {
626+ panic!("expected a tool call");
627+ };
628+ assert_eq!(call.progress, Progress::Completed);
629+ assert_eq!(call.output, "the notes");
630+ assert_eq!(
631+ call.title, "Read notes.md",
632+ "what the update did not carry is kept"
633+ );
634+}
635+
636+#[test]
637+fn an_update_for_a_call_never_announced_is_shown_not_lost() {
638+ let mut world = world(&["amy"]);
639+ world.say("@amy go");
640+ world.tool_update("amy", "ghost", completed_with("out"));
641+
642+ let Trace::ToolCall(call) = &world.traces()[0] else {
643+ panic!("expected a tool call");
644+ };
645+ assert_eq!(
646+ (call.title.as_str(), call.output.as_str()),
647+ ("Tool call", "out")
648+ );
649+}
650+
651+#[test]
652+fn two_tool_calls_of_a_turn_are_two_messages_updated_apart() {
653+ let mut world = world(&["amy"]);
654+ world.say("@amy go");
655+ world.tool_call("amy", "a", "First");
656+ world.tool_call("amy", "b", "Second");
657+ world.tool_update("amy", "a", completed_with("one"));
658+
659+ let traces = world.traces();
660+ assert_eq!(traces.len(), 2);
661+ assert!(matches!(&traces[0], Trace::ToolCall(c) if c.output == "one"));
662+ assert!(matches!(&traces[1], Trace::ToolCall(c) if c.output.is_empty()));
663+}
664+
665+#[test]
666+fn the_same_call_announced_twice_is_one_message() {
667+ let mut world = world(&["amy"]);
668+ world.say("@amy go");
669+ world.tool_call("amy", "a", "First");
670+ world.tool_call("amy", "a", "First again");
671+ assert_eq!(world.traces().len(), 1);
672+}
673+
674+#[test]
675+fn a_plan_is_one_message_that_is_replaced_each_time_it_changes() {
676+ let mut world = world(&["amy"]);
677+ world.say("@amy go");
678+ world.plan(
679+ "amy",
680+ &[("read", Progress::InProgress), ("write", Progress::Pending)],
681+ );
682+ world.plan(
683+ "amy",
684+ &[
685+ ("read", Progress::Completed),
686+ ("write", Progress::InProgress),
687+ ],
688+ );
689+
690+ let traces = world.traces();
691+ assert_eq!(traces.len(), 1);
692+ let Trace::Plan(steps) = &traces[0] else {
693+ panic!("expected a plan");
694+ };
695+ assert_eq!(steps[0].progress, Progress::Completed);
696+ assert_eq!(steps[1].progress, Progress::InProgress);
697+}
698+
699+#[test]
700+fn the_text_written_after_a_tool_call_comes_after_it_in_the_channel() {
701+ let mut world = world(&["amy"]);
702+ world.say("@amy go");
703+ world.agent_says("amy", "Let me look. ");
704+ world.tool_call("amy", "t1", "Look");
705+ world.agent_says("amy", "Found it.");
706+
707+ let kinds: Vec<String> = world
708+ .messages()
709+ .into_iter()
710+ .skip(1)
711+ .map(|(author, text)| match author {
712+ Author::Agent(_) => format!("text: {text}"),
713+ Author::Trace(_) => "trace".to_string(),
714+ other => format!("{other:?}"),
715+ })
716+ .collect();
717+ assert_eq!(
718+ kinds,
719+ vec!["text: Let me look. ", "trace", "text: Found it."]
720+ );
721+}
722+
723+#[test]
724+fn a_call_of_one_turn_does_not_get_updated_by_the_next_turn() {
725+ let mut world = world(&["amy"]);
726+ world.say("@amy go");
727+ world.tool_call("amy", "t1", "First turn");
728+ world.finish("amy");
729+ world.say("again");
730+ world.tool_call("amy", "t1", "Second turn");
731+
732+ assert_eq!(world.traces().len(), 2);
733+}
734+
735+#[test]
736+fn traces_are_not_told_to_other_agents_as_context() {
737+ let mut world = world(&["amy", "bob"]);
738+ world.say("@amy go");
739+ world.tool_call("amy", "t1", "Secret tool title");
740+ world.plan("amy", &[("a secret step", Progress::Pending)]);
741+ world.answer("amy", "all done");
742+ world.say("@bob your view?");
743+
744+ let bob = world.last_prompt_of("bob");
745+ assert!(bob.contains("amy: all done"), "{bob}");
746+ assert!(
747+ !bob.contains("Secret tool title") && !bob.contains("a secret step"),
748+ "{bob}"
749+ );
750+}
751+
752+#[test]
753+fn a_trace_does_not_change_who_a_message_without_mention_goes_to() {
754+ let mut world = world(&["amy", "bob"]);
755+ world.say("@amy go");
756+ world.tool_call("amy", "t1", "Look");
757+ world.answer("amy", "done");
758+ world.say("and then?");
759+
760+ assert_eq!(world.last_prompt_of("amy"), "and then?");
761+ assert_eq!(
762+ world
763+ .prompts()
764+ .iter()
765+ .filter(|(who, _)| who == "bob")
766+ .count(),
767+ 0
768+ );
769+}
770+
771+#[test]
772+fn a_notice_of_an_agent_is_shown_with_its_name() {
773+ let mut world = world(&["amy"]);
774+ world.say("@amy go");
775+ world.controller.handle_event(AgentEvent::Notice {
776+ agent: name("amy"),
777+ channel: world.channel,
778+ text: "Context nearly full".to_string(),
779+ });
780+ assert_eq!(world.system_notices(), vec!["@amy: Context nearly full"]);
781+}
added crates/ui/tests/file_reference.rs +165 -0
new file mode 100644
@@ -0,0 +1,165 @@
1+//! Naming a file in the middle of a sentence with `$`, driven like a user would.
2+
3+mod support;
4+
5+use gpui_kit::TestAppContext;
6+use support::{click, exists, open_ready_app_in, press, type_in, type_in_focused};
7+
8+/// A folder of files that is removed when the test ends.
9+struct Folder(std::path::PathBuf);
10+
11+impl Folder {
12+ fn with(name: &str, files: &[&str]) -> Self {
13+ let root =
14+ std::env::temp_dir().join(format!("synedrion-reference-{name}-{}", std::process::id()));
15+ let _ = std::fs::remove_dir_all(&root);
16+ for file in files {
17+ let path = root.join(file);
18+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
19+ std::fs::write(path, "content").unwrap();
20+ }
21+ Folder(root)
22+ }
23+}
24+
25+impl Drop for Folder {
26+ fn drop(&mut self) {
27+ let _ = std::fs::remove_dir_all(&self.0);
28+ }
29+}
30+
31+fn last_prompt(harness: &support::Harness) -> String {
32+ harness
33+ .agents
34+ .prompts
35+ .lock()
36+ .unwrap()
37+ .last()
38+ .expect("a prompt was sent")
39+ .2
40+ .clone()
41+}
42+
43+fn last_files(harness: &support::Harness) -> Vec<std::path::PathBuf> {
44+ harness.agents.files.lock().unwrap().last().unwrap().clone()
45+}
46+
47+#[gpui_kit::test]
48+fn a_dollar_in_a_sentence_lists_the_files_and_the_picked_one_is_written_in_the_sentence(
49+ cx: &mut TestAppContext,
50+) {
51+ let folder = Folder::with("sentence", &["notes.md", "src/main.rs", "src/lib.rs"]);
52+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
53+
54+ type_in(cx, &harness, "composer", "@bob look at $");
55+ assert!(
56+ exists(cx, &harness, "suggest-file-2"),
57+ "every file is listed"
58+ );
59+
60+ type_in_focused(cx, &harness, "main");
61+ assert!(exists(cx, &harness, "suggest-file-0"));
62+ assert!(
63+ !exists(cx, &harness, "suggest-file-1"),
64+ "only src/main.rs matches"
65+ );
66+ press(cx, &harness, "tab");
67+
68+ assert!(exists(cx, &harness, "attachment-0"), "the file is attached");
69+ assert!(
70+ !exists(cx, &harness, "suggest-file-0"),
71+ "the list is closed"
72+ );
73+
74+ type_in_focused(cx, &harness, "and fix it");
75+ click(cx, &harness, "send");
76+
77+ assert_eq!(last_prompt(&harness), "@bob look at src/main.rs and fix it");
78+ assert_eq!(last_files(&harness), vec![folder.0.join("src/main.rs")]);
79+ assert_eq!(
80+ harness.said_in(harness.first_channel()),
81+ vec!["@bob look at src/main.rs and fix it"],
82+ "the file is already named in the sentence, so no extra line"
83+ );
84+}
85+
86+#[gpui_kit::test]
87+fn a_click_on_a_row_does_the_same_as_tab(cx: &mut TestAppContext) {
88+ let folder = Folder::with("click", &["a.txt", "b.txt"]);
89+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
90+ type_in(cx, &harness, "composer", "@bob compare $b");
91+ click(cx, &harness, "suggest-file-0");
92+ type_in_focused(cx, &harness, "please");
93+ click(cx, &harness, "send");
94+
95+ assert_eq!(last_prompt(&harness), "@bob compare b.txt please");
96+ assert_eq!(last_files(&harness), vec![folder.0.join("b.txt")]);
97+}
98+
99+#[gpui_kit::test]
100+fn several_files_can_be_named_in_one_sentence(cx: &mut TestAppContext) {
101+ let folder = Folder::with("two", &["a.txt", "b.txt"]);
102+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
103+ type_in(cx, &harness, "composer", "@bob compare $a");
104+ press(cx, &harness, "tab");
105+ type_in_focused(cx, &harness, "and $b");
106+ press(cx, &harness, "tab");
107+ click(cx, &harness, "send");
108+
109+ assert_eq!(last_prompt(&harness), "@bob compare a.txt and b.txt");
110+ assert_eq!(
111+ last_files(&harness),
112+ vec![folder.0.join("a.txt"), folder.0.join("b.txt")]
113+ );
114+}
115+
116+#[gpui_kit::test]
117+fn nothing_that_matches_says_so(cx: &mut TestAppContext) {
118+ let folder = Folder::with("none", &["a.txt"]);
119+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
120+ type_in(cx, &harness, "composer", "@bob read $zzz");
121+ assert!(!exists(cx, &harness, "suggest-file-0"));
122+ assert!(exists(cx, &harness, "no-file-match"));
123+}
124+
125+#[gpui_kit::test]
126+fn a_dollar_that_is_not_a_file_reference_opens_nothing(cx: &mut TestAppContext) {
127+ let folder = Folder::with("price", &["a.txt"]);
128+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
129+ type_in(cx, &harness, "composer", "@bob it costs US$5");
130+ assert!(!exists(cx, &harness, "suggest-file-0"));
131+ assert!(!exists(cx, &harness, "no-file-match"));
132+}
133+
134+#[gpui_kit::test]
135+fn the_list_closes_once_the_reference_is_followed_by_a_space(cx: &mut TestAppContext) {
136+ let folder = Folder::with("closes", &["a.txt"]);
137+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
138+ type_in(cx, &harness, "composer", "@bob look at $a");
139+ assert!(exists(cx, &harness, "suggest-file-0"));
140+ type_in_focused(cx, &harness, " and more");
141+ assert!(!exists(cx, &harness, "suggest-file-0"));
142+}
143+
144+#[gpui_kit::test]
145+fn the_dollar_works_before_anyone_was_addressed_in_the_current_folder(cx: &mut TestAppContext) {
146+ let harness = support::open_ready_app(cx, &["bob"]);
147+ type_in(cx, &harness, "composer", "see $Cargo");
148+ assert!(
149+ exists(cx, &harness, "suggest-file-0") || exists(cx, &harness, "no-file-match"),
150+ "the list opens, in the folder Synedrion runs in"
151+ );
152+}
153+
154+#[gpui_kit::test]
155+fn taking_the_chip_back_out_leaves_the_sentence_alone(cx: &mut TestAppContext) {
156+ let folder = Folder::with("chip", &["a.txt"]);
157+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
158+ type_in(cx, &harness, "composer", "@bob look at $a");
159+ press(cx, &harness, "tab");
160+ click(cx, &harness, "remove-attachment-0");
161+ click(cx, &harness, "send");
162+
163+ assert_eq!(last_prompt(&harness), "@bob look at a.txt");
164+ assert!(last_files(&harness).is_empty());
165+}
new file mode 100644
@@ -0,0 +1,165 @@
1+//! Naming a file in the middle of a sentence with `$`, driven like a user would.
2+
3+mod support;
4+
5+use gpui_kit::TestAppContext;
6+use support::{click, exists, open_ready_app_in, press, type_in, type_in_focused};
7+
8+/// A folder of files that is removed when the test ends.
9+struct Folder(std::path::PathBuf);
10+
11+impl Folder {
12+ fn with(name: &str, files: &[&str]) -> Self {
13+ let root =
14+ std::env::temp_dir().join(format!("synedrion-reference-{name}-{}", std::process::id()));
15+ let _ = std::fs::remove_dir_all(&root);
16+ for file in files {
17+ let path = root.join(file);
18+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
19+ std::fs::write(path, "content").unwrap();
20+ }
21+ Folder(root)
22+ }
23+}
24+
25+impl Drop for Folder {
26+ fn drop(&mut self) {
27+ let _ = std::fs::remove_dir_all(&self.0);
28+ }
29+}
30+
31+fn last_prompt(harness: &support::Harness) -> String {
32+ harness
33+ .agents
34+ .prompts
35+ .lock()
36+ .unwrap()
37+ .last()
38+ .expect("a prompt was sent")
39+ .2
40+ .clone()
41+}
42+
43+fn last_files(harness: &support::Harness) -> Vec<std::path::PathBuf> {
44+ harness.agents.files.lock().unwrap().last().unwrap().clone()
45+}
46+
47+#[gpui_kit::test]
48+fn a_dollar_in_a_sentence_lists_the_files_and_the_picked_one_is_written_in_the_sentence(
49+ cx: &mut TestAppContext,
50+) {
51+ let folder = Folder::with("sentence", &["notes.md", "src/main.rs", "src/lib.rs"]);
52+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
53+
54+ type_in(cx, &harness, "composer", "@bob look at $");
55+ assert!(
56+ exists(cx, &harness, "suggest-file-2"),
57+ "every file is listed"
58+ );
59+
60+ type_in_focused(cx, &harness, "main");
61+ assert!(exists(cx, &harness, "suggest-file-0"));
62+ assert!(
63+ !exists(cx, &harness, "suggest-file-1"),
64+ "only src/main.rs matches"
65+ );
66+ press(cx, &harness, "tab");
67+
68+ assert!(exists(cx, &harness, "attachment-0"), "the file is attached");
69+ assert!(
70+ !exists(cx, &harness, "suggest-file-0"),
71+ "the list is closed"
72+ );
73+
74+ type_in_focused(cx, &harness, "and fix it");
75+ click(cx, &harness, "send");
76+
77+ assert_eq!(last_prompt(&harness), "@bob look at src/main.rs and fix it");
78+ assert_eq!(last_files(&harness), vec![folder.0.join("src/main.rs")]);
79+ assert_eq!(
80+ harness.said_in(harness.first_channel()),
81+ vec!["@bob look at src/main.rs and fix it"],
82+ "the file is already named in the sentence, so no extra line"
83+ );
84+}
85+
86+#[gpui_kit::test]
87+fn a_click_on_a_row_does_the_same_as_tab(cx: &mut TestAppContext) {
88+ let folder = Folder::with("click", &["a.txt", "b.txt"]);
89+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
90+ type_in(cx, &harness, "composer", "@bob compare $b");
91+ click(cx, &harness, "suggest-file-0");
92+ type_in_focused(cx, &harness, "please");
93+ click(cx, &harness, "send");
94+
95+ assert_eq!(last_prompt(&harness), "@bob compare b.txt please");
96+ assert_eq!(last_files(&harness), vec![folder.0.join("b.txt")]);
97+}
98+
99+#[gpui_kit::test]
100+fn several_files_can_be_named_in_one_sentence(cx: &mut TestAppContext) {
101+ let folder = Folder::with("two", &["a.txt", "b.txt"]);
102+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
103+ type_in(cx, &harness, "composer", "@bob compare $a");
104+ press(cx, &harness, "tab");
105+ type_in_focused(cx, &harness, "and $b");
106+ press(cx, &harness, "tab");
107+ click(cx, &harness, "send");
108+
109+ assert_eq!(last_prompt(&harness), "@bob compare a.txt and b.txt");
110+ assert_eq!(
111+ last_files(&harness),
112+ vec![folder.0.join("a.txt"), folder.0.join("b.txt")]
113+ );
114+}
115+
116+#[gpui_kit::test]
117+fn nothing_that_matches_says_so(cx: &mut TestAppContext) {
118+ let folder = Folder::with("none", &["a.txt"]);
119+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
120+ type_in(cx, &harness, "composer", "@bob read $zzz");
121+ assert!(!exists(cx, &harness, "suggest-file-0"));
122+ assert!(exists(cx, &harness, "no-file-match"));
123+}
124+
125+#[gpui_kit::test]
126+fn a_dollar_that_is_not_a_file_reference_opens_nothing(cx: &mut TestAppContext) {
127+ let folder = Folder::with("price", &["a.txt"]);
128+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
129+ type_in(cx, &harness, "composer", "@bob it costs US$5");
130+ assert!(!exists(cx, &harness, "suggest-file-0"));
131+ assert!(!exists(cx, &harness, "no-file-match"));
132+}
133+
134+#[gpui_kit::test]
135+fn the_list_closes_once_the_reference_is_followed_by_a_space(cx: &mut TestAppContext) {
136+ let folder = Folder::with("closes", &["a.txt"]);
137+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
138+ type_in(cx, &harness, "composer", "@bob look at $a");
139+ assert!(exists(cx, &harness, "suggest-file-0"));
140+ type_in_focused(cx, &harness, " and more");
141+ assert!(!exists(cx, &harness, "suggest-file-0"));
142+}
143+
144+#[gpui_kit::test]
145+fn the_dollar_works_before_anyone_was_addressed_in_the_current_folder(cx: &mut TestAppContext) {
146+ let harness = support::open_ready_app(cx, &["bob"]);
147+ type_in(cx, &harness, "composer", "see $Cargo");
148+ assert!(
149+ exists(cx, &harness, "suggest-file-0") || exists(cx, &harness, "no-file-match"),
150+ "the list opens, in the folder Synedrion runs in"
151+ );
152+}
153+
154+#[gpui_kit::test]
155+fn taking_the_chip_back_out_leaves_the_sentence_alone(cx: &mut TestAppContext) {
156+ let folder = Folder::with("chip", &["a.txt"]);
157+ let harness = open_ready_app_in(cx, &["bob"], &folder.0);
158+ type_in(cx, &harness, "composer", "@bob look at $a");
159+ press(cx, &harness, "tab");
160+ click(cx, &harness, "remove-attachment-0");
161+ click(cx, &harness, "send");
162+
163+ assert_eq!(last_prompt(&harness), "@bob look at a.txt");
164+ assert!(last_files(&harness).is_empty());
165+}
added crates/ui/tests/folder_browser.rs +139 -0
new file mode 100644
@@ -0,0 +1,139 @@
1+//! The folder browser of the agent form, driven like a user would: open it, walk through the
2+//! folders, choose one.
3+
4+mod support;
5+
6+use std::path::PathBuf;
7+
8+use gpui_kit::TestAppContext;
9+use support::{click, exists, open_ready_app, type_in};
10+
11+/// A folder of folders that is removed when the test ends.
12+struct Tree(PathBuf);
13+
14+impl Tree {
15+ fn new(name: &str, folders: &[&str]) -> Self {
16+ let root =
17+ std::env::temp_dir().join(format!("synedrion-browser-{name}-{}", std::process::id()));
18+ let _ = std::fs::remove_dir_all(&root);
19+ std::fs::create_dir_all(&root).unwrap();
20+ for folder in folders {
21+ std::fs::create_dir_all(root.join(folder)).unwrap();
22+ }
23+ Tree(root)
24+ }
25+}
26+
27+impl Drop for Tree {
28+ fn drop(&mut self) {
29+ let _ = std::fs::remove_dir_all(&self.0);
30+ }
31+}
32+
33+fn open_browser_on(cx: &mut TestAppContext, tree: &Tree) -> support::Harness {
34+ let harness = open_ready_app(cx, &[]);
35+ click(cx, &harness, "dock-agents");
36+ type_in(
37+ cx,
38+ &harness,
39+ "agent-form-dir",
40+ &tree.0.display().to_string(),
41+ );
42+ click(cx, &harness, "browse-folders");
43+ harness
44+}
45+
46+fn browsed_folder(cx: &mut TestAppContext, harness: &support::Harness) -> Option<PathBuf> {
47+ cx.update(|cx| harness.app.read(cx).browsed_folder().map(PathBuf::from))
48+}
49+
50+fn working_folder_field(cx: &mut TestAppContext, harness: &support::Harness) -> String {
51+ cx.update(|cx| harness.app.read(cx).working_folder_text(cx))
52+}
53+
54+#[gpui_kit::test]
55+fn the_browser_is_closed_until_the_browse_button_is_clicked(cx: &mut TestAppContext) {
56+ let harness = open_ready_app(cx, &[]);
57+ click(cx, &harness, "dock-agents");
58+ assert!(exists(cx, &harness, "browse-folders"));
59+ assert!(!exists(cx, &harness, "folder-browser"));
60+ click(cx, &harness, "browse-folders");
61+ assert!(exists(cx, &harness, "folder-browser"));
62+ assert!(!exists(cx, &harness, "browse-folders"));
63+}
64+
65+#[gpui_kit::test]
66+fn the_browser_opens_on_the_folder_typed_in_the_field(cx: &mut TestAppContext) {
67+ let tree = Tree::new("typed", &["alpha", "beta"]);
68+ let harness = open_browser_on(cx, &tree);
69+ assert_eq!(browsed_folder(cx, &harness), Some(tree.0.clone()));
70+ assert!(exists(cx, &harness, "folder-row-0"));
71+ assert!(exists(cx, &harness, "folder-row-1"));
72+ assert!(!exists(cx, &harness, "folder-row-2"));
73+}
74+
75+#[gpui_kit::test]
76+fn clicking_a_folder_goes_into_it_and_the_up_row_goes_back(cx: &mut TestAppContext) {
77+ let tree = Tree::new("walk", &["alpha/inner", "beta"]);
78+ let harness = open_browser_on(cx, &tree);
79+
80+ click(cx, &harness, "folder-row-0");
81+ assert_eq!(browsed_folder(cx, &harness), Some(tree.0.join("alpha")));
82+ assert!(exists(cx, &harness, "folder-row-0"), "inner is listed");
83+ assert!(!exists(cx, &harness, "folder-row-1"));
84+
85+ click(cx, &harness, "folder-up");
86+ assert_eq!(browsed_folder(cx, &harness), Some(tree.0.clone()));
87+ assert!(exists(cx, &harness, "folder-row-1"), "back at the top");
88+}
89+
90+#[gpui_kit::test]
91+fn a_folder_without_sub_folders_says_so(cx: &mut TestAppContext) {
92+ let tree = Tree::new("empty", &[]);
93+ let harness = open_browser_on(cx, &tree);
94+ assert!(exists(cx, &harness, "no-folders"));
95+}
96+
97+#[gpui_kit::test]
98+fn using_the_folder_on_show_fills_the_field_and_closes_the_browser(cx: &mut TestAppContext) {
99+ let tree = Tree::new("choose", &["project"]);
100+ let harness = open_browser_on(cx, &tree);
101+ click(cx, &harness, "folder-row-0");
102+ click(cx, &harness, "folder-choose");
103+
104+ assert_eq!(
105+ working_folder_field(cx, &harness),
106+ tree.0.join("project").display().to_string()
107+ );
108+ assert!(!exists(cx, &harness, "folder-browser"));
109+}
110+
111+#[gpui_kit::test]
112+fn cancelling_closes_the_browser_and_leaves_the_field_alone(cx: &mut TestAppContext) {
113+ let tree = Tree::new("cancel", &["project"]);
114+ let harness = open_browser_on(cx, &tree);
115+ click(cx, &harness, "folder-row-0");
116+ click(cx, &harness, "folder-cancel");
117+
118+ assert_eq!(
119+ working_folder_field(cx, &harness),
120+ tree.0.display().to_string()
121+ );
122+ assert!(!exists(cx, &harness, "folder-browser"));
123+}
124+
125+#[gpui_kit::test]
126+fn the_chosen_folder_is_saved_with_the_agent(cx: &mut TestAppContext) {
127+ use synedrion_domain::repository::Repository as _;
128+
129+ let tree = Tree::new("saved", &["project"]);
130+ let harness = open_browser_on(cx, &tree);
131+ click(cx, &harness, "folder-row-0");
132+ click(cx, &harness, "folder-choose");
133+ type_in(cx, &harness, "agent-form-name", "bob");
134+ type_in(cx, &harness, "agent-form-command", "run");
135+ click(cx, &harness, "save-agent");
136+
137+ let agents = harness.repository.list_agents().unwrap();
138+ assert_eq!(agents[0].working_dir, Some(tree.0.join("project")));
139+}
new file mode 100644
@@ -0,0 +1,139 @@
1+//! The folder browser of the agent form, driven like a user would: open it, walk through the
2+//! folders, choose one.
3+
4+mod support;
5+
6+use std::path::PathBuf;
7+
8+use gpui_kit::TestAppContext;
9+use support::{click, exists, open_ready_app, type_in};
10+
11+/// A folder of folders that is removed when the test ends.
12+struct Tree(PathBuf);
13+
14+impl Tree {
15+ fn new(name: &str, folders: &[&str]) -> Self {
16+ let root =
17+ std::env::temp_dir().join(format!("synedrion-browser-{name}-{}", std::process::id()));
18+ let _ = std::fs::remove_dir_all(&root);
19+ std::fs::create_dir_all(&root).unwrap();
20+ for folder in folders {
21+ std::fs::create_dir_all(root.join(folder)).unwrap();
22+ }
23+ Tree(root)
24+ }
25+}
26+
27+impl Drop for Tree {
28+ fn drop(&mut self) {
29+ let _ = std::fs::remove_dir_all(&self.0);
30+ }
31+}
32+
33+fn open_browser_on(cx: &mut TestAppContext, tree: &Tree) -> support::Harness {
34+ let harness = open_ready_app(cx, &[]);
35+ click(cx, &harness, "dock-agents");
36+ type_in(
37+ cx,
38+ &harness,
39+ "agent-form-dir",
40+ &tree.0.display().to_string(),
41+ );
42+ click(cx, &harness, "browse-folders");
43+ harness
44+}
45+
46+fn browsed_folder(cx: &mut TestAppContext, harness: &support::Harness) -> Option<PathBuf> {
47+ cx.update(|cx| harness.app.read(cx).browsed_folder().map(PathBuf::from))
48+}
49+
50+fn working_folder_field(cx: &mut TestAppContext, harness: &support::Harness) -> String {
51+ cx.update(|cx| harness.app.read(cx).working_folder_text(cx))
52+}
53+
54+#[gpui_kit::test]
55+fn the_browser_is_closed_until_the_browse_button_is_clicked(cx: &mut TestAppContext) {
56+ let harness = open_ready_app(cx, &[]);
57+ click(cx, &harness, "dock-agents");
58+ assert!(exists(cx, &harness, "browse-folders"));
59+ assert!(!exists(cx, &harness, "folder-browser"));
60+ click(cx, &harness, "browse-folders");
61+ assert!(exists(cx, &harness, "folder-browser"));
62+ assert!(!exists(cx, &harness, "browse-folders"));
63+}
64+
65+#[gpui_kit::test]
66+fn the_browser_opens_on_the_folder_typed_in_the_field(cx: &mut TestAppContext) {
67+ let tree = Tree::new("typed", &["alpha", "beta"]);
68+ let harness = open_browser_on(cx, &tree);
69+ assert_eq!(browsed_folder(cx, &harness), Some(tree.0.clone()));
70+ assert!(exists(cx, &harness, "folder-row-0"));
71+ assert!(exists(cx, &harness, "folder-row-1"));
72+ assert!(!exists(cx, &harness, "folder-row-2"));
73+}
74+
75+#[gpui_kit::test]
76+fn clicking_a_folder_goes_into_it_and_the_up_row_goes_back(cx: &mut TestAppContext) {
77+ let tree = Tree::new("walk", &["alpha/inner", "beta"]);
78+ let harness = open_browser_on(cx, &tree);
79+
80+ click(cx, &harness, "folder-row-0");
81+ assert_eq!(browsed_folder(cx, &harness), Some(tree.0.join("alpha")));
82+ assert!(exists(cx, &harness, "folder-row-0"), "inner is listed");
83+ assert!(!exists(cx, &harness, "folder-row-1"));
84+
85+ click(cx, &harness, "folder-up");
86+ assert_eq!(browsed_folder(cx, &harness), Some(tree.0.clone()));
87+ assert!(exists(cx, &harness, "folder-row-1"), "back at the top");
88+}
89+
90+#[gpui_kit::test]
91+fn a_folder_without_sub_folders_says_so(cx: &mut TestAppContext) {
92+ let tree = Tree::new("empty", &[]);
93+ let harness = open_browser_on(cx, &tree);
94+ assert!(exists(cx, &harness, "no-folders"));
95+}
96+
97+#[gpui_kit::test]
98+fn using_the_folder_on_show_fills_the_field_and_closes_the_browser(cx: &mut TestAppContext) {
99+ let tree = Tree::new("choose", &["project"]);
100+ let harness = open_browser_on(cx, &tree);
101+ click(cx, &harness, "folder-row-0");
102+ click(cx, &harness, "folder-choose");
103+
104+ assert_eq!(
105+ working_folder_field(cx, &harness),
106+ tree.0.join("project").display().to_string()
107+ );
108+ assert!(!exists(cx, &harness, "folder-browser"));
109+}
110+
111+#[gpui_kit::test]
112+fn cancelling_closes_the_browser_and_leaves_the_field_alone(cx: &mut TestAppContext) {
113+ let tree = Tree::new("cancel", &["project"]);
114+ let harness = open_browser_on(cx, &tree);
115+ click(cx, &harness, "folder-row-0");
116+ click(cx, &harness, "folder-cancel");
117+
118+ assert_eq!(
119+ working_folder_field(cx, &harness),
120+ tree.0.display().to_string()
121+ );
122+ assert!(!exists(cx, &harness, "folder-browser"));
123+}
124+
125+#[gpui_kit::test]
126+fn the_chosen_folder_is_saved_with_the_agent(cx: &mut TestAppContext) {
127+ use synedrion_domain::repository::Repository as _;
128+
129+ let tree = Tree::new("saved", &["project"]);
130+ let harness = open_browser_on(cx, &tree);
131+ click(cx, &harness, "folder-row-0");
132+ click(cx, &harness, "folder-choose");
133+ type_in(cx, &harness, "agent-form-name", "bob");
134+ type_in(cx, &harness, "agent-form-command", "run");
135+ click(cx, &harness, "save-agent");
136+
137+ let agents = harness.repository.list_agents().unwrap();
138+ assert_eq!(agents[0].working_dir, Some(tree.0.join("project")));
139+}
added crates/ui/tests/settings_and_traces.rs +364 -0
new file mode 100644
@@ -0,0 +1,364 @@
1+//! The settings panel, the tool calls and plans in the conversation, and the stop button, driven
2+//! like a user would.
3+
4+mod support;
5+
6+use gpui_kit::TestAppContext;
7+use support::{click, exists, open_ready_app, press, type_in, type_in_focused};
8+use synedrion_acp::events::{AgentEvent, TurnOutcome};
9+use synedrion_domain::agent::AgentName;
10+use synedrion_domain::repository::Repository;
11+use synedrion_domain::settings::ChatSettings;
12+use synedrion_domain::trace::{PlanStep, Progress, ToolCallChange, ToolCallTrace};
13+
14+/// Replaces what a field holds: selects it all, then types.
15+fn replace_in(
16+ cx: &mut TestAppContext,
17+ harness: &support::Harness,
18+ target: &'static str,
19+ text: &str,
20+) {
21+ click(cx, harness, target);
22+ press(cx, harness, "ctrl-a");
23+ type_in_focused(cx, harness, text);
24+}
25+
26+fn notice(cx: &mut TestAppContext, harness: &support::Harness) -> String {
27+ cx.update(|cx| {
28+ harness
29+ .app
30+ .read(cx)
31+ .notice()
32+ .unwrap_or_default()
33+ .to_string()
34+ })
35+}
36+
37+/// An identifier built at run time, which the helpers want for the whole run of the test.
38+fn id(text: String) -> &'static str {
39+ Box::leak(text.into_boxed_str())
40+}
41+
42+fn name(text: &str) -> AgentName {
43+ AgentName::new(text).unwrap()
44+}
45+
46+// -------------------------------------------------------------------------------- settings
47+
48+#[gpui_kit::test]
49+fn the_settings_panel_opens_from_the_bar_and_closes_from_its_title(cx: &mut TestAppContext) {
50+ let harness = open_ready_app(cx, &[]);
51+ assert!(!exists(cx, &harness, "panel-app-settings"));
52+ click(cx, &harness, "dock-app-settings");
53+ assert!(exists(cx, &harness, "panel-app-settings"));
54+ click(cx, &harness, "close-app-settings");
55+ assert!(!exists(cx, &harness, "panel-app-settings"));
56+}
57+
58+#[gpui_kit::test]
59+fn valid_settings_are_saved_and_the_user_is_told(cx: &mut TestAppContext) {
60+ let harness = open_ready_app(cx, &[]);
61+ click(cx, &harness, "dock-app-settings");
62+ replace_in(cx, &harness, "settings-context", "5");
63+ replace_in(cx, &harness, "settings-depth", "1");
64+ click(cx, &harness, "save-settings");
65+
66+ assert_eq!(
67+ harness.repository.load_settings().unwrap(),
68+ ChatSettings {
69+ context_messages: 5,
70+ chain_depth: 1
71+ }
72+ );
73+ assert!(notice(cx, &harness).contains("Settings saved"));
74+}
75+
76+#[gpui_kit::test]
77+fn a_setting_that_is_not_a_number_is_refused_and_nothing_is_saved(cx: &mut TestAppContext) {
78+ let harness = open_ready_app(cx, &[]);
79+ click(cx, &harness, "dock-app-settings");
80+ replace_in(cx, &harness, "settings-depth", "lots");
81+ click(cx, &harness, "save-settings");
82+
83+ assert!(notice(cx, &harness).contains("Chain depth must be a whole number"));
84+ assert_eq!(
85+ harness.repository.load_settings().unwrap(),
86+ ChatSettings::default()
87+ );
88+}
89+
90+#[gpui_kit::test]
91+fn a_setting_above_its_limit_is_refused(cx: &mut TestAppContext) {
92+ let harness = open_ready_app(cx, &[]);
93+ click(cx, &harness, "dock-app-settings");
94+ replace_in(cx, &harness, "settings-context", "100000");
95+ click(cx, &harness, "save-settings");
96+
97+ assert!(notice(cx, &harness).contains("Messages of context must be at most"));
98+ assert_eq!(
99+ harness.repository.load_settings().unwrap(),
100+ ChatSettings::default()
101+ );
102+}
103+
104+#[gpui_kit::test]
105+fn saved_settings_apply_to_the_next_message(cx: &mut TestAppContext) {
106+ let harness = open_ready_app(cx, &["bob"]);
107+ click(cx, &harness, "dock-app-settings");
108+ replace_in(cx, &harness, "settings-context", "0");
109+ click(cx, &harness, "save-settings");
110+
111+ type_in(cx, &harness, "composer", "private words");
112+ click(cx, &harness, "send");
113+ type_in(cx, &harness, "composer", "@bob now");
114+ click(cx, &harness, "send");
115+
116+ let prompts = harness.agents.prompts.lock().unwrap().clone();
117+ assert_eq!(prompts[0].2, "@bob now", "no context was given");
118+}
119+
120+#[gpui_kit::test]
121+fn without_changing_the_settings_the_agent_is_told_what_was_said(cx: &mut TestAppContext) {
122+ let harness = open_ready_app(cx, &["bob"]);
123+ type_in(cx, &harness, "composer", "private words");
124+ click(cx, &harness, "send");
125+ type_in(cx, &harness, "composer", "@bob now");
126+ click(cx, &harness, "send");
127+
128+ let prompts = harness.agents.prompts.lock().unwrap().clone();
129+ assert!(prompts[0].2.contains("Ada: private words"));
130+}
131+
132+// ------------------------------------------------------------------ tool calls and plans
133+
134+fn tool_call(harness: &support::Harness, cx: &mut TestAppContext, call_id: &str, output: &str) {
135+ harness.agent_event(
136+ cx,
137+ AgentEvent::ToolCall {
138+ agent: name("bob"),
139+ channel: harness.first_channel(),
140+ call: ToolCallTrace {
141+ id: call_id.to_string(),
142+ title: "Read notes.md".to_string(),
143+ kind: "read".to_string(),
144+ progress: Progress::Completed,
145+ output: output.to_string(),
146+ },
147+ },
148+ );
149+}
150+
151+/// The identifier of the last message of the first channel.
152+fn last_message_id(harness: &support::Harness) -> i64 {
153+ harness
154+ .repository
155+ .recent_messages(harness.first_channel(), 100)
156+ .unwrap()
157+ .last()
158+ .unwrap()
159+ .id
160+ .0
161+}
162+
163+fn started(cx: &mut TestAppContext) -> support::Harness {
164+ let harness = open_ready_app(cx, &["bob"]);
165+ type_in(cx, &harness, "composer", "@bob read it");
166+ click(cx, &harness, "send");
167+ harness
168+}
169+
170+#[gpui_kit::test]
171+fn a_tool_call_is_drawn_with_its_title_and_status_and_its_output_is_folded(
172+ cx: &mut TestAppContext,
173+) {
174+ let harness = started(cx);
175+ tool_call(&harness, cx, "t1", "the notes");
176+ let message = last_message_id(&harness);
177+
178+ assert!(exists(cx, &harness, id(format!("trace-{message}"))));
179+ assert!(exists(cx, &harness, id(format!("trace-status-{message}"))));
180+ assert!(exists(cx, &harness, id(format!("trace-toggle-{message}"))));
181+ assert!(
182+ !exists(cx, &harness, id(format!("trace-output-{message}"))),
183+ "the output is folded"
184+ );
185+}
186+
187+#[gpui_kit::test]
188+fn the_output_of_a_tool_call_unfolds_and_folds_again(cx: &mut TestAppContext) {
189+ let harness = started(cx);
190+ tool_call(&harness, cx, "t1", "the notes");
191+ let message = last_message_id(&harness);
192+
193+ click(cx, &harness, id(format!("trace-toggle-{message}")));
194+ assert!(exists(cx, &harness, id(format!("trace-output-{message}"))));
195+ assert!(cx.update(|cx| harness.app.read(cx).trace_is_expanded(message)));
196+
197+ click(cx, &harness, id(format!("trace-toggle-{message}")));
198+ assert!(!exists(cx, &harness, id(format!("trace-output-{message}"))));
199+}
200+
201+#[gpui_kit::test]
202+fn a_tool_call_without_output_has_nothing_to_unfold(cx: &mut TestAppContext) {
203+ let harness = started(cx);
204+ tool_call(&harness, cx, "t1", "");
205+ let message = last_message_id(&harness);
206+
207+ assert!(exists(cx, &harness, id(format!("trace-{message}"))));
208+ assert!(!exists(cx, &harness, id(format!("trace-toggle-{message}"))));
209+}
210+
211+#[gpui_kit::test]
212+fn an_update_shows_in_the_same_row(cx: &mut TestAppContext) {
213+ let harness = started(cx);
214+ tool_call(&harness, cx, "t1", "");
215+ let message = last_message_id(&harness);
216+ assert!(!exists(cx, &harness, id(format!("trace-toggle-{message}"))));
217+
218+ harness.agent_event(
219+ cx,
220+ AgentEvent::ToolCallUpdated {
221+ agent: name("bob"),
222+ channel: harness.first_channel(),
223+ id: "t1".to_string(),
224+ change: ToolCallChange {
225+ output: Some("now with output".to_string()),
226+ ..Default::default()
227+ },
228+ },
229+ );
230+ assert_eq!(last_message_id(&harness), message, "no new message");
231+ assert!(exists(cx, &harness, id(format!("trace-toggle-{message}"))));
232+}
233+
234+#[gpui_kit::test]
235+fn a_plan_is_drawn_step_by_step_and_updated_in_place(cx: &mut TestAppContext) {
236+ let harness = started(cx);
237+ let plan = |steps: &[(&str, Progress)]| AgentEvent::Plan {
238+ agent: name("bob"),
239+ channel: harness.first_channel(),
240+ steps: steps
241+ .iter()
242+ .map(|(text, progress)| PlanStep {
243+ text: text.to_string(),
244+ progress: *progress,
245+ })
246+ .collect(),
247+ };
248+ harness.agent_event(cx, plan(&[("read", Progress::InProgress)]));
249+ let message = last_message_id(&harness);
250+ assert!(exists(cx, &harness, id(format!("plan-step-{message}-0"))));
251+ assert!(!exists(cx, &harness, id(format!("plan-step-{message}-1"))));
252+
253+ harness.agent_event(
254+ cx,
255+ plan(&[("read", Progress::Completed), ("write", Progress::Pending)]),
256+ );
257+ assert_eq!(last_message_id(&harness), message);
258+ assert!(exists(cx, &harness, id(format!("plan-step-{message}-1"))));
259+}
260+
261+#[gpui_kit::test]
262+fn the_list_of_messages_counts_the_traces_so_that_the_last_row_is_drawn(cx: &mut TestAppContext) {
263+ let harness = started(cx);
264+ tool_call(&harness, cx, "t1", "out");
265+ harness.agent_event(
266+ cx,
267+ AgentEvent::Text {
268+ agent: name("bob"),
269+ channel: harness.first_channel(),
270+ chunk: "after the tool".to_string(),
271+ },
272+ );
273+ let (rows, loaded) = cx.update(|cx| {
274+ let app = harness.app.read(cx);
275+ (app.rows_in_view(cx), app.messages_loaded())
276+ });
277+ assert_eq!(rows, loaded);
278+ assert_eq!(loaded, 3);
279+}
280+
281+#[gpui_kit::test]
282+fn a_notice_of_an_agent_appears_in_the_conversation(cx: &mut TestAppContext) {
283+ let harness = started(cx);
284+ harness.agent_event(
285+ cx,
286+ AgentEvent::Notice {
287+ agent: name("bob"),
288+ channel: harness.first_channel(),
289+ text: "Context nearly full".to_string(),
290+ },
291+ );
292+ assert!(
293+ harness
294+ .said_in(harness.first_channel())
295+ .contains(&"@bob: Context nearly full".to_string())
296+ );
297+}
298+
299+// ---------------------------------------------------------------------- the whole chain
300+
301+#[gpui_kit::test]
302+fn an_agent_that_mentions_another_calls_it_and_the_stop_button_ends_the_chain(
303+ cx: &mut TestAppContext,
304+) {
305+ let harness = open_ready_app(cx, &["amy", "bob", "cat"]);
306+ let channel = harness.first_channel();
307+ type_in(cx, &harness, "composer", "@amy go");
308+ click(cx, &harness, "send");
309+
310+ harness.agent_event(
311+ cx,
312+ AgentEvent::Text {
313+ agent: name("amy"),
314+ channel,
315+ chunk: "@bob please".to_string(),
316+ },
317+ );
318+ harness.agent_event(
319+ cx,
320+ AgentEvent::TurnFinished {
321+ agent: name("amy"),
322+ channel,
323+ outcome: TurnOutcome::Completed,
324+ },
325+ );
326+ let prompted: Vec<String> = harness
327+ .agents
328+ .prompts
329+ .lock()
330+ .unwrap()
331+ .iter()
332+ .map(|(agent, _, _)| agent.clone())
333+ .collect();
334+ assert_eq!(prompted, vec!["amy", "bob"]);
335+ assert!(exists(cx, &harness, "stop"), "bob is working");
336+
337+ harness.agent_event(
338+ cx,
339+ AgentEvent::Text {
340+ agent: name("bob"),
341+ channel,
342+ chunk: "@cat over to you".to_string(),
343+ },
344+ );
345+ click(cx, &harness, "stop");
346+ harness.agent_event(
347+ cx,
348+ AgentEvent::TurnFinished {
349+ agent: name("bob"),
350+ channel,
351+ outcome: TurnOutcome::Completed,
352+ },
353+ );
354+
355+ assert_eq!(
356+ harness.agents.prompts.lock().unwrap().len(),
357+ 2,
358+ "cat was not called"
359+ );
360+ assert_eq!(
361+ harness.agents.cancelled.lock().unwrap().clone(),
362+ vec![("bob".to_string(), channel)]
363+ );
364+}
new file mode 100644
@@ -0,0 +1,364 @@
1+//! The settings panel, the tool calls and plans in the conversation, and the stop button, driven
2+//! like a user would.
3+
4+mod support;
5+
6+use gpui_kit::TestAppContext;
7+use support::{click, exists, open_ready_app, press, type_in, type_in_focused};
8+use synedrion_acp::events::{AgentEvent, TurnOutcome};
9+use synedrion_domain::agent::AgentName;
10+use synedrion_domain::repository::Repository;
11+use synedrion_domain::settings::ChatSettings;
12+use synedrion_domain::trace::{PlanStep, Progress, ToolCallChange, ToolCallTrace};
13+
14+/// Replaces what a field holds: selects it all, then types.
15+fn replace_in(
16+ cx: &mut TestAppContext,
17+ harness: &support::Harness,
18+ target: &'static str,
19+ text: &str,
20+) {
21+ click(cx, harness, target);
22+ press(cx, harness, "ctrl-a");
23+ type_in_focused(cx, harness, text);
24+}
25+
26+fn notice(cx: &mut TestAppContext, harness: &support::Harness) -> String {
27+ cx.update(|cx| {
28+ harness
29+ .app
30+ .read(cx)
31+ .notice()
32+ .unwrap_or_default()
33+ .to_string()
34+ })
35+}
36+
37+/// An identifier built at run time, which the helpers want for the whole run of the test.
38+fn id(text: String) -> &'static str {
39+ Box::leak(text.into_boxed_str())
40+}
41+
42+fn name(text: &str) -> AgentName {
43+ AgentName::new(text).unwrap()
44+}
45+
46+// -------------------------------------------------------------------------------- settings
47+
48+#[gpui_kit::test]
49+fn the_settings_panel_opens_from_the_bar_and_closes_from_its_title(cx: &mut TestAppContext) {
50+ let harness = open_ready_app(cx, &[]);
51+ assert!(!exists(cx, &harness, "panel-app-settings"));
52+ click(cx, &harness, "dock-app-settings");
53+ assert!(exists(cx, &harness, "panel-app-settings"));
54+ click(cx, &harness, "close-app-settings");
55+ assert!(!exists(cx, &harness, "panel-app-settings"));
56+}
57+
58+#[gpui_kit::test]
59+fn valid_settings_are_saved_and_the_user_is_told(cx: &mut TestAppContext) {
60+ let harness = open_ready_app(cx, &[]);
61+ click(cx, &harness, "dock-app-settings");
62+ replace_in(cx, &harness, "settings-context", "5");
63+ replace_in(cx, &harness, "settings-depth", "1");
64+ click(cx, &harness, "save-settings");
65+
66+ assert_eq!(
67+ harness.repository.load_settings().unwrap(),
68+ ChatSettings {
69+ context_messages: 5,
70+ chain_depth: 1
71+ }
72+ );
73+ assert!(notice(cx, &harness).contains("Settings saved"));
74+}
75+
76+#[gpui_kit::test]
77+fn a_setting_that_is_not_a_number_is_refused_and_nothing_is_saved(cx: &mut TestAppContext) {
78+ let harness = open_ready_app(cx, &[]);
79+ click(cx, &harness, "dock-app-settings");
80+ replace_in(cx, &harness, "settings-depth", "lots");
81+ click(cx, &harness, "save-settings");
82+
83+ assert!(notice(cx, &harness).contains("Chain depth must be a whole number"));
84+ assert_eq!(
85+ harness.repository.load_settings().unwrap(),
86+ ChatSettings::default()
87+ );
88+}
89+
90+#[gpui_kit::test]
91+fn a_setting_above_its_limit_is_refused(cx: &mut TestAppContext) {
92+ let harness = open_ready_app(cx, &[]);
93+ click(cx, &harness, "dock-app-settings");
94+ replace_in(cx, &harness, "settings-context", "100000");
95+ click(cx, &harness, "save-settings");
96+
97+ assert!(notice(cx, &harness).contains("Messages of context must be at most"));
98+ assert_eq!(
99+ harness.repository.load_settings().unwrap(),
100+ ChatSettings::default()
101+ );
102+}
103+
104+#[gpui_kit::test]
105+fn saved_settings_apply_to_the_next_message(cx: &mut TestAppContext) {
106+ let harness = open_ready_app(cx, &["bob"]);
107+ click(cx, &harness, "dock-app-settings");
108+ replace_in(cx, &harness, "settings-context", "0");
109+ click(cx, &harness, "save-settings");
110+
111+ type_in(cx, &harness, "composer", "private words");
112+ click(cx, &harness, "send");
113+ type_in(cx, &harness, "composer", "@bob now");
114+ click(cx, &harness, "send");
115+
116+ let prompts = harness.agents.prompts.lock().unwrap().clone();
117+ assert_eq!(prompts[0].2, "@bob now", "no context was given");
118+}
119+
120+#[gpui_kit::test]
121+fn without_changing_the_settings_the_agent_is_told_what_was_said(cx: &mut TestAppContext) {
122+ let harness = open_ready_app(cx, &["bob"]);
123+ type_in(cx, &harness, "composer", "private words");
124+ click(cx, &harness, "send");
125+ type_in(cx, &harness, "composer", "@bob now");
126+ click(cx, &harness, "send");
127+
128+ let prompts = harness.agents.prompts.lock().unwrap().clone();
129+ assert!(prompts[0].2.contains("Ada: private words"));
130+}
131+
132+// ------------------------------------------------------------------ tool calls and plans
133+
134+fn tool_call(harness: &support::Harness, cx: &mut TestAppContext, call_id: &str, output: &str) {
135+ harness.agent_event(
136+ cx,
137+ AgentEvent::ToolCall {
138+ agent: name("bob"),
139+ channel: harness.first_channel(),
140+ call: ToolCallTrace {
141+ id: call_id.to_string(),
142+ title: "Read notes.md".to_string(),
143+ kind: "read".to_string(),
144+ progress: Progress::Completed,
145+ output: output.to_string(),
146+ },
147+ },
148+ );
149+}
150+
151+/// The identifier of the last message of the first channel.
152+fn last_message_id(harness: &support::Harness) -> i64 {
153+ harness
154+ .repository
155+ .recent_messages(harness.first_channel(), 100)
156+ .unwrap()
157+ .last()
158+ .unwrap()
159+ .id
160+ .0
161+}
162+
163+fn started(cx: &mut TestAppContext) -> support::Harness {
164+ let harness = open_ready_app(cx, &["bob"]);
165+ type_in(cx, &harness, "composer", "@bob read it");
166+ click(cx, &harness, "send");
167+ harness
168+}
169+
170+#[gpui_kit::test]
171+fn a_tool_call_is_drawn_with_its_title_and_status_and_its_output_is_folded(
172+ cx: &mut TestAppContext,
173+) {
174+ let harness = started(cx);
175+ tool_call(&harness, cx, "t1", "the notes");
176+ let message = last_message_id(&harness);
177+
178+ assert!(exists(cx, &harness, id(format!("trace-{message}"))));
179+ assert!(exists(cx, &harness, id(format!("trace-status-{message}"))));
180+ assert!(exists(cx, &harness, id(format!("trace-toggle-{message}"))));
181+ assert!(
182+ !exists(cx, &harness, id(format!("trace-output-{message}"))),
183+ "the output is folded"
184+ );
185+}
186+
187+#[gpui_kit::test]
188+fn the_output_of_a_tool_call_unfolds_and_folds_again(cx: &mut TestAppContext) {
189+ let harness = started(cx);
190+ tool_call(&harness, cx, "t1", "the notes");
191+ let message = last_message_id(&harness);
192+
193+ click(cx, &harness, id(format!("trace-toggle-{message}")));
194+ assert!(exists(cx, &harness, id(format!("trace-output-{message}"))));
195+ assert!(cx.update(|cx| harness.app.read(cx).trace_is_expanded(message)));
196+
197+ click(cx, &harness, id(format!("trace-toggle-{message}")));
198+ assert!(!exists(cx, &harness, id(format!("trace-output-{message}"))));
199+}
200+
201+#[gpui_kit::test]
202+fn a_tool_call_without_output_has_nothing_to_unfold(cx: &mut TestAppContext) {
203+ let harness = started(cx);
204+ tool_call(&harness, cx, "t1", "");
205+ let message = last_message_id(&harness);
206+
207+ assert!(exists(cx, &harness, id(format!("trace-{message}"))));
208+ assert!(!exists(cx, &harness, id(format!("trace-toggle-{message}"))));
209+}
210+
211+#[gpui_kit::test]
212+fn an_update_shows_in_the_same_row(cx: &mut TestAppContext) {
213+ let harness = started(cx);
214+ tool_call(&harness, cx, "t1", "");
215+ let message = last_message_id(&harness);
216+ assert!(!exists(cx, &harness, id(format!("trace-toggle-{message}"))));
217+
218+ harness.agent_event(
219+ cx,
220+ AgentEvent::ToolCallUpdated {
221+ agent: name("bob"),
222+ channel: harness.first_channel(),
223+ id: "t1".to_string(),
224+ change: ToolCallChange {
225+ output: Some("now with output".to_string()),
226+ ..Default::default()
227+ },
228+ },
229+ );
230+ assert_eq!(last_message_id(&harness), message, "no new message");
231+ assert!(exists(cx, &harness, id(format!("trace-toggle-{message}"))));
232+}
233+
234+#[gpui_kit::test]
235+fn a_plan_is_drawn_step_by_step_and_updated_in_place(cx: &mut TestAppContext) {
236+ let harness = started(cx);
237+ let plan = |steps: &[(&str, Progress)]| AgentEvent::Plan {
238+ agent: name("bob"),
239+ channel: harness.first_channel(),
240+ steps: steps
241+ .iter()
242+ .map(|(text, progress)| PlanStep {
243+ text: text.to_string(),
244+ progress: *progress,
245+ })
246+ .collect(),
247+ };
248+ harness.agent_event(cx, plan(&[("read", Progress::InProgress)]));
249+ let message = last_message_id(&harness);
250+ assert!(exists(cx, &harness, id(format!("plan-step-{message}-0"))));
251+ assert!(!exists(cx, &harness, id(format!("plan-step-{message}-1"))));
252+
253+ harness.agent_event(
254+ cx,
255+ plan(&[("read", Progress::Completed), ("write", Progress::Pending)]),
256+ );
257+ assert_eq!(last_message_id(&harness), message);
258+ assert!(exists(cx, &harness, id(format!("plan-step-{message}-1"))));
259+}
260+
261+#[gpui_kit::test]
262+fn the_list_of_messages_counts_the_traces_so_that_the_last_row_is_drawn(cx: &mut TestAppContext) {
263+ let harness = started(cx);
264+ tool_call(&harness, cx, "t1", "out");
265+ harness.agent_event(
266+ cx,
267+ AgentEvent::Text {
268+ agent: name("bob"),
269+ channel: harness.first_channel(),
270+ chunk: "after the tool".to_string(),
271+ },
272+ );
273+ let (rows, loaded) = cx.update(|cx| {
274+ let app = harness.app.read(cx);
275+ (app.rows_in_view(cx), app.messages_loaded())
276+ });
277+ assert_eq!(rows, loaded);
278+ assert_eq!(loaded, 3);
279+}
280+
281+#[gpui_kit::test]
282+fn a_notice_of_an_agent_appears_in_the_conversation(cx: &mut TestAppContext) {
283+ let harness = started(cx);
284+ harness.agent_event(
285+ cx,
286+ AgentEvent::Notice {
287+ agent: name("bob"),
288+ channel: harness.first_channel(),
289+ text: "Context nearly full".to_string(),
290+ },
291+ );
292+ assert!(
293+ harness
294+ .said_in(harness.first_channel())
295+ .contains(&"@bob: Context nearly full".to_string())
296+ );
297+}
298+
299+// ---------------------------------------------------------------------- the whole chain
300+
301+#[gpui_kit::test]
302+fn an_agent_that_mentions_another_calls_it_and_the_stop_button_ends_the_chain(
303+ cx: &mut TestAppContext,
304+) {
305+ let harness = open_ready_app(cx, &["amy", "bob", "cat"]);
306+ let channel = harness.first_channel();
307+ type_in(cx, &harness, "composer", "@amy go");
308+ click(cx, &harness, "send");
309+
310+ harness.agent_event(
311+ cx,
312+ AgentEvent::Text {
313+ agent: name("amy"),
314+ channel,
315+ chunk: "@bob please".to_string(),
316+ },
317+ );
318+ harness.agent_event(
319+ cx,
320+ AgentEvent::TurnFinished {
321+ agent: name("amy"),
322+ channel,
323+ outcome: TurnOutcome::Completed,
324+ },
325+ );
326+ let prompted: Vec<String> = harness
327+ .agents
328+ .prompts
329+ .lock()
330+ .unwrap()
331+ .iter()
332+ .map(|(agent, _, _)| agent.clone())
333+ .collect();
334+ assert_eq!(prompted, vec!["amy", "bob"]);
335+ assert!(exists(cx, &harness, "stop"), "bob is working");
336+
337+ harness.agent_event(
338+ cx,
339+ AgentEvent::Text {
340+ agent: name("bob"),
341+ channel,
342+ chunk: "@cat over to you".to_string(),
343+ },
344+ );
345+ click(cx, &harness, "stop");
346+ harness.agent_event(
347+ cx,
348+ AgentEvent::TurnFinished {
349+ agent: name("bob"),
350+ channel,
351+ outcome: TurnOutcome::Completed,
352+ },
353+ );
354+
355+ assert_eq!(
356+ harness.agents.prompts.lock().unwrap().len(),
357+ 2,
358+ "cat was not called"
359+ );
360+ assert_eq!(
361+ harness.agents.cancelled.lock().unwrap().clone(),
362+ vec![("bob".to_string(), channel)]
363+ );
364+}
added crates/ui/tests/suggestion_keys.rs +153 -0
new file mode 100644
@@ -0,0 +1,153 @@
1+//! Moving in the list above the message box with the keyboard: the arrows, Tab, Enter, Escape.
2+
3+mod support;
4+
5+use gpui_kit::TestAppContext;
6+use support::{click, exists, open_ready_app, press, type_in, type_in_focused};
7+
8+fn selected(cx: &mut TestAppContext, harness: &support::Harness) -> usize {
9+ cx.update(|cx| harness.app.read(cx).selected_suggestion())
10+}
11+
12+/// Three agents, `@` typed: the list holds `amy`, `bea`, `bob`, in that order.
13+fn with_three_agents_listed(cx: &mut TestAppContext) -> support::Harness {
14+ let harness = open_ready_app(cx, &["bob", "amy", "bea"]);
15+ type_in(cx, &harness, "composer", "hello @");
16+ assert!(exists(cx, &harness, "suggest-amy") && exists(cx, &harness, "suggest-bob"));
17+ harness
18+}
19+
20+fn said(harness: &support::Harness) -> Vec<String> {
21+ harness.said_in(harness.first_channel())
22+}
23+
24+#[gpui_kit::test]
25+fn the_first_row_is_selected_until_an_arrow_moves_it(cx: &mut TestAppContext) {
26+ let harness = with_three_agents_listed(cx);
27+ assert_eq!(selected(cx, &harness), 0);
28+}
29+
30+#[gpui_kit::test]
31+fn down_moves_the_selection_and_tab_takes_the_selected_row(cx: &mut TestAppContext) {
32+ let harness = with_three_agents_listed(cx);
33+ press(cx, &harness, "down");
34+ assert_eq!(selected(cx, &harness), 1);
35+
36+ press(cx, &harness, "tab");
37+ assert!(!exists(cx, &harness, "suggest-amy"), "the list is closed");
38+ type_in_focused(cx, &harness, "now");
39+ click(cx, &harness, "send");
40+ assert_eq!(said(&harness), vec!["hello @bea now"]);
41+}
42+
43+#[gpui_kit::test]
44+fn up_from_the_first_row_goes_round_to_the_last(cx: &mut TestAppContext) {
45+ let harness = with_three_agents_listed(cx);
46+ press(cx, &harness, "up");
47+ assert_eq!(selected(cx, &harness), 2);
48+ press(cx, &harness, "tab");
49+ type_in_focused(cx, &harness, "hi");
50+ click(cx, &harness, "send");
51+ assert_eq!(said(&harness), vec!["hello @bob hi"]);
52+}
53+
54+#[gpui_kit::test]
55+fn down_from_the_last_row_goes_round_to_the_first(cx: &mut TestAppContext) {
56+ let harness = with_three_agents_listed(cx);
57+ for _ in 0..3 {
58+ press(cx, &harness, "down");
59+ }
60+ assert_eq!(selected(cx, &harness), 0);
61+}
62+
63+#[gpui_kit::test]
64+fn enter_takes_the_row_once_the_arrows_moved_the_selection_and_sends_nothing(
65+ cx: &mut TestAppContext,
66+) {
67+ let harness = with_three_agents_listed(cx);
68+ press(cx, &harness, "down");
69+ press(cx, &harness, "enter");
70+
71+ assert!(said(&harness).is_empty(), "taking a row is not sending");
72+ assert!(!exists(cx, &harness, "suggest-amy"));
73+ type_in_focused(cx, &harness, "go");
74+ press(cx, &harness, "enter");
75+ assert_eq!(said(&harness), vec!["hello @bea go"]);
76+}
77+
78+#[gpui_kit::test]
79+fn enter_still_sends_when_the_arrows_were_not_used(cx: &mut TestAppContext) {
80+ let harness = with_three_agents_listed(cx);
81+ press(cx, &harness, "enter");
82+ assert_eq!(said(&harness), vec!["hello @"]);
83+}
84+
85+#[gpui_kit::test]
86+fn typing_puts_the_selection_back_on_the_first_row(cx: &mut TestAppContext) {
87+ let harness = with_three_agents_listed(cx);
88+ press(cx, &harness, "down");
89+ press(cx, &harness, "down");
90+ assert_eq!(selected(cx, &harness), 2);
91+ type_in_focused(cx, &harness, "b");
92+ assert_eq!(selected(cx, &harness), 0);
93+}
94+
95+#[gpui_kit::test]
96+fn typing_after_the_arrows_makes_enter_send_again(cx: &mut TestAppContext) {
97+ let harness = with_three_agents_listed(cx);
98+ press(cx, &harness, "down");
99+ type_in_focused(cx, &harness, "b");
100+ press(cx, &harness, "enter");
101+ assert_eq!(said(&harness), vec!["hello @b"]);
102+}
103+
104+#[gpui_kit::test]
105+fn escape_closes_the_list_and_keeps_the_text(cx: &mut TestAppContext) {
106+ let harness = with_three_agents_listed(cx);
107+ press(cx, &harness, "escape");
108+ assert!(!exists(cx, &harness, "suggest-amy"));
109+ assert!(said(&harness).is_empty());
110+ click(cx, &harness, "send");
111+ assert_eq!(said(&harness), vec!["hello @"], "the text is as it was");
112+}
113+
114+#[gpui_kit::test]
115+fn the_list_comes_back_when_typing_goes_on_after_escape(cx: &mut TestAppContext) {
116+ let harness = with_three_agents_listed(cx);
117+ press(cx, &harness, "escape");
118+ type_in_focused(cx, &harness, "b");
119+ assert!(exists(cx, &harness, "suggest-bob"));
120+}
121+
122+#[gpui_kit::test]
123+fn the_arrows_move_in_the_list_of_commands_and_of_files_too(cx: &mut TestAppContext) {
124+ let folder = std::env::temp_dir().join(format!("synedrion-keys-{}", std::process::id()));
125+ let _ = std::fs::remove_dir_all(&folder);
126+ std::fs::create_dir_all(&folder).unwrap();
127+ for file in ["a.txt", "b.txt"] {
128+ std::fs::write(folder.join(file), "x").unwrap();
129+ }
130+ let harness = support::open_ready_app_in(cx, &["bob"], &folder);
131+
132+ type_in(cx, &harness, "composer", "@bob read $");
133+ press(cx, &harness, "down");
134+ press(cx, &harness, "tab");
135+ click(cx, &harness, "send");
136+ let _ = std::fs::remove_dir_all(&folder);
137+
138+ assert_eq!(said(&harness), vec!["@bob read b.txt"]);
139+ assert_eq!(
140+ harness.agents.files.lock().unwrap().last().unwrap().clone(),
141+ vec![folder.join("b.txt")]
142+ );
143+}
144+
145+#[gpui_kit::test]
146+fn the_arrows_do_nothing_to_the_text_when_no_list_is_open(cx: &mut TestAppContext) {
147+ let harness = open_ready_app(cx, &["bob"]);
148+ type_in(cx, &harness, "composer", "plain text");
149+ press(cx, &harness, "down");
150+ press(cx, &harness, "up");
151+ click(cx, &harness, "send");
152+ assert_eq!(said(&harness), vec!["plain text"]);
153+}
new file mode 100644
@@ -0,0 +1,153 @@
1+//! Moving in the list above the message box with the keyboard: the arrows, Tab, Enter, Escape.
2+
3+mod support;
4+
5+use gpui_kit::TestAppContext;
6+use support::{click, exists, open_ready_app, press, type_in, type_in_focused};
7+
8+fn selected(cx: &mut TestAppContext, harness: &support::Harness) -> usize {
9+ cx.update(|cx| harness.app.read(cx).selected_suggestion())
10+}
11+
12+/// Three agents, `@` typed: the list holds `amy`, `bea`, `bob`, in that order.
13+fn with_three_agents_listed(cx: &mut TestAppContext) -> support::Harness {
14+ let harness = open_ready_app(cx, &["bob", "amy", "bea"]);
15+ type_in(cx, &harness, "composer", "hello @");
16+ assert!(exists(cx, &harness, "suggest-amy") && exists(cx, &harness, "suggest-bob"));
17+ harness
18+}
19+
20+fn said(harness: &support::Harness) -> Vec<String> {
21+ harness.said_in(harness.first_channel())
22+}
23+
24+#[gpui_kit::test]
25+fn the_first_row_is_selected_until_an_arrow_moves_it(cx: &mut TestAppContext) {
26+ let harness = with_three_agents_listed(cx);
27+ assert_eq!(selected(cx, &harness), 0);
28+}
29+
30+#[gpui_kit::test]
31+fn down_moves_the_selection_and_tab_takes_the_selected_row(cx: &mut TestAppContext) {
32+ let harness = with_three_agents_listed(cx);
33+ press(cx, &harness, "down");
34+ assert_eq!(selected(cx, &harness), 1);
35+
36+ press(cx, &harness, "tab");
37+ assert!(!exists(cx, &harness, "suggest-amy"), "the list is closed");
38+ type_in_focused(cx, &harness, "now");
39+ click(cx, &harness, "send");
40+ assert_eq!(said(&harness), vec!["hello @bea now"]);
41+}
42+
43+#[gpui_kit::test]
44+fn up_from_the_first_row_goes_round_to_the_last(cx: &mut TestAppContext) {
45+ let harness = with_three_agents_listed(cx);
46+ press(cx, &harness, "up");
47+ assert_eq!(selected(cx, &harness), 2);
48+ press(cx, &harness, "tab");
49+ type_in_focused(cx, &harness, "hi");
50+ click(cx, &harness, "send");
51+ assert_eq!(said(&harness), vec!["hello @bob hi"]);
52+}
53+
54+#[gpui_kit::test]
55+fn down_from_the_last_row_goes_round_to_the_first(cx: &mut TestAppContext) {
56+ let harness = with_three_agents_listed(cx);
57+ for _ in 0..3 {
58+ press(cx, &harness, "down");
59+ }
60+ assert_eq!(selected(cx, &harness), 0);
61+}
62+
63+#[gpui_kit::test]
64+fn enter_takes_the_row_once_the_arrows_moved_the_selection_and_sends_nothing(
65+ cx: &mut TestAppContext,
66+) {
67+ let harness = with_three_agents_listed(cx);
68+ press(cx, &harness, "down");
69+ press(cx, &harness, "enter");
70+
71+ assert!(said(&harness).is_empty(), "taking a row is not sending");
72+ assert!(!exists(cx, &harness, "suggest-amy"));
73+ type_in_focused(cx, &harness, "go");
74+ press(cx, &harness, "enter");
75+ assert_eq!(said(&harness), vec!["hello @bea go"]);
76+}
77+
78+#[gpui_kit::test]
79+fn enter_still_sends_when_the_arrows_were_not_used(cx: &mut TestAppContext) {
80+ let harness = with_three_agents_listed(cx);
81+ press(cx, &harness, "enter");
82+ assert_eq!(said(&harness), vec!["hello @"]);
83+}
84+
85+#[gpui_kit::test]
86+fn typing_puts_the_selection_back_on_the_first_row(cx: &mut TestAppContext) {
87+ let harness = with_three_agents_listed(cx);
88+ press(cx, &harness, "down");
89+ press(cx, &harness, "down");
90+ assert_eq!(selected(cx, &harness), 2);
91+ type_in_focused(cx, &harness, "b");
92+ assert_eq!(selected(cx, &harness), 0);
93+}
94+
95+#[gpui_kit::test]
96+fn typing_after_the_arrows_makes_enter_send_again(cx: &mut TestAppContext) {
97+ let harness = with_three_agents_listed(cx);
98+ press(cx, &harness, "down");
99+ type_in_focused(cx, &harness, "b");
100+ press(cx, &harness, "enter");
101+ assert_eq!(said(&harness), vec!["hello @b"]);
102+}
103+
104+#[gpui_kit::test]
105+fn escape_closes_the_list_and_keeps_the_text(cx: &mut TestAppContext) {
106+ let harness = with_three_agents_listed(cx);
107+ press(cx, &harness, "escape");
108+ assert!(!exists(cx, &harness, "suggest-amy"));
109+ assert!(said(&harness).is_empty());
110+ click(cx, &harness, "send");
111+ assert_eq!(said(&harness), vec!["hello @"], "the text is as it was");
112+}
113+
114+#[gpui_kit::test]
115+fn the_list_comes_back_when_typing_goes_on_after_escape(cx: &mut TestAppContext) {
116+ let harness = with_three_agents_listed(cx);
117+ press(cx, &harness, "escape");
118+ type_in_focused(cx, &harness, "b");
119+ assert!(exists(cx, &harness, "suggest-bob"));
120+}
121+
122+#[gpui_kit::test]
123+fn the_arrows_move_in_the_list_of_commands_and_of_files_too(cx: &mut TestAppContext) {
124+ let folder = std::env::temp_dir().join(format!("synedrion-keys-{}", std::process::id()));
125+ let _ = std::fs::remove_dir_all(&folder);
126+ std::fs::create_dir_all(&folder).unwrap();
127+ for file in ["a.txt", "b.txt"] {
128+ std::fs::write(folder.join(file), "x").unwrap();
129+ }
130+ let harness = support::open_ready_app_in(cx, &["bob"], &folder);
131+
132+ type_in(cx, &harness, "composer", "@bob read $");
133+ press(cx, &harness, "down");
134+ press(cx, &harness, "tab");
135+ click(cx, &harness, "send");
136+ let _ = std::fs::remove_dir_all(&folder);
137+
138+ assert_eq!(said(&harness), vec!["@bob read b.txt"]);
139+ assert_eq!(
140+ harness.agents.files.lock().unwrap().last().unwrap().clone(),
141+ vec![folder.join("b.txt")]
142+ );
143+}
144+
145+#[gpui_kit::test]
146+fn the_arrows_do_nothing_to_the_text_when_no_list_is_open(cx: &mut TestAppContext) {
147+ let harness = open_ready_app(cx, &["bob"]);
148+ type_in(cx, &harness, "composer", "plain text");
149+ press(cx, &harness, "down");
150+ press(cx, &harness, "up");
151+ click(cx, &harness, "send");
152+ assert_eq!(said(&harness), vec!["plain text"]);
153+}
modified crates/ui/tests/support/mod.rs +59 -0
@@ -5,6 +5,7 @@
55
66 use std::sync::{Arc, Mutex};
77
8+use gpui_kit::test::TestWindowExt as _;
89 use gpui_kit::{AppContext, Entity, TestAppContext, WindowHandle, base::Root, px, size};
910 use synedrion_acp::events::{PermissionChoice, PermissionRequestId};
1011 use synedrion_domain::agent::{AgentDeclaration, AgentName, AgentStatus};
@@ -22,6 +23,15 @@ pub struct FakeAgents {
2223 pub files: Mutex<Vec<Vec<std::path::PathBuf>>>,
2324 pub answers: Mutex<Vec<(PermissionRequestId, PermissionChoice)>>,
2425 pub cancelled: Mutex<Vec<(String, ChannelId)>>,
26+ /// The agents that cannot be reached: handing them a prompt fails.
27+ pub unreachable: Mutex<Vec<String>>,
28+}
29+
30+impl FakeAgents {
31+ /// From now on, `agent` cannot be reached.
32+ pub fn fail_for(&self, agent: &str) {
33+ self.unreachable.lock().unwrap().push(agent.to_string());
34+ }
2535 }
2636
2737 impl AgentGateway for FakeAgents {
@@ -32,6 +42,14 @@ impl AgentGateway for FakeAgents {
3242 text: &str,
3343 files: &[std::path::PathBuf],
3444 ) -> Result<(), String> {
45+ if self
46+ .unreachable
47+ .lock()
48+ .unwrap()
49+ .contains(&declaration.name.to_string())
50+ {
51+ return Err("not reachable in this test".to_string());
52+ }
3553 self.prompts.lock().unwrap().push((
3654 declaration.name.to_string(),
3755 channel,
@@ -143,6 +161,47 @@ impl Harness {
143161 }
144162 }
145163
164+// Helpers that drive the window like a user: each renders a frame first, so that what a
165+// previous action changed is there to be found.
166+
167+pub fn type_in(cx: &mut TestAppContext, harness: &Harness, target: &'static str, text: &str) {
168+ cx.update_window(harness.window.into(), |_, window, cx| {
169+ window.render_frame(cx);
170+ window.click(target, cx);
171+ window.input(text, cx);
172+ })
173+ .unwrap();
174+}
175+
176+/// Types into whatever has the focus, without clicking anywhere first.
177+pub fn type_in_focused(cx: &mut TestAppContext, harness: &Harness, text: &str) {
178+ cx.update_window(harness.window.into(), |_, window, cx| {
179+ window.input(text, cx)
180+ })
181+ .unwrap();
182+}
183+
184+pub fn click(cx: &mut TestAppContext, harness: &Harness, target: &'static str) {
185+ cx.update_window(harness.window.into(), |_, window, cx| {
186+ window.render_frame(cx);
187+ window.click(target, cx);
188+ })
189+ .unwrap();
190+}
191+
192+pub fn press(cx: &mut TestAppContext, harness: &Harness, key: &str) {
193+ cx.update_window(harness.window.into(), |_, window, cx| window.press(key, cx))
194+ .unwrap();
195+}
196+
197+pub fn exists(cx: &mut TestAppContext, harness: &Harness, target: &'static str) -> bool {
198+ cx.update_window(harness.window.into(), |_, window, cx| {
199+ window.render_frame(cx);
200+ window.try_find(target).is_some()
201+ })
202+ .unwrap()
203+}
204+
146205 fn open_window(
147206 cx: &mut TestAppContext,
148207 repository: Arc<SqliteRepository>,
@@ -5,6 +5,7 @@
5 5
6 use std::sync::{Arc, Mutex};6 use std::sync::{Arc, Mutex};
7 7
8+use gpui_kit::test::TestWindowExt as _;
8 use gpui_kit::{AppContext, Entity, TestAppContext, WindowHandle, base::Root, px, size};9 use gpui_kit::{AppContext, Entity, TestAppContext, WindowHandle, base::Root, px, size};
9 use synedrion_acp::events::{PermissionChoice, PermissionRequestId};10 use synedrion_acp::events::{PermissionChoice, PermissionRequestId};
10 use synedrion_domain::agent::{AgentDeclaration, AgentName, AgentStatus};11 use synedrion_domain::agent::{AgentDeclaration, AgentName, AgentStatus};
@@ -22,6 +23,15 @@ pub struct FakeAgents {
22 pub files: Mutex<Vec<Vec<std::path::PathBuf>>>,23 pub files: Mutex<Vec<Vec<std::path::PathBuf>>>,
23 pub answers: Mutex<Vec<(PermissionRequestId, PermissionChoice)>>,24 pub answers: Mutex<Vec<(PermissionRequestId, PermissionChoice)>>,
24 pub cancelled: Mutex<Vec<(String, ChannelId)>>,25 pub cancelled: Mutex<Vec<(String, ChannelId)>>,
26+ /// The agents that cannot be reached: handing them a prompt fails.
27+ pub unreachable: Mutex<Vec<String>>,
28+}
29+
30+impl FakeAgents {
31+ /// From now on, `agent` cannot be reached.
32+ pub fn fail_for(&self, agent: &str) {
33+ self.unreachable.lock().unwrap().push(agent.to_string());
34+ }
25 }35 }
26 36
27 impl AgentGateway for FakeAgents {37 impl AgentGateway for FakeAgents {
@@ -32,6 +42,14 @@ impl AgentGateway for FakeAgents {
32 text: &str,42 text: &str,
33 files: &[std::path::PathBuf],43 files: &[std::path::PathBuf],
34 ) -> Result<(), String> {44 ) -> Result<(), String> {
45+ if self
46+ .unreachable
47+ .lock()
48+ .unwrap()
49+ .contains(&declaration.name.to_string())
50+ {
51+ return Err("not reachable in this test".to_string());
52+ }
35 self.prompts.lock().unwrap().push((53 self.prompts.lock().unwrap().push((
36 declaration.name.to_string(),54 declaration.name.to_string(),
37 channel,55 channel,
@@ -143,6 +161,47 @@ impl Harness {
143 }161 }
144 }162 }
145 163
164+// Helpers that drive the window like a user: each renders a frame first, so that what a
165+// previous action changed is there to be found.
166+
167+pub fn type_in(cx: &mut TestAppContext, harness: &Harness, target: &'static str, text: &str) {
168+ cx.update_window(harness.window.into(), |_, window, cx| {
169+ window.render_frame(cx);
170+ window.click(target, cx);
171+ window.input(text, cx);
172+ })
173+ .unwrap();
174+}
175+
176+/// Types into whatever has the focus, without clicking anywhere first.
177+pub fn type_in_focused(cx: &mut TestAppContext, harness: &Harness, text: &str) {
178+ cx.update_window(harness.window.into(), |_, window, cx| {
179+ window.input(text, cx)
180+ })
181+ .unwrap();
182+}
183+
184+pub fn click(cx: &mut TestAppContext, harness: &Harness, target: &'static str) {
185+ cx.update_window(harness.window.into(), |_, window, cx| {
186+ window.render_frame(cx);
187+ window.click(target, cx);
188+ })
189+ .unwrap();
190+}
191+
192+pub fn press(cx: &mut TestAppContext, harness: &Harness, key: &str) {
193+ cx.update_window(harness.window.into(), |_, window, cx| window.press(key, cx))
194+ .unwrap();
195+}
196+
197+pub fn exists(cx: &mut TestAppContext, harness: &Harness, target: &'static str) -> bool {
198+ cx.update_window(harness.window.into(), |_, window, cx| {
199+ window.render_frame(cx);
200+ window.try_find(target).is_some()
201+ })
202+ .unwrap()
203+}
204+
146 fn open_window(205 fn open_window(
147 cx: &mut TestAppContext,206 cx: &mut TestAppContext,
148 repository: Arc<SqliteRepository>,207 repository: Arc<SqliteRepository>,
modified crates/ui/tests/window.rs +3 -39
@@ -7,7 +7,9 @@ mod support;
77
88 use gpui_kit::test::TestWindowExt as _;
99 use gpui_kit::{AppContext as _, TestAppContext};
10-use support::{open_app, open_ready_app, open_ready_app_in};
10+use support::{
11+ click, exists, open_app, open_ready_app, open_ready_app_in, press, type_in, type_in_focused,
12+};
1113 use synedrion_domain::message::Author;
1214 use synedrion_domain::repository::Repository;
1315
@@ -71,44 +73,6 @@ fn create_profile(cx: &mut TestAppContext, harness: &support::Harness, name: &st
7173 .unwrap();
7274 }
7375
74-fn type_in(cx: &mut TestAppContext, harness: &support::Harness, target: &'static str, text: &str) {
75- cx.update_window(harness.window.into(), |_, window, cx| {
76- window.render_frame(cx);
77- window.click(target, cx);
78- window.input(text, cx);
79- })
80- .unwrap();
81-}
82-
83-/// Types into whatever has the focus, without clicking anywhere first.
84-fn type_in_focused(cx: &mut TestAppContext, harness: &support::Harness, text: &str) {
85- cx.update_window(harness.window.into(), |_, window, cx| {
86- window.input(text, cx)
87- })
88- .unwrap();
89-}
90-
91-fn click(cx: &mut TestAppContext, harness: &support::Harness, target: &'static str) {
92- cx.update_window(harness.window.into(), |_, window, cx| {
93- window.render_frame(cx);
94- window.click(target, cx);
95- })
96- .unwrap();
97-}
98-
99-fn press(cx: &mut TestAppContext, harness: &support::Harness, key: &str) {
100- cx.update_window(harness.window.into(), |_, window, cx| window.press(key, cx))
101- .unwrap();
102-}
103-
104-fn exists(cx: &mut TestAppContext, harness: &support::Harness, target: &'static str) -> bool {
105- cx.update_window(harness.window.into(), |_, window, cx| {
106- window.render_frame(cx);
107- window.try_find(target).is_some()
108- })
109- .unwrap()
110-}
111-
11276 #[gpui_kit::test]
11377 fn enter_sends_the_message(cx: &mut TestAppContext) {
11478 let harness = open_ready_app(cx, &[]);
@@ -7,7 +7,9 @@ mod support;
7 7
8 use gpui_kit::test::TestWindowExt as _;8 use gpui_kit::test::TestWindowExt as _;
9 use gpui_kit::{AppContext as _, TestAppContext};9 use gpui_kit::{AppContext as _, TestAppContext};
10-use support::{open_app, open_ready_app, open_ready_app_in};10+use support::{
11+ click, exists, open_app, open_ready_app, open_ready_app_in, press, type_in, type_in_focused,
12+};
11 use synedrion_domain::message::Author;13 use synedrion_domain::message::Author;
12 use synedrion_domain::repository::Repository;14 use synedrion_domain::repository::Repository;
13 15
@@ -71,44 +73,6 @@ fn create_profile(cx: &mut TestAppContext, harness: &support::Harness, name: &st
71 .unwrap();73 .unwrap();
72 }74 }
73 75
74-fn type_in(cx: &mut TestAppContext, harness: &support::Harness, target: &'static str, text: &str) {
75- cx.update_window(harness.window.into(), |_, window, cx| {
76- window.render_frame(cx);
77- window.click(target, cx);
78- window.input(text, cx);
79- })
80- .unwrap();
81-}
82-
83-/// Types into whatever has the focus, without clicking anywhere first.
84-fn type_in_focused(cx: &mut TestAppContext, harness: &support::Harness, text: &str) {
85- cx.update_window(harness.window.into(), |_, window, cx| {
86- window.input(text, cx)
87- })
88- .unwrap();
89-}
90-
91-fn click(cx: &mut TestAppContext, harness: &support::Harness, target: &'static str) {
92- cx.update_window(harness.window.into(), |_, window, cx| {
93- window.render_frame(cx);
94- window.click(target, cx);
95- })
96- .unwrap();
97-}
98-
99-fn press(cx: &mut TestAppContext, harness: &support::Harness, key: &str) {
100- cx.update_window(harness.window.into(), |_, window, cx| window.press(key, cx))
101- .unwrap();
102-}
103-
104-fn exists(cx: &mut TestAppContext, harness: &support::Harness, target: &'static str) -> bool {
105- cx.update_window(harness.window.into(), |_, window, cx| {
106- window.render_frame(cx);
107- window.try_find(target).is_some()
108- })
109- .unwrap()
110-}
111-
112 #[gpui_kit::test]76 #[gpui_kit::test]
113 fn enter_sends_the_message(cx: &mut TestAppContext) {77 fn enter_sends_the_message(cx: &mut TestAppContext) {
114 let harness = open_ready_app(cx, &[]);78 let harness = open_ready_app(cx, &[]);
modified docs/diagrams/packages.drawio +1 -1
@@ -1,5 +1,5 @@
11 <mxfile host="app.diagrams.net">
2- <diagram id="synedrion-packages" name="Packages (planned)">
2+ <diagram id="synedrion-packages" name="Packages">
33 <mxGraphModel dx="1000" dy="600" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1100" pageHeight="600" math="0" shadow="0">
44 <root>
55 <mxCell id="0" />
@@ -1,5 +1,5 @@
1 <mxfile host="app.diagrams.net">1 <mxfile host="app.diagrams.net">
2- <diagram id="synedrion-packages" name="Packages (planned)">2+ <diagram id="synedrion-packages" name="Packages">
3 <mxGraphModel dx="1000" dy="600" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1100" pageHeight="600" math="0" shadow="0">3 <mxGraphModel dx="1000" dy="600" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="1100" pageHeight="600" math="0" shadow="0">
4 <root>4 <root>
5 <mxCell id="0" />5 <mxCell id="0" />
modified docs/en/README.md +4 -4
@@ -2,7 +2,7 @@
22
33 Synedrion is a desktop application, written in Rust with GPUI Kit, that works like Slack or Discord: it has channels, and the participants are AI agents that talk through the Agent Client Protocol (ACP), plus the one human who runs the application.
44
5-> **Status: version 0.1.0 is built, and has never been seen on a screen.** Its behaviour is covered by automated tests, including headless window tests. Its look is not. Agents talking to each other, sending the channel's earlier messages to an agent, and showing tool calls are planned, not built. Nothing has been tried against a real agent yet.
5+> **Status: the features planned for versions 0.1.0 and 0.2.0 are built.** Their behaviour is covered by automated tests, including headless window tests. The author of the code has never seen the window: the person who ran it reported what worked and what did not. Tool calls and plans, agents calling agents and the context of the channel have only been tried against the test agent, not a real one.
66
77 ## How this documentation is organised
88
@@ -11,9 +11,9 @@ The documentation follows the [Diátaxis](https://diataxis.fr) method: each page
1111 | You want to… | Go to |
1212 | --- | --- |
1313 | Learn by doing | [Your first conversation with an agent](tutorials/first-conversation.md) |
14-| Accomplish a task | [Build and run Synedrion](how-to/build-and-run.md), [manage channels](how-to/manage-channels.md), [declare an agent](how-to/declare-an-agent.md), [run the tests](how-to/run-the-tests.md), [set up a development sandbox](how-to/set-up-the-sandbox.md), [log the conversation with an agent](how-to/log-an-agent-conversation.md), [use an agent's commands and attach files](how-to/use-commands-and-attach-files.md), [copy a message or a block of code](how-to/copy-text-and-code.md) |
15-| Look up exact details | [Agent declaration](reference/agent-declaration.md), [mentions](reference/mentions.md), [ACP methods](reference/acp-methods.md), [the database](reference/database.md), [the test agent](reference/test-agent.md), [how messages are drawn](reference/message-rendering.md), [slash commands and attached files](reference/slash-commands.md) |
16-| Understand why it is built this way | [Vision](explanation/vision.md), [Architecture](explanation/architecture.md), [Technology choices](explanation/technology-choices.md) |
14+| Accomplish a task | [Build and run Synedrion](how-to/build-and-run.md), [manage channels](how-to/manage-channels.md), [declare an agent](how-to/declare-an-agent.md), [run the tests](how-to/run-the-tests.md), [set up a development sandbox](how-to/set-up-the-sandbox.md), [log the conversation with an agent](how-to/log-an-agent-conversation.md), [use an agent's commands and attach files](how-to/use-commands-and-attach-files.md), [copy a message or a block of code](how-to/copy-text-and-code.md), [let agents call each other](how-to/let-agents-call-each-other.md) |
15+| Look up exact details | [Agent declaration](reference/agent-declaration.md), [mentions](reference/mentions.md), [ACP methods](reference/acp-methods.md), [the database](reference/database.md), [the test agent](reference/test-agent.md), [how messages are drawn](reference/message-rendering.md), [slash commands and attached files](reference/slash-commands.md), [settings](reference/settings.md), [the context of the channel](reference/channel-context.md), [tool calls, plans and what cannot be shown](reference/tool-calls-and-plans.md) |
16+| Understand why it is built this way | [Vision](explanation/vision.md), [Architecture](explanation/architecture.md), [Technology choices](explanation/technology-choices.md), [Agents calling agents](explanation/agents-calling-agents.md), [Client capabilities](explanation/client-capabilities.md) |
1717
1818 ## Where to start
1919
@@ -2,7 +2,7 @@
2 2
3 Synedrion is a desktop application, written in Rust with GPUI Kit, that works like Slack or Discord: it has channels, and the participants are AI agents that talk through the Agent Client Protocol (ACP), plus the one human who runs the application.3 Synedrion is a desktop application, written in Rust with GPUI Kit, that works like Slack or Discord: it has channels, and the participants are AI agents that talk through the Agent Client Protocol (ACP), plus the one human who runs the application.
4 4
5-> **Status: version 0.1.0 is built, and has never been seen on a screen.** Its behaviour is covered by automated tests, including headless window tests. Its look is not. Agents talking to each other, sending the channel's earlier messages to an agent, and showing tool calls are planned, not built. Nothing has been tried against a real agent yet.5+> **Status: the features planned for versions 0.1.0 and 0.2.0 are built.** Their behaviour is covered by automated tests, including headless window tests. The author of the code has never seen the window: the person who ran it reported what worked and what did not. Tool calls and plans, agents calling agents and the context of the channel have only been tried against the test agent, not a real one.
6 6
7 ## How this documentation is organised7 ## How this documentation is organised
8 8
@@ -11,9 +11,9 @@ The documentation follows the [Diátaxis](https://diataxis.fr) method: each page
11 | You want to… | Go to |11 | You want to… | Go to |
12 | --- | --- |12 | --- | --- |
13 | Learn by doing | [Your first conversation with an agent](tutorials/first-conversation.md) |13 | Learn by doing | [Your first conversation with an agent](tutorials/first-conversation.md) |
14-| Accomplish a task | [Build and run Synedrion](how-to/build-and-run.md), [manage channels](how-to/manage-channels.md), [declare an agent](how-to/declare-an-agent.md), [run the tests](how-to/run-the-tests.md), [set up a development sandbox](how-to/set-up-the-sandbox.md), [log the conversation with an agent](how-to/log-an-agent-conversation.md), [use an agent's commands and attach files](how-to/use-commands-and-attach-files.md), [copy a message or a block of code](how-to/copy-text-and-code.md) |14+| Accomplish a task | [Build and run Synedrion](how-to/build-and-run.md), [manage channels](how-to/manage-channels.md), [declare an agent](how-to/declare-an-agent.md), [run the tests](how-to/run-the-tests.md), [set up a development sandbox](how-to/set-up-the-sandbox.md), [log the conversation with an agent](how-to/log-an-agent-conversation.md), [use an agent's commands and attach files](how-to/use-commands-and-attach-files.md), [copy a message or a block of code](how-to/copy-text-and-code.md), [let agents call each other](how-to/let-agents-call-each-other.md) |
15-| Look up exact details | [Agent declaration](reference/agent-declaration.md), [mentions](reference/mentions.md), [ACP methods](reference/acp-methods.md), [the database](reference/database.md), [the test agent](reference/test-agent.md), [how messages are drawn](reference/message-rendering.md), [slash commands and attached files](reference/slash-commands.md) |15+| Look up exact details | [Agent declaration](reference/agent-declaration.md), [mentions](reference/mentions.md), [ACP methods](reference/acp-methods.md), [the database](reference/database.md), [the test agent](reference/test-agent.md), [how messages are drawn](reference/message-rendering.md), [slash commands and attached files](reference/slash-commands.md), [settings](reference/settings.md), [the context of the channel](reference/channel-context.md), [tool calls, plans and what cannot be shown](reference/tool-calls-and-plans.md) |
16-| Understand why it is built this way | [Vision](explanation/vision.md), [Architecture](explanation/architecture.md), [Technology choices](explanation/technology-choices.md) |16+| Understand why it is built this way | [Vision](explanation/vision.md), [Architecture](explanation/architecture.md), [Technology choices](explanation/technology-choices.md), [Agents calling agents](explanation/agents-calling-agents.md), [Client capabilities](explanation/client-capabilities.md) |
17 17
18 ## Where to start18 ## Where to start
19 19
added docs/en/explanation/agents-calling-agents.md +41 -0
new file mode 100644
@@ -0,0 +1,41 @@
1+# Agents calling agents
2+
3+## What is this about?
4+
5+In Synedrion the participants of a channel are agents, and the user. When an agent's answer mentions another agent with `@name`, that agent is called, exactly as if the user had mentioned it. This is what turns a channel into a deliberation between agents instead of a series of separate conversations with each one. It also creates a risk that a conversation with a human in it does not have: two agents can call each other forever, each call costing a turn of a model, often a local one.
6+
7+## How it works
8+
9+The message of the user starts a chain. The agents it calls are at the first hop, the agents they call at the second, and so on. A call that would go beyond the **chain depth** setting is not made, and the channel says so. The default is 3, which is low on purpose: it is easy to raise, and an unexpected loop costs something.
10+
11+An agent is called when its **turn ends normally**, with its whole answer, and not while the answer is still being written. A mention in the middle of a sentence that the agent then changes its mind about would otherwise already have called someone. The called agent receives the whole answer, not only the sentence with the mention, since the rest is what it is asked to react to. It also receives the messages it has not seen, as every agent does (see [the context of the channel](../reference/channel-context.md)).
12+
13+Three guard rails keep this under control:
14+
15+- **The depth.** A chain cannot be longer than the setting, whatever the agents say.
16+- **Stop.** The user can stop every turn of the channel with one click, and the answers that still arrive afterwards call nobody. Without the second part, a click right when an agent finishes would stop that agent and still let its answer start another one.
17+- **Self-mentions.** An agent that writes its own name is not called again: agents quote themselves.
18+
19+A turn that was cancelled, that failed or that was refused calls nobody, since there is no answer worth passing on.
20+
21+## Why a depth
22+
23+Several ways to bound a chain were considered.
24+
25+- **A depth, chosen.** It is the simplest to explain and to predict: the user knows how many model turns one message can cost at most. It does not need to understand what the agents say.
26+- **Detecting loops by what is said.** An agent can repeat itself usefully, and two agents can be stuck while saying different words every time. Whatever the detection, it would be wrong in both directions.
27+- **A budget of time or tokens.** Closer to what the user cares about, but the application does not know the tokens of every agent, and a time limit cuts a long, useful turn.
28+- **Asking the user at each hop.** Safe, and it defeats the purpose of agents working together.
29+- **No limit and the stop button only.** The cost of a mistake is paid before the user notices it.
30+
31+The depth is a floor of safety, not a measure of quality: a chain of three well-chosen calls is more useful than a long one.
32+
33+## Limits of the current design
34+
35+- The bookkeeping of "who is working" is per agent and channel. If two prompts are queued for the same agent in the same channel, the first one ending shows the agent as idle while the second one is still to run.
36+- Two agents called by the same answer run in parallel, each in its own process: Synedrion does not order them.
37+- Agents decide what to do with a mention of themselves in their own instructions. Synedrion does not tell an agent about the other agents.
38+
39+## How it relates to the rest
40+
41+The setting and its limits: [settings](../reference/settings.md). Steps to use it: [how to let agents call each other](../how-to/let-agents-call-each-other.md). Who receives a message in general: [mentions](../reference/mentions.md).
new file mode 100644
@@ -0,0 +1,41 @@
1+# Agents calling agents
2+
3+## What is this about?
4+
5+In Synedrion the participants of a channel are agents, and the user. When an agent's answer mentions another agent with `@name`, that agent is called, exactly as if the user had mentioned it. This is what turns a channel into a deliberation between agents instead of a series of separate conversations with each one. It also creates a risk that a conversation with a human in it does not have: two agents can call each other forever, each call costing a turn of a model, often a local one.
6+
7+## How it works
8+
9+The message of the user starts a chain. The agents it calls are at the first hop, the agents they call at the second, and so on. A call that would go beyond the **chain depth** setting is not made, and the channel says so. The default is 3, which is low on purpose: it is easy to raise, and an unexpected loop costs something.
10+
11+An agent is called when its **turn ends normally**, with its whole answer, and not while the answer is still being written. A mention in the middle of a sentence that the agent then changes its mind about would otherwise already have called someone. The called agent receives the whole answer, not only the sentence with the mention, since the rest is what it is asked to react to. It also receives the messages it has not seen, as every agent does (see [the context of the channel](../reference/channel-context.md)).
12+
13+Three guard rails keep this under control:
14+
15+- **The depth.** A chain cannot be longer than the setting, whatever the agents say.
16+- **Stop.** The user can stop every turn of the channel with one click, and the answers that still arrive afterwards call nobody. Without the second part, a click right when an agent finishes would stop that agent and still let its answer start another one.
17+- **Self-mentions.** An agent that writes its own name is not called again: agents quote themselves.
18+
19+A turn that was cancelled, that failed or that was refused calls nobody, since there is no answer worth passing on.
20+
21+## Why a depth
22+
23+Several ways to bound a chain were considered.
24+
25+- **A depth, chosen.** It is the simplest to explain and to predict: the user knows how many model turns one message can cost at most. It does not need to understand what the agents say.
26+- **Detecting loops by what is said.** An agent can repeat itself usefully, and two agents can be stuck while saying different words every time. Whatever the detection, it would be wrong in both directions.
27+- **A budget of time or tokens.** Closer to what the user cares about, but the application does not know the tokens of every agent, and a time limit cuts a long, useful turn.
28+- **Asking the user at each hop.** Safe, and it defeats the purpose of agents working together.
29+- **No limit and the stop button only.** The cost of a mistake is paid before the user notices it.
30+
31+The depth is a floor of safety, not a measure of quality: a chain of three well-chosen calls is more useful than a long one.
32+
33+## Limits of the current design
34+
35+- The bookkeeping of "who is working" is per agent and channel. If two prompts are queued for the same agent in the same channel, the first one ending shows the agent as idle while the second one is still to run.
36+- Two agents called by the same answer run in parallel, each in its own process: Synedrion does not order them.
37+- Agents decide what to do with a mention of themselves in their own instructions. Synedrion does not tell an agent about the other agents.
38+
39+## How it relates to the rest
40+
41+The setting and its limits: [settings](../reference/settings.md). Steps to use it: [how to let agents call each other](../how-to/let-agents-call-each-other.md). Who receives a message in general: [mentions](../reference/mentions.md).
modified docs/en/explanation/architecture.md +13 -10
@@ -1,6 +1,6 @@
11 # Architecture
22
3-> **Status: version 0.1.0 is built.** What follows describes the code as it is, except where a point is marked as planned. Agents talking to each other, sending the channel's earlier messages to an agent, and showing tool calls are not built yet.
3+> **Status: the features of versions 0.1.0 and 0.2.0 are built.** What follows describes the code as it is. The window has never been seen on a screen by the author of the code.
44
55 ## What is this about?
66
@@ -8,21 +8,22 @@ Synedrion has four parts: a domain model, a store that persists it, an ACP layer
88
99 | Crate | What it is for |
1010 | --- | --- |
11-| `synedrion-domain` | The types of the application (user, agent, channel, message), the rules that need no database or window (names, mentions and their completion), and the `Repository` trait. It depends on nothing, not even an external crate. |
11+| `synedrion-domain` | The types of the application (user, agent, channel, message, trace, settings), the rules that need no database or window (names, mentions and their completion, slash commands, the context given to an agent), and the `Repository` trait. It depends on nothing, not even an external crate. |
1212 | `synedrion-store` | `SqliteRepository`, the implementation of `Repository` with SQLite through `rusqlite`, the schema migrations, and where the file lives. |
1313 | `synedrion-acp` | `AgentHub`: starts agent processes, speaks ACP with them through the official `agent-client-protocol` crate, and reports what they do as events. It also contains the test agent. |
14-| `synedrion-ui` | The `ChatController`, which links the database to the agents and knows nothing about windows, and the GPUI Kit windows, which only draw and report clicks. |
14+| `synedrion-ui` | The `ChatController`, which links the database to the agents and knows nothing about windows (its parts: what each agent is handed, agents calling agents, tool calls and plans), and the GPUI Kit windows, which only draw and report clicks. |
1515
1616 ## From a mention to a reply
1717
1818 When the user sends a message containing `@name`, the following happens.
1919
2020 1. The controller stores the message, then finds the mentions in the text with a pure function of the domain. A mention of an unknown name is left as it is and reported to the user.
21-2. For each declared agent that is mentioned, the controller hands the message to the `AgentHub`.
21+2. For each declared agent that is mentioned, the controller builds what the agent receives: the messages of the channel that it has not seen yet, then the message (see [the context of the channel](../reference/channel-context.md)). It hands that to the `AgentHub`.
2222 3. If the agent's process is not running, the hub starts it with the command of its declaration, on a thread of its own. See [agent declaration](../reference/agent-declaration.md).
2323 4. The first time that process is used, the hub calls `initialize`. The first time that agent is addressed in that channel, it calls `session/new`.
24-5. The hub sends the message with `session/prompt`. The agent answers with a stream of `session/update` notifications. The hub reports each piece of text as an event, and the controller appends it to a single message of the agent in the channel, updating the database as the text grows. The turn ends when the agent answers the `session/prompt` call, and a message that did not end normally (cancelled, failed, refused) leaves a notice in the channel.
24+5. The hub sends the message with `session/prompt`. The agent answers with a stream of `session/update` notifications. The hub reports each piece of text as an event, and the controller appends it to a single message of the agent in the channel, updating the database as the text grows. Tool calls and plans become cards in the channel, and the text that follows them starts a new message. The turn ends when the agent answers the `session/prompt` call, and a message that did not end normally (cancelled, failed, refused) leaves a notice in the channel.
2525 6. If the agent asks for permission with `session/request_permission`, the question is shown in the channel as a card, and the user's answer is sent back.
26+7. When the turn ended normally and the answer mentions another declared agent, the controller hands that agent the answer, one hop further in a chain whose length is limited (see [agents calling agents](agents-calling-agents.md)).
2627
2728 The events cross from the agents' threads to the window through a queue, and the window only redraws what the controller says changed. The calls are listed in the [ACP methods reference](../reference/acp-methods.md).
2829
@@ -38,9 +39,11 @@ The events cross from the agents' threads to the window through a queue, and the
3839
3940 **Agents are launched by a command.** An agent is declared by a command, its arguments, its environment and a working folder, like the `agent_servers` of the Zed editor. This also covers agents inside a sandbox: the command is then `sbx exec`, which starts the agent in the sandbox and gives Synedrion its standard input and output, which is where ACP travels. The exact syntax of `sbx exec` is still to be checked on a real sandbox.
4041
41-**The agent receives the message that mentions it, as typed.** An agent that only sees that message cannot follow the discussion. Sending it the last messages of the channel, and only those that appeared since its previous turn, is planned (ticket #14).
42+**The agent receives the messages it has not seen, then the message.** An agent that only sees the message that mentions it cannot follow the discussion. It already knows what it said itself, so it is told what was said around it since its last turn, up to a number and a size that the user can bound. The record of what each agent was handed is kept in memory: it lives as long as the agents' sessions do.
4243
43-**Agents may mention each other, with guard rails, in a later version.** The plan (ticket #15) is a maximum chain depth with a low default, a stop button for the whole chain, and ignoring an agent that mentions itself. Today, a mention in an agent's answer does nothing.
44+**Agents may mention each other, with guard rails.** A maximum chain depth with a low default, a stop button for the whole chain, and ignoring an agent that mentions itself. See [agents calling agents](agents-calling-agents.md).
45+
46+**What an agent does besides writing is part of the history.** Tool calls and plans are stored as messages of their own kind, so that they are kept, ordered with the text, and can be updated in place while the agent works.
4447
4548 ## Rejected alternatives
4649
@@ -49,9 +52,9 @@ The events cross from the agents' threads to the window through a queue, and the
4952
5053 ## Open points
5154
52-- Whether Synedrion offers agents access to files and terminals, the optional `fs/*` and `terminal/*` client capabilities of ACP, is undecided because it is a security decision (ticket #18). Today it offers none.
53-- Nothing has been tried against a real agent such as mini-me: the tests use a test agent built on the same ACP library.
54-- The window has never been seen on a screen. Its behaviour is tested, its look is not.
55+- Synedrion offers agents no access to files and terminals, the optional `fs/*` and `terminal/*` client capabilities of ACP. That is a decision, and its reasons are in [client capabilities](client-capabilities.md). It is open to being decided again.
56+- The mentions, the commands and the attached files were tried with mini-me. The context of the channel, agents calling agents, and tool calls and plans were tried only with the test agent, which is built on the same ACP library: whether a real agent sends and receives these as the test agent does is not known.
57+- The window has never been seen on a screen by the author of the code. Its behaviour is tested, its look is not.
5558
5659 ## How it relates to the rest
5760
@@ -1,6 +1,6 @@
1 # Architecture1 # Architecture
2 2
3-> **Status: version 0.1.0 is built.** What follows describes the code as it is, except where a point is marked as planned. Agents talking to each other, sending the channel's earlier messages to an agent, and showing tool calls are not built yet.3+> **Status: the features of versions 0.1.0 and 0.2.0 are built.** What follows describes the code as it is. The window has never been seen on a screen by the author of the code.
4 4
5 ## What is this about?5 ## What is this about?
6 6
@@ -8,21 +8,22 @@ Synedrion has four parts: a domain model, a store that persists it, an ACP layer
8 8
9 | Crate | What it is for |9 | Crate | What it is for |
10 | --- | --- |10 | --- | --- |
11-| `synedrion-domain` | The types of the application (user, agent, channel, message), the rules that need no database or window (names, mentions and their completion), and the `Repository` trait. It depends on nothing, not even an external crate. |11+| `synedrion-domain` | The types of the application (user, agent, channel, message, trace, settings), the rules that need no database or window (names, mentions and their completion, slash commands, the context given to an agent), and the `Repository` trait. It depends on nothing, not even an external crate. |
12 | `synedrion-store` | `SqliteRepository`, the implementation of `Repository` with SQLite through `rusqlite`, the schema migrations, and where the file lives. |12 | `synedrion-store` | `SqliteRepository`, the implementation of `Repository` with SQLite through `rusqlite`, the schema migrations, and where the file lives. |
13 | `synedrion-acp` | `AgentHub`: starts agent processes, speaks ACP with them through the official `agent-client-protocol` crate, and reports what they do as events. It also contains the test agent. |13 | `synedrion-acp` | `AgentHub`: starts agent processes, speaks ACP with them through the official `agent-client-protocol` crate, and reports what they do as events. It also contains the test agent. |
14-| `synedrion-ui` | The `ChatController`, which links the database to the agents and knows nothing about windows, and the GPUI Kit windows, which only draw and report clicks. |14+| `synedrion-ui` | The `ChatController`, which links the database to the agents and knows nothing about windows (its parts: what each agent is handed, agents calling agents, tool calls and plans), and the GPUI Kit windows, which only draw and report clicks. |
15 15
16 ## From a mention to a reply16 ## From a mention to a reply
17 17
18 When the user sends a message containing `@name`, the following happens.18 When the user sends a message containing `@name`, the following happens.
19 19
20 1. The controller stores the message, then finds the mentions in the text with a pure function of the domain. A mention of an unknown name is left as it is and reported to the user.20 1. The controller stores the message, then finds the mentions in the text with a pure function of the domain. A mention of an unknown name is left as it is and reported to the user.
21-2. For each declared agent that is mentioned, the controller hands the message to the `AgentHub`.21+2. For each declared agent that is mentioned, the controller builds what the agent receives: the messages of the channel that it has not seen yet, then the message (see [the context of the channel](../reference/channel-context.md)). It hands that to the `AgentHub`.
22 3. If the agent's process is not running, the hub starts it with the command of its declaration, on a thread of its own. See [agent declaration](../reference/agent-declaration.md).22 3. If the agent's process is not running, the hub starts it with the command of its declaration, on a thread of its own. See [agent declaration](../reference/agent-declaration.md).
23 4. The first time that process is used, the hub calls `initialize`. The first time that agent is addressed in that channel, it calls `session/new`.23 4. The first time that process is used, the hub calls `initialize`. The first time that agent is addressed in that channel, it calls `session/new`.
24-5. The hub sends the message with `session/prompt`. The agent answers with a stream of `session/update` notifications. The hub reports each piece of text as an event, and the controller appends it to a single message of the agent in the channel, updating the database as the text grows. The turn ends when the agent answers the `session/prompt` call, and a message that did not end normally (cancelled, failed, refused) leaves a notice in the channel.24+5. The hub sends the message with `session/prompt`. The agent answers with a stream of `session/update` notifications. The hub reports each piece of text as an event, and the controller appends it to a single message of the agent in the channel, updating the database as the text grows. Tool calls and plans become cards in the channel, and the text that follows them starts a new message. The turn ends when the agent answers the `session/prompt` call, and a message that did not end normally (cancelled, failed, refused) leaves a notice in the channel.
25 6. If the agent asks for permission with `session/request_permission`, the question is shown in the channel as a card, and the user's answer is sent back.25 6. If the agent asks for permission with `session/request_permission`, the question is shown in the channel as a card, and the user's answer is sent back.
26+7. When the turn ended normally and the answer mentions another declared agent, the controller hands that agent the answer, one hop further in a chain whose length is limited (see [agents calling agents](agents-calling-agents.md)).
26 27
27 The events cross from the agents' threads to the window through a queue, and the window only redraws what the controller says changed. The calls are listed in the [ACP methods reference](../reference/acp-methods.md).28 The events cross from the agents' threads to the window through a queue, and the window only redraws what the controller says changed. The calls are listed in the [ACP methods reference](../reference/acp-methods.md).
28 29
@@ -38,9 +39,11 @@ The events cross from the agents' threads to the window through a queue, and the
38 39
39 **Agents are launched by a command.** An agent is declared by a command, its arguments, its environment and a working folder, like the `agent_servers` of the Zed editor. This also covers agents inside a sandbox: the command is then `sbx exec`, which starts the agent in the sandbox and gives Synedrion its standard input and output, which is where ACP travels. The exact syntax of `sbx exec` is still to be checked on a real sandbox.40 **Agents are launched by a command.** An agent is declared by a command, its arguments, its environment and a working folder, like the `agent_servers` of the Zed editor. This also covers agents inside a sandbox: the command is then `sbx exec`, which starts the agent in the sandbox and gives Synedrion its standard input and output, which is where ACP travels. The exact syntax of `sbx exec` is still to be checked on a real sandbox.
40 41
41-**The agent receives the message that mentions it, as typed.** An agent that only sees that message cannot follow the discussion. Sending it the last messages of the channel, and only those that appeared since its previous turn, is planned (ticket #14).42+**The agent receives the messages it has not seen, then the message.** An agent that only sees the message that mentions it cannot follow the discussion. It already knows what it said itself, so it is told what was said around it since its last turn, up to a number and a size that the user can bound. The record of what each agent was handed is kept in memory: it lives as long as the agents' sessions do.
42 43
43-**Agents may mention each other, with guard rails, in a later version.** The plan (ticket #15) is a maximum chain depth with a low default, a stop button for the whole chain, and ignoring an agent that mentions itself. Today, a mention in an agent's answer does nothing.44+**Agents may mention each other, with guard rails.** A maximum chain depth with a low default, a stop button for the whole chain, and ignoring an agent that mentions itself. See [agents calling agents](agents-calling-agents.md).
45+
46+**What an agent does besides writing is part of the history.** Tool calls and plans are stored as messages of their own kind, so that they are kept, ordered with the text, and can be updated in place while the agent works.
44 47
45 ## Rejected alternatives48 ## Rejected alternatives
46 49
@@ -49,9 +52,9 @@ The events cross from the agents' threads to the window through a queue, and the
49 52
50 ## Open points53 ## Open points
51 54
52-- Whether Synedrion offers agents access to files and terminals, the optional `fs/*` and `terminal/*` client capabilities of ACP, is undecided because it is a security decision (ticket #18). Today it offers none.55+- Synedrion offers agents no access to files and terminals, the optional `fs/*` and `terminal/*` client capabilities of ACP. That is a decision, and its reasons are in [client capabilities](client-capabilities.md). It is open to being decided again.
53-- Nothing has been tried against a real agent such as mini-me: the tests use a test agent built on the same ACP library.56+- The mentions, the commands and the attached files were tried with mini-me. The context of the channel, agents calling agents, and tool calls and plans were tried only with the test agent, which is built on the same ACP library: whether a real agent sends and receives these as the test agent does is not known.
54-- The window has never been seen on a screen. Its behaviour is tested, its look is not.57+- The window has never been seen on a screen by the author of the code. Its behaviour is tested, its look is not.
55 58
56 ## How it relates to the rest59 ## How it relates to the rest
57 60
added docs/en/explanation/client-capabilities.md +42 -0
new file mode 100644
@@ -0,0 +1,42 @@
1+# Client capabilities: why Synedrion offers agents no file or terminal access
2+
3+## What is this about?
4+
5+ACP lets a client offer its agents optional services: reading and writing text files (`fs/read_text_file`, `fs/write_text_file`) and running commands in terminals (`terminal/*`). The client says which ones it offers when it starts the agent, in the `initialize` call. Synedrion does not offer any of them, and says so. This page records that decision, taken for ticket #18.
6+
7+## What the decision is
8+
9+Synedrion announces no capability at `initialize`: not `fs.readTextFile`, not `fs.writeTextFile`, not `terminal`. A test pins it, so that offering one becomes a decision made on purpose and not a side effect.
10+
11+An agent that wants to read, write or run something does it with its own tools, inside its own process.
12+
13+## Why
14+
15+The agents of Synedrion run on the same machine as the application, and possibly in a sandbox: that is the point of starting them with `sbx exec`. A sandbox exists to keep an agent away from the files and the processes of the host. If Synedrion offered `fs/*` or `terminal/*`, the agent would ask the application, which runs on the host outside the sandbox, to do what the sandbox forbids it to do. The service would be a hole in the wall, and it would work for the agent that is *not* in a sandbox as much as for the one that is, which is exactly where an unwanted write does the most damage.
16+
17+Offering them safely is possible, but it is a real piece of work and not a switch:
18+
19+- limiting every path to the working folder of the agent, with links and `..` resolved before the check;
20+- asking the user before each write, or at least the first one;
21+- a per-agent choice, since a trusted agent and a sandboxed one are not the same case;
22+- running commands with a visible output, a limit of time and a way to kill them.
23+
24+None of this is needed for the agents that exist today.
25+
26+## What was checked
27+
28+mini-me, started by Synedrion with no capability announced, answered prompts, announced its commands, and received attached files. Its own tools, such as its shell tool, were not exercised in that check, so this page does not say they work. It says that the agent starts and answers without what Synedrion does not offer.
29+
30+## Rejected alternatives
31+
32+- **Offering file access limited to the working folder, with confirmation for writes.** The most useful of the options, and the one to build first if the decision changes. It was not built because no agent needs it yet, and a half-checked scope is worse than none.
33+- **Offering everything, per agent, off by default.** A switch in the declaration. It needs the same scoping as the option above to be safe, so it is the same work.
34+- **Offering everything.** Rejected for the reason above.
35+
36+## When to decide again
37+
38+When an agent that Synedrion should support asks for these capabilities and works badly without them. The first thing to write then is the scoped read access, with a ticket of its own.
39+
40+## How it relates to the rest
41+
42+The calls Synedrion makes and does not make: [ACP methods](../reference/acp-methods.md). Why agents are launched in a sandbox: [architecture](architecture.md).
new file mode 100644
@@ -0,0 +1,42 @@
1+# Client capabilities: why Synedrion offers agents no file or terminal access
2+
3+## What is this about?
4+
5+ACP lets a client offer its agents optional services: reading and writing text files (`fs/read_text_file`, `fs/write_text_file`) and running commands in terminals (`terminal/*`). The client says which ones it offers when it starts the agent, in the `initialize` call. Synedrion does not offer any of them, and says so. This page records that decision, taken for ticket #18.
6+
7+## What the decision is
8+
9+Synedrion announces no capability at `initialize`: not `fs.readTextFile`, not `fs.writeTextFile`, not `terminal`. A test pins it, so that offering one becomes a decision made on purpose and not a side effect.
10+
11+An agent that wants to read, write or run something does it with its own tools, inside its own process.
12+
13+## Why
14+
15+The agents of Synedrion run on the same machine as the application, and possibly in a sandbox: that is the point of starting them with `sbx exec`. A sandbox exists to keep an agent away from the files and the processes of the host. If Synedrion offered `fs/*` or `terminal/*`, the agent would ask the application, which runs on the host outside the sandbox, to do what the sandbox forbids it to do. The service would be a hole in the wall, and it would work for the agent that is *not* in a sandbox as much as for the one that is, which is exactly where an unwanted write does the most damage.
16+
17+Offering them safely is possible, but it is a real piece of work and not a switch:
18+
19+- limiting every path to the working folder of the agent, with links and `..` resolved before the check;
20+- asking the user before each write, or at least the first one;
21+- a per-agent choice, since a trusted agent and a sandboxed one are not the same case;
22+- running commands with a visible output, a limit of time and a way to kill them.
23+
24+None of this is needed for the agents that exist today.
25+
26+## What was checked
27+
28+mini-me, started by Synedrion with no capability announced, answered prompts, announced its commands, and received attached files. Its own tools, such as its shell tool, were not exercised in that check, so this page does not say they work. It says that the agent starts and answers without what Synedrion does not offer.
29+
30+## Rejected alternatives
31+
32+- **Offering file access limited to the working folder, with confirmation for writes.** The most useful of the options, and the one to build first if the decision changes. It was not built because no agent needs it yet, and a half-checked scope is worse than none.
33+- **Offering everything, per agent, off by default.** A switch in the declaration. It needs the same scoping as the option above to be safe, so it is the same work.
34+- **Offering everything.** Rejected for the reason above.
35+
36+## When to decide again
37+
38+When an agent that Synedrion should support asks for these capabilities and works badly without them. The first thing to write then is the scoped read access, with a ticket of its own.
39+
40+## How it relates to the rest
41+
42+The calls Synedrion makes and does not make: [ACP methods](../reference/acp-methods.md). Why agents are launched in a sandbox: [architecture](architecture.md).
modified docs/en/how-to/declare-an-agent.md +1 -1
@@ -10,7 +10,7 @@ This guide declares an ACP agent so that you can mention it in a channel. It ass
1010 - **Command**: the program that starts the agent.
1111 - **Arguments**: one per line.
1212 - **Environment**: one `NAME=value` per line.
13- - **Working folder**: optional.
13+ - **Working folder**: optional. Type the path, or click **Browse…**, click folders to walk through them (`..` goes up), then **Use this folder**.
1414 3. Click **Save agent**. The agent appears in the list above the form.
1515 4. Write `@name` followed by your message in the conversation. You can leave the panel open, or close it with the robot button or the x in its title.
1616
@@ -10,7 +10,7 @@ This guide declares an ACP agent so that you can mention it in a channel. It ass
10 - **Command**: the program that starts the agent.10 - **Command**: the program that starts the agent.
11 - **Arguments**: one per line.11 - **Arguments**: one per line.
12 - **Environment**: one `NAME=value` per line.12 - **Environment**: one `NAME=value` per line.
13- - **Working folder**: optional.13+ - **Working folder**: optional. Type the path, or click **Browse…**, click folders to walk through them (`..` goes up), then **Use this folder**.
14 3. Click **Save agent**. The agent appears in the list above the form.14 3. Click **Save agent**. The agent appears in the list above the form.
15 4. Write `@name` followed by your message in the conversation. You can leave the panel open, or close it with the robot button or the x in its title.15 4. Write `@name` followed by your message in the conversation. You can leave the panel open, or close it with the robot button or the x in its title.
16 16
added docs/en/how-to/let-agents-call-each-other.md +36 -0
new file mode 100644
@@ -0,0 +1,36 @@
1+# How to let agents call each other
2+
3+This guide makes an agent hand work to another agent, and shows how to stop it. It assumes two agents are declared, for example `amy` and `bob`. See [how to declare an agent](declare-an-agent.md).
4+
5+## Steps
6+
7+1. Ask the first agent to involve the second one: `@amy review the plan and ask @bob to check the build`.
8+2. Wait for `@amy` to finish its answer. If the answer contains `@bob`, `@bob` is called as soon as the answer is complete, and receives the whole answer of `@amy`, introduced by `[Message from @amy]`.
9+3. Watch the channel. The answer of `@bob` appears as a message of its own. If it mentions `@amy` or another agent, that agent is called in turn.
10+
11+An agent has to write the mention in its answer for this to happen. An agent whose instructions do not tell it about the other agents will not mention them: put their names in its own instructions or configuration.
12+
13+## Stop the whole chain
14+
15+Click **Stop** while an agent works. Every agent working in the channel is asked to stop, and an answer that still arrives after the click calls nobody.
16+
17+## Change how far a chain may go
18+
19+1. Open the **Settings** panel.
20+2. Change **Chain depth**: the number of agents that may call one another in a row after your message. `3` is the default. `0` forbids it, and `10` is the most.
21+3. Click **Save settings**. It applies from the next message.
22+
23+When a chain reaches the limit, the agent that was about to be called is not called, and a message of Synedrion in the channel says so: `Chain stopped: @bob called @amy, but the limit of 3 agent(s) calling one another in a row is reached. The limit is in the settings.`
24+
25+## Variants
26+
27+- **Agents that must never call each other.** Set the depth to `0`. Mentions in answers then do nothing, and no notice is shown.
28+- **An agent that mentions itself.** Ignored: it is not called again.
29+- **A mention of a name no agent carries.** Ignored.
30+- **An agent that cannot be reached.** A message says `Could not reach @name` with the reason, and the rest goes on.
31+
32+## See also
33+
34+- Why the limit is a depth, and what else was considered: [agents calling agents](../explanation/agents-calling-agents.md)
35+- What the agent called is told: [the context of the channel](../reference/channel-context.md)
36+- Every setting: [settings](../reference/settings.md)
new file mode 100644
@@ -0,0 +1,36 @@
1+# How to let agents call each other
2+
3+This guide makes an agent hand work to another agent, and shows how to stop it. It assumes two agents are declared, for example `amy` and `bob`. See [how to declare an agent](declare-an-agent.md).
4+
5+## Steps
6+
7+1. Ask the first agent to involve the second one: `@amy review the plan and ask @bob to check the build`.
8+2. Wait for `@amy` to finish its answer. If the answer contains `@bob`, `@bob` is called as soon as the answer is complete, and receives the whole answer of `@amy`, introduced by `[Message from @amy]`.
9+3. Watch the channel. The answer of `@bob` appears as a message of its own. If it mentions `@amy` or another agent, that agent is called in turn.
10+
11+An agent has to write the mention in its answer for this to happen. An agent whose instructions do not tell it about the other agents will not mention them: put their names in its own instructions or configuration.
12+
13+## Stop the whole chain
14+
15+Click **Stop** while an agent works. Every agent working in the channel is asked to stop, and an answer that still arrives after the click calls nobody.
16+
17+## Change how far a chain may go
18+
19+1. Open the **Settings** panel.
20+2. Change **Chain depth**: the number of agents that may call one another in a row after your message. `3` is the default. `0` forbids it, and `10` is the most.
21+3. Click **Save settings**. It applies from the next message.
22+
23+When a chain reaches the limit, the agent that was about to be called is not called, and a message of Synedrion in the channel says so: `Chain stopped: @bob called @amy, but the limit of 3 agent(s) calling one another in a row is reached. The limit is in the settings.`
24+
25+## Variants
26+
27+- **Agents that must never call each other.** Set the depth to `0`. Mentions in answers then do nothing, and no notice is shown.
28+- **An agent that mentions itself.** Ignored: it is not called again.
29+- **A mention of a name no agent carries.** Ignored.
30+- **An agent that cannot be reached.** A message says `Could not reach @name` with the reason, and the rest goes on.
31+
32+## See also
33+
34+- Why the limit is a depth, and what else was considered: [agents calling agents](../explanation/agents-calling-agents.md)
35+- What the agent called is told: [the context of the channel](../reference/channel-context.md)
36+- Every setting: [settings](../reference/settings.md)
modified docs/en/how-to/run-the-tests.md +7 -5
@@ -22,7 +22,7 @@ Both commands work from a clean checkout. No network, no model and no screen are
2222 ## Variants
2323
2424 - **One crate only.** `cargo test -p synedrion-domain`, `-p synedrion-store`, `-p synedrion-acp` or `-p synedrion-ui`.
25-- **Only the window tests.** `cargo test -p synedrion-ui --test window`.
25+- **Only the window tests.** `cargo test -p synedrion-ui --test window`, and the other files of `crates/ui/tests`: `--test folder_browser`, `--test settings_and_traces`, and `--test conversation` (the controller with a stand-in for the agents, no window).
2626 - **Only the agent process tests.** `cargo test -p synedrion-acp --test hub`. They start the [test agent](../reference/test-agent.md) as a real process and wait up to 20 seconds for each event, so a slow machine makes them slower, not flaky.
2727 - **Format the code.** `cargo fmt --all` rewrites the files instead of only checking them.
2828
@@ -30,11 +30,13 @@ Both commands work from a clean checkout. No network, no model and no screen are
3030
3131 | Suite | What it checks |
3232 | --- | --- |
33-| `synedrion-domain` unit tests | Names, mentions and their completion, the rules that need no database or window |
34-| `synedrion-store` unit tests | The SQLite schema and migrations, every database operation, persistence across reopening the file, where the file lives |
35-| `synedrion-acp` unit tests and `tests/hub.rs` | The permission bookkeeping, and the real behaviour with an agent process: answers in chunks, permissions, cancellation, an agent that dies, one that does not exist |
36-| `synedrion-ui` unit tests | The controller (what a message or an agent event does), the agent form, formatting |
33+| `synedrion-domain` unit tests | Names, mentions and their completion, slash commands, the context given to an agent, traces, settings: the rules that need no database or window |
34+| `synedrion-store` unit tests | The SQLite schema and migrations (including an upgrade that keeps the messages), every database operation, the settings, persistence across reopening the file, where the file lives |
35+| `synedrion-acp` unit tests and `tests/hub.rs` | The permission bookkeeping, the translation of every kind of `session/update`, the capabilities announced, and the real behaviour with an agent process: answers in chunks, tool calls and plans, permissions, cancellation, an agent that dies, one that does not exist |
36+| `synedrion-ui` unit tests | The controller (what a message or an agent event does), the agent form, the list of files and of folders, formatting |
3737 | `synedrion-ui` `tests/window.rs` | The window driven like a user: profile, channels, sending, mentions, suggestions, permission questions, the Tab completion, the Stop button, the dock of panels and its resizing, declaring agents |
38+| `synedrion-ui` `tests/folder_browser.rs`, `tests/settings_and_traces.rs` | The folder browser of the agent form, the settings panel, the cards of tool calls and plans, and a chain of agents stopped from the window |
39+| `synedrion-ui` `tests/conversation.rs` | The context given to each agent, agents calling agents (the limit, the stop, the self-mention), and the tool calls and plans in the channel, without a window |
3840
3941 ## Not covered
4042
@@ -22,7 +22,7 @@ Both commands work from a clean checkout. No network, no model and no screen are
22 ## Variants22 ## Variants
23 23
24 - **One crate only.** `cargo test -p synedrion-domain`, `-p synedrion-store`, `-p synedrion-acp` or `-p synedrion-ui`.24 - **One crate only.** `cargo test -p synedrion-domain`, `-p synedrion-store`, `-p synedrion-acp` or `-p synedrion-ui`.
25-- **Only the window tests.** `cargo test -p synedrion-ui --test window`.25+- **Only the window tests.** `cargo test -p synedrion-ui --test window`, and the other files of `crates/ui/tests`: `--test folder_browser`, `--test settings_and_traces`, and `--test conversation` (the controller with a stand-in for the agents, no window).
26 - **Only the agent process tests.** `cargo test -p synedrion-acp --test hub`. They start the [test agent](../reference/test-agent.md) as a real process and wait up to 20 seconds for each event, so a slow machine makes them slower, not flaky.26 - **Only the agent process tests.** `cargo test -p synedrion-acp --test hub`. They start the [test agent](../reference/test-agent.md) as a real process and wait up to 20 seconds for each event, so a slow machine makes them slower, not flaky.
27 - **Format the code.** `cargo fmt --all` rewrites the files instead of only checking them.27 - **Format the code.** `cargo fmt --all` rewrites the files instead of only checking them.
28 28
@@ -30,11 +30,13 @@ Both commands work from a clean checkout. No network, no model and no screen are
30 30
31 | Suite | What it checks |31 | Suite | What it checks |
32 | --- | --- |32 | --- | --- |
33-| `synedrion-domain` unit tests | Names, mentions and their completion, the rules that need no database or window |33+| `synedrion-domain` unit tests | Names, mentions and their completion, slash commands, the context given to an agent, traces, settings: the rules that need no database or window |
34-| `synedrion-store` unit tests | The SQLite schema and migrations, every database operation, persistence across reopening the file, where the file lives |34+| `synedrion-store` unit tests | The SQLite schema and migrations (including an upgrade that keeps the messages), every database operation, the settings, persistence across reopening the file, where the file lives |
35-| `synedrion-acp` unit tests and `tests/hub.rs` | The permission bookkeeping, and the real behaviour with an agent process: answers in chunks, permissions, cancellation, an agent that dies, one that does not exist |35+| `synedrion-acp` unit tests and `tests/hub.rs` | The permission bookkeeping, the translation of every kind of `session/update`, the capabilities announced, and the real behaviour with an agent process: answers in chunks, tool calls and plans, permissions, cancellation, an agent that dies, one that does not exist |
36-| `synedrion-ui` unit tests | The controller (what a message or an agent event does), the agent form, formatting |36+| `synedrion-ui` unit tests | The controller (what a message or an agent event does), the agent form, the list of files and of folders, formatting |
37 | `synedrion-ui` `tests/window.rs` | The window driven like a user: profile, channels, sending, mentions, suggestions, permission questions, the Tab completion, the Stop button, the dock of panels and its resizing, declaring agents |37 | `synedrion-ui` `tests/window.rs` | The window driven like a user: profile, channels, sending, mentions, suggestions, permission questions, the Tab completion, the Stop button, the dock of panels and its resizing, declaring agents |
38+| `synedrion-ui` `tests/folder_browser.rs`, `tests/settings_and_traces.rs` | The folder browser of the agent form, the settings panel, the cards of tool calls and plans, and a chain of agents stopped from the window |
39+| `synedrion-ui` `tests/conversation.rs` | The context given to each agent, agents calling agents (the limit, the stop, the self-mention), and the tool calls and plans in the channel, without a window |
38 40
39 ## Not covered41 ## Not covered
40 42
modified docs/en/how-to/use-commands-and-attach-files.md +11 -2
@@ -6,7 +6,7 @@ This guide runs a command of an agent, such as `/new` or `/compact`, and attache
66
77 1. In the message box, type `/`. A list opens above it.
88 2. Type the first letters of the command to narrow the list.
9-3. Press Tab to take the first row, or click the one you want. The command is completed, followed by a space.
9+3. Press Tab to take the highlighted row (the first, or the one the Up and Down keys moved to), or click the one you want. The command is completed, followed by a space.
1010 4. Type the arguments if the row's hint shows that the command takes some, then send.
1111
1212 The agent answers like to any message. To run a command on a particular agent, mention it in front: `@mini-me /new`.
@@ -15,13 +15,22 @@ The agent answers like to any message. To run a command on a particular agent, m
1515
1616 1. Type `/file`, or pick it in the list that opens when you type `/`.
1717 2. Type some letters of the file name or of its folder. The list keeps the matching files.
18-3. Press Tab to take the first one, or click another. It appears above the message box.
18+3. Press Tab to take the highlighted one, or click another. It appears above the message box.
1919 4. Repeat from step 1 for another file. Click the cross next to a file to take it back out.
2020 5. Write your message, and send.
2121
22+## Name a file in the middle of a sentence
23+
24+1. Write your message, and where the file belongs type `$` followed by some letters of its name: `@bob look at $main`.
25+2. The list of files opens. Press Tab to take the highlighted one, or click another. Up and Down move the highlight, and Enter takes the highlighted row once you used them.
26+3. The path replaces what you typed, in the sentence, and the file is attached: `@bob look at src/main.rs `. Go on typing.
27+
28+The file also appears above the message box, and its cross takes the attachment back out without touching the sentence.
29+
2230 ## Variants
2331
2432 - **The list shows no command of the agent.** The agent announces its commands when its session for this channel is created, that is after your first message to it. Send one message first.
33+- **A `$` in the text opens a list you did not want.** A `$` glued to a word (`US$5`) opens nothing. Otherwise the list closes as soon as you type a space after what follows the `$`.
2534 - **The list shows no file.** The files are those of the agent's working folder, or of the folder Synedrion runs in. Declare the agent with a working folder (see [how to declare an agent](declare-an-agent.md)).
2635 - **Mentioning another agent.** The list follows the agents the message would go to: write the mention first, then the slash.
2736
@@ -6,7 +6,7 @@ This guide runs a command of an agent, such as `/new` or `/compact`, and attache
6 6
7 1. In the message box, type `/`. A list opens above it.7 1. In the message box, type `/`. A list opens above it.
8 2. Type the first letters of the command to narrow the list.8 2. Type the first letters of the command to narrow the list.
9-3. Press Tab to take the first row, or click the one you want. The command is completed, followed by a space.9+3. Press Tab to take the highlighted row (the first, or the one the Up and Down keys moved to), or click the one you want. The command is completed, followed by a space.
10 4. Type the arguments if the row's hint shows that the command takes some, then send.10 4. Type the arguments if the row's hint shows that the command takes some, then send.
11 11
12 The agent answers like to any message. To run a command on a particular agent, mention it in front: `@mini-me /new`.12 The agent answers like to any message. To run a command on a particular agent, mention it in front: `@mini-me /new`.
@@ -15,13 +15,22 @@ The agent answers like to any message. To run a command on a particular agent, m
15 15
16 1. Type `/file`, or pick it in the list that opens when you type `/`.16 1. Type `/file`, or pick it in the list that opens when you type `/`.
17 2. Type some letters of the file name or of its folder. The list keeps the matching files.17 2. Type some letters of the file name or of its folder. The list keeps the matching files.
18-3. Press Tab to take the first one, or click another. It appears above the message box.18+3. Press Tab to take the highlighted one, or click another. It appears above the message box.
19 4. Repeat from step 1 for another file. Click the cross next to a file to take it back out.19 4. Repeat from step 1 for another file. Click the cross next to a file to take it back out.
20 5. Write your message, and send.20 5. Write your message, and send.
21 21
22+## Name a file in the middle of a sentence
23+
24+1. Write your message, and where the file belongs type `$` followed by some letters of its name: `@bob look at $main`.
25+2. The list of files opens. Press Tab to take the highlighted one, or click another. Up and Down move the highlight, and Enter takes the highlighted row once you used them.
26+3. The path replaces what you typed, in the sentence, and the file is attached: `@bob look at src/main.rs `. Go on typing.
27+
28+The file also appears above the message box, and its cross takes the attachment back out without touching the sentence.
29+
22 ## Variants30 ## Variants
23 31
24 - **The list shows no command of the agent.** The agent announces its commands when its session for this channel is created, that is after your first message to it. Send one message first.32 - **The list shows no command of the agent.** The agent announces its commands when its session for this channel is created, that is after your first message to it. Send one message first.
33+- **A `$` in the text opens a list you did not want.** A `$` glued to a word (`US$5`) opens nothing. Otherwise the list closes as soon as you type a space after what follows the `$`.
25 - **The list shows no file.** The files are those of the agent's working folder, or of the folder Synedrion runs in. Declare the agent with a working folder (see [how to declare an agent](declare-an-agent.md)).34 - **The list shows no file.** The files are those of the agent's working folder, or of the folder Synedrion runs in. Declare the agent with a working folder (see [how to declare an agent](declare-an-agent.md)).
26 - **Mentioning another agent.** The list follows the agents the message would go to: write the mention first, then the slash.35 - **Mentioning another agent.** The list follows the agents the message would go to: write the mention first, then the slash.
27 36
modified docs/en/reference/acp-methods.md +6 -6
@@ -8,11 +8,11 @@ ACP is JSON-RPC over the standard input and output of the agent process. Synedri
88
99 | Method | Protocol | Synedrion |
1010 | --- | --- | --- |
11-| `initialize` | Baseline. Negotiates versions and exchanges capabilities. | Called once per agent process. Synedrion sets no client capability. |
11+| `initialize` | Baseline. Negotiates versions and exchanges capabilities. | Called once per agent process. Synedrion announces no client capability, by decision: see [client capabilities](../explanation/client-capabilities.md). |
1212 | `authenticate` | Baseline, used if the agent requires it. | Not called. |
1313 | `session/new` | Baseline. Creates a session. | Called once per pair of agent and channel, with the working folder of the declaration, or the folder where Synedrion runs. |
14-| `session/prompt` | Baseline. Sends the user's prompt. | Called for each message addressed to an agent, with one text block (the message as typed, or the bare command for a slash command) followed by one `resource_link` block per attached file. |
15-| `session/cancel` | Notification, no response expected. | Sent by the **Stop** button, for each agent working in the channel. |
14+| `session/prompt` | Baseline. Sends the user's prompt. | Called for each message addressed to an agent, with one text block followed by one `resource_link` block per attached file. The text is the message as typed, preceded by the context of the channel when there is some, or the bare command for a slash command, or, for an agent called by another agent, the answer of that agent. |
15+| `session/cancel` | Notification, no response expected. | Sent by the **Stop** button, for each agent working in the channel. The answers of the cancelled turns call nobody. |
1616 | `session/load` | Optional, needs the `loadSession` capability. Resumes a session. | Not used: sessions do not survive a restart of Synedrion. |
1717 | `session/set_mode` | Optional. Switches operating mode. | Not used. |
1818 | `logout` | Optional, needs `agentCapabilities.auth.logout`. | Not used. |
@@ -22,15 +22,15 @@ ACP is JSON-RPC over the standard input and output of the agent process. Synedri
2222 | Method | Protocol | Synedrion |
2323 | --- | --- | --- |
2424 | `session/request_permission` | Baseline. Asks the user to authorise a tool call. | Shown as a card in the channel with the agent's title and options. The chosen option is sent back. **Dismiss** answers with a cancellation, which the agent takes as a refusal. If the turn is cancelled first, the card is withdrawn and the agent gets a cancellation. |
25-| `fs/read_text_file`, `fs/write_text_file` | Optional, need the `fs.readTextFile` and `fs.writeTextFile` capabilities. | Not offered (undecided, ticket #18). |
26-| `terminal/create`, `terminal/output`, `terminal/release`, `terminal/wait_for_exit`, `terminal/kill` | Optional, need the `terminal` capability. | Not offered (undecided, ticket #18). |
25+| `fs/read_text_file`, `fs/write_text_file` | Optional, need the `fs.readTextFile` and `fs.writeTextFile` capabilities. | Not offered, by decision: see [client capabilities](../explanation/client-capabilities.md). |
26+| `terminal/create`, `terminal/output`, `terminal/release`, `terminal/wait_for_exit`, `terminal/kill` | Optional, need the `terminal` capability. | Not offered, by decision: see [client capabilities](../explanation/client-capabilities.md). |
2727 | `elicitation/create` | Optional, needs the matching elicitation capability. | Not offered. |
2828
2929 ## Notifications the agent sends to the client
3030
3131 | Notification | Protocol | Synedrion |
3232 | --- | --- | --- |
33-| `session/update` | Progress, message chunks, thought chunks, tool calls, plans, available commands, mode changes. | The text of the agent's answer is put end to end in one message. Its reasoning (thought chunks) is shown live in a card while the agent works, and is not kept. The list of available commands feeds the `/` list. Everything else is ignored for now (tool calls and plans: ticket #17). |
33+| `session/update` | Progress, message chunks, thought chunks, tool calls, plans, available commands, mode changes. | The text of the agent's answer is put end to end in one message, and a new message starts after a tool call or a plan. Its reasoning (thought chunks) is shown live in a card while the agent works, and is not kept. Tool calls and their updates, and plans, are kept in the channel as cards: see [tool calls, plans and what cannot be shown](tool-calls-and-plans.md). Notices are shown. The list of available commands feeds the `/` list. Content that cannot be drawn is shown as a short note, and an update of an unknown kind as a notice. Usage figures, modes, configuration options, the session title and the echo of the user's message are not shown. |
3434 | `elicitation/complete` | Reports completion of an out-of-band URL interaction. | Ignored. |
3535
3636 ## Stop reasons
@@ -8,11 +8,11 @@ ACP is JSON-RPC over the standard input and output of the agent process. Synedri
8 8
9 | Method | Protocol | Synedrion |9 | Method | Protocol | Synedrion |
10 | --- | --- | --- |10 | --- | --- | --- |
11-| `initialize` | Baseline. Negotiates versions and exchanges capabilities. | Called once per agent process. Synedrion sets no client capability. |11+| `initialize` | Baseline. Negotiates versions and exchanges capabilities. | Called once per agent process. Synedrion announces no client capability, by decision: see [client capabilities](../explanation/client-capabilities.md). |
12 | `authenticate` | Baseline, used if the agent requires it. | Not called. |12 | `authenticate` | Baseline, used if the agent requires it. | Not called. |
13 | `session/new` | Baseline. Creates a session. | Called once per pair of agent and channel, with the working folder of the declaration, or the folder where Synedrion runs. |13 | `session/new` | Baseline. Creates a session. | Called once per pair of agent and channel, with the working folder of the declaration, or the folder where Synedrion runs. |
14-| `session/prompt` | Baseline. Sends the user's prompt. | Called for each message addressed to an agent, with one text block (the message as typed, or the bare command for a slash command) followed by one `resource_link` block per attached file. |14+| `session/prompt` | Baseline. Sends the user's prompt. | Called for each message addressed to an agent, with one text block followed by one `resource_link` block per attached file. The text is the message as typed, preceded by the context of the channel when there is some, or the bare command for a slash command, or, for an agent called by another agent, the answer of that agent. |
15-| `session/cancel` | Notification, no response expected. | Sent by the **Stop** button, for each agent working in the channel. |15+| `session/cancel` | Notification, no response expected. | Sent by the **Stop** button, for each agent working in the channel. The answers of the cancelled turns call nobody. |
16 | `session/load` | Optional, needs the `loadSession` capability. Resumes a session. | Not used: sessions do not survive a restart of Synedrion. |16 | `session/load` | Optional, needs the `loadSession` capability. Resumes a session. | Not used: sessions do not survive a restart of Synedrion. |
17 | `session/set_mode` | Optional. Switches operating mode. | Not used. |17 | `session/set_mode` | Optional. Switches operating mode. | Not used. |
18 | `logout` | Optional, needs `agentCapabilities.auth.logout`. | Not used. |18 | `logout` | Optional, needs `agentCapabilities.auth.logout`. | Not used. |
@@ -22,15 +22,15 @@ ACP is JSON-RPC over the standard input and output of the agent process. Synedri
22 | Method | Protocol | Synedrion |22 | Method | Protocol | Synedrion |
23 | --- | --- | --- |23 | --- | --- | --- |
24 | `session/request_permission` | Baseline. Asks the user to authorise a tool call. | Shown as a card in the channel with the agent's title and options. The chosen option is sent back. **Dismiss** answers with a cancellation, which the agent takes as a refusal. If the turn is cancelled first, the card is withdrawn and the agent gets a cancellation. |24 | `session/request_permission` | Baseline. Asks the user to authorise a tool call. | Shown as a card in the channel with the agent's title and options. The chosen option is sent back. **Dismiss** answers with a cancellation, which the agent takes as a refusal. If the turn is cancelled first, the card is withdrawn and the agent gets a cancellation. |
25-| `fs/read_text_file`, `fs/write_text_file` | Optional, need the `fs.readTextFile` and `fs.writeTextFile` capabilities. | Not offered (undecided, ticket #18). |25+| `fs/read_text_file`, `fs/write_text_file` | Optional, need the `fs.readTextFile` and `fs.writeTextFile` capabilities. | Not offered, by decision: see [client capabilities](../explanation/client-capabilities.md). |
26-| `terminal/create`, `terminal/output`, `terminal/release`, `terminal/wait_for_exit`, `terminal/kill` | Optional, need the `terminal` capability. | Not offered (undecided, ticket #18). |26+| `terminal/create`, `terminal/output`, `terminal/release`, `terminal/wait_for_exit`, `terminal/kill` | Optional, need the `terminal` capability. | Not offered, by decision: see [client capabilities](../explanation/client-capabilities.md). |
27 | `elicitation/create` | Optional, needs the matching elicitation capability. | Not offered. |27 | `elicitation/create` | Optional, needs the matching elicitation capability. | Not offered. |
28 28
29 ## Notifications the agent sends to the client29 ## Notifications the agent sends to the client
30 30
31 | Notification | Protocol | Synedrion |31 | Notification | Protocol | Synedrion |
32 | --- | --- | --- |32 | --- | --- | --- |
33-| `session/update` | Progress, message chunks, thought chunks, tool calls, plans, available commands, mode changes. | The text of the agent's answer is put end to end in one message. Its reasoning (thought chunks) is shown live in a card while the agent works, and is not kept. The list of available commands feeds the `/` list. Everything else is ignored for now (tool calls and plans: ticket #17). |33+| `session/update` | Progress, message chunks, thought chunks, tool calls, plans, available commands, mode changes. | The text of the agent's answer is put end to end in one message, and a new message starts after a tool call or a plan. Its reasoning (thought chunks) is shown live in a card while the agent works, and is not kept. Tool calls and their updates, and plans, are kept in the channel as cards: see [tool calls, plans and what cannot be shown](tool-calls-and-plans.md). Notices are shown. The list of available commands feeds the `/` list. Content that cannot be drawn is shown as a short note, and an update of an unknown kind as a notice. Usage figures, modes, configuration options, the session title and the echo of the user's message are not shown. |
34 | `elicitation/complete` | Reports completion of an out-of-band URL interaction. | Ignored. |34 | `elicitation/complete` | Reports completion of an out-of-band URL interaction. | Ignored. |
35 35
36 ## Stop reasons36 ## Stop reasons
modified docs/en/reference/agent-declaration.md +16 -1
@@ -8,7 +8,7 @@ An agent is declared in the **Agents** panel, and stored in the database.
88 | `command` | Command | The program to run. Required. |
99 | `args` | Arguments | One argument per line. Blank lines are ignored and each line is trimmed. |
1010 | `env` | Environment | One `NAME=value` per line, split at the first `=`. The name cannot be empty nor contain a space. Blank lines are ignored. |
11-| `working_dir` | Working folder | Optional. It is sent to the agent as the folder of its sessions. It is not the folder the process starts in: the process starts where Synedrion was started. |
11+| `working_dir` | Working folder | Optional. It is sent to the agent as the folder of its sessions. It is not the folder the process starts in: the process starts where Synedrion was started. The path can be typed, or chosen with the **Browse…** button of the form. |
1212
1313 The command is executed as declared, and ACP travels over the standard input and output of the process. When no working folder is declared, the sessions use the folder where Synedrion runs.
1414
@@ -22,6 +22,21 @@ The command is executed as declared, and ACP travels over the standard input and
2222 | Delete | Removes the declaration. Past messages stay. A running process is not stopped by this. |
2323 | Invalid form | Nothing is saved, and a notice names the field: `Name …`, `Command …`, or `Environment line N must look like NAME=value`. |
2424
25+## The folder browser
26+
27+**Browse…**, under the working folder field, opens a list of folders in the form.
28+
29+| Part | Behaviour |
30+| --- | --- |
31+| Where it opens | On the folder typed in the field when it exists, otherwise on the home folder (`HOME`), otherwise on the folder where Synedrion runs. |
32+| The path shown | The folder whose content is listed. |
33+| `..` | Goes to the folder above. Absent at the top of the file system. |
34+| A folder of the list | Goes into it. Only folders are listed, sorted without regard to case. Hidden folders (their name starts with a dot) are left out. At most 200 are listed, and a line says when there were more: type the path to go further. |
35+| **Use this folder** | Puts the folder on show in the field, and closes the list. |
36+| **Cancel** | Closes the list and leaves the field as it was. |
37+
38+The list is drawn by Synedrion, not by a dialog of the operating system, so that it looks and behaves the same everywhere. It has not been seen on a screen.
39+
2540 ## Examples
2641
2742 ### mini-me, a local process
@@ -8,7 +8,7 @@ An agent is declared in the **Agents** panel, and stored in the database.
8 | `command` | Command | The program to run. Required. |8 | `command` | Command | The program to run. Required. |
9 | `args` | Arguments | One argument per line. Blank lines are ignored and each line is trimmed. |9 | `args` | Arguments | One argument per line. Blank lines are ignored and each line is trimmed. |
10 | `env` | Environment | One `NAME=value` per line, split at the first `=`. The name cannot be empty nor contain a space. Blank lines are ignored. |10 | `env` | Environment | One `NAME=value` per line, split at the first `=`. The name cannot be empty nor contain a space. Blank lines are ignored. |
11-| `working_dir` | Working folder | Optional. It is sent to the agent as the folder of its sessions. It is not the folder the process starts in: the process starts where Synedrion was started. |11+| `working_dir` | Working folder | Optional. It is sent to the agent as the folder of its sessions. It is not the folder the process starts in: the process starts where Synedrion was started. The path can be typed, or chosen with the **Browse…** button of the form. |
12 12
13 The command is executed as declared, and ACP travels over the standard input and output of the process. When no working folder is declared, the sessions use the folder where Synedrion runs.13 The command is executed as declared, and ACP travels over the standard input and output of the process. When no working folder is declared, the sessions use the folder where Synedrion runs.
14 14
@@ -22,6 +22,21 @@ The command is executed as declared, and ACP travels over the standard input and
22 | Delete | Removes the declaration. Past messages stay. A running process is not stopped by this. |22 | Delete | Removes the declaration. Past messages stay. A running process is not stopped by this. |
23 | Invalid form | Nothing is saved, and a notice names the field: `Name …`, `Command …`, or `Environment line N must look like NAME=value`. |23 | Invalid form | Nothing is saved, and a notice names the field: `Name …`, `Command …`, or `Environment line N must look like NAME=value`. |
24 24
25+## The folder browser
26+
27+**Browse…**, under the working folder field, opens a list of folders in the form.
28+
29+| Part | Behaviour |
30+| --- | --- |
31+| Where it opens | On the folder typed in the field when it exists, otherwise on the home folder (`HOME`), otherwise on the folder where Synedrion runs. |
32+| The path shown | The folder whose content is listed. |
33+| `..` | Goes to the folder above. Absent at the top of the file system. |
34+| A folder of the list | Goes into it. Only folders are listed, sorted without regard to case. Hidden folders (their name starts with a dot) are left out. At most 200 are listed, and a line says when there were more: type the path to go further. |
35+| **Use this folder** | Puts the folder on show in the field, and closes the list. |
36+| **Cancel** | Closes the list and leaves the field as it was. |
37+
38+The list is drawn by Synedrion, not by a dialog of the operating system, so that it looks and behaves the same everywhere. It has not been seen on a screen.
39+
25 ## Examples40 ## Examples
26 41
27 ### mini-me, a local process42 ### mini-me, a local process
added docs/en/reference/channel-context.md +60 -0
new file mode 100644
@@ -0,0 +1,60 @@
1+# Reference: the context of the channel
2+
3+An agent keeps its own conversation, so it already knows what the user and it said to one another. What it cannot know is what was said around it. The text it receives therefore starts with the messages it has not seen, then comes the message itself.
4+
5+## What an agent is told
6+
7+For an agent and a channel, the messages told are those of the channel that satisfy all of these:
8+
9+| Rule | Detail |
10+| --- | --- |
11+| Not seen yet | Posted after the last message that the agent was handed in this channel. Before its first turn in the channel, every earlier message counts. |
12+| Not its own | Messages written by the agent itself are left out, whatever the case of its name: it knows what it said. |
13+| Conversation only | Notices of Synedrion (such as `Could not reach @bob`) and [traces](tool-calls-and-plans.md) (tool calls and plans) are left out. |
14+| Not too many | At most `Messages of context` of them, the latest ones. The older ones are counted. See [settings](settings.md). |
15+
16+About 200 earlier messages of the channel are looked at. A message of the user is signed with their display name, a message of an agent with its name.
17+
18+## The text that is sent
19+
20+| Case | The agent receives |
21+| --- | --- |
22+| Nothing to tell, message of the user | The message exactly as typed. |
23+| Something to tell, message of the user | The context, a blank line, then the message as typed. |
24+| Message of another agent (an agent calling it) | The context if any, a blank line, then `[Message from @name]`, a line break, and the whole answer of that agent. |
25+| A slash command it understands | The bare command, without context: an agent recognises a command only at the very start. See [slash commands](slash-commands.md). |
26+
27+The context has this shape:
28+
29+```text
30+[Channel context: what was said since your last turn]
31+[3 earlier message(s) not shown]
32+Ada: the build is red
33+amy: I will look at the logs
34+[End of channel context]
35+
36+@bob can you check too?
37+```
38+
39+The line `[N earlier message(s) not shown]` appears only when some were left out.
40+
41+## Limits
42+
43+| Limit | Value | When it is reached |
44+| --- | --- | --- |
45+| One earlier message | 2,000 characters | The message is cut, and ends with `[message cut: N more character(s)]`. |
46+| The whole context | 12,000 characters | The oldest messages are dropped, until it fits, and counted in `[N earlier message(s) not shown]`. |
47+| The message that calls the agent | None | It is handed over whole. |
48+
49+Characters are counted, not bytes, and a character is never split.
50+
51+## What is not covered
52+
53+- The record of what an agent was handed is kept while Synedrion runs. After a restart, every agent is told the latest messages again, which matches the fact that its sessions do not survive a restart either.
54+- If an agent's process dies and is started again while Synedrion keeps running, its new session has lost what the old one knew, and what was already handed over is not sent again.
55+- A command such as `/new` or `/compact` makes an agent forget, and Synedrion does not send again what it had handed over before.
56+
57+## Related
58+
59+- Changing the numbers: [settings](settings.md)
60+- Who receives a message: [mentions](mentions.md)
new file mode 100644
@@ -0,0 +1,60 @@
1+# Reference: the context of the channel
2+
3+An agent keeps its own conversation, so it already knows what the user and it said to one another. What it cannot know is what was said around it. The text it receives therefore starts with the messages it has not seen, then comes the message itself.
4+
5+## What an agent is told
6+
7+For an agent and a channel, the messages told are those of the channel that satisfy all of these:
8+
9+| Rule | Detail |
10+| --- | --- |
11+| Not seen yet | Posted after the last message that the agent was handed in this channel. Before its first turn in the channel, every earlier message counts. |
12+| Not its own | Messages written by the agent itself are left out, whatever the case of its name: it knows what it said. |
13+| Conversation only | Notices of Synedrion (such as `Could not reach @bob`) and [traces](tool-calls-and-plans.md) (tool calls and plans) are left out. |
14+| Not too many | At most `Messages of context` of them, the latest ones. The older ones are counted. See [settings](settings.md). |
15+
16+About 200 earlier messages of the channel are looked at. A message of the user is signed with their display name, a message of an agent with its name.
17+
18+## The text that is sent
19+
20+| Case | The agent receives |
21+| --- | --- |
22+| Nothing to tell, message of the user | The message exactly as typed. |
23+| Something to tell, message of the user | The context, a blank line, then the message as typed. |
24+| Message of another agent (an agent calling it) | The context if any, a blank line, then `[Message from @name]`, a line break, and the whole answer of that agent. |
25+| A slash command it understands | The bare command, without context: an agent recognises a command only at the very start. See [slash commands](slash-commands.md). |
26+
27+The context has this shape:
28+
29+```text
30+[Channel context: what was said since your last turn]
31+[3 earlier message(s) not shown]
32+Ada: the build is red
33+amy: I will look at the logs
34+[End of channel context]
35+
36+@bob can you check too?
37+```
38+
39+The line `[N earlier message(s) not shown]` appears only when some were left out.
40+
41+## Limits
42+
43+| Limit | Value | When it is reached |
44+| --- | --- | --- |
45+| One earlier message | 2,000 characters | The message is cut, and ends with `[message cut: N more character(s)]`. |
46+| The whole context | 12,000 characters | The oldest messages are dropped, until it fits, and counted in `[N earlier message(s) not shown]`. |
47+| The message that calls the agent | None | It is handed over whole. |
48+
49+Characters are counted, not bytes, and a character is never split.
50+
51+## What is not covered
52+
53+- The record of what an agent was handed is kept while Synedrion runs. After a restart, every agent is told the latest messages again, which matches the fact that its sessions do not survive a restart either.
54+- If an agent's process dies and is started again while Synedrion keeps running, its new session has lost what the old one knew, and what was already handed over is not sent again.
55+- A command such as `/new` or `/compact` makes an agent forget, and Synedrion does not send again what it had handed over before.
56+
57+## Related
58+
59+- Changing the numbers: [settings](settings.md)
60+- Who receives a message: [mentions](mentions.md)
modified docs/en/reference/database.md +20 -3
@@ -12,7 +12,7 @@ Synedrion keeps everything in one SQLite file, opened through `rusqlite` with SQ
1212
1313 The folder is created when missing. The application refuses to start if none of the needed variables is set. Only the Linux layout has been run; the macOS and Windows paths are covered by unit tests of the path rules only.
1414
15-## Schema (version 1)
15+## Schema (version 3)
1616
1717 Names are compared without regard to case (`COLLATE NOCASE`). Foreign keys are enforced.
1818
@@ -46,17 +46,34 @@ Names are compared without regard to case (`COLLATE NOCASE`). Foreign keys are e
4646 | --- | --- | --- |
4747 | `id` | integer | Primary key, autoincrement. |
4848 | `channel_id` | integer | References `channel(id)`, deleted with the channel. |
49-| `author_kind` | text | `user`, `agent` or `system`. |
50-| `author_name` | text | The agent's name for an agent, null otherwise. Not a reference: messages stay when an agent is deleted. |
49+| `author_kind` | text | `user`, `agent`, `system` or `trace`. |
50+| `author_name` | text | The agent's name for an agent or a trace, null otherwise. Not a reference: messages stay when an agent is deleted. |
5151 | `content` | text | Markdown text. Grows while an agent's answer is being received. |
5252 | `created_at_ms` | integer | Milliseconds since 1970-01-01 UTC. |
5353
5454 An index on `(channel_id, id)` serves "the last messages of a channel".
5555
56+A message of kind `trace` holds what an agent did besides writing, as plain text: see [tool calls, plans and what cannot be shown](tool-calls-and-plans.md).
57+
58+### `setting`
59+
60+| Column | Type | Notes |
61+| --- | --- | --- |
62+| `key` | text | Primary key: `context_messages` or `chain_depth`. |
63+| `value` | text | A whole number, written as text. |
64+
65+See [settings](settings.md).
66+
5667 ## Migrations
5768
5869 The version of the schema is SQLite's `user_version`. Migrations run at start, in order, each in one transaction. A file whose version is higher than the application knows is refused rather than modified.
5970
71+| Version | What it adds |
72+| --- | --- |
73+| 1 | The user, the agents, the channels and the messages. |
74+| 2 | The `setting` table. |
75+| 3 | The `trace` kind of author. SQLite cannot change a `CHECK`, so the `message` table is rebuilt and its rows copied, with their identifiers, so that the counter goes on after them. A test checks that the messages of a version 1 file survive. |
76+
6077 ## Related
6178
6279 - The interface the rest of the application sees: the `Repository` trait of the `synedrion-domain` crate.
@@ -12,7 +12,7 @@ Synedrion keeps everything in one SQLite file, opened through `rusqlite` with SQ
12 12
13 The folder is created when missing. The application refuses to start if none of the needed variables is set. Only the Linux layout has been run; the macOS and Windows paths are covered by unit tests of the path rules only.13 The folder is created when missing. The application refuses to start if none of the needed variables is set. Only the Linux layout has been run; the macOS and Windows paths are covered by unit tests of the path rules only.
14 14
15-## Schema (version 1)15+## Schema (version 3)
16 16
17 Names are compared without regard to case (`COLLATE NOCASE`). Foreign keys are enforced.17 Names are compared without regard to case (`COLLATE NOCASE`). Foreign keys are enforced.
18 18
@@ -46,17 +46,34 @@ Names are compared without regard to case (`COLLATE NOCASE`). Foreign keys are e
46 | --- | --- | --- |46 | --- | --- | --- |
47 | `id` | integer | Primary key, autoincrement. |47 | `id` | integer | Primary key, autoincrement. |
48 | `channel_id` | integer | References `channel(id)`, deleted with the channel. |48 | `channel_id` | integer | References `channel(id)`, deleted with the channel. |
49-| `author_kind` | text | `user`, `agent` or `system`. |49+| `author_kind` | text | `user`, `agent`, `system` or `trace`. |
50-| `author_name` | text | The agent's name for an agent, null otherwise. Not a reference: messages stay when an agent is deleted. |50+| `author_name` | text | The agent's name for an agent or a trace, null otherwise. Not a reference: messages stay when an agent is deleted. |
51 | `content` | text | Markdown text. Grows while an agent's answer is being received. |51 | `content` | text | Markdown text. Grows while an agent's answer is being received. |
52 | `created_at_ms` | integer | Milliseconds since 1970-01-01 UTC. |52 | `created_at_ms` | integer | Milliseconds since 1970-01-01 UTC. |
53 53
54 An index on `(channel_id, id)` serves "the last messages of a channel".54 An index on `(channel_id, id)` serves "the last messages of a channel".
55 55
56+A message of kind `trace` holds what an agent did besides writing, as plain text: see [tool calls, plans and what cannot be shown](tool-calls-and-plans.md).
57+
58+### `setting`
59+
60+| Column | Type | Notes |
61+| --- | --- | --- |
62+| `key` | text | Primary key: `context_messages` or `chain_depth`. |
63+| `value` | text | A whole number, written as text. |
64+
65+See [settings](settings.md).
66+
56 ## Migrations67 ## Migrations
57 68
58 The version of the schema is SQLite's `user_version`. Migrations run at start, in order, each in one transaction. A file whose version is higher than the application knows is refused rather than modified.69 The version of the schema is SQLite's `user_version`. Migrations run at start, in order, each in one transaction. A file whose version is higher than the application knows is refused rather than modified.
59 70
71+| Version | What it adds |
72+| --- | --- |
73+| 1 | The user, the agents, the channels and the messages. |
74+| 2 | The `setting` table. |
75+| 3 | The `trace` kind of author. SQLite cannot change a `CHECK`, so the `message` table is rebuilt and its rows copied, with their identifiers, so that the counter goes on after them. A test checks that the messages of a version 1 file survive. |
76+
60 ## Related77 ## Related
61 78
62 - The interface the rest of the application sees: the `Repository` trait of the `synedrion-domain` crate.79 - The interface the rest of the application sees: the `Repository` trait of the `synedrion-domain` crate.
modified docs/en/reference/mentions.md +16 -6
@@ -14,16 +14,26 @@ A mention addresses an agent from a message: `@name`.
1414 | Case | Ignored when matching: `@BOB` addresses the agent declared as `bob`. |
1515 | Repeated mentions | Counted once, in order of first appearance, whatever their case. |
1616
17+## Who a message addresses
18+
19+| The message | Addressed |
20+| --- | --- |
21+| Starts with mentions (`@bob say hi to @mouse`) | Only the mentions it starts with: `bob`. `@mouse` is only talked about, and calls nobody. |
22+| Starts with several mentions (`@bob @mouse discuss it`, `@bob, @mouse discuss it`) | Each of them. Spaces and commas may separate them. |
23+| Does not start with a mention (`say hi to @bob and @mouse`) | Every agent it mentions. |
24+
25+The leading mentions end at the first word that is not a mention: in `@bob and @mouse what do you think`, only `bob` is addressed. Write `@bob @mouse what do you think` to address both. The same rule applies to the answers of agents (see [agents calling agents](../explanation/agents-calling-agents.md)) and to the messages that decide who a plain message goes to.
26+
1727 ## What a mention does
1828
1929 | Case | Effect |
2030 | --- | --- |
21-| Name of a declared agent | The agent receives the message. A message with several mentions reaches each agent once. |
22-| Name that no agent carries | Nothing is sent. The text stays as written and a notice names the unknown agents. |
31+| Name of a declared agent that the message addresses | The agent receives the message. A message addressing several agents reaches each of them once. |
32+| Name that no agent carries, among those the message addresses | Nothing is sent. The text stays as written and a notice names the unknown agents. A name that is only talked about (`@bob greet @ghost`) raises no notice. |
2333 | Message without mention | Stored in the channel. It goes on with the agents that the user addressed in their latest message that addressed any (see below), and to nobody when there is none. |
24-| Mention inside an agent's answer | Nothing, for now: agents cannot yet address each other. |
34+| Mention inside an agent's answer | When the agent's turn ends normally, the agent mentioned is called with that answer, within the limit of the chain depth. An agent that mentions itself, or a name no agent carries, calls nobody. See [agents calling agents](../explanation/agents-calling-agents.md). |
2535
26-The agent receives the message exactly as typed, mention included, without the spaces around it. It does not yet receive the earlier messages of the channel.
36+The agent receives the message exactly as typed, mention included, without the spaces around it, preceded by the messages of the channel that it has not seen yet, when there are some. See [the context of the channel](channel-context.md).
2737
2838 ## Going on without mentioning again
2939
@@ -36,13 +46,13 @@ A message that contains no mention at all goes to the agents named by the latest
3646 | The last addressed agent was deleted | The message goes to nobody. |
3747 | Another channel | Each channel has its own recipients. |
3848
39-Only the messages of the user count: a mention written by an agent changes nothing. About 200 earlier messages of the channel are looked at. While there are recipients, a line above the message box says who a plain message goes to.
49+Only the messages of the user count: a mention written by an agent calls that agent, but does not change who the user's next plain message goes to. About 200 earlier messages of the channel are looked at. While there are recipients, a line above the message box says who a plain message goes to.
4050
4151 A message that starts with a slash command keeps these rules: its recipients are found the same way, and the mentions in front of the command are removed from what the agent receives. See [slash commands](slash-commands.md).
4252
4353 ## Suggestions while typing
4454
45-While the text ends with `@` followed by the beginning of a name, buttons propose the declared agents whose name starts with those letters, ignoring case, in alphabetical order. A lone `@` proposes all agents. The first proposal stands out. Clicking a proposal, or pressing Tab, replaces the beginning with `@name ` (a space follows), puts the cursor after it, and the proposals go away. Tab takes the first proposal, and only while the message box has the focus: when no agent is proposed, Tab does what it always does. A mention followed by a space, or in the middle of the text, triggers no proposal: only the end of the text is looked at.
55+While the text ends with `@` followed by the beginning of a name, buttons propose the declared agents whose name starts with those letters, ignoring case, in alphabetical order. A lone `@` proposes all agents. The first proposal stands out, and the arrow keys move the highlight (see [the keyboard in the lists](slash-commands.md)). Clicking a proposal, or pressing Tab, replaces the beginning with `@name ` (a space follows), puts the cursor after it, and the proposals go away. Tab takes the highlighted proposal, and only while the message box has the focus: when no agent is proposed, Tab does what it always does. A mention followed by a space, or in the middle of the text, triggers no proposal: only the end of the text is looked at.
4656
4757 ## Related
4858
@@ -14,16 +14,26 @@ A mention addresses an agent from a message: `@name`.
14 | Case | Ignored when matching: `@BOB` addresses the agent declared as `bob`. |14 | Case | Ignored when matching: `@BOB` addresses the agent declared as `bob`. |
15 | Repeated mentions | Counted once, in order of first appearance, whatever their case. |15 | Repeated mentions | Counted once, in order of first appearance, whatever their case. |
16 16
17+## Who a message addresses
18+
19+| The message | Addressed |
20+| --- | --- |
21+| Starts with mentions (`@bob say hi to @mouse`) | Only the mentions it starts with: `bob`. `@mouse` is only talked about, and calls nobody. |
22+| Starts with several mentions (`@bob @mouse discuss it`, `@bob, @mouse discuss it`) | Each of them. Spaces and commas may separate them. |
23+| Does not start with a mention (`say hi to @bob and @mouse`) | Every agent it mentions. |
24+
25+The leading mentions end at the first word that is not a mention: in `@bob and @mouse what do you think`, only `bob` is addressed. Write `@bob @mouse what do you think` to address both. The same rule applies to the answers of agents (see [agents calling agents](../explanation/agents-calling-agents.md)) and to the messages that decide who a plain message goes to.
26+
17 ## What a mention does27 ## What a mention does
18 28
19 | Case | Effect |29 | Case | Effect |
20 | --- | --- |30 | --- | --- |
21-| Name of a declared agent | The agent receives the message. A message with several mentions reaches each agent once. |31+| Name of a declared agent that the message addresses | The agent receives the message. A message addressing several agents reaches each of them once. |
22-| Name that no agent carries | Nothing is sent. The text stays as written and a notice names the unknown agents. |32+| Name that no agent carries, among those the message addresses | Nothing is sent. The text stays as written and a notice names the unknown agents. A name that is only talked about (`@bob greet @ghost`) raises no notice. |
23 | Message without mention | Stored in the channel. It goes on with the agents that the user addressed in their latest message that addressed any (see below), and to nobody when there is none. |33 | Message without mention | Stored in the channel. It goes on with the agents that the user addressed in their latest message that addressed any (see below), and to nobody when there is none. |
24-| Mention inside an agent's answer | Nothing, for now: agents cannot yet address each other. |34+| Mention inside an agent's answer | When the agent's turn ends normally, the agent mentioned is called with that answer, within the limit of the chain depth. An agent that mentions itself, or a name no agent carries, calls nobody. See [agents calling agents](../explanation/agents-calling-agents.md). |
25 35
26-The agent receives the message exactly as typed, mention included, without the spaces around it. It does not yet receive the earlier messages of the channel.36+The agent receives the message exactly as typed, mention included, without the spaces around it, preceded by the messages of the channel that it has not seen yet, when there are some. See [the context of the channel](channel-context.md).
27 37
28 ## Going on without mentioning again38 ## Going on without mentioning again
29 39
@@ -36,13 +46,13 @@ A message that contains no mention at all goes to the agents named by the latest
36 | The last addressed agent was deleted | The message goes to nobody. |46 | The last addressed agent was deleted | The message goes to nobody. |
37 | Another channel | Each channel has its own recipients. |47 | Another channel | Each channel has its own recipients. |
38 48
39-Only the messages of the user count: a mention written by an agent changes nothing. About 200 earlier messages of the channel are looked at. While there are recipients, a line above the message box says who a plain message goes to.49+Only the messages of the user count: a mention written by an agent calls that agent, but does not change who the user's next plain message goes to. About 200 earlier messages of the channel are looked at. While there are recipients, a line above the message box says who a plain message goes to.
40 50
41 A message that starts with a slash command keeps these rules: its recipients are found the same way, and the mentions in front of the command are removed from what the agent receives. See [slash commands](slash-commands.md).51 A message that starts with a slash command keeps these rules: its recipients are found the same way, and the mentions in front of the command are removed from what the agent receives. See [slash commands](slash-commands.md).
42 52
43 ## Suggestions while typing53 ## Suggestions while typing
44 54
45-While the text ends with `@` followed by the beginning of a name, buttons propose the declared agents whose name starts with those letters, ignoring case, in alphabetical order. A lone `@` proposes all agents. The first proposal stands out. Clicking a proposal, or pressing Tab, replaces the beginning with `@name ` (a space follows), puts the cursor after it, and the proposals go away. Tab takes the first proposal, and only while the message box has the focus: when no agent is proposed, Tab does what it always does. A mention followed by a space, or in the middle of the text, triggers no proposal: only the end of the text is looked at.55+While the text ends with `@` followed by the beginning of a name, buttons propose the declared agents whose name starts with those letters, ignoring case, in alphabetical order. A lone `@` proposes all agents. The first proposal stands out, and the arrow keys move the highlight (see [the keyboard in the lists](slash-commands.md)). Clicking a proposal, or pressing Tab, replaces the beginning with `@name ` (a space follows), puts the cursor after it, and the proposals go away. Tab takes the highlighted proposal, and only while the message box has the focus: when no agent is proposed, Tab does what it always does. A mention followed by a space, or in the middle of the text, triggers no proposal: only the end of the text is looked at.
46 56
47 ## Related57 ## Related
48 58
modified docs/en/reference/message-rendering.md +2 -1
@@ -4,7 +4,8 @@
44 | --- | --- |
55 | An agent | Markdown, through the Markdown view of GPUI Kit. The text can be selected with the mouse. |
66 | The user | Plain text, as typed. |
7-| Synedrion (notices) | Plain text, in italics. |
7+| Synedrion (notices) | Plain text, in italics. A notice of an agent is shown the same way, signed `@name:`. |
8+| An agent's tool calls and plans | Cards, not text: see [tool calls, plans and what cannot be shown](tool-calls-and-plans.md). |
89
910 The user's own text is not interpreted so that characters such as `*` or `_` are never turned into formatting by surprise. The text stored in the database is always what the author wrote: Markdown is only a way of drawing it.
1011
@@ -4,7 +4,8 @@
4 | --- | --- |4 | --- | --- |
5 | An agent | Markdown, through the Markdown view of GPUI Kit. The text can be selected with the mouse. |5 | An agent | Markdown, through the Markdown view of GPUI Kit. The text can be selected with the mouse. |
6 | The user | Plain text, as typed. |6 | The user | Plain text, as typed. |
7-| Synedrion (notices) | Plain text, in italics. |7+| Synedrion (notices) | Plain text, in italics. A notice of an agent is shown the same way, signed `@name:`. |
8+| An agent's tool calls and plans | Cards, not text: see [tool calls, plans and what cannot be shown](tool-calls-and-plans.md). |
8 9
9 The user's own text is not interpreted so that characters such as `*` or `_` are never turned into formatting by surprise. The text stored in the database is always what the author wrote: Markdown is only a way of drawing it.10 The user's own text is not interpreted so that characters such as `*` or `_` are never turned into formatting by surprise. The text stored in the database is always what the author wrote: Markdown is only a way of drawing it.
10 11
added docs/en/reference/settings.md +27 -0
new file mode 100644
@@ -0,0 +1,27 @@
1+# Reference: settings
2+
3+The **Settings** panel holds the two settings of the conversation. Open it with the button of the bar that has sliders on it. Both settings apply from the next message, and are kept in the database.
4+
5+| Setting | Field | Default | Allowed | Meaning |
6+| --- | --- | --- | --- | --- |
7+| Messages of context | `Messages of context` | 20 | 0 to 100 | How many messages, at most, an agent is told about besides the one that calls it: those sent in the channel since its last turn. `0` tells it nothing more than the message. See [the context of the channel](channel-context.md). |
8+| Chain depth | `Chain depth` | 3 | 0 to 10 | How many times in a row an agent's answer may call another agent. `0` forbids agents from calling one another. See [agents calling agents](../explanation/agents-calling-agents.md). |
9+
10+## Saving
11+
12+| Action | Effect |
13+| --- | --- |
14+| **Save settings** with two whole numbers inside the limits | Stores them, and a notice says `Settings saved. They apply from the next message.` |
15+| A value that is not a whole number (empty, letters, a minus sign, a decimal point) | Nothing is saved, and a notice says `Chain depth must be a whole number, not "…"` or the same for `Messages of context`. |
16+| A value above the limit | Nothing is saved, and a notice says `… must be at most 100` or `… at most 10`. |
17+| Both values wrong | The first one, in the order of the table, is reported. |
18+
19+Surrounding spaces are ignored.
20+
21+## Where they are kept
22+
23+Each setting is a row of the `setting` table, with the keys `context_messages` and `chain_depth`. A setting that was never saved has its default. A stored value that makes no sense is reported as a storage error at start instead of being replaced silently. See [the database](database.md).
24+
25+## Related
26+
27+- Using the chain depth: [how to let agents call each other](../how-to/let-agents-call-each-other.md)
new file mode 100644
@@ -0,0 +1,27 @@
1+# Reference: settings
2+
3+The **Settings** panel holds the two settings of the conversation. Open it with the button of the bar that has sliders on it. Both settings apply from the next message, and are kept in the database.
4+
5+| Setting | Field | Default | Allowed | Meaning |
6+| --- | --- | --- | --- | --- |
7+| Messages of context | `Messages of context` | 20 | 0 to 100 | How many messages, at most, an agent is told about besides the one that calls it: those sent in the channel since its last turn. `0` tells it nothing more than the message. See [the context of the channel](channel-context.md). |
8+| Chain depth | `Chain depth` | 3 | 0 to 10 | How many times in a row an agent's answer may call another agent. `0` forbids agents from calling one another. See [agents calling agents](../explanation/agents-calling-agents.md). |
9+
10+## Saving
11+
12+| Action | Effect |
13+| --- | --- |
14+| **Save settings** with two whole numbers inside the limits | Stores them, and a notice says `Settings saved. They apply from the next message.` |
15+| A value that is not a whole number (empty, letters, a minus sign, a decimal point) | Nothing is saved, and a notice says `Chain depth must be a whole number, not "…"` or the same for `Messages of context`. |
16+| A value above the limit | Nothing is saved, and a notice says `… must be at most 100` or `… at most 10`. |
17+| Both values wrong | The first one, in the order of the table, is reported. |
18+
19+Surrounding spaces are ignored.
20+
21+## Where they are kept
22+
23+Each setting is a row of the `setting` table, with the keys `context_messages` and `chain_depth`. A setting that was never saved has its default. A stored value that makes no sense is reported as a storage error at start instead of being replaced silently. See [the database](database.md).
24+
25+## Related
26+
27+- Using the chain depth: [how to let agents call each other](../how-to/let-agents-call-each-other.md)
modified docs/en/reference/slash-commands.md +30 -1
@@ -2,6 +2,20 @@
22
33 A message that starts with `/` is a slash command. Mentions in front of it are allowed: `@mini-me /compact`.
44
5+## The keyboard in the lists
6+
7+The list above the message box is the same for agents (after `@`), commands (after `/`) and files (after `/file` or `$`). While it is open and the message box has the focus:
8+
9+| Key | Effect |
10+| --- | --- |
11+| Down, Up | Moves the highlight one row down or up, and goes round at both ends. The highlighted row is the one Tab takes. At first it is the first row. |
12+| Tab | Takes the highlighted row. |
13+| Enter | Takes the highlighted row, but only once the arrows moved the highlight. Before that, Enter sends the message, as it always did. |
14+| Escape | Closes the list and keeps the text. The list opens again when typing goes on. |
15+| Any other key | Is typed as usual, and puts the highlight back on the first row. |
16+
17+A key combined with a modifier (Shift, Control, Alt, Command) is left alone, except that Shift+Tab keeps moving the focus. When no list is open, the arrows, Tab, Enter and Escape do what they always do.
18+
519 ## Commands of the agents
620
721 An agent announces the commands it understands (and the skills it offers as commands) when a session is created for it in a channel, and may announce them again later. Synedrion keeps the latest announcement of each agent. mini-me, for example, announces `compact`, `new` and `unload`.
@@ -10,7 +24,7 @@ An agent announces the commands it understands (and the skills it offers as comm
1024 | --- | --- |
1125 | `/` | A list opens above the message box with the commands of the agents the message would go to, and `/file`. |
1226 | `/co` | The list keeps the commands whose name starts with these letters, ignoring case. |
13-| Tab, or a click on a row | Completes the command with the first row (Tab) or the row clicked, followed by a space. |
27+| Tab, or a click on a row | Completes the command with the highlighted row (Tab) or the row clicked, followed by a space. |
1428
1529 The agents a message would go to are the ones it mentions, or, when it mentions nobody, the ones the user addressed last (see [mentions](mentions.md)). A command that two of them announce is listed once. Each row shows the name, then the hint of what the command expects (in angle brackets) and its description.
1630
@@ -47,6 +61,21 @@ The folder is the working folder of the first agent the message would go to, or
4761 | Send with files but no text | Nothing is sent, and a notice asks for a message. The files stay attached. |
4862 | The same file picked twice | It is attached once. |
4963
64+## `$`: naming a file in a sentence
65+
66+`$` followed by the beginning of a name, anywhere in the text, opens the same list of files as `/file`, in the same folder and with the same rules (matching, order, 8 rows, files left out).
67+
68+| Case | Effect |
69+| --- | --- |
70+| The text ends with `$` and some characters without a space | The list shows the matching files. `$` alone lists them all. |
71+| Tab, or a click on a row | The `$` and what follows are replaced with the path of the file relative to the folder, followed by a space, and the file is attached like with `/file`. |
72+| A space typed after the characters | The reference is complete and the list closes. |
73+| `$` glued to a word or to another `$` (`US$5`, `a_$b`) | Not a reference: nothing opens. |
74+| Several `$` in the text | Only the last one, being typed at the end, counts. |
75+| Send while a `$` is still unfinished | The text is sent as typed: nothing is refused. |
76+
77+A file named in the sentence is attached, so the agent receives the link as well as the path. The message stored in the channel adds its `[attached: path]` line only for the attached files that its text does not already name.
78+
5079 ### The links
5180
5281 Each file is sent as an ACP `resource_link`: its name, and its address, `file://` followed by the path as written, without percent-encoding. mini-me strips the prefix and uses what follows as the path, and puts `[attached file: path]` in what its model reads.
@@ -2,6 +2,20 @@
2 2
3 A message that starts with `/` is a slash command. Mentions in front of it are allowed: `@mini-me /compact`.3 A message that starts with `/` is a slash command. Mentions in front of it are allowed: `@mini-me /compact`.
4 4
5+## The keyboard in the lists
6+
7+The list above the message box is the same for agents (after `@`), commands (after `/`) and files (after `/file` or `$`). While it is open and the message box has the focus:
8+
9+| Key | Effect |
10+| --- | --- |
11+| Down, Up | Moves the highlight one row down or up, and goes round at both ends. The highlighted row is the one Tab takes. At first it is the first row. |
12+| Tab | Takes the highlighted row. |
13+| Enter | Takes the highlighted row, but only once the arrows moved the highlight. Before that, Enter sends the message, as it always did. |
14+| Escape | Closes the list and keeps the text. The list opens again when typing goes on. |
15+| Any other key | Is typed as usual, and puts the highlight back on the first row. |
16+
17+A key combined with a modifier (Shift, Control, Alt, Command) is left alone, except that Shift+Tab keeps moving the focus. When no list is open, the arrows, Tab, Enter and Escape do what they always do.
18+
5 ## Commands of the agents19 ## Commands of the agents
6 20
7 An agent announces the commands it understands (and the skills it offers as commands) when a session is created for it in a channel, and may announce them again later. Synedrion keeps the latest announcement of each agent. mini-me, for example, announces `compact`, `new` and `unload`.21 An agent announces the commands it understands (and the skills it offers as commands) when a session is created for it in a channel, and may announce them again later. Synedrion keeps the latest announcement of each agent. mini-me, for example, announces `compact`, `new` and `unload`.
@@ -10,7 +24,7 @@ An agent announces the commands it understands (and the skills it offers as comm
10 | --- | --- |24 | --- | --- |
11 | `/` | A list opens above the message box with the commands of the agents the message would go to, and `/file`. |25 | `/` | A list opens above the message box with the commands of the agents the message would go to, and `/file`. |
12 | `/co` | The list keeps the commands whose name starts with these letters, ignoring case. |26 | `/co` | The list keeps the commands whose name starts with these letters, ignoring case. |
13-| Tab, or a click on a row | Completes the command with the first row (Tab) or the row clicked, followed by a space. |27+| Tab, or a click on a row | Completes the command with the highlighted row (Tab) or the row clicked, followed by a space. |
14 28
15 The agents a message would go to are the ones it mentions, or, when it mentions nobody, the ones the user addressed last (see [mentions](mentions.md)). A command that two of them announce is listed once. Each row shows the name, then the hint of what the command expects (in angle brackets) and its description.29 The agents a message would go to are the ones it mentions, or, when it mentions nobody, the ones the user addressed last (see [mentions](mentions.md)). A command that two of them announce is listed once. Each row shows the name, then the hint of what the command expects (in angle brackets) and its description.
16 30
@@ -47,6 +61,21 @@ The folder is the working folder of the first agent the message would go to, or
47 | Send with files but no text | Nothing is sent, and a notice asks for a message. The files stay attached. |61 | Send with files but no text | Nothing is sent, and a notice asks for a message. The files stay attached. |
48 | The same file picked twice | It is attached once. |62 | The same file picked twice | It is attached once. |
49 63
64+## `$`: naming a file in a sentence
65+
66+`$` followed by the beginning of a name, anywhere in the text, opens the same list of files as `/file`, in the same folder and with the same rules (matching, order, 8 rows, files left out).
67+
68+| Case | Effect |
69+| --- | --- |
70+| The text ends with `$` and some characters without a space | The list shows the matching files. `$` alone lists them all. |
71+| Tab, or a click on a row | The `$` and what follows are replaced with the path of the file relative to the folder, followed by a space, and the file is attached like with `/file`. |
72+| A space typed after the characters | The reference is complete and the list closes. |
73+| `$` glued to a word or to another `$` (`US$5`, `a_$b`) | Not a reference: nothing opens. |
74+| Several `$` in the text | Only the last one, being typed at the end, counts. |
75+| Send while a `$` is still unfinished | The text is sent as typed: nothing is refused. |
76+
77+A file named in the sentence is attached, so the agent receives the link as well as the path. The message stored in the channel adds its `[attached: path]` line only for the attached files that its text does not already name.
78+
50 ### The links79 ### The links
51 80
52 Each file is sent as an ACP `resource_link`: its name, and its address, `file://` followed by the path as written, without percent-encoding. mini-me strips the prefix and uses what follows as the path, and puts `[attached file: path]` in what its model reads.81 Each file is sent as an ACP `resource_link`: its name, and its address, `file://` followed by the path as written, without percent-encoding. mini-me strips the prefix and uses what follows as the path, and puts `[attached file: path]` in what its model reads.
modified docs/en/reference/test-agent.md +1 -0
@@ -33,6 +33,7 @@ The behaviour is chosen by a keyword: the first word of the prompt that is not a
3333 | `ask` | Asks permission to "Delete the build folder", with the options `allow` ("Allow") and `reject` ("Reject"), then says `permission granted`, `permission rejected` or `permission cancelled`, and ends the turn normally. |
3434 | `slow` | Says `working` and waits until the turn is cancelled, then ends it as cancelled. |
3535 | `think` | Sends three pieces of reasoning (`pondering the question `), then answers `done`. |
36+| `tools` | Sends a plan of two steps, a tool call `Read notes.md` (kind `read`, running), then an update that completes it with the output `the notes`, then answers `tools done`. |
3637 | `/new` | Says `fresh start`. |
3738 | `/greet Bob` | Says `hello Bob`. |
3839 | anything else | Repeats the prompt word by word, one chunk per word, then ends the turn normally. |
@@ -33,6 +33,7 @@ The behaviour is chosen by a keyword: the first word of the prompt that is not a
33 | `ask` | Asks permission to "Delete the build folder", with the options `allow` ("Allow") and `reject` ("Reject"), then says `permission granted`, `permission rejected` or `permission cancelled`, and ends the turn normally. |33 | `ask` | Asks permission to "Delete the build folder", with the options `allow` ("Allow") and `reject` ("Reject"), then says `permission granted`, `permission rejected` or `permission cancelled`, and ends the turn normally. |
34 | `slow` | Says `working` and waits until the turn is cancelled, then ends it as cancelled. |34 | `slow` | Says `working` and waits until the turn is cancelled, then ends it as cancelled. |
35 | `think` | Sends three pieces of reasoning (`pondering the question `), then answers `done`. |35 | `think` | Sends three pieces of reasoning (`pondering the question `), then answers `done`. |
36+| `tools` | Sends a plan of two steps, a tool call `Read notes.md` (kind `read`, running), then an update that completes it with the output `the notes`, then answers `tools done`. |
36 | `/new` | Says `fresh start`. |37 | `/new` | Says `fresh start`. |
37 | `/greet Bob` | Says `hello Bob`. |38 | `/greet Bob` | Says `hello Bob`. |
38 | anything else | Repeats the prompt word by word, one chunk per word, then ends the turn normally. |39 | anything else | Repeats the prompt word by word, one chunk per word, then ends the turn normally. |
added docs/en/reference/tool-calls-and-plans.md +65 -0
new file mode 100644
@@ -0,0 +1,65 @@
1+# Reference: tool calls, plans and what cannot be shown
2+
3+An agent can do more than write: it announces the tools it calls and the plan it follows. Synedrion keeps these in the channel, next to the messages, as **traces**, so that the history shows how an answer came about.
4+
5+## Tool calls
6+
7+A tool call is one card in the conversation, written by the agent that made it.
8+
9+| Part | What it shows |
10+| --- | --- |
11+| Title | What the tool is doing, as the agent says it. |
12+| Kind | The category the agent gives: `read`, `edit`, `delete`, `move`, `search`, `execute`, `think`, `fetch`, `switch_mode`, or `other`. |
13+| Status | `waiting`, `running`, `done` or `failed`. `failed` takes the error colour of the theme. |
14+| Output | Folded at first. **Show output** unfolds it, in a monospace font, and **Hide output** folds it again. The button exists only when there is an output. Which cards are unfolded is not kept when Synedrion restarts. |
15+
16+An update from the agent changes the same card. It carries only what changed: its status, its title, its kind, and its output, which replaces the one before. An update about a call that was never announced makes a card titled `Tool call`, so that nothing is lost. Announcing the same call again changes its card instead of adding one. A call is forgotten when the turn ends, so the next turn may reuse an identifier.
17+
18+The output kept is at most 4,000 characters, ending with `[output cut: N more character(s)]` when it was longer.
19+
20+## Plans
21+
22+The plan of an agent is one card, replaced each time the agent sends a new version of it. Each step is a line with a sign: `[ ]` waiting, `[~]` in progress, `[x]` done, `[!]` failed.
23+
24+## Order in the channel
25+
26+What the agent writes after a tool call or a plan goes into a new message after the card, as it happened. The messages of one answer can therefore be several, with cards between them.
27+
28+## What cannot be drawn
29+
30+Nothing an agent sends for the user to read is dropped without a mark. What cannot be drawn comes through as a short text in brackets.
31+
32+| The agent sends | It is shown as |
33+| --- | --- |
34+| An image, in its answer or in a tool's output | `[image: not displayed]` |
35+| Audio | `[audio: not displayed]` |
36+| A link to a resource | `[link: ` the address `]` |
37+| A text resource embedded in the content | Its text |
38+| A binary resource | `[binary resource: ` the address `]` |
39+| A change to a file | `Changes to ` the path `:`, then the old lines each after `- ` and the new lines each after `+ `. A file that did not exist: `New file ` the path `:` and its text. |
40+| A terminal | `[terminal ` the identifier `: its output is not displayed]` |
41+| A tool call with no content but a raw output | The raw output: a string as it is, anything else as compact JSON. |
42+| A notice (`Notice` update) | A notice of Synedrion in the channel: `@name: title: detail`. |
43+| An update of a kind this version does not know | A notice: `@name: The agent sent an update that this version of Synedrion cannot show.` |
44+
45+These updates carry nothing for the user and show nothing: usage figures, the current mode, the configuration options, the title of the session, the context compaction, and the echo of the user's own message. The list of commands feeds the `/` list instead.
46+
47+## How a trace is stored
48+
49+A trace is a message whose author kind is `trace` and whose author name is the agent. Its content is plain text: a first line that says what it is, then the details.
50+
51+| Kind | Content |
52+| --- | --- |
53+| Tool call | `tool`, a tab, the status word (`pending`, `in_progress`, `completed`, `failed`), a tab, the identifier, a tab, the kind, a tab, the title; then a line break and the output. Line breaks and tabs inside the identifier, kind and title become spaces. |
54+| Plan | `plan`; then one line per step: the status word, a tab, the text. |
55+
56+A message of a trace that cannot be read back is drawn as the text it holds. Traces are not told to other agents as [context](channel-context.md), and do not change who a message without a mention goes to.
57+
58+## What was checked
59+
60+The translation of every kind of update, the storage and the controller are covered by automated tests, and the whole path from an agent process to the channel was run against the test agent. The cards have never been seen on a screen, and no real agent was tried: whether a given agent sends these updates, and how, is its own.
61+
62+## Related
63+
64+- The messages around the cards: [how messages are drawn](message-rendering.md)
65+- The protocol side: [ACP methods](acp-methods.md)
new file mode 100644
@@ -0,0 +1,65 @@
1+# Reference: tool calls, plans and what cannot be shown
2+
3+An agent can do more than write: it announces the tools it calls and the plan it follows. Synedrion keeps these in the channel, next to the messages, as **traces**, so that the history shows how an answer came about.
4+
5+## Tool calls
6+
7+A tool call is one card in the conversation, written by the agent that made it.
8+
9+| Part | What it shows |
10+| --- | --- |
11+| Title | What the tool is doing, as the agent says it. |
12+| Kind | The category the agent gives: `read`, `edit`, `delete`, `move`, `search`, `execute`, `think`, `fetch`, `switch_mode`, or `other`. |
13+| Status | `waiting`, `running`, `done` or `failed`. `failed` takes the error colour of the theme. |
14+| Output | Folded at first. **Show output** unfolds it, in a monospace font, and **Hide output** folds it again. The button exists only when there is an output. Which cards are unfolded is not kept when Synedrion restarts. |
15+
16+An update from the agent changes the same card. It carries only what changed: its status, its title, its kind, and its output, which replaces the one before. An update about a call that was never announced makes a card titled `Tool call`, so that nothing is lost. Announcing the same call again changes its card instead of adding one. A call is forgotten when the turn ends, so the next turn may reuse an identifier.
17+
18+The output kept is at most 4,000 characters, ending with `[output cut: N more character(s)]` when it was longer.
19+
20+## Plans
21+
22+The plan of an agent is one card, replaced each time the agent sends a new version of it. Each step is a line with a sign: `[ ]` waiting, `[~]` in progress, `[x]` done, `[!]` failed.
23+
24+## Order in the channel
25+
26+What the agent writes after a tool call or a plan goes into a new message after the card, as it happened. The messages of one answer can therefore be several, with cards between them.
27+
28+## What cannot be drawn
29+
30+Nothing an agent sends for the user to read is dropped without a mark. What cannot be drawn comes through as a short text in brackets.
31+
32+| The agent sends | It is shown as |
33+| --- | --- |
34+| An image, in its answer or in a tool's output | `[image: not displayed]` |
35+| Audio | `[audio: not displayed]` |
36+| A link to a resource | `[link: ` the address `]` |
37+| A text resource embedded in the content | Its text |
38+| A binary resource | `[binary resource: ` the address `]` |
39+| A change to a file | `Changes to ` the path `:`, then the old lines each after `- ` and the new lines each after `+ `. A file that did not exist: `New file ` the path `:` and its text. |
40+| A terminal | `[terminal ` the identifier `: its output is not displayed]` |
41+| A tool call with no content but a raw output | The raw output: a string as it is, anything else as compact JSON. |
42+| A notice (`Notice` update) | A notice of Synedrion in the channel: `@name: title: detail`. |
43+| An update of a kind this version does not know | A notice: `@name: The agent sent an update that this version of Synedrion cannot show.` |
44+
45+These updates carry nothing for the user and show nothing: usage figures, the current mode, the configuration options, the title of the session, the context compaction, and the echo of the user's own message. The list of commands feeds the `/` list instead.
46+
47+## How a trace is stored
48+
49+A trace is a message whose author kind is `trace` and whose author name is the agent. Its content is plain text: a first line that says what it is, then the details.
50+
51+| Kind | Content |
52+| --- | --- |
53+| Tool call | `tool`, a tab, the status word (`pending`, `in_progress`, `completed`, `failed`), a tab, the identifier, a tab, the kind, a tab, the title; then a line break and the output. Line breaks and tabs inside the identifier, kind and title become spaces. |
54+| Plan | `plan`; then one line per step: the status word, a tab, the text. |
55+
56+A message of a trace that cannot be read back is drawn as the text it holds. Traces are not told to other agents as [context](channel-context.md), and do not change who a message without a mention goes to.
57+
58+## What was checked
59+
60+The translation of every kind of update, the storage and the controller are covered by automated tests, and the whole path from an agent process to the channel was run against the test agent. The cards have never been seen on a screen, and no real agent was tried: whether a given agent sends these updates, and how, is its own.
61+
62+## Related
63+
64+- The messages around the cards: [how messages are drawn](message-rendering.md)
65+- The protocol side: [ACP methods](acp-methods.md)
modified docs/fr/README.md +4 -4
@@ -2,7 +2,7 @@
22
33 Synedrion est une application de bureau, écrite en Rust avec GPUI Kit, qui fonctionne comme Slack ou Discord : elle a des channels, et les participants sont des agents d'IA qui discutent via l'Agent Client Protocol (ACP), plus l'unique humain qui utilise l'application.
44
5-> **État : la version 0.1.0 est construite, et n'a jamais été vue sur un écran.** Son comportement est couvert par des tests automatisés, dont des tests de fenêtre sans écran. Son apparence ne l'est pas. Les agents qui se parlent entre eux, l'envoi à un agent des messages précédents du channel, et l'affichage des appels d'outils sont prévus, pas construits. Rien n'a encore été essayé avec un vrai agent.
5+> **État : les fonctionnalités prévues pour les versions 0.1.0 et 0.2.0 sont construites.** Leur comportement est couvert par des tests automatisés, dont des tests de fenêtre sans écran. L'auteur du code n'a jamais vu la fenêtre : la personne qui l'a lancée a rapporté ce qui marchait et ce qui ne marchait pas. Les appels d'outils et les plans, les agents qui s'appellent et le contexte du channel n'ont été essayés qu'avec l'agent de test, pas avec un vrai agent.
66
77 ## Organisation de cette documentation
88
@@ -11,9 +11,9 @@ La documentation suit la méthode [Diátaxis](https://diataxis.fr) : chaque page
1111 | Vous voulez… | Aller à |
1212 | --- | --- |
1313 | Apprendre en faisant | [Votre première conversation avec un agent](tutorials/premiere-conversation.md) |
14-| Accomplir une tâche | [Construire et lancer Synedrion](how-to/construire-et-lancer.md), [gérer les channels](how-to/gerer-les-channels.md), [déclarer un agent](how-to/declarer-un-agent.md), [lancer les tests](how-to/lancer-les-tests.md), [préparer un sandbox de développement](how-to/preparer-le-sandbox.md), [journaliser la conversation avec un agent](how-to/journaliser-une-conversation-avec-un-agent.md), [utiliser les commandes d'un agent et joindre des fichiers](how-to/utiliser-commandes-et-joindre-fichiers.md), [copier un message ou un bloc de code](how-to/copier-texte-et-code.md) |
15-| Consulter les détails exacts | [Déclaration d'un agent](reference/declaration-agent.md), [mentions](reference/mentions.md), [méthodes ACP](reference/methodes-acp.md), [la base de données](reference/base-de-donnees.md), [l'agent de test](reference/agent-de-test.md), [comment les messages sont dessinés](reference/rendu-des-messages.md), [commandes et fichiers joints](reference/commandes-et-fichiers.md) |
16-| Comprendre pourquoi c'est construit ainsi | [Vision](explanation/vision.md), [Architecture](explanation/architecture.md), [Choix techniques](explanation/choix-techniques.md) |
14+| Accomplir une tâche | [Construire et lancer Synedrion](how-to/construire-et-lancer.md), [gérer les channels](how-to/gerer-les-channels.md), [déclarer un agent](how-to/declarer-un-agent.md), [lancer les tests](how-to/lancer-les-tests.md), [préparer un sandbox de développement](how-to/preparer-le-sandbox.md), [journaliser la conversation avec un agent](how-to/journaliser-une-conversation-avec-un-agent.md), [utiliser les commandes d'un agent et joindre des fichiers](how-to/utiliser-commandes-et-joindre-fichiers.md), [copier un message ou un bloc de code](how-to/copier-texte-et-code.md), [laisser les agents s'appeler entre eux](how-to/laisser-les-agents-s-appeler.md) |
15+| Consulter les détails exacts | [Déclaration d'un agent](reference/declaration-agent.md), [mentions](reference/mentions.md), [méthodes ACP](reference/methodes-acp.md), [la base de données](reference/base-de-donnees.md), [l'agent de test](reference/agent-de-test.md), [comment les messages sont dessinés](reference/rendu-des-messages.md), [commandes et fichiers joints](reference/commandes-et-fichiers.md), [réglages](reference/reglages.md), [le contexte du channel](reference/contexte-du-channel.md), [appels d'outils, plans, et ce qui ne peut pas être montré](reference/appels-d-outils-et-plans.md) |
16+| Comprendre pourquoi c'est construit ainsi | [Vision](explanation/vision.md), [Architecture](explanation/architecture.md), [Choix techniques](explanation/choix-techniques.md), [Les agents qui s'appellent](explanation/agents-qui-s-appellent.md), [Capacités du client](explanation/capacites-du-client.md) |
1717
1818 ## Par où commencer
1919
@@ -2,7 +2,7 @@
2 2
3 Synedrion est une application de bureau, écrite en Rust avec GPUI Kit, qui fonctionne comme Slack ou Discord : elle a des channels, et les participants sont des agents d'IA qui discutent via l'Agent Client Protocol (ACP), plus l'unique humain qui utilise l'application.3 Synedrion est une application de bureau, écrite en Rust avec GPUI Kit, qui fonctionne comme Slack ou Discord : elle a des channels, et les participants sont des agents d'IA qui discutent via l'Agent Client Protocol (ACP), plus l'unique humain qui utilise l'application.
4 4
5-> **État : la version 0.1.0 est construite, et n'a jamais été vue sur un écran.** Son comportement est couvert par des tests automatisés, dont des tests de fenêtre sans écran. Son apparence ne l'est pas. Les agents qui se parlent entre eux, l'envoi à un agent des messages précédents du channel, et l'affichage des appels d'outils sont prévus, pas construits. Rien n'a encore été essayé avec un vrai agent.5+> **État : les fonctionnalités prévues pour les versions 0.1.0 et 0.2.0 sont construites.** Leur comportement est couvert par des tests automatisés, dont des tests de fenêtre sans écran. L'auteur du code n'a jamais vu la fenêtre : la personne qui l'a lancée a rapporté ce qui marchait et ce qui ne marchait pas. Les appels d'outils et les plans, les agents qui s'appellent et le contexte du channel n'ont été essayés qu'avec l'agent de test, pas avec un vrai agent.
6 6
7 ## Organisation de cette documentation7 ## Organisation de cette documentation
8 8
@@ -11,9 +11,9 @@ La documentation suit la méthode [Diátaxis](https://diataxis.fr) : chaque page
11 | Vous voulez… | Aller à |11 | Vous voulez… | Aller à |
12 | --- | --- |12 | --- | --- |
13 | Apprendre en faisant | [Votre première conversation avec un agent](tutorials/premiere-conversation.md) |13 | Apprendre en faisant | [Votre première conversation avec un agent](tutorials/premiere-conversation.md) |
14-| Accomplir une tâche | [Construire et lancer Synedrion](how-to/construire-et-lancer.md), [gérer les channels](how-to/gerer-les-channels.md), [déclarer un agent](how-to/declarer-un-agent.md), [lancer les tests](how-to/lancer-les-tests.md), [préparer un sandbox de développement](how-to/preparer-le-sandbox.md), [journaliser la conversation avec un agent](how-to/journaliser-une-conversation-avec-un-agent.md), [utiliser les commandes d'un agent et joindre des fichiers](how-to/utiliser-commandes-et-joindre-fichiers.md), [copier un message ou un bloc de code](how-to/copier-texte-et-code.md) |14+| Accomplir une tâche | [Construire et lancer Synedrion](how-to/construire-et-lancer.md), [gérer les channels](how-to/gerer-les-channels.md), [déclarer un agent](how-to/declarer-un-agent.md), [lancer les tests](how-to/lancer-les-tests.md), [préparer un sandbox de développement](how-to/preparer-le-sandbox.md), [journaliser la conversation avec un agent](how-to/journaliser-une-conversation-avec-un-agent.md), [utiliser les commandes d'un agent et joindre des fichiers](how-to/utiliser-commandes-et-joindre-fichiers.md), [copier un message ou un bloc de code](how-to/copier-texte-et-code.md), [laisser les agents s'appeler entre eux](how-to/laisser-les-agents-s-appeler.md) |
15-| Consulter les détails exacts | [Déclaration d'un agent](reference/declaration-agent.md), [mentions](reference/mentions.md), [méthodes ACP](reference/methodes-acp.md), [la base de données](reference/base-de-donnees.md), [l'agent de test](reference/agent-de-test.md), [comment les messages sont dessinés](reference/rendu-des-messages.md), [commandes et fichiers joints](reference/commandes-et-fichiers.md) |15+| Consulter les détails exacts | [Déclaration d'un agent](reference/declaration-agent.md), [mentions](reference/mentions.md), [méthodes ACP](reference/methodes-acp.md), [la base de données](reference/base-de-donnees.md), [l'agent de test](reference/agent-de-test.md), [comment les messages sont dessinés](reference/rendu-des-messages.md), [commandes et fichiers joints](reference/commandes-et-fichiers.md), [réglages](reference/reglages.md), [le contexte du channel](reference/contexte-du-channel.md), [appels d'outils, plans, et ce qui ne peut pas être montré](reference/appels-d-outils-et-plans.md) |
16-| Comprendre pourquoi c'est construit ainsi | [Vision](explanation/vision.md), [Architecture](explanation/architecture.md), [Choix techniques](explanation/choix-techniques.md) |16+| Comprendre pourquoi c'est construit ainsi | [Vision](explanation/vision.md), [Architecture](explanation/architecture.md), [Choix techniques](explanation/choix-techniques.md), [Les agents qui s'appellent](explanation/agents-qui-s-appellent.md), [Capacités du client](explanation/capacites-du-client.md) |
17 17
18 ## Par où commencer18 ## Par où commencer
19 19
added docs/fr/explanation/agents-qui-s-appellent.md +41 -0
new file mode 100644
@@ -0,0 +1,41 @@
1+# Les agents qui s'appellent
2+
3+## De quoi s'agit-il ?
4+
5+Dans Synedrion, les participants d'un channel sont des agents, et l'utilisateur. Quand la réponse d'un agent mentionne un autre agent avec `@nom`, cet agent est appelé, exactement comme si l'utilisateur l'avait mentionné. C'est ce qui fait d'un channel une délibération entre agents plutôt qu'une série de conversations séparées avec chacun. Cela crée aussi un risque qu'une conversation avec un humain n'a pas : deux agents peuvent s'appeler indéfiniment, chaque appel coûtant un tour de modèle, souvent un modèle local.
6+
7+## Comment ça marche
8+
9+Le message de l'utilisateur démarre une chaîne. Les agents qu'il appelle sont au premier saut, ceux qu'ils appellent au deuxième, et ainsi de suite. Un appel qui dépasserait le réglage de **profondeur de chaîne** n'est pas fait, et le channel le dit. La valeur par défaut est 3, basse à dessein : elle est facile à relever, et une boucle inattendue coûte quelque chose.
10+
11+Un agent est appelé quand son **tour se termine normalement**, avec sa réponse entière, et pas pendant que la réponse s'écrit encore. Une mention au milieu d'une phrase dont l'agent changerait ensuite d'avis aurait sinon déjà appelé quelqu'un. L'agent appelé reçoit la réponse entière, pas seulement la phrase qui contient la mention, puisque le reste est ce à quoi on lui demande de réagir. Il reçoit aussi les messages qu'il n'a pas vus, comme tout agent (voir [le contexte du channel](../reference/contexte-du-channel.md)).
12+
13+Trois garde-fous gardent cela sous contrôle :
14+
15+- **La profondeur.** Une chaîne ne peut pas être plus longue que le réglage, quoi que disent les agents.
16+- **Stop.** L'utilisateur peut arrêter tous les tours du channel d'un clic, et les réponses qui arrivent encore ensuite n'appellent personne. Sans la seconde partie, un clic au moment même où un agent termine arrêterait cet agent et laisserait pourtant sa réponse en démarrer un autre.
17+- **Auto-mentions.** Un agent qui écrit son propre nom n'est pas rappelé : les agents se citent eux-mêmes.
18+
19+Un tour annulé, échoué ou refusé n'appelle personne, puisqu'il n'y a pas de réponse qui mérite d'être transmise.
20+
21+## Pourquoi une profondeur
22+
23+Plusieurs façons de borner une chaîne ont été envisagées.
24+
25+- **Une profondeur, retenue.** C'est la plus simple à expliquer et à prévoir : l'utilisateur sait combien de tours de modèle un message peut coûter au plus. Il n'a pas besoin de comprendre ce que disent les agents.
26+- **Détecter les boucles d'après ce qui est dit.** Un agent peut se répéter utilement, et deux agents peuvent être bloqués en disant des mots différents à chaque fois. Quelle que soit la détection, elle se tromperait dans les deux sens.
27+- **Un budget de temps ou de jetons.** Plus proche de ce qui importe à l'utilisateur, mais l'application ne connaît pas les jetons de chaque agent, et une limite de temps coupe un long tour utile.
28+- **Demander à l'utilisateur à chaque saut.** Sûr, et cela annule l'intérêt d'agents qui travaillent ensemble.
29+- **Aucune limite et le seul bouton stop.** Le coût d'une erreur est payé avant que l'utilisateur la remarque.
30+
31+La profondeur est un plancher de sécurité, pas une mesure de qualité : une chaîne de trois appels bien choisis vaut mieux qu'une longue.
32+
33+## Limites de la conception actuelle
34+
35+- Le suivi de « qui travaille » est par agent et par channel. Si deux prompts sont en file pour le même agent dans le même channel, la fin du premier montre l'agent comme inactif alors que le second reste à faire.
36+- Deux agents appelés par la même réponse tournent en parallèle, chacun dans son propre processus : Synedrion ne les ordonne pas.
37+- Les agents décident quoi faire d'une mention d'eux-mêmes dans leurs propres instructions. Synedrion ne parle pas des autres agents à un agent.
38+
39+## Liens avec le reste
40+
41+Le réglage et ses limites : [réglages](../reference/reglages.md). Les étapes pour l'utiliser : [laisser les agents s'appeler entre eux](../how-to/laisser-les-agents-s-appeler.md). Qui reçoit un message en général : [mentions](../reference/mentions.md).
new file mode 100644
@@ -0,0 +1,41 @@
1+# Les agents qui s'appellent
2+
3+## De quoi s'agit-il ?
4+
5+Dans Synedrion, les participants d'un channel sont des agents, et l'utilisateur. Quand la réponse d'un agent mentionne un autre agent avec `@nom`, cet agent est appelé, exactement comme si l'utilisateur l'avait mentionné. C'est ce qui fait d'un channel une délibération entre agents plutôt qu'une série de conversations séparées avec chacun. Cela crée aussi un risque qu'une conversation avec un humain n'a pas : deux agents peuvent s'appeler indéfiniment, chaque appel coûtant un tour de modèle, souvent un modèle local.
6+
7+## Comment ça marche
8+
9+Le message de l'utilisateur démarre une chaîne. Les agents qu'il appelle sont au premier saut, ceux qu'ils appellent au deuxième, et ainsi de suite. Un appel qui dépasserait le réglage de **profondeur de chaîne** n'est pas fait, et le channel le dit. La valeur par défaut est 3, basse à dessein : elle est facile à relever, et une boucle inattendue coûte quelque chose.
10+
11+Un agent est appelé quand son **tour se termine normalement**, avec sa réponse entière, et pas pendant que la réponse s'écrit encore. Une mention au milieu d'une phrase dont l'agent changerait ensuite d'avis aurait sinon déjà appelé quelqu'un. L'agent appelé reçoit la réponse entière, pas seulement la phrase qui contient la mention, puisque le reste est ce à quoi on lui demande de réagir. Il reçoit aussi les messages qu'il n'a pas vus, comme tout agent (voir [le contexte du channel](../reference/contexte-du-channel.md)).
12+
13+Trois garde-fous gardent cela sous contrôle :
14+
15+- **La profondeur.** Une chaîne ne peut pas être plus longue que le réglage, quoi que disent les agents.
16+- **Stop.** L'utilisateur peut arrêter tous les tours du channel d'un clic, et les réponses qui arrivent encore ensuite n'appellent personne. Sans la seconde partie, un clic au moment même où un agent termine arrêterait cet agent et laisserait pourtant sa réponse en démarrer un autre.
17+- **Auto-mentions.** Un agent qui écrit son propre nom n'est pas rappelé : les agents se citent eux-mêmes.
18+
19+Un tour annulé, échoué ou refusé n'appelle personne, puisqu'il n'y a pas de réponse qui mérite d'être transmise.
20+
21+## Pourquoi une profondeur
22+
23+Plusieurs façons de borner une chaîne ont été envisagées.
24+
25+- **Une profondeur, retenue.** C'est la plus simple à expliquer et à prévoir : l'utilisateur sait combien de tours de modèle un message peut coûter au plus. Il n'a pas besoin de comprendre ce que disent les agents.
26+- **Détecter les boucles d'après ce qui est dit.** Un agent peut se répéter utilement, et deux agents peuvent être bloqués en disant des mots différents à chaque fois. Quelle que soit la détection, elle se tromperait dans les deux sens.
27+- **Un budget de temps ou de jetons.** Plus proche de ce qui importe à l'utilisateur, mais l'application ne connaît pas les jetons de chaque agent, et une limite de temps coupe un long tour utile.
28+- **Demander à l'utilisateur à chaque saut.** Sûr, et cela annule l'intérêt d'agents qui travaillent ensemble.
29+- **Aucune limite et le seul bouton stop.** Le coût d'une erreur est payé avant que l'utilisateur la remarque.
30+
31+La profondeur est un plancher de sécurité, pas une mesure de qualité : une chaîne de trois appels bien choisis vaut mieux qu'une longue.
32+
33+## Limites de la conception actuelle
34+
35+- Le suivi de « qui travaille » est par agent et par channel. Si deux prompts sont en file pour le même agent dans le même channel, la fin du premier montre l'agent comme inactif alors que le second reste à faire.
36+- Deux agents appelés par la même réponse tournent en parallèle, chacun dans son propre processus : Synedrion ne les ordonne pas.
37+- Les agents décident quoi faire d'une mention d'eux-mêmes dans leurs propres instructions. Synedrion ne parle pas des autres agents à un agent.
38+
39+## Liens avec le reste
40+
41+Le réglage et ses limites : [réglages](../reference/reglages.md). Les étapes pour l'utiliser : [laisser les agents s'appeler entre eux](../how-to/laisser-les-agents-s-appeler.md). Qui reçoit un message en général : [mentions](../reference/mentions.md).
modified docs/fr/explanation/architecture.md +13 -10
@@ -1,6 +1,6 @@
11 # Architecture
22
3-> **État : la version 0.1.0 est construite.** Ce qui suit décrit le code tel qu'il est, sauf quand un point est signalé comme prévu. Les agents qui se parlent entre eux, l'envoi à un agent des messages précédents du channel, et l'affichage des appels d'outils ne sont pas encore construits.
3+> **État : les fonctionnalités des versions 0.1.0 et 0.2.0 sont construites.** Ce qui suit décrit le code tel qu'il est. La fenêtre n'a jamais été vue sur un écran par l'auteur du code.
44
55 ## De quoi s'agit-il ?
66
@@ -8,21 +8,22 @@ Synedrion comporte quatre parties : un modèle de domaine, un store qui le persi
88
99 | Crate | À quoi elle sert |
1010 | --- | --- |
11-| `synedrion-domain` | Les types de l'application (utilisateur, agent, channel, message), les règles qui n'ont besoin ni de base de données ni de fenêtre (noms, mentions et leur complétion), et le trait `Repository`. Elle ne dépend de rien, pas même d'une crate externe. |
11+| `synedrion-domain` | Les types de l'application (utilisateur, agent, channel, message, trace, réglages), les règles qui n'ont besoin ni de base de données ni de fenêtre (noms, mentions et leur complétion, commandes `/`, le contexte donné à un agent), et le trait `Repository`. Elle ne dépend de rien, pas même d'une crate externe. |
1212 | `synedrion-store` | `SqliteRepository`, l'implémentation de `Repository` avec SQLite via `rusqlite`, les migrations du schéma, et l'emplacement du fichier. |
1313 | `synedrion-acp` | `AgentHub` : démarre les processus des agents, parle ACP avec eux grâce à la crate officielle `agent-client-protocol`, et rapporte ce qu'ils font sous forme d'événements. Elle contient aussi l'agent de test. |
14-| `synedrion-ui` | Le `ChatController`, qui relie la base aux agents et ignore tout des fenêtres, et les fenêtres GPUI Kit, qui se contentent de dessiner et de relayer les clics. |
14+| `synedrion-ui` | Le `ChatController`, qui relie la base aux agents et ignore tout des fenêtres (ses parties : ce que reçoit chaque agent, les agents qui s'appellent, les appels d'outils et les plans), et les fenêtres GPUI Kit, qui se contentent de dessiner et de relayer les clics. |
1515
1616 ## D'une mention à une réponse
1717
1818 Quand l'utilisateur envoie un message contenant `@nom`, voici ce qui se passe.
1919
2020 1. Le contrôleur enregistre le message, puis cherche les mentions dans le texte avec une fonction pure du domaine. La mention d'un nom inconnu est laissée telle quelle et signalée à l'utilisateur.
21-2. Pour chaque agent déclaré qui est mentionné, le contrôleur remet le message à l'`AgentHub`.
21+2. Pour chaque agent déclaré qui est mentionné, le contrôleur construit ce que l'agent reçoit : les messages du channel qu'il n'a pas encore vus, puis le message (voir [le contexte du channel](../reference/contexte-du-channel.md)). Il remet cela à l'`AgentHub`.
2222 3. Si le processus de l'agent ne tourne pas, le hub le démarre avec la commande de sa déclaration, sur un thread à lui. Voir la [déclaration d'un agent](../reference/declaration-agent.md).
2323 4. À la première utilisation de ce processus, le hub appelle `initialize`. À la première fois que cet agent est sollicité dans ce channel, il appelle `session/new`.
24-5. Le hub envoie le message avec `session/prompt`. L'agent répond par un flux de notifications `session/update`. Le hub rapporte chaque morceau de texte comme un événement, et le contrôleur l'ajoute à un unique message de l'agent dans le channel, en mettant à jour la base à mesure que le texte grandit. Le tour se termine quand l'agent répond à l'appel `session/prompt`, et un tour qui ne s'est pas terminé normalement (annulé, échoué, refusé) laisse une notice dans le channel.
24+5. Le hub envoie le message avec `session/prompt`. L'agent répond par un flux de notifications `session/update`. Le hub rapporte chaque morceau de texte comme un événement, et le contrôleur l'ajoute à un unique message de l'agent dans le channel, en mettant à jour la base à mesure que le texte grandit. Les appels d'outils et les plans deviennent des cartes dans le channel, et le texte qui les suit commence un nouveau message. Le tour se termine quand l'agent répond à l'appel `session/prompt`, et un tour qui ne s'est pas terminé normalement (annulé, échoué, refusé) laisse une notice dans le channel.
2525 6. Si l'agent demande une autorisation avec `session/request_permission`, la question est affichée dans le channel sous forme de carte, et la réponse de l'utilisateur lui est renvoyée.
26+7. Quand le tour s'est terminé normalement et que la réponse mentionne un autre agent déclaré, le contrôleur remet la réponse à cet agent, un saut plus loin dans une chaîne dont la longueur est limitée (voir [les agents qui s'appellent](agents-qui-s-appellent.md)).
2627
2728 Les événements passent des threads des agents à la fenêtre par une file, et la fenêtre ne redessine que ce que le contrôleur dit avoir changé. Les appels sont listés dans la [référence des méthodes ACP](../reference/methodes-acp.md).
2829
@@ -38,9 +39,11 @@ Les événements passent des threads des agents à la fenêtre par une file, et
3839
3940 **Les agents sont lancés par une commande.** Un agent est déclaré par une commande, ses arguments, son environnement et un dossier de travail, comme les `agent_servers` de l'éditeur Zed. Cela couvre aussi les agents dans une sandbox : la commande est alors `sbx exec`, qui démarre l'agent dans la sandbox et donne à Synedrion son entrée et sa sortie standard, par où passe ACP. La syntaxe exacte de `sbx exec` reste à vérifier sur une vraie sandbox.
4041
41-**L'agent reçoit le message qui le mentionne, tel que saisi.** Un agent qui ne verrait que ce message ne pourrait pas suivre la discussion. Lui envoyer les derniers messages du channel, et seulement ceux apparus depuis son tour précédent, est prévu (ticket #14).
42+**L'agent reçoit les messages qu'il n'a pas vus, puis le message.** Un agent qui ne verrait que le message qui le mentionne ne pourrait pas suivre la discussion. Il sait déjà ce qu'il a dit lui-même, on lui dit donc ce qui s'est dit autour de lui depuis son dernier tour, jusqu'à un nombre et une taille que l'utilisateur peut borner. Le relevé de ce qui a été remis à chaque agent est gardé en mémoire : il vit aussi longtemps que les sessions des agents.
4243
43-**Les agents pourront se mentionner, avec des garde-fous, dans une version ultérieure.** Le plan (ticket #15) est une profondeur maximale de chaîne avec une valeur par défaut basse, un bouton stop pour toute la chaîne, et l'ignorance d'un agent qui se mentionne lui-même. Aujourd'hui, une mention dans la réponse d'un agent ne fait rien.
44+**Les agents peuvent se mentionner, avec des garde-fous.** Une profondeur maximale de chaîne avec une valeur par défaut basse, un bouton stop pour toute la chaîne, et l'ignorance d'un agent qui se mentionne lui-même. Voir [les agents qui s'appellent](agents-qui-s-appellent.md).
45+
46+**Ce qu'un agent fait en plus d'écrire fait partie de l'historique.** Les appels d'outils et les plans sont stockés comme des messages d'un genre à eux, pour qu'ils soient conservés, ordonnés avec le texte, et modifiables sur place pendant que l'agent travaille.
4447
4548 ## Alternatives écartées
4649
@@ -49,9 +52,9 @@ Les événements passent des threads des agents à la fenêtre par une file, et
4952
5053 ## Points ouverts
5154
52-- Synedrion offrira-t-il aux agents l'accès aux fichiers et aux terminaux, les capacités client optionnelles `fs/*` et `terminal/*` d'ACP ? Ce n'est pas décidé, car c'est une décision de sécurité (ticket #18). Aujourd'hui il n'en offre aucune.
53-- Rien n'a été essayé avec un vrai agent comme mini-me : les tests utilisent un agent de test bâti sur la même bibliothèque ACP.
54-- La fenêtre n'a jamais été vue sur un écran. Son comportement est testé, son apparence ne l'est pas.
55+- Synedrion n'offre aux agents aucun accès aux fichiers ni aux terminaux, les capacités client optionnelles `fs/*` et `terminal/*` d'ACP. C'est une décision, dont les raisons sont dans les [capacités du client](capacites-du-client.md). Elle peut être reprise.
56+- Les mentions, les commandes et les fichiers joints ont été essayés avec mini-me. Le contexte du channel, les agents qui s'appellent, et les appels d'outils et plans n'ont été essayés qu'avec l'agent de test, bâti sur la même bibliothèque ACP : on ne sait pas si un vrai agent les envoie et les reçoit comme l'agent de test.
57+- La fenêtre n'a jamais été vue sur un écran par l'auteur du code. Son comportement est testé, son apparence ne l'est pas.
5558
5659 ## Liens avec le reste
5760
@@ -1,6 +1,6 @@
1 # Architecture1 # Architecture
2 2
3-> **État : la version 0.1.0 est construite.** Ce qui suit décrit le code tel qu'il est, sauf quand un point est signalé comme prévu. Les agents qui se parlent entre eux, l'envoi à un agent des messages précédents du channel, et l'affichage des appels d'outils ne sont pas encore construits.3+> **État : les fonctionnalités des versions 0.1.0 et 0.2.0 sont construites.** Ce qui suit décrit le code tel qu'il est. La fenêtre n'a jamais été vue sur un écran par l'auteur du code.
4 4
5 ## De quoi s'agit-il ?5 ## De quoi s'agit-il ?
6 6
@@ -8,21 +8,22 @@ Synedrion comporte quatre parties : un modèle de domaine, un store qui le persi
8 8
9 | Crate | À quoi elle sert |9 | Crate | À quoi elle sert |
10 | --- | --- |10 | --- | --- |
11-| `synedrion-domain` | Les types de l'application (utilisateur, agent, channel, message), les règles qui n'ont besoin ni de base de données ni de fenêtre (noms, mentions et leur complétion), et le trait `Repository`. Elle ne dépend de rien, pas même d'une crate externe. |11+| `synedrion-domain` | Les types de l'application (utilisateur, agent, channel, message, trace, réglages), les règles qui n'ont besoin ni de base de données ni de fenêtre (noms, mentions et leur complétion, commandes `/`, le contexte donné à un agent), et le trait `Repository`. Elle ne dépend de rien, pas même d'une crate externe. |
12 | `synedrion-store` | `SqliteRepository`, l'implémentation de `Repository` avec SQLite via `rusqlite`, les migrations du schéma, et l'emplacement du fichier. |12 | `synedrion-store` | `SqliteRepository`, l'implémentation de `Repository` avec SQLite via `rusqlite`, les migrations du schéma, et l'emplacement du fichier. |
13 | `synedrion-acp` | `AgentHub` : démarre les processus des agents, parle ACP avec eux grâce à la crate officielle `agent-client-protocol`, et rapporte ce qu'ils font sous forme d'événements. Elle contient aussi l'agent de test. |13 | `synedrion-acp` | `AgentHub` : démarre les processus des agents, parle ACP avec eux grâce à la crate officielle `agent-client-protocol`, et rapporte ce qu'ils font sous forme d'événements. Elle contient aussi l'agent de test. |
14-| `synedrion-ui` | Le `ChatController`, qui relie la base aux agents et ignore tout des fenêtres, et les fenêtres GPUI Kit, qui se contentent de dessiner et de relayer les clics. |14+| `synedrion-ui` | Le `ChatController`, qui relie la base aux agents et ignore tout des fenêtres (ses parties : ce que reçoit chaque agent, les agents qui s'appellent, les appels d'outils et les plans), et les fenêtres GPUI Kit, qui se contentent de dessiner et de relayer les clics. |
15 15
16 ## D'une mention à une réponse16 ## D'une mention à une réponse
17 17
18 Quand l'utilisateur envoie un message contenant `@nom`, voici ce qui se passe.18 Quand l'utilisateur envoie un message contenant `@nom`, voici ce qui se passe.
19 19
20 1. Le contrôleur enregistre le message, puis cherche les mentions dans le texte avec une fonction pure du domaine. La mention d'un nom inconnu est laissée telle quelle et signalée à l'utilisateur.20 1. Le contrôleur enregistre le message, puis cherche les mentions dans le texte avec une fonction pure du domaine. La mention d'un nom inconnu est laissée telle quelle et signalée à l'utilisateur.
21-2. Pour chaque agent déclaré qui est mentionné, le contrôleur remet le message à l'`AgentHub`.21+2. Pour chaque agent déclaré qui est mentionné, le contrôleur construit ce que l'agent reçoit : les messages du channel qu'il n'a pas encore vus, puis le message (voir [le contexte du channel](../reference/contexte-du-channel.md)). Il remet cela à l'`AgentHub`.
22 3. Si le processus de l'agent ne tourne pas, le hub le démarre avec la commande de sa déclaration, sur un thread à lui. Voir la [déclaration d'un agent](../reference/declaration-agent.md).22 3. Si le processus de l'agent ne tourne pas, le hub le démarre avec la commande de sa déclaration, sur un thread à lui. Voir la [déclaration d'un agent](../reference/declaration-agent.md).
23 4. À la première utilisation de ce processus, le hub appelle `initialize`. À la première fois que cet agent est sollicité dans ce channel, il appelle `session/new`.23 4. À la première utilisation de ce processus, le hub appelle `initialize`. À la première fois que cet agent est sollicité dans ce channel, il appelle `session/new`.
24-5. Le hub envoie le message avec `session/prompt`. L'agent répond par un flux de notifications `session/update`. Le hub rapporte chaque morceau de texte comme un événement, et le contrôleur l'ajoute à un unique message de l'agent dans le channel, en mettant à jour la base à mesure que le texte grandit. Le tour se termine quand l'agent répond à l'appel `session/prompt`, et un tour qui ne s'est pas terminé normalement (annulé, échoué, refusé) laisse une notice dans le channel.24+5. Le hub envoie le message avec `session/prompt`. L'agent répond par un flux de notifications `session/update`. Le hub rapporte chaque morceau de texte comme un événement, et le contrôleur l'ajoute à un unique message de l'agent dans le channel, en mettant à jour la base à mesure que le texte grandit. Les appels d'outils et les plans deviennent des cartes dans le channel, et le texte qui les suit commence un nouveau message. Le tour se termine quand l'agent répond à l'appel `session/prompt`, et un tour qui ne s'est pas terminé normalement (annulé, échoué, refusé) laisse une notice dans le channel.
25 6. Si l'agent demande une autorisation avec `session/request_permission`, la question est affichée dans le channel sous forme de carte, et la réponse de l'utilisateur lui est renvoyée.25 6. Si l'agent demande une autorisation avec `session/request_permission`, la question est affichée dans le channel sous forme de carte, et la réponse de l'utilisateur lui est renvoyée.
26+7. Quand le tour s'est terminé normalement et que la réponse mentionne un autre agent déclaré, le contrôleur remet la réponse à cet agent, un saut plus loin dans une chaîne dont la longueur est limitée (voir [les agents qui s'appellent](agents-qui-s-appellent.md)).
26 27
27 Les événements passent des threads des agents à la fenêtre par une file, et la fenêtre ne redessine que ce que le contrôleur dit avoir changé. Les appels sont listés dans la [référence des méthodes ACP](../reference/methodes-acp.md).28 Les événements passent des threads des agents à la fenêtre par une file, et la fenêtre ne redessine que ce que le contrôleur dit avoir changé. Les appels sont listés dans la [référence des méthodes ACP](../reference/methodes-acp.md).
28 29
@@ -38,9 +39,11 @@ Les événements passent des threads des agents à la fenêtre par une file, et
38 39
39 **Les agents sont lancés par une commande.** Un agent est déclaré par une commande, ses arguments, son environnement et un dossier de travail, comme les `agent_servers` de l'éditeur Zed. Cela couvre aussi les agents dans une sandbox : la commande est alors `sbx exec`, qui démarre l'agent dans la sandbox et donne à Synedrion son entrée et sa sortie standard, par où passe ACP. La syntaxe exacte de `sbx exec` reste à vérifier sur une vraie sandbox.40 **Les agents sont lancés par une commande.** Un agent est déclaré par une commande, ses arguments, son environnement et un dossier de travail, comme les `agent_servers` de l'éditeur Zed. Cela couvre aussi les agents dans une sandbox : la commande est alors `sbx exec`, qui démarre l'agent dans la sandbox et donne à Synedrion son entrée et sa sortie standard, par où passe ACP. La syntaxe exacte de `sbx exec` reste à vérifier sur une vraie sandbox.
40 41
41-**L'agent reçoit le message qui le mentionne, tel que saisi.** Un agent qui ne verrait que ce message ne pourrait pas suivre la discussion. Lui envoyer les derniers messages du channel, et seulement ceux apparus depuis son tour précédent, est prévu (ticket #14).42+**L'agent reçoit les messages qu'il n'a pas vus, puis le message.** Un agent qui ne verrait que le message qui le mentionne ne pourrait pas suivre la discussion. Il sait déjà ce qu'il a dit lui-même, on lui dit donc ce qui s'est dit autour de lui depuis son dernier tour, jusqu'à un nombre et une taille que l'utilisateur peut borner. Le relevé de ce qui a été remis à chaque agent est gardé en mémoire : il vit aussi longtemps que les sessions des agents.
42 43
43-**Les agents pourront se mentionner, avec des garde-fous, dans une version ultérieure.** Le plan (ticket #15) est une profondeur maximale de chaîne avec une valeur par défaut basse, un bouton stop pour toute la chaîne, et l'ignorance d'un agent qui se mentionne lui-même. Aujourd'hui, une mention dans la réponse d'un agent ne fait rien.44+**Les agents peuvent se mentionner, avec des garde-fous.** Une profondeur maximale de chaîne avec une valeur par défaut basse, un bouton stop pour toute la chaîne, et l'ignorance d'un agent qui se mentionne lui-même. Voir [les agents qui s'appellent](agents-qui-s-appellent.md).
45+
46+**Ce qu'un agent fait en plus d'écrire fait partie de l'historique.** Les appels d'outils et les plans sont stockés comme des messages d'un genre à eux, pour qu'ils soient conservés, ordonnés avec le texte, et modifiables sur place pendant que l'agent travaille.
44 47
45 ## Alternatives écartées48 ## Alternatives écartées
46 49
@@ -49,9 +52,9 @@ Les événements passent des threads des agents à la fenêtre par une file, et
49 52
50 ## Points ouverts53 ## Points ouverts
51 54
52-- Synedrion offrira-t-il aux agents l'accès aux fichiers et aux terminaux, les capacités client optionnelles `fs/*` et `terminal/*` d'ACP ? Ce n'est pas décidé, car c'est une décision de sécurité (ticket #18). Aujourd'hui il n'en offre aucune.55+- Synedrion n'offre aux agents aucun accès aux fichiers ni aux terminaux, les capacités client optionnelles `fs/*` et `terminal/*` d'ACP. C'est une décision, dont les raisons sont dans les [capacités du client](capacites-du-client.md). Elle peut être reprise.
53-- Rien n'a été essayé avec un vrai agent comme mini-me : les tests utilisent un agent de test bâti sur la même bibliothèque ACP.56+- Les mentions, les commandes et les fichiers joints ont été essayés avec mini-me. Le contexte du channel, les agents qui s'appellent, et les appels d'outils et plans n'ont été essayés qu'avec l'agent de test, bâti sur la même bibliothèque ACP : on ne sait pas si un vrai agent les envoie et les reçoit comme l'agent de test.
54-- La fenêtre n'a jamais été vue sur un écran. Son comportement est testé, son apparence ne l'est pas.57+- La fenêtre n'a jamais été vue sur un écran par l'auteur du code. Son comportement est testé, son apparence ne l'est pas.
55 58
56 ## Liens avec le reste59 ## Liens avec le reste
57 60
added docs/fr/explanation/capacites-du-client.md +42 -0
new file mode 100644
@@ -0,0 +1,42 @@
1+# Capacités du client : pourquoi Synedrion n'offre aux agents aucun accès aux fichiers ni aux terminaux
2+
3+## De quoi s'agit-il ?
4+
5+ACP permet à un client d'offrir à ses agents des services optionnels : lire et écrire des fichiers texte (`fs/read_text_file`, `fs/write_text_file`) et lancer des commandes dans des terminaux (`terminal/*`). Le client dit lesquels il offre quand il démarre l'agent, dans l'appel `initialize`. Synedrion n'en offre aucun, et le dit. Cette page consigne cette décision, prise pour le ticket #18.
6+
7+## Quelle est la décision
8+
9+Synedrion n'annonce aucune capacité à `initialize` : ni `fs.readTextFile`, ni `fs.writeTextFile`, ni `terminal`. Un test la fige, pour qu'en offrir une devienne une décision prise exprès et pas un effet de bord.
10+
11+Un agent qui veut lire, écrire ou lancer quelque chose le fait avec ses propres outils, dans son propre processus.
12+
13+## Pourquoi
14+
15+Les agents de Synedrion tournent sur la même machine que l'application, et éventuellement dans une sandbox : c'est le but de les démarrer avec `sbx exec`. Une sandbox existe pour garder un agent loin des fichiers et des processus de l'hôte. Si Synedrion offrait `fs/*` ou `terminal/*`, l'agent demanderait à l'application, qui tourne sur l'hôte hors de la sandbox, de faire ce que la sandbox lui interdit. Le service serait un trou dans le mur, et il fonctionnerait pour l'agent qui n'est *pas* dans une sandbox autant que pour celui qui y est, c'est-à-dire là où une écriture non voulue fait le plus de dégâts.
16+
17+Les offrir en sécurité est possible, mais c'est un vrai travail et pas un interrupteur :
18+
19+- limiter chaque chemin au dossier de travail de l'agent, en résolvant les liens et les `..` avant la vérification ;
20+- demander à l'utilisateur avant chaque écriture, ou au moins la première ;
21+- un choix par agent, puisqu'un agent de confiance et un agent en sandbox ne sont pas le même cas ;
22+- lancer les commandes avec une sortie visible, une limite de temps et un moyen de les tuer.
23+
24+Rien de cela n'est nécessaire pour les agents qui existent aujourd'hui.
25+
26+## Ce qui a été vérifié
27+
28+mini-me, démarré par Synedrion sans aucune capacité annoncée, a répondu à des prompts, annoncé ses commandes, et reçu des fichiers joints. Ses propres outils, comme son outil shell, n'ont pas été exercés dans cette vérification, donc cette page ne dit pas qu'ils fonctionnent. Elle dit que l'agent démarre et répond sans ce que Synedrion n'offre pas.
29+
30+## Alternatives écartées
31+
32+- **Offrir l'accès aux fichiers limité au dossier de travail, avec confirmation pour les écritures.** La plus utile des options, et celle à construire en premier si la décision change. Elle n'a pas été construite parce qu'aucun agent n'en a besoin pour l'instant, et un périmètre à moitié vérifié vaut moins que pas de périmètre.
33+- **Tout offrir, par agent, désactivé par défaut.** Un interrupteur dans la déclaration. Il demande le même cloisonnement que l'option ci-dessus pour être sûr, c'est donc le même travail.
34+- **Tout offrir.** Écarté pour la raison ci-dessus.
35+
36+## Quand décider de nouveau
37+
38+Quand un agent que Synedrion devrait prendre en charge demande ces capacités et fonctionne mal sans elles. La première chose à écrire alors est l'accès en lecture cloisonné, avec un ticket à lui.
39+
40+## Liens avec le reste
41+
42+Les appels que Synedrion fait et ne fait pas : [méthodes ACP](../reference/methodes-acp.md). Pourquoi les agents sont lancés dans une sandbox : [architecture](architecture.md).
new file mode 100644
@@ -0,0 +1,42 @@
1+# Capacités du client : pourquoi Synedrion n'offre aux agents aucun accès aux fichiers ni aux terminaux
2+
3+## De quoi s'agit-il ?
4+
5+ACP permet à un client d'offrir à ses agents des services optionnels : lire et écrire des fichiers texte (`fs/read_text_file`, `fs/write_text_file`) et lancer des commandes dans des terminaux (`terminal/*`). Le client dit lesquels il offre quand il démarre l'agent, dans l'appel `initialize`. Synedrion n'en offre aucun, et le dit. Cette page consigne cette décision, prise pour le ticket #18.
6+
7+## Quelle est la décision
8+
9+Synedrion n'annonce aucune capacité à `initialize` : ni `fs.readTextFile`, ni `fs.writeTextFile`, ni `terminal`. Un test la fige, pour qu'en offrir une devienne une décision prise exprès et pas un effet de bord.
10+
11+Un agent qui veut lire, écrire ou lancer quelque chose le fait avec ses propres outils, dans son propre processus.
12+
13+## Pourquoi
14+
15+Les agents de Synedrion tournent sur la même machine que l'application, et éventuellement dans une sandbox : c'est le but de les démarrer avec `sbx exec`. Une sandbox existe pour garder un agent loin des fichiers et des processus de l'hôte. Si Synedrion offrait `fs/*` ou `terminal/*`, l'agent demanderait à l'application, qui tourne sur l'hôte hors de la sandbox, de faire ce que la sandbox lui interdit. Le service serait un trou dans le mur, et il fonctionnerait pour l'agent qui n'est *pas* dans une sandbox autant que pour celui qui y est, c'est-à-dire là où une écriture non voulue fait le plus de dégâts.
16+
17+Les offrir en sécurité est possible, mais c'est un vrai travail et pas un interrupteur :
18+
19+- limiter chaque chemin au dossier de travail de l'agent, en résolvant les liens et les `..` avant la vérification ;
20+- demander à l'utilisateur avant chaque écriture, ou au moins la première ;
21+- un choix par agent, puisqu'un agent de confiance et un agent en sandbox ne sont pas le même cas ;
22+- lancer les commandes avec une sortie visible, une limite de temps et un moyen de les tuer.
23+
24+Rien de cela n'est nécessaire pour les agents qui existent aujourd'hui.
25+
26+## Ce qui a été vérifié
27+
28+mini-me, démarré par Synedrion sans aucune capacité annoncée, a répondu à des prompts, annoncé ses commandes, et reçu des fichiers joints. Ses propres outils, comme son outil shell, n'ont pas été exercés dans cette vérification, donc cette page ne dit pas qu'ils fonctionnent. Elle dit que l'agent démarre et répond sans ce que Synedrion n'offre pas.
29+
30+## Alternatives écartées
31+
32+- **Offrir l'accès aux fichiers limité au dossier de travail, avec confirmation pour les écritures.** La plus utile des options, et celle à construire en premier si la décision change. Elle n'a pas été construite parce qu'aucun agent n'en a besoin pour l'instant, et un périmètre à moitié vérifié vaut moins que pas de périmètre.
33+- **Tout offrir, par agent, désactivé par défaut.** Un interrupteur dans la déclaration. Il demande le même cloisonnement que l'option ci-dessus pour être sûr, c'est donc le même travail.
34+- **Tout offrir.** Écarté pour la raison ci-dessus.
35+
36+## Quand décider de nouveau
37+
38+Quand un agent que Synedrion devrait prendre en charge demande ces capacités et fonctionne mal sans elles. La première chose à écrire alors est l'accès en lecture cloisonné, avec un ticket à lui.
39+
40+## Liens avec le reste
41+
42+Les appels que Synedrion fait et ne fait pas : [méthodes ACP](../reference/methodes-acp.md). Pourquoi les agents sont lancés dans une sandbox : [architecture](architecture.md).
modified docs/fr/how-to/declarer-un-agent.md +1 -1
@@ -10,7 +10,7 @@ Ce guide déclare un agent ACP pour que vous puissiez le mentionner dans un chan
1010 - **Command** : le programme qui démarre l'agent.
1111 - **Arguments** : un par ligne.
1212 - **Environment** : un `NOM=valeur` par ligne.
13- - **Working folder** : facultatif.
13+ - **Working folder** : facultatif. Saisissez le chemin, ou cliquez sur **Browse…**, cliquez sur des dossiers pour les parcourir (`..` remonte), puis sur **Use this folder**.
1414 3. Cliquez sur **Save agent**. L'agent apparaît dans la liste au-dessus du formulaire.
1515 4. Écrivez `@nom` suivi de votre message dans la conversation. Vous pouvez laisser le panneau ouvert, ou le fermer avec le bouton robot ou la croix de son titre.
1616
@@ -10,7 +10,7 @@ Ce guide déclare un agent ACP pour que vous puissiez le mentionner dans un chan
10 - **Command** : le programme qui démarre l'agent.10 - **Command** : le programme qui démarre l'agent.
11 - **Arguments** : un par ligne.11 - **Arguments** : un par ligne.
12 - **Environment** : un `NOM=valeur` par ligne.12 - **Environment** : un `NOM=valeur` par ligne.
13- - **Working folder** : facultatif.13+ - **Working folder** : facultatif. Saisissez le chemin, ou cliquez sur **Browse…**, cliquez sur des dossiers pour les parcourir (`..` remonte), puis sur **Use this folder**.
14 3. Cliquez sur **Save agent**. L'agent apparaît dans la liste au-dessus du formulaire.14 3. Cliquez sur **Save agent**. L'agent apparaît dans la liste au-dessus du formulaire.
15 4. Écrivez `@nom` suivi de votre message dans la conversation. Vous pouvez laisser le panneau ouvert, ou le fermer avec le bouton robot ou la croix de son titre.15 4. Écrivez `@nom` suivi de votre message dans la conversation. Vous pouvez laisser le panneau ouvert, ou le fermer avec le bouton robot ou la croix de son titre.
16 16
added docs/fr/how-to/laisser-les-agents-s-appeler.md +36 -0
new file mode 100644
@@ -0,0 +1,36 @@
1+# Comment laisser les agents s'appeler entre eux
2+
3+Ce guide fait confier du travail à un agent par un autre agent, et montre comment l'arrêter. Il suppose que deux agents sont déclarés, par exemple `amy` et `bob`. Voir [comment déclarer un agent](declarer-un-agent.md).
4+
5+## Étapes
6+
7+1. Demandez au premier agent d'impliquer le second : `@amy relis le plan et demande à @bob de vérifier le build`.
8+2. Attendez que `@amy` ait fini sa réponse. Si la réponse contient `@bob`, `@bob` est appelé dès que la réponse est complète, et reçoit la réponse entière de `@amy`, introduite par `[Message from @amy]`.
9+3. Regardez le channel. La réponse de `@bob` apparaît comme un message à part. S'il mentionne `@amy` ou un autre agent, cet agent est appelé à son tour.
10+
11+Il faut que l'agent écrive la mention dans sa réponse pour que cela arrive. Un agent dont les instructions ne lui parlent pas des autres agents ne les mentionnera pas : mettez leurs noms dans ses propres instructions ou sa configuration.
12+
13+## Arrêter toute la chaîne
14+
15+Cliquez sur **Stop** pendant qu'un agent travaille. Chaque agent qui travaille dans le channel reçoit la demande de s'arrêter, et une réponse qui arrive encore après le clic n'appelle personne.
16+
17+## Changer jusqu'où une chaîne peut aller
18+
19+1. Ouvrez le panneau **Settings**.
20+2. Changez **Chain depth** : le nombre d'agents qui peuvent s'appeler de suite après votre message. `3` est la valeur par défaut. `0` l'interdit, et `10` est le maximum.
21+3. Cliquez sur **Save settings**. Cela s'applique dès le message suivant.
22+
23+Quand une chaîne atteint la limite, l'agent qui allait être appelé ne l'est pas, et un message de Synedrion dans le channel le dit : `Chain stopped: @bob called @amy, but the limit of 3 agent(s) calling one another in a row is reached. The limit is in the settings.`
24+
25+## Variantes
26+
27+- **Des agents qui ne doivent jamais s'appeler.** Mettez la profondeur à `0`. Les mentions dans les réponses ne font alors rien, et aucune notice n'est affichée.
28+- **Un agent qui se mentionne lui-même.** Ignoré : il n'est pas rappelé.
29+- **Une mention d'un nom qu'aucun agent ne porte.** Ignorée.
30+- **Un agent injoignable.** Un message dit `Could not reach @nom` avec la raison, et le reste continue.
31+
32+## Voir aussi
33+
34+- Pourquoi la limite est une profondeur, et ce qui a été envisagé d'autre : [les agents qui s'appellent](../explanation/agents-qui-s-appellent.md)
35+- Ce que l'agent appelé reçoit : [le contexte du channel](../reference/contexte-du-channel.md)
36+- Tous les réglages : [réglages](../reference/reglages.md)
new file mode 100644
@@ -0,0 +1,36 @@
1+# Comment laisser les agents s'appeler entre eux
2+
3+Ce guide fait confier du travail à un agent par un autre agent, et montre comment l'arrêter. Il suppose que deux agents sont déclarés, par exemple `amy` et `bob`. Voir [comment déclarer un agent](declarer-un-agent.md).
4+
5+## Étapes
6+
7+1. Demandez au premier agent d'impliquer le second : `@amy relis le plan et demande à @bob de vérifier le build`.
8+2. Attendez que `@amy` ait fini sa réponse. Si la réponse contient `@bob`, `@bob` est appelé dès que la réponse est complète, et reçoit la réponse entière de `@amy`, introduite par `[Message from @amy]`.
9+3. Regardez le channel. La réponse de `@bob` apparaît comme un message à part. S'il mentionne `@amy` ou un autre agent, cet agent est appelé à son tour.
10+
11+Il faut que l'agent écrive la mention dans sa réponse pour que cela arrive. Un agent dont les instructions ne lui parlent pas des autres agents ne les mentionnera pas : mettez leurs noms dans ses propres instructions ou sa configuration.
12+
13+## Arrêter toute la chaîne
14+
15+Cliquez sur **Stop** pendant qu'un agent travaille. Chaque agent qui travaille dans le channel reçoit la demande de s'arrêter, et une réponse qui arrive encore après le clic n'appelle personne.
16+
17+## Changer jusqu'où une chaîne peut aller
18+
19+1. Ouvrez le panneau **Settings**.
20+2. Changez **Chain depth** : le nombre d'agents qui peuvent s'appeler de suite après votre message. `3` est la valeur par défaut. `0` l'interdit, et `10` est le maximum.
21+3. Cliquez sur **Save settings**. Cela s'applique dès le message suivant.
22+
23+Quand une chaîne atteint la limite, l'agent qui allait être appelé ne l'est pas, et un message de Synedrion dans le channel le dit : `Chain stopped: @bob called @amy, but the limit of 3 agent(s) calling one another in a row is reached. The limit is in the settings.`
24+
25+## Variantes
26+
27+- **Des agents qui ne doivent jamais s'appeler.** Mettez la profondeur à `0`. Les mentions dans les réponses ne font alors rien, et aucune notice n'est affichée.
28+- **Un agent qui se mentionne lui-même.** Ignoré : il n'est pas rappelé.
29+- **Une mention d'un nom qu'aucun agent ne porte.** Ignorée.
30+- **Un agent injoignable.** Un message dit `Could not reach @nom` avec la raison, et le reste continue.
31+
32+## Voir aussi
33+
34+- Pourquoi la limite est une profondeur, et ce qui a été envisagé d'autre : [les agents qui s'appellent](../explanation/agents-qui-s-appellent.md)
35+- Ce que l'agent appelé reçoit : [le contexte du channel](../reference/contexte-du-channel.md)
36+- Tous les réglages : [réglages](../reference/reglages.md)
modified docs/fr/how-to/lancer-les-tests.md +7 -5
@@ -22,7 +22,7 @@ Les deux commandes fonctionnent depuis un dépôt fraîchement cloné. Il ne fau
2222 ## Variantes
2323
2424 - **Une seule crate.** `cargo test -p synedrion-domain`, `-p synedrion-store`, `-p synedrion-acp` ou `-p synedrion-ui`.
25-- **Seulement les tests de fenêtre.** `cargo test -p synedrion-ui --test window`.
25+- **Seulement les tests de fenêtre.** `cargo test -p synedrion-ui --test window`, et les autres fichiers de `crates/ui/tests` : `--test folder_browser`, `--test settings_and_traces`, et `--test conversation` (le contrôleur avec un faux des agents, sans fenêtre).
2626 - **Seulement les tests de processus d'agent.** `cargo test -p synedrion-acp --test hub`. Ils lancent l'[agent de test](../reference/agent-de-test.md) comme un vrai processus et attendent jusqu'à 20 secondes chaque événement : une machine lente les rend plus lents, pas instables.
2727 - **Formater le code.** `cargo fmt --all` réécrit les fichiers au lieu de seulement les vérifier.
2828
@@ -30,11 +30,13 @@ Les deux commandes fonctionnent depuis un dépôt fraîchement cloné. Il ne fau
3030
3131 | Suite | Ce qu'elle vérifie |
3232 | --- | --- |
33-| Tests unitaires de `synedrion-domain` | Les noms, les mentions et leur complétion, les règles qui n'ont besoin ni de base de données ni de fenêtre |
34-| Tests unitaires de `synedrion-store` | Le schéma SQLite et ses migrations, chaque opération sur la base, la persistance après réouverture du fichier, l'emplacement du fichier |
35-| Tests unitaires de `synedrion-acp` et `tests/hub.rs` | La gestion des permissions, et le comportement réel avec un processus d'agent : réponses par morceaux, permissions, annulation, un agent qui meurt, un agent qui n'existe pas |
36-| Tests unitaires de `synedrion-ui` | Le contrôleur (ce que font un message ou un événement d'agent), le formulaire d'agent, la mise en forme |
33+| Tests unitaires de `synedrion-domain` | Les noms, les mentions et leur complétion, les commandes `/`, le contexte donné à un agent, les traces, les réglages : les règles qui n'ont besoin ni de base de données ni de fenêtre |
34+| Tests unitaires de `synedrion-store` | Le schéma SQLite et ses migrations (dont une mise à niveau qui garde les messages), chaque opération sur la base, les réglages, la persistance après réouverture du fichier, l'emplacement du fichier |
35+| Tests unitaires de `synedrion-acp` et `tests/hub.rs` | La gestion des permissions, la traduction de chaque genre de `session/update`, les capacités annoncées, et le comportement réel avec un processus d'agent : réponses par morceaux, appels d'outils et plans, permissions, annulation, un agent qui meurt, un agent qui n'existe pas |
36+| Tests unitaires de `synedrion-ui` | Le contrôleur (ce que font un message ou un événement d'agent), le formulaire d'agent, la liste des fichiers et des dossiers, la mise en forme |
3737 | `tests/window.rs` de `synedrion-ui` | La fenêtre pilotée comme le ferait un utilisateur : profil, channels, envoi, mentions, suggestions, questions de permission, complétion par Tab, bouton Stop, dock de panneaux et son redimensionnement, déclaration des agents |
38+| `tests/folder_browser.rs` et `tests/settings_and_traces.rs` de `synedrion-ui` | Le navigateur de dossiers du formulaire d'agent, le panneau de réglages, les cartes d'appels d'outils et de plans, et une chaîne d'agents arrêtée depuis la fenêtre |
39+| `tests/conversation.rs` de `synedrion-ui` | Le contexte donné à chaque agent, les agents qui s'appellent (la limite, l'arrêt, l'auto-mention), et les appels d'outils et plans dans le channel, sans fenêtre |
3840
3941 ## Ce qui n'est pas couvert
4042
@@ -22,7 +22,7 @@ Les deux commandes fonctionnent depuis un dépôt fraîchement cloné. Il ne fau
22 ## Variantes22 ## Variantes
23 23
24 - **Une seule crate.** `cargo test -p synedrion-domain`, `-p synedrion-store`, `-p synedrion-acp` ou `-p synedrion-ui`.24 - **Une seule crate.** `cargo test -p synedrion-domain`, `-p synedrion-store`, `-p synedrion-acp` ou `-p synedrion-ui`.
25-- **Seulement les tests de fenêtre.** `cargo test -p synedrion-ui --test window`.25+- **Seulement les tests de fenêtre.** `cargo test -p synedrion-ui --test window`, et les autres fichiers de `crates/ui/tests` : `--test folder_browser`, `--test settings_and_traces`, et `--test conversation` (le contrôleur avec un faux des agents, sans fenêtre).
26 - **Seulement les tests de processus d'agent.** `cargo test -p synedrion-acp --test hub`. Ils lancent l'[agent de test](../reference/agent-de-test.md) comme un vrai processus et attendent jusqu'à 20 secondes chaque événement : une machine lente les rend plus lents, pas instables.26 - **Seulement les tests de processus d'agent.** `cargo test -p synedrion-acp --test hub`. Ils lancent l'[agent de test](../reference/agent-de-test.md) comme un vrai processus et attendent jusqu'à 20 secondes chaque événement : une machine lente les rend plus lents, pas instables.
27 - **Formater le code.** `cargo fmt --all` réécrit les fichiers au lieu de seulement les vérifier.27 - **Formater le code.** `cargo fmt --all` réécrit les fichiers au lieu de seulement les vérifier.
28 28
@@ -30,11 +30,13 @@ Les deux commandes fonctionnent depuis un dépôt fraîchement cloné. Il ne fau
30 30
31 | Suite | Ce qu'elle vérifie |31 | Suite | Ce qu'elle vérifie |
32 | --- | --- |32 | --- | --- |
33-| Tests unitaires de `synedrion-domain` | Les noms, les mentions et leur complétion, les règles qui n'ont besoin ni de base de données ni de fenêtre |33+| Tests unitaires de `synedrion-domain` | Les noms, les mentions et leur complétion, les commandes `/`, le contexte donné à un agent, les traces, les réglages : les règles qui n'ont besoin ni de base de données ni de fenêtre |
34-| Tests unitaires de `synedrion-store` | Le schéma SQLite et ses migrations, chaque opération sur la base, la persistance après réouverture du fichier, l'emplacement du fichier |34+| Tests unitaires de `synedrion-store` | Le schéma SQLite et ses migrations (dont une mise à niveau qui garde les messages), chaque opération sur la base, les réglages, la persistance après réouverture du fichier, l'emplacement du fichier |
35-| Tests unitaires de `synedrion-acp` et `tests/hub.rs` | La gestion des permissions, et le comportement réel avec un processus d'agent : réponses par morceaux, permissions, annulation, un agent qui meurt, un agent qui n'existe pas |35+| Tests unitaires de `synedrion-acp` et `tests/hub.rs` | La gestion des permissions, la traduction de chaque genre de `session/update`, les capacités annoncées, et le comportement réel avec un processus d'agent : réponses par morceaux, appels d'outils et plans, permissions, annulation, un agent qui meurt, un agent qui n'existe pas |
36-| Tests unitaires de `synedrion-ui` | Le contrôleur (ce que font un message ou un événement d'agent), le formulaire d'agent, la mise en forme |36+| Tests unitaires de `synedrion-ui` | Le contrôleur (ce que font un message ou un événement d'agent), le formulaire d'agent, la liste des fichiers et des dossiers, la mise en forme |
37 | `tests/window.rs` de `synedrion-ui` | La fenêtre pilotée comme le ferait un utilisateur : profil, channels, envoi, mentions, suggestions, questions de permission, complétion par Tab, bouton Stop, dock de panneaux et son redimensionnement, déclaration des agents |37 | `tests/window.rs` de `synedrion-ui` | La fenêtre pilotée comme le ferait un utilisateur : profil, channels, envoi, mentions, suggestions, questions de permission, complétion par Tab, bouton Stop, dock de panneaux et son redimensionnement, déclaration des agents |
38+| `tests/folder_browser.rs` et `tests/settings_and_traces.rs` de `synedrion-ui` | Le navigateur de dossiers du formulaire d'agent, le panneau de réglages, les cartes d'appels d'outils et de plans, et une chaîne d'agents arrêtée depuis la fenêtre |
39+| `tests/conversation.rs` de `synedrion-ui` | Le contexte donné à chaque agent, les agents qui s'appellent (la limite, l'arrêt, l'auto-mention), et les appels d'outils et plans dans le channel, sans fenêtre |
38 40
39 ## Ce qui n'est pas couvert41 ## Ce qui n'est pas couvert
40 42
modified docs/fr/how-to/utiliser-commandes-et-joindre-fichiers.md +11 -2
@@ -6,7 +6,7 @@ Ce guide lance une commande d'un agent, comme `/new` ou `/compact`, et joint des
66
77 1. Dans la zone de message, tapez `/`. Une liste s'ouvre au-dessus.
88 2. Tapez les premières lettres de la commande pour réduire la liste.
9-3. Appuyez sur Tab pour prendre la première ligne, ou cliquez sur celle que vous voulez. La commande est complétée, suivie d'une espace.
9+3. Appuyez sur Tab pour prendre la ligne en surbrillance (la première, ou celle où les touches Haut et Bas vous ont amené), ou cliquez sur celle que vous voulez. La commande est complétée, suivie d'une espace.
1010 4. Tapez les arguments si l'indication de la ligne montre que la commande en prend, puis envoyez.
1111
1212 L'agent répond comme à n'importe quel message. Pour lancer une commande sur un agent précis, mentionnez-le devant : `@mini-me /new`.
@@ -15,13 +15,22 @@ L'agent répond comme à n'importe quel message. Pour lancer une commande sur un
1515
1616 1. Tapez `/file`, ou choisissez-le dans la liste qui s'ouvre quand vous tapez `/`.
1717 2. Tapez quelques lettres du nom du fichier ou de son dossier. La liste garde les fichiers qui correspondent.
18-3. Appuyez sur Tab pour prendre le premier, ou cliquez sur un autre. Il apparaît au-dessus de la zone de message.
18+3. Appuyez sur Tab pour prendre celui en surbrillance, ou cliquez sur un autre. Il apparaît au-dessus de la zone de message.
1919 4. Recommencez à l'étape 1 pour un autre fichier. Cliquez sur la croix à côté d'un fichier pour le retirer.
2020 5. Écrivez votre message, et envoyez.
2121
22+## Désigner un fichier au milieu d'une phrase
23+
24+1. Écrivez votre message, et là où le fichier a sa place tapez `$` suivi de quelques lettres de son nom : `@bob regarde $main`.
25+2. La liste des fichiers s'ouvre. Appuyez sur Tab pour prendre celui en surbrillance, ou cliquez sur un autre. Haut et Bas déplacent la surbrillance, et Entrée prend la ligne en surbrillance une fois que vous les avez utilisées.
26+3. Le chemin remplace ce que vous avez tapé, dans la phrase, et le fichier est joint : `@bob regarde src/main.rs `. Continuez à écrire.
27+
28+Le fichier apparaît aussi au-dessus de la zone de message, et sa croix retire la pièce jointe sans toucher à la phrase.
29+
2230 ## Variantes
2331
2432 - **La liste ne montre aucune commande de l'agent.** L'agent annonce ses commandes quand sa session pour ce channel est créée, donc après votre premier message. Envoyez d'abord un message.
33+- **Un `$` dans le texte ouvre une liste que vous ne vouliez pas.** Un `$` collé à un mot (`US$5`) n'ouvre rien. Sinon la liste se ferme dès que vous tapez une espace après ce qui suit le `$`.
2534 - **La liste ne montre aucun fichier.** Ce sont les fichiers du dossier de travail de l'agent, ou du dossier où Synedrion s'exécute. Déclarez l'agent avec un dossier de travail (voir [comment déclarer un agent](declarer-un-agent.md)).
2635 - **Mentionner un autre agent.** La liste suit les agents à qui irait le message : écrivez d'abord la mention, puis la barre oblique.
2736
@@ -6,7 +6,7 @@ Ce guide lance une commande d'un agent, comme `/new` ou `/compact`, et joint des
6 6
7 1. Dans la zone de message, tapez `/`. Une liste s'ouvre au-dessus.7 1. Dans la zone de message, tapez `/`. Une liste s'ouvre au-dessus.
8 2. Tapez les premières lettres de la commande pour réduire la liste.8 2. Tapez les premières lettres de la commande pour réduire la liste.
9-3. Appuyez sur Tab pour prendre la première ligne, ou cliquez sur celle que vous voulez. La commande est complétée, suivie d'une espace.9+3. Appuyez sur Tab pour prendre la ligne en surbrillance (la première, ou celle où les touches Haut et Bas vous ont amené), ou cliquez sur celle que vous voulez. La commande est complétée, suivie d'une espace.
10 4. Tapez les arguments si l'indication de la ligne montre que la commande en prend, puis envoyez.10 4. Tapez les arguments si l'indication de la ligne montre que la commande en prend, puis envoyez.
11 11
12 L'agent répond comme à n'importe quel message. Pour lancer une commande sur un agent précis, mentionnez-le devant : `@mini-me /new`.12 L'agent répond comme à n'importe quel message. Pour lancer une commande sur un agent précis, mentionnez-le devant : `@mini-me /new`.
@@ -15,13 +15,22 @@ L'agent répond comme à n'importe quel message. Pour lancer une commande sur un
15 15
16 1. Tapez `/file`, ou choisissez-le dans la liste qui s'ouvre quand vous tapez `/`.16 1. Tapez `/file`, ou choisissez-le dans la liste qui s'ouvre quand vous tapez `/`.
17 2. Tapez quelques lettres du nom du fichier ou de son dossier. La liste garde les fichiers qui correspondent.17 2. Tapez quelques lettres du nom du fichier ou de son dossier. La liste garde les fichiers qui correspondent.
18-3. Appuyez sur Tab pour prendre le premier, ou cliquez sur un autre. Il apparaît au-dessus de la zone de message.18+3. Appuyez sur Tab pour prendre celui en surbrillance, ou cliquez sur un autre. Il apparaît au-dessus de la zone de message.
19 4. Recommencez à l'étape 1 pour un autre fichier. Cliquez sur la croix à côté d'un fichier pour le retirer.19 4. Recommencez à l'étape 1 pour un autre fichier. Cliquez sur la croix à côté d'un fichier pour le retirer.
20 5. Écrivez votre message, et envoyez.20 5. Écrivez votre message, et envoyez.
21 21
22+## Désigner un fichier au milieu d'une phrase
23+
24+1. Écrivez votre message, et là où le fichier a sa place tapez `$` suivi de quelques lettres de son nom : `@bob regarde $main`.
25+2. La liste des fichiers s'ouvre. Appuyez sur Tab pour prendre celui en surbrillance, ou cliquez sur un autre. Haut et Bas déplacent la surbrillance, et Entrée prend la ligne en surbrillance une fois que vous les avez utilisées.
26+3. Le chemin remplace ce que vous avez tapé, dans la phrase, et le fichier est joint : `@bob regarde src/main.rs `. Continuez à écrire.
27+
28+Le fichier apparaît aussi au-dessus de la zone de message, et sa croix retire la pièce jointe sans toucher à la phrase.
29+
22 ## Variantes30 ## Variantes
23 31
24 - **La liste ne montre aucune commande de l'agent.** L'agent annonce ses commandes quand sa session pour ce channel est créée, donc après votre premier message. Envoyez d'abord un message.32 - **La liste ne montre aucune commande de l'agent.** L'agent annonce ses commandes quand sa session pour ce channel est créée, donc après votre premier message. Envoyez d'abord un message.
33+- **Un `$` dans le texte ouvre une liste que vous ne vouliez pas.** Un `$` collé à un mot (`US$5`) n'ouvre rien. Sinon la liste se ferme dès que vous tapez une espace après ce qui suit le `$`.
25 - **La liste ne montre aucun fichier.** Ce sont les fichiers du dossier de travail de l'agent, ou du dossier où Synedrion s'exécute. Déclarez l'agent avec un dossier de travail (voir [comment déclarer un agent](declarer-un-agent.md)).34 - **La liste ne montre aucun fichier.** Ce sont les fichiers du dossier de travail de l'agent, ou du dossier où Synedrion s'exécute. Déclarez l'agent avec un dossier de travail (voir [comment déclarer un agent](declarer-un-agent.md)).
26 - **Mentionner un autre agent.** La liste suit les agents à qui irait le message : écrivez d'abord la mention, puis la barre oblique.35 - **Mentionner un autre agent.** La liste suit les agents à qui irait le message : écrivez d'abord la mention, puis la barre oblique.
27 36
modified docs/fr/reference/agent-de-test.md +1 -0
@@ -33,6 +33,7 @@ Le comportement est choisi par un mot-clé : le premier mot du prompt qui n'est
3333 | `ask` | Demande la permission de « Delete the build folder », avec les options `allow` (« Allow ») et `reject` (« Reject »), puis dit `permission granted`, `permission rejected` ou `permission cancelled`, et termine le tour normalement. |
3434 | `slow` | Dit `working` et attend que le tour soit annulé, puis le termine comme annulé. |
3535 | `think` | Envoie trois morceaux de raisonnement (`pondering the question `), puis répond `done`. |
36+| `tools` | Envoie un plan de deux étapes, un appel d'outil `Read notes.md` (genre `read`, en cours), puis une mise à jour qui le termine avec la sortie `the notes`, puis répond `tools done`. |
3637 | `/new` | Dit `fresh start`. |
3738 | `/greet Bob` | Dit `hello Bob`. |
3839 | autre chose | Répète le prompt mot à mot, un morceau par mot, puis termine le tour normalement. |
@@ -33,6 +33,7 @@ Le comportement est choisi par un mot-clé : le premier mot du prompt qui n'est
33 | `ask` | Demande la permission de « Delete the build folder », avec les options `allow` (« Allow ») et `reject` (« Reject »), puis dit `permission granted`, `permission rejected` ou `permission cancelled`, et termine le tour normalement. |33 | `ask` | Demande la permission de « Delete the build folder », avec les options `allow` (« Allow ») et `reject` (« Reject »), puis dit `permission granted`, `permission rejected` ou `permission cancelled`, et termine le tour normalement. |
34 | `slow` | Dit `working` et attend que le tour soit annulé, puis le termine comme annulé. |34 | `slow` | Dit `working` et attend que le tour soit annulé, puis le termine comme annulé. |
35 | `think` | Envoie trois morceaux de raisonnement (`pondering the question `), puis répond `done`. |35 | `think` | Envoie trois morceaux de raisonnement (`pondering the question `), puis répond `done`. |
36+| `tools` | Envoie un plan de deux étapes, un appel d'outil `Read notes.md` (genre `read`, en cours), puis une mise à jour qui le termine avec la sortie `the notes`, puis répond `tools done`. |
36 | `/new` | Dit `fresh start`. |37 | `/new` | Dit `fresh start`. |
37 | `/greet Bob` | Dit `hello Bob`. |38 | `/greet Bob` | Dit `hello Bob`. |
38 | autre chose | Répète le prompt mot à mot, un morceau par mot, puis termine le tour normalement. |39 | autre chose | Répète le prompt mot à mot, un morceau par mot, puis termine le tour normalement. |
added docs/fr/reference/appels-d-outils-et-plans.md +65 -0
new file mode 100644
@@ -0,0 +1,65 @@
1+# Référence : appels d'outils, plans, et ce qui ne peut pas être montré
2+
3+Un agent peut faire plus qu'écrire : il annonce les outils qu'il appelle et le plan qu'il suit. Synedrion les garde dans le channel, à côté des messages, sous forme de **traces**, pour que l'historique montre comment une réponse est née.
4+
5+## Appels d'outils
6+
7+Un appel d'outil est une carte dans la conversation, écrite par l'agent qui l'a fait.
8+
9+| Partie | Ce qu'elle montre |
10+| --- | --- |
11+| Titre | Ce que fait l'outil, comme l'agent le dit. |
12+| Genre | La catégorie donnée par l'agent : `read`, `edit`, `delete`, `move`, `search`, `execute`, `think`, `fetch`, `switch_mode`, ou `other`. |
13+| État | `waiting`, `running`, `done` ou `failed`. `failed` prend la couleur d'erreur du thème. |
14+| Sortie | Repliée au départ. **Show output** la déplie, en police à chasse fixe, et **Hide output** la replie. Le bouton n'existe que s'il y a une sortie. Les cartes dépliées ne sont pas retenues quand Synedrion redémarre. |
15+
16+Une mise à jour de l'agent modifie la même carte. Elle ne porte que ce qui a changé : son état, son titre, son genre, et sa sortie, qui remplace la précédente. Une mise à jour d'un appel jamais annoncé crée une carte intitulée `Tool call`, pour que rien ne soit perdu. Annoncer de nouveau le même appel modifie sa carte au lieu d'en ajouter une. Un appel est oublié à la fin du tour, donc le tour suivant peut réutiliser un identifiant.
17+
18+La sortie conservée fait au plus 4 000 caractères, et se termine par `[output cut: N more character(s)]` quand elle était plus longue.
19+
20+## Plans
21+
22+Le plan d'un agent est une carte, remplacée chaque fois que l'agent en envoie une nouvelle version. Chaque étape est une ligne précédée d'un signe : `[ ]` en attente, `[~]` en cours, `[x]` faite, `[!]` échouée.
23+
24+## Ordre dans le channel
25+
26+Ce que l'agent écrit après un appel d'outil ou un plan va dans un nouveau message après la carte, comme cela s'est passé. Les messages d'une réponse peuvent donc être plusieurs, avec des cartes entre eux.
27+
28+## Ce qui ne peut pas être dessiné
29+
30+Rien de ce qu'un agent envoie pour que l'utilisateur le lise n'est abandonné sans trace. Ce qui ne peut pas être dessiné apparaît sous la forme d'un court texte entre crochets.
31+
32+| L'agent envoie | C'est montré comme |
33+| --- | --- |
34+| Une image, dans sa réponse ou dans la sortie d'un outil | `[image: not displayed]` |
35+| Du son | `[audio: not displayed]` |
36+| Un lien vers une ressource | `[link: ` l'adresse `]` |
37+| Une ressource texte incluse dans le contenu | Son texte |
38+| Une ressource binaire | `[binary resource: ` l'adresse `]` |
39+| Une modification de fichier | `Changes to ` le chemin `:`, puis les anciennes lignes chacune après `- ` et les nouvelles chacune après `+ `. Un fichier qui n'existait pas : `New file ` le chemin `:` et son texte. |
40+| Un terminal | `[terminal ` l'identifiant `: its output is not displayed]` |
41+| Un appel d'outil sans contenu mais avec une sortie brute | La sortie brute : une chaîne telle quelle, tout autre chose en JSON compact. |
42+| Une notice (mise à jour `Notice`) | Une notice de Synedrion dans le channel : `@nom: titre: détail`. |
43+| Une mise à jour d'un genre que cette version ne connaît pas | Une notice : `@nom: The agent sent an update that this version of Synedrion cannot show.` |
44+
45+Ces mises à jour ne portent rien pour l'utilisateur et ne montrent rien : les chiffres d'utilisation, le mode courant, les options de configuration, le titre de la session, le compactage du contexte, et l'écho du message de l'utilisateur lui-même. La liste des commandes alimente plutôt la liste de `/`.
46+
47+## Comment une trace est stockée
48+
49+Une trace est un message dont le genre d'auteur est `trace` et dont le nom d'auteur est l'agent. Son contenu est du texte simple : une première ligne qui dit ce que c'est, puis les détails.
50+
51+| Genre | Contenu |
52+| --- | --- |
53+| Appel d'outil | `tool`, une tabulation, le mot d'état (`pending`, `in_progress`, `completed`, `failed`), une tabulation, l'identifiant, une tabulation, le genre, une tabulation, le titre ; puis un saut de ligne et la sortie. Les sauts de ligne et tabulations dans l'identifiant, le genre et le titre deviennent des espaces. |
54+| Plan | `plan` ; puis une ligne par étape : le mot d'état, une tabulation, le texte. |
55+
56+Un message de trace qu'on ne peut pas relire est dessiné comme le texte qu'il contient. Les traces ne sont pas transmises aux autres agents comme [contexte](contexte-du-channel.md), et ne changent pas à qui va un message sans mention.
57+
58+## Ce qui a été vérifié
59+
60+La traduction de chaque genre de mise à jour, le stockage et le contrôleur sont couverts par des tests automatisés, et tout le chemin d'un processus d'agent jusqu'au channel a été exécuté avec l'agent de test. Les cartes n'ont jamais été vues sur un écran, et aucun vrai agent n'a été essayé : savoir si un agent donné envoie ces mises à jour, et comment, relève de lui.
61+
62+## Voir aussi
63+
64+- Les messages autour des cartes : [comment les messages sont dessinés](rendu-des-messages.md)
65+- Le côté protocole : [méthodes ACP](methodes-acp.md)
new file mode 100644
@@ -0,0 +1,65 @@
1+# Référence : appels d'outils, plans, et ce qui ne peut pas être montré
2+
3+Un agent peut faire plus qu'écrire : il annonce les outils qu'il appelle et le plan qu'il suit. Synedrion les garde dans le channel, à côté des messages, sous forme de **traces**, pour que l'historique montre comment une réponse est née.
4+
5+## Appels d'outils
6+
7+Un appel d'outil est une carte dans la conversation, écrite par l'agent qui l'a fait.
8+
9+| Partie | Ce qu'elle montre |
10+| --- | --- |
11+| Titre | Ce que fait l'outil, comme l'agent le dit. |
12+| Genre | La catégorie donnée par l'agent : `read`, `edit`, `delete`, `move`, `search`, `execute`, `think`, `fetch`, `switch_mode`, ou `other`. |
13+| État | `waiting`, `running`, `done` ou `failed`. `failed` prend la couleur d'erreur du thème. |
14+| Sortie | Repliée au départ. **Show output** la déplie, en police à chasse fixe, et **Hide output** la replie. Le bouton n'existe que s'il y a une sortie. Les cartes dépliées ne sont pas retenues quand Synedrion redémarre. |
15+
16+Une mise à jour de l'agent modifie la même carte. Elle ne porte que ce qui a changé : son état, son titre, son genre, et sa sortie, qui remplace la précédente. Une mise à jour d'un appel jamais annoncé crée une carte intitulée `Tool call`, pour que rien ne soit perdu. Annoncer de nouveau le même appel modifie sa carte au lieu d'en ajouter une. Un appel est oublié à la fin du tour, donc le tour suivant peut réutiliser un identifiant.
17+
18+La sortie conservée fait au plus 4 000 caractères, et se termine par `[output cut: N more character(s)]` quand elle était plus longue.
19+
20+## Plans
21+
22+Le plan d'un agent est une carte, remplacée chaque fois que l'agent en envoie une nouvelle version. Chaque étape est une ligne précédée d'un signe : `[ ]` en attente, `[~]` en cours, `[x]` faite, `[!]` échouée.
23+
24+## Ordre dans le channel
25+
26+Ce que l'agent écrit après un appel d'outil ou un plan va dans un nouveau message après la carte, comme cela s'est passé. Les messages d'une réponse peuvent donc être plusieurs, avec des cartes entre eux.
27+
28+## Ce qui ne peut pas être dessiné
29+
30+Rien de ce qu'un agent envoie pour que l'utilisateur le lise n'est abandonné sans trace. Ce qui ne peut pas être dessiné apparaît sous la forme d'un court texte entre crochets.
31+
32+| L'agent envoie | C'est montré comme |
33+| --- | --- |
34+| Une image, dans sa réponse ou dans la sortie d'un outil | `[image: not displayed]` |
35+| Du son | `[audio: not displayed]` |
36+| Un lien vers une ressource | `[link: ` l'adresse `]` |
37+| Une ressource texte incluse dans le contenu | Son texte |
38+| Une ressource binaire | `[binary resource: ` l'adresse `]` |
39+| Une modification de fichier | `Changes to ` le chemin `:`, puis les anciennes lignes chacune après `- ` et les nouvelles chacune après `+ `. Un fichier qui n'existait pas : `New file ` le chemin `:` et son texte. |
40+| Un terminal | `[terminal ` l'identifiant `: its output is not displayed]` |
41+| Un appel d'outil sans contenu mais avec une sortie brute | La sortie brute : une chaîne telle quelle, tout autre chose en JSON compact. |
42+| Une notice (mise à jour `Notice`) | Une notice de Synedrion dans le channel : `@nom: titre: détail`. |
43+| Une mise à jour d'un genre que cette version ne connaît pas | Une notice : `@nom: The agent sent an update that this version of Synedrion cannot show.` |
44+
45+Ces mises à jour ne portent rien pour l'utilisateur et ne montrent rien : les chiffres d'utilisation, le mode courant, les options de configuration, le titre de la session, le compactage du contexte, et l'écho du message de l'utilisateur lui-même. La liste des commandes alimente plutôt la liste de `/`.
46+
47+## Comment une trace est stockée
48+
49+Une trace est un message dont le genre d'auteur est `trace` et dont le nom d'auteur est l'agent. Son contenu est du texte simple : une première ligne qui dit ce que c'est, puis les détails.
50+
51+| Genre | Contenu |
52+| --- | --- |
53+| Appel d'outil | `tool`, une tabulation, le mot d'état (`pending`, `in_progress`, `completed`, `failed`), une tabulation, l'identifiant, une tabulation, le genre, une tabulation, le titre ; puis un saut de ligne et la sortie. Les sauts de ligne et tabulations dans l'identifiant, le genre et le titre deviennent des espaces. |
54+| Plan | `plan` ; puis une ligne par étape : le mot d'état, une tabulation, le texte. |
55+
56+Un message de trace qu'on ne peut pas relire est dessiné comme le texte qu'il contient. Les traces ne sont pas transmises aux autres agents comme [contexte](contexte-du-channel.md), et ne changent pas à qui va un message sans mention.
57+
58+## Ce qui a été vérifié
59+
60+La traduction de chaque genre de mise à jour, le stockage et le contrôleur sont couverts par des tests automatisés, et tout le chemin d'un processus d'agent jusqu'au channel a été exécuté avec l'agent de test. Les cartes n'ont jamais été vues sur un écran, et aucun vrai agent n'a été essayé : savoir si un agent donné envoie ces mises à jour, et comment, relève de lui.
61+
62+## Voir aussi
63+
64+- Les messages autour des cartes : [comment les messages sont dessinés](rendu-des-messages.md)
65+- Le côté protocole : [méthodes ACP](methodes-acp.md)
modified docs/fr/reference/base-de-donnees.md +20 -3
@@ -12,7 +12,7 @@ Synedrion garde tout dans un seul fichier SQLite, ouvert avec `rusqlite`, SQLite
1212
1313 Le dossier est créé s'il manque. L'application refuse de démarrer si aucune des variables nécessaires n'est définie. Seule l'organisation Linux a été exécutée ; les chemins macOS et Windows ne sont couverts que par les tests unitaires des règles de chemin.
1414
15-## Schéma (version 1)
15+## Schéma (version 3)
1616
1717 Les noms sont comparés sans tenir compte de la casse (`COLLATE NOCASE`). Les clés étrangères sont appliquées.
1818
@@ -46,17 +46,34 @@ Les noms sont comparés sans tenir compte de la casse (`COLLATE NOCASE`). Les cl
4646 | --- | --- | --- |
4747 | `id` | entier | Clé primaire, auto-incrément. |
4848 | `channel_id` | entier | Référence `channel(id)`, supprimé avec le channel. |
49-| `author_kind` | texte | `user`, `agent` ou `system`. |
50-| `author_name` | texte | Le nom de l'agent pour un agent, nul sinon. Pas une référence : les messages restent quand un agent est supprimé. |
49+| `author_kind` | texte | `user`, `agent`, `system` ou `trace`. |
50+| `author_name` | texte | Le nom de l'agent pour un agent ou une trace, nul sinon. Pas une référence : les messages restent quand un agent est supprimé. |
5151 | `content` | texte | Texte Markdown. Il grandit pendant la réception de la réponse d'un agent. |
5252 | `created_at_ms` | entier | Millisecondes depuis le 1er janvier 1970 UTC. |
5353
5454 Un index sur `(channel_id, id)` sert à « les derniers messages d'un channel ».
5555
56+Un message de genre `trace` contient ce qu'un agent a fait en plus d'écrire, sous forme de texte simple : voir [appels d'outils, plans, et ce qui ne peut pas être montré](appels-d-outils-et-plans.md).
57+
58+### `setting`
59+
60+| Colonne | Type | Notes |
61+| --- | --- | --- |
62+| `key` | texte | Clé primaire : `context_messages` ou `chain_depth`. |
63+| `value` | texte | Un nombre entier, écrit sous forme de texte. |
64+
65+Voir les [réglages](reglages.md).
66+
5667 ## Migrations
5768
5869 La version du schéma est le `user_version` de SQLite. Les migrations s'exécutent au démarrage, dans l'ordre, chacune dans une transaction. Un fichier dont la version est supérieure à celle que connaît l'application est refusé plutôt que modifié.
5970
71+| Version | Ce qu'elle ajoute |
72+| --- | --- |
73+| 1 | L'utilisateur, les agents, les channels et les messages. |
74+| 2 | La table `setting`. |
75+| 3 | Le genre d'auteur `trace`. SQLite ne sait pas modifier un `CHECK`, la table `message` est donc reconstruite et ses lignes copiées, avec leurs identifiants, pour que le compteur continue après elles. Un test vérifie que les messages d'un fichier de version 1 survivent. |
76+
6077 ## Voir aussi
6178
6279 - L'interface que voit le reste de l'application : le trait `Repository` de la crate `synedrion-domain`.
@@ -12,7 +12,7 @@ Synedrion garde tout dans un seul fichier SQLite, ouvert avec `rusqlite`, SQLite
12 12
13 Le dossier est créé s'il manque. L'application refuse de démarrer si aucune des variables nécessaires n'est définie. Seule l'organisation Linux a été exécutée ; les chemins macOS et Windows ne sont couverts que par les tests unitaires des règles de chemin.13 Le dossier est créé s'il manque. L'application refuse de démarrer si aucune des variables nécessaires n'est définie. Seule l'organisation Linux a été exécutée ; les chemins macOS et Windows ne sont couverts que par les tests unitaires des règles de chemin.
14 14
15-## Schéma (version 1)15+## Schéma (version 3)
16 16
17 Les noms sont comparés sans tenir compte de la casse (`COLLATE NOCASE`). Les clés étrangères sont appliquées.17 Les noms sont comparés sans tenir compte de la casse (`COLLATE NOCASE`). Les clés étrangères sont appliquées.
18 18
@@ -46,17 +46,34 @@ Les noms sont comparés sans tenir compte de la casse (`COLLATE NOCASE`). Les cl
46 | --- | --- | --- |46 | --- | --- | --- |
47 | `id` | entier | Clé primaire, auto-incrément. |47 | `id` | entier | Clé primaire, auto-incrément. |
48 | `channel_id` | entier | Référence `channel(id)`, supprimé avec le channel. |48 | `channel_id` | entier | Référence `channel(id)`, supprimé avec le channel. |
49-| `author_kind` | texte | `user`, `agent` ou `system`. |49+| `author_kind` | texte | `user`, `agent`, `system` ou `trace`. |
50-| `author_name` | texte | Le nom de l'agent pour un agent, nul sinon. Pas une référence : les messages restent quand un agent est supprimé. |50+| `author_name` | texte | Le nom de l'agent pour un agent ou une trace, nul sinon. Pas une référence : les messages restent quand un agent est supprimé. |
51 | `content` | texte | Texte Markdown. Il grandit pendant la réception de la réponse d'un agent. |51 | `content` | texte | Texte Markdown. Il grandit pendant la réception de la réponse d'un agent. |
52 | `created_at_ms` | entier | Millisecondes depuis le 1er janvier 1970 UTC. |52 | `created_at_ms` | entier | Millisecondes depuis le 1er janvier 1970 UTC. |
53 53
54 Un index sur `(channel_id, id)` sert à « les derniers messages d'un channel ».54 Un index sur `(channel_id, id)` sert à « les derniers messages d'un channel ».
55 55
56+Un message de genre `trace` contient ce qu'un agent a fait en plus d'écrire, sous forme de texte simple : voir [appels d'outils, plans, et ce qui ne peut pas être montré](appels-d-outils-et-plans.md).
57+
58+### `setting`
59+
60+| Colonne | Type | Notes |
61+| --- | --- | --- |
62+| `key` | texte | Clé primaire : `context_messages` ou `chain_depth`. |
63+| `value` | texte | Un nombre entier, écrit sous forme de texte. |
64+
65+Voir les [réglages](reglages.md).
66+
56 ## Migrations67 ## Migrations
57 68
58 La version du schéma est le `user_version` de SQLite. Les migrations s'exécutent au démarrage, dans l'ordre, chacune dans une transaction. Un fichier dont la version est supérieure à celle que connaît l'application est refusé plutôt que modifié.69 La version du schéma est le `user_version` de SQLite. Les migrations s'exécutent au démarrage, dans l'ordre, chacune dans une transaction. Un fichier dont la version est supérieure à celle que connaît l'application est refusé plutôt que modifié.
59 70
71+| Version | Ce qu'elle ajoute |
72+| --- | --- |
73+| 1 | L'utilisateur, les agents, les channels et les messages. |
74+| 2 | La table `setting`. |
75+| 3 | Le genre d'auteur `trace`. SQLite ne sait pas modifier un `CHECK`, la table `message` est donc reconstruite et ses lignes copiées, avec leurs identifiants, pour que le compteur continue après elles. Un test vérifie que les messages d'un fichier de version 1 survivent. |
76+
60 ## Voir aussi77 ## Voir aussi
61 78
62 - L'interface que voit le reste de l'application : le trait `Repository` de la crate `synedrion-domain`.79 - L'interface que voit le reste de l'application : le trait `Repository` de la crate `synedrion-domain`.
modified docs/fr/reference/commandes-et-fichiers.md +30 -1
@@ -2,6 +2,20 @@
22
33 Un message qui commence par `/` est une commande. Des mentions devant sont permises : `@mini-me /compact`.
44
5+## Le clavier dans les listes
6+
7+La liste au-dessus de la zone de message est la même pour les agents (après `@`), les commandes (après `/`) et les fichiers (après `/file` ou `$`). Tant qu'elle est ouverte et que la zone de message a le focus :
8+
9+| Touche | Effet |
10+| --- | --- |
11+| Bas, Haut | Déplace la surbrillance d'une ligne vers le bas ou le haut, et boucle aux deux bouts. La ligne en surbrillance est celle que prend Tab. Au départ, c'est la première. |
12+| Tab | Prend la ligne en surbrillance. |
13+| Entrée | Prend la ligne en surbrillance, mais seulement une fois que les flèches ont déplacé la surbrillance. Avant cela, Entrée envoie le message, comme avant. |
14+| Échap | Ferme la liste et garde le texte. La liste se rouvre quand on continue à taper. |
15+| Toute autre touche | Est saisie comme d'habitude, et remet la surbrillance sur la première ligne. |
16+
17+Une touche combinée à un modificateur (Maj, Contrôle, Alt, Commande) est laissée de côté, sauf que Maj+Tab continue de déplacer le focus. Quand aucune liste n'est ouverte, les flèches, Tab, Entrée et Échap font ce qu'ils ont toujours fait.
18+
519 ## Commandes des agents
620
721 Un agent annonce les commandes qu'il comprend (et les skills qu'il offre comme commandes) quand une session est créée pour lui dans un channel, et peut les annoncer de nouveau plus tard. Synedrion garde la dernière annonce de chaque agent. mini-me, par exemple, annonce `compact`, `new` et `unload`.
@@ -10,7 +24,7 @@ Un agent annonce les commandes qu'il comprend (et les skills qu'il offre comme c
1024 | --- | --- |
1125 | `/` | Une liste s'ouvre au-dessus de la zone de message avec les commandes des agents à qui irait le message, et `/file`. |
1226 | `/co` | La liste garde les commandes dont le nom commence par ces lettres, sans tenir compte de la casse. |
13-| Tab, ou un clic sur une ligne | Complète la commande avec la première ligne (Tab) ou la ligne cliquée, suivie d'une espace. |
27+| Tab, ou un clic sur une ligne | Complète la commande avec la ligne en surbrillance (Tab) ou la ligne cliquée, suivie d'une espace. |
1428
1529 Les agents à qui irait un message sont ceux qu'il mentionne ou, s'il ne mentionne personne, ceux que l'utilisateur a désignés en dernier (voir les [mentions](mentions.md)). Une commande que deux d'entre eux annoncent n'est listée qu'une fois. Chaque ligne montre le nom, puis l'indication de ce que la commande attend (entre chevrons) et sa description.
1630
@@ -47,6 +61,21 @@ Le dossier est le dossier de travail du premier agent à qui irait le message, o
4761 | Envoyer des fichiers sans texte | Rien n'est envoyé, et une notice demande un message. Les fichiers restent joints. |
4862 | Le même fichier choisi deux fois | Il n'est joint qu'une fois. |
4963
64+## `$` : désigner un fichier dans une phrase
65+
66+`$` suivi du début d'un nom, n'importe où dans le texte, ouvre la même liste de fichiers que `/file`, dans le même dossier et avec les mêmes règles (correspondance, ordre, 8 lignes, fichiers écartés).
67+
68+| Cas | Effet |
69+| --- | --- |
70+| Le texte se termine par `$` et quelques caractères sans espace | La liste montre les fichiers qui correspondent. `$` seul les liste tous. |
71+| Tab, ou un clic sur une ligne | Le `$` et ce qui suit sont remplacés par le chemin du fichier relatif au dossier, suivi d'une espace, et le fichier est joint comme avec `/file`. |
72+| Une espace tapée après les caractères | La référence est complète et la liste se ferme. |
73+| `$` collé à un mot ou à un autre `$` (`US$5`, `a_$b`) | Pas une référence : rien ne s'ouvre. |
74+| Plusieurs `$` dans le texte | Seul le dernier, en cours de frappe à la fin, compte. |
75+| Envoi alors qu'un `$` est inachevé | Le texte est envoyé tel que saisi : rien n'est refusé. |
76+
77+Un fichier désigné dans la phrase est joint, donc l'agent reçoit le lien en plus du chemin. Le message enregistré dans le channel n'ajoute sa ligne `[attached: chemin]` que pour les fichiers joints que son texte ne nomme pas déjà.
78+
5079 ### Les liens
5180
5281 Chaque fichier est envoyé comme un `resource_link` ACP : son nom, et son adresse, `file://` suivi du chemin tel qu'écrit, sans encodage en pourcentage. mini-me retire le préfixe et utilise ce qui suit comme chemin, et met `[attached file: chemin]` dans ce que lit son modèle.
@@ -2,6 +2,20 @@
2 2
3 Un message qui commence par `/` est une commande. Des mentions devant sont permises : `@mini-me /compact`.3 Un message qui commence par `/` est une commande. Des mentions devant sont permises : `@mini-me /compact`.
4 4
5+## Le clavier dans les listes
6+
7+La liste au-dessus de la zone de message est la même pour les agents (après `@`), les commandes (après `/`) et les fichiers (après `/file` ou `$`). Tant qu'elle est ouverte et que la zone de message a le focus :
8+
9+| Touche | Effet |
10+| --- | --- |
11+| Bas, Haut | Déplace la surbrillance d'une ligne vers le bas ou le haut, et boucle aux deux bouts. La ligne en surbrillance est celle que prend Tab. Au départ, c'est la première. |
12+| Tab | Prend la ligne en surbrillance. |
13+| Entrée | Prend la ligne en surbrillance, mais seulement une fois que les flèches ont déplacé la surbrillance. Avant cela, Entrée envoie le message, comme avant. |
14+| Échap | Ferme la liste et garde le texte. La liste se rouvre quand on continue à taper. |
15+| Toute autre touche | Est saisie comme d'habitude, et remet la surbrillance sur la première ligne. |
16+
17+Une touche combinée à un modificateur (Maj, Contrôle, Alt, Commande) est laissée de côté, sauf que Maj+Tab continue de déplacer le focus. Quand aucune liste n'est ouverte, les flèches, Tab, Entrée et Échap font ce qu'ils ont toujours fait.
18+
5 ## Commandes des agents19 ## Commandes des agents
6 20
7 Un agent annonce les commandes qu'il comprend (et les skills qu'il offre comme commandes) quand une session est créée pour lui dans un channel, et peut les annoncer de nouveau plus tard. Synedrion garde la dernière annonce de chaque agent. mini-me, par exemple, annonce `compact`, `new` et `unload`.21 Un agent annonce les commandes qu'il comprend (et les skills qu'il offre comme commandes) quand une session est créée pour lui dans un channel, et peut les annoncer de nouveau plus tard. Synedrion garde la dernière annonce de chaque agent. mini-me, par exemple, annonce `compact`, `new` et `unload`.
@@ -10,7 +24,7 @@ Un agent annonce les commandes qu'il comprend (et les skills qu'il offre comme c
10 | --- | --- |24 | --- | --- |
11 | `/` | Une liste s'ouvre au-dessus de la zone de message avec les commandes des agents à qui irait le message, et `/file`. |25 | `/` | Une liste s'ouvre au-dessus de la zone de message avec les commandes des agents à qui irait le message, et `/file`. |
12 | `/co` | La liste garde les commandes dont le nom commence par ces lettres, sans tenir compte de la casse. |26 | `/co` | La liste garde les commandes dont le nom commence par ces lettres, sans tenir compte de la casse. |
13-| Tab, ou un clic sur une ligne | Complète la commande avec la première ligne (Tab) ou la ligne cliquée, suivie d'une espace. |27+| Tab, ou un clic sur une ligne | Complète la commande avec la ligne en surbrillance (Tab) ou la ligne cliquée, suivie d'une espace. |
14 28
15 Les agents à qui irait un message sont ceux qu'il mentionne ou, s'il ne mentionne personne, ceux que l'utilisateur a désignés en dernier (voir les [mentions](mentions.md)). Une commande que deux d'entre eux annoncent n'est listée qu'une fois. Chaque ligne montre le nom, puis l'indication de ce que la commande attend (entre chevrons) et sa description.29 Les agents à qui irait un message sont ceux qu'il mentionne ou, s'il ne mentionne personne, ceux que l'utilisateur a désignés en dernier (voir les [mentions](mentions.md)). Une commande que deux d'entre eux annoncent n'est listée qu'une fois. Chaque ligne montre le nom, puis l'indication de ce que la commande attend (entre chevrons) et sa description.
16 30
@@ -47,6 +61,21 @@ Le dossier est le dossier de travail du premier agent à qui irait le message, o
47 | Envoyer des fichiers sans texte | Rien n'est envoyé, et une notice demande un message. Les fichiers restent joints. |61 | Envoyer des fichiers sans texte | Rien n'est envoyé, et une notice demande un message. Les fichiers restent joints. |
48 | Le même fichier choisi deux fois | Il n'est joint qu'une fois. |62 | Le même fichier choisi deux fois | Il n'est joint qu'une fois. |
49 63
64+## `$` : désigner un fichier dans une phrase
65+
66+`$` suivi du début d'un nom, n'importe où dans le texte, ouvre la même liste de fichiers que `/file`, dans le même dossier et avec les mêmes règles (correspondance, ordre, 8 lignes, fichiers écartés).
67+
68+| Cas | Effet |
69+| --- | --- |
70+| Le texte se termine par `$` et quelques caractères sans espace | La liste montre les fichiers qui correspondent. `$` seul les liste tous. |
71+| Tab, ou un clic sur une ligne | Le `$` et ce qui suit sont remplacés par le chemin du fichier relatif au dossier, suivi d'une espace, et le fichier est joint comme avec `/file`. |
72+| Une espace tapée après les caractères | La référence est complète et la liste se ferme. |
73+| `$` collé à un mot ou à un autre `$` (`US$5`, `a_$b`) | Pas une référence : rien ne s'ouvre. |
74+| Plusieurs `$` dans le texte | Seul le dernier, en cours de frappe à la fin, compte. |
75+| Envoi alors qu'un `$` est inachevé | Le texte est envoyé tel que saisi : rien n'est refusé. |
76+
77+Un fichier désigné dans la phrase est joint, donc l'agent reçoit le lien en plus du chemin. Le message enregistré dans le channel n'ajoute sa ligne `[attached: chemin]` que pour les fichiers joints que son texte ne nomme pas déjà.
78+
50 ### Les liens79 ### Les liens
51 80
52 Chaque fichier est envoyé comme un `resource_link` ACP : son nom, et son adresse, `file://` suivi du chemin tel qu'écrit, sans encodage en pourcentage. mini-me retire le préfixe et utilise ce qui suit comme chemin, et met `[attached file: chemin]` dans ce que lit son modèle.81 Chaque fichier est envoyé comme un `resource_link` ACP : son nom, et son adresse, `file://` suivi du chemin tel qu'écrit, sans encodage en pourcentage. mini-me retire le préfixe et utilise ce qui suit comme chemin, et met `[attached file: chemin]` dans ce que lit son modèle.
added docs/fr/reference/contexte-du-channel.md +60 -0
new file mode 100644
@@ -0,0 +1,60 @@
1+# Référence : le contexte du channel
2+
3+Un agent garde sa propre conversation, il sait donc déjà ce que l'utilisateur et lui se sont dit. Ce qu'il ne peut pas savoir, c'est ce qui s'est dit autour de lui. Le texte qu'il reçoit commence donc par les messages qu'il n'a pas encore vus, puis vient le message lui-même.
4+
5+## Ce qu'on dit à un agent
6+
7+Pour un agent et un channel, les messages transmis sont ceux du channel qui respectent toutes ces règles :
8+
9+| Règle | Détail |
10+| --- | --- |
11+| Pas encore vu | Posté après le dernier message remis à l'agent dans ce channel. Avant son premier tour dans le channel, tous les messages précédents comptent. |
12+| Pas les siens | Les messages écrits par l'agent lui-même sont omis, quelle que soit la casse de son nom : il sait ce qu'il a dit. |
13+| Conversation seulement | Les notices de Synedrion (comme `Could not reach @bob`) et les [traces](appels-d-outils-et-plans.md) (appels d'outils et plans) sont omises. |
14+| Pas trop | Au plus `Messages of context` d'entre eux, les plus récents. Les plus anciens sont comptés. Voir les [réglages](reglages.md). |
15+
16+Environ 200 messages précédents du channel sont regardés. Un message de l'utilisateur est signé de son nom d'affichage, un message d'agent de son nom.
17+
18+## Le texte envoyé
19+
20+| Cas | L'agent reçoit |
21+| --- | --- |
22+| Rien à dire, message de l'utilisateur | Le message exactement comme saisi. |
23+| Quelque chose à dire, message de l'utilisateur | Le contexte, une ligne vide, puis le message comme saisi. |
24+| Message d'un autre agent (un agent qui l'appelle) | Le contexte s'il y en a, une ligne vide, puis `[Message from @nom]`, un saut de ligne, et la réponse entière de cet agent. |
25+| Une commande `/` qu'il comprend | La commande seule, sans contexte : un agent ne reconnaît une commande qu'au tout début. Voir les [commandes et fichiers joints](commandes-et-fichiers.md). |
26+
27+Le contexte a cette forme :
28+
29+```text
30+[Channel context: what was said since your last turn]
31+[3 earlier message(s) not shown]
32+Ada: the build is red
33+amy: I will look at the logs
34+[End of channel context]
35+
36+@bob can you check too?
37+```
38+
39+La ligne `[N earlier message(s) not shown]` n'apparaît que lorsque certains messages ont été laissés de côté.
40+
41+## Limites
42+
43+| Limite | Valeur | Quand elle est atteinte |
44+| --- | --- | --- |
45+| Un message précédent | 2 000 caractères | Le message est coupé, et se termine par `[message cut: N more character(s)]`. |
46+| Le contexte entier | 12 000 caractères | Les plus anciens messages sont retirés, jusqu'à ce que cela tienne, et comptés dans `[N earlier message(s) not shown]`. |
47+| Le message qui appelle l'agent | Aucune | Il est remis en entier. |
48+
49+On compte des caractères, pas des octets, et un caractère n'est jamais coupé en deux.
50+
51+## Ce qui n'est pas couvert
52+
53+- Le relevé de ce qui a été remis à chaque agent est gardé tant que Synedrion tourne. Après un redémarrage, chaque agent reçoit de nouveau les derniers messages, ce qui correspond au fait que ses sessions ne survivent pas non plus à un redémarrage.
54+- Si le processus d'un agent meurt et est relancé pendant que Synedrion continue de tourner, sa nouvelle session a perdu ce que savait l'ancienne, et ce qui avait déjà été remis n'est pas renvoyé.
55+- Une commande comme `/new` ou `/compact` fait oublier l'agent, et Synedrion ne renvoie pas ce qu'il avait remis avant.
56+
57+## Voir aussi
58+
59+- Changer les nombres : [réglages](reglages.md)
60+- Qui reçoit un message : [mentions](mentions.md)
new file mode 100644
@@ -0,0 +1,60 @@
1+# Référence : le contexte du channel
2+
3+Un agent garde sa propre conversation, il sait donc déjà ce que l'utilisateur et lui se sont dit. Ce qu'il ne peut pas savoir, c'est ce qui s'est dit autour de lui. Le texte qu'il reçoit commence donc par les messages qu'il n'a pas encore vus, puis vient le message lui-même.
4+
5+## Ce qu'on dit à un agent
6+
7+Pour un agent et un channel, les messages transmis sont ceux du channel qui respectent toutes ces règles :
8+
9+| Règle | Détail |
10+| --- | --- |
11+| Pas encore vu | Posté après le dernier message remis à l'agent dans ce channel. Avant son premier tour dans le channel, tous les messages précédents comptent. |
12+| Pas les siens | Les messages écrits par l'agent lui-même sont omis, quelle que soit la casse de son nom : il sait ce qu'il a dit. |
13+| Conversation seulement | Les notices de Synedrion (comme `Could not reach @bob`) et les [traces](appels-d-outils-et-plans.md) (appels d'outils et plans) sont omises. |
14+| Pas trop | Au plus `Messages of context` d'entre eux, les plus récents. Les plus anciens sont comptés. Voir les [réglages](reglages.md). |
15+
16+Environ 200 messages précédents du channel sont regardés. Un message de l'utilisateur est signé de son nom d'affichage, un message d'agent de son nom.
17+
18+## Le texte envoyé
19+
20+| Cas | L'agent reçoit |
21+| --- | --- |
22+| Rien à dire, message de l'utilisateur | Le message exactement comme saisi. |
23+| Quelque chose à dire, message de l'utilisateur | Le contexte, une ligne vide, puis le message comme saisi. |
24+| Message d'un autre agent (un agent qui l'appelle) | Le contexte s'il y en a, une ligne vide, puis `[Message from @nom]`, un saut de ligne, et la réponse entière de cet agent. |
25+| Une commande `/` qu'il comprend | La commande seule, sans contexte : un agent ne reconnaît une commande qu'au tout début. Voir les [commandes et fichiers joints](commandes-et-fichiers.md). |
26+
27+Le contexte a cette forme :
28+
29+```text
30+[Channel context: what was said since your last turn]
31+[3 earlier message(s) not shown]
32+Ada: the build is red
33+amy: I will look at the logs
34+[End of channel context]
35+
36+@bob can you check too?
37+```
38+
39+La ligne `[N earlier message(s) not shown]` n'apparaît que lorsque certains messages ont été laissés de côté.
40+
41+## Limites
42+
43+| Limite | Valeur | Quand elle est atteinte |
44+| --- | --- | --- |
45+| Un message précédent | 2 000 caractères | Le message est coupé, et se termine par `[message cut: N more character(s)]`. |
46+| Le contexte entier | 12 000 caractères | Les plus anciens messages sont retirés, jusqu'à ce que cela tienne, et comptés dans `[N earlier message(s) not shown]`. |
47+| Le message qui appelle l'agent | Aucune | Il est remis en entier. |
48+
49+On compte des caractères, pas des octets, et un caractère n'est jamais coupé en deux.
50+
51+## Ce qui n'est pas couvert
52+
53+- Le relevé de ce qui a été remis à chaque agent est gardé tant que Synedrion tourne. Après un redémarrage, chaque agent reçoit de nouveau les derniers messages, ce qui correspond au fait que ses sessions ne survivent pas non plus à un redémarrage.
54+- Si le processus d'un agent meurt et est relancé pendant que Synedrion continue de tourner, sa nouvelle session a perdu ce que savait l'ancienne, et ce qui avait déjà été remis n'est pas renvoyé.
55+- Une commande comme `/new` ou `/compact` fait oublier l'agent, et Synedrion ne renvoie pas ce qu'il avait remis avant.
56+
57+## Voir aussi
58+
59+- Changer les nombres : [réglages](reglages.md)
60+- Qui reçoit un message : [mentions](mentions.md)
modified docs/fr/reference/declaration-agent.md +16 -1
@@ -8,7 +8,7 @@ Un agent se déclare dans le panneau **Agents**, et est enregistré dans la base
88 | `command` | Command | Le programme à exécuter. Obligatoire. |
99 | `args` | Arguments | Un argument par ligne. Les lignes vides sont ignorées et chaque ligne est nettoyée de ses espaces de bord. |
1010 | `env` | Environment | Un `NOM=valeur` par ligne, coupé au premier `=`. Le nom ne peut pas être vide ni contenir d'espace. Les lignes vides sont ignorées. |
11-| `working_dir` | Working folder | Facultatif. Il est envoyé à l'agent comme dossier de ses sessions. Ce n'est pas le dossier où démarre le processus : le processus démarre là où Synedrion a été lancé. |
11+| `working_dir` | Working folder | Facultatif. Il est envoyé à l'agent comme dossier de ses sessions. Ce n'est pas le dossier où démarre le processus : le processus démarre là où Synedrion a été lancé. Le chemin peut être saisi, ou choisi avec le bouton **Browse…** du formulaire. |
1212
1313 La commande est exécutée telle que déclarée, et ACP passe par l'entrée et la sortie standard du processus. Quand aucun dossier de travail n'est déclaré, les sessions utilisent le dossier où Synedrion s'exécute.
1414
@@ -22,6 +22,21 @@ La commande est exécutée telle que déclarée, et ACP passe par l'entrée et l
2222 | Delete | Retire la déclaration. Les anciens messages restent. Un processus en cours n'est pas arrêté par cela. |
2323 | Formulaire invalide | Rien n'est enregistré, et une notice nomme le champ : `Name …`, `Command …`, ou `Environment line N must look like NAME=value`. |
2424
25+## Le navigateur de dossiers
26+
27+**Browse…**, sous le champ du dossier de travail, ouvre dans le formulaire une liste de dossiers.
28+
29+| Partie | Comportement |
30+| --- | --- |
31+| Où il s'ouvre | Sur le dossier saisi dans le champ s'il existe, sinon sur le dossier personnel (`HOME`), sinon sur le dossier où tourne Synedrion. |
32+| Le chemin affiché | Le dossier dont le contenu est listé. |
33+| `..` | Va au dossier au-dessus. Absent tout en haut du système de fichiers. |
34+| Un dossier de la liste | Y entre. Seuls les dossiers sont listés, triés sans tenir compte de la casse. Les dossiers cachés (dont le nom commence par un point) sont omis. Au plus 200 sont listés, et une ligne le dit quand il y en avait plus : saisissez le chemin pour aller plus loin. |
35+| **Use this folder** | Met le dossier affiché dans le champ, et ferme la liste. |
36+| **Cancel** | Ferme la liste et laisse le champ comme il était. |
37+
38+La liste est dessinée par Synedrion, pas par une boîte de dialogue du système, pour qu'elle ait le même aspect et le même comportement partout. Elle n'a pas été vue sur un écran.
39+
2540 ## Exemples
2641
2742 ### mini-me, un processus local
@@ -8,7 +8,7 @@ Un agent se déclare dans le panneau **Agents**, et est enregistré dans la base
8 | `command` | Command | Le programme à exécuter. Obligatoire. |8 | `command` | Command | Le programme à exécuter. Obligatoire. |
9 | `args` | Arguments | Un argument par ligne. Les lignes vides sont ignorées et chaque ligne est nettoyée de ses espaces de bord. |9 | `args` | Arguments | Un argument par ligne. Les lignes vides sont ignorées et chaque ligne est nettoyée de ses espaces de bord. |
10 | `env` | Environment | Un `NOM=valeur` par ligne, coupé au premier `=`. Le nom ne peut pas être vide ni contenir d'espace. Les lignes vides sont ignorées. |10 | `env` | Environment | Un `NOM=valeur` par ligne, coupé au premier `=`. Le nom ne peut pas être vide ni contenir d'espace. Les lignes vides sont ignorées. |
11-| `working_dir` | Working folder | Facultatif. Il est envoyé à l'agent comme dossier de ses sessions. Ce n'est pas le dossier où démarre le processus : le processus démarre là où Synedrion a été lancé. |11+| `working_dir` | Working folder | Facultatif. Il est envoyé à l'agent comme dossier de ses sessions. Ce n'est pas le dossier où démarre le processus : le processus démarre là où Synedrion a été lancé. Le chemin peut être saisi, ou choisi avec le bouton **Browse…** du formulaire. |
12 12
13 La commande est exécutée telle que déclarée, et ACP passe par l'entrée et la sortie standard du processus. Quand aucun dossier de travail n'est déclaré, les sessions utilisent le dossier où Synedrion s'exécute.13 La commande est exécutée telle que déclarée, et ACP passe par l'entrée et la sortie standard du processus. Quand aucun dossier de travail n'est déclaré, les sessions utilisent le dossier où Synedrion s'exécute.
14 14
@@ -22,6 +22,21 @@ La commande est exécutée telle que déclarée, et ACP passe par l'entrée et l
22 | Delete | Retire la déclaration. Les anciens messages restent. Un processus en cours n'est pas arrêté par cela. |22 | Delete | Retire la déclaration. Les anciens messages restent. Un processus en cours n'est pas arrêté par cela. |
23 | Formulaire invalide | Rien n'est enregistré, et une notice nomme le champ : `Name …`, `Command …`, ou `Environment line N must look like NAME=value`. |23 | Formulaire invalide | Rien n'est enregistré, et une notice nomme le champ : `Name …`, `Command …`, ou `Environment line N must look like NAME=value`. |
24 24
25+## Le navigateur de dossiers
26+
27+**Browse…**, sous le champ du dossier de travail, ouvre dans le formulaire une liste de dossiers.
28+
29+| Partie | Comportement |
30+| --- | --- |
31+| Où il s'ouvre | Sur le dossier saisi dans le champ s'il existe, sinon sur le dossier personnel (`HOME`), sinon sur le dossier où tourne Synedrion. |
32+| Le chemin affiché | Le dossier dont le contenu est listé. |
33+| `..` | Va au dossier au-dessus. Absent tout en haut du système de fichiers. |
34+| Un dossier de la liste | Y entre. Seuls les dossiers sont listés, triés sans tenir compte de la casse. Les dossiers cachés (dont le nom commence par un point) sont omis. Au plus 200 sont listés, et une ligne le dit quand il y en avait plus : saisissez le chemin pour aller plus loin. |
35+| **Use this folder** | Met le dossier affiché dans le champ, et ferme la liste. |
36+| **Cancel** | Ferme la liste et laisse le champ comme il était. |
37+
38+La liste est dessinée par Synedrion, pas par une boîte de dialogue du système, pour qu'elle ait le même aspect et le même comportement partout. Elle n'a pas été vue sur un écran.
39+
25 ## Exemples40 ## Exemples
26 41
27 ### mini-me, un processus local42 ### mini-me, un processus local
modified docs/fr/reference/mentions.md +16 -6
@@ -14,16 +14,26 @@ Une mention s'adresse à un agent depuis un message : `@nom`.
1414 | Casse | Ignorée pour la correspondance : `@BOB` s'adresse à l'agent déclaré `bob`. |
1515 | Mentions répétées | Comptées une seule fois, dans l'ordre de première apparition, quelle que soit leur casse. |
1616
17+## À qui s'adresse un message
18+
19+| Le message | Destinataires |
20+| --- | --- |
21+| Commence par des mentions (`@bob dis bonjour à @mouse`) | Seulement les mentions du début : `bob`. `@mouse` est seulement évoqué, et n'appelle personne. |
22+| Commence par plusieurs mentions (`@bob @mouse discutez-en`, `@bob, @mouse discutez-en`) | Chacune d'elles. Des espaces et des virgules peuvent les séparer. |
23+| Ne commence pas par une mention (`dis bonjour à @bob et @mouse`) | Chaque agent qu'il mentionne. |
24+
25+Les mentions du début s'arrêtent au premier mot qui n'est pas une mention : dans `@bob et @mouse qu'en pensez-vous`, seul `bob` est destinataire. Écrivez `@bob @mouse qu'en pensez-vous` pour viser les deux. La même règle s'applique aux réponses des agents (voir [les agents qui s'appellent](../explanation/agents-qui-s-appellent.md)) et aux messages qui décident à qui va un message simple.
26+
1727 ## Ce que fait une mention
1828
1929 | Cas | Effet |
2030 | --- | --- |
21-| Nom d'un agent déclaré | L'agent reçoit le message. Un message avec plusieurs mentions atteint chaque agent une fois. |
22-| Nom qu'aucun agent ne porte | Rien n'est envoyé. Le texte reste tel qu'écrit et une notice nomme les agents inconnus. |
31+| Nom d'un agent déclaré que le message vise | L'agent reçoit le message. Un message qui vise plusieurs agents atteint chacun une fois. |
32+| Nom qu'aucun agent ne porte, parmi ceux que le message vise | Rien n'est envoyé. Le texte reste tel qu'écrit et une notice nomme les agents inconnus. Un nom seulement évoqué (`@bob salue @ghost`) ne déclenche aucune notice. |
2333 | Message sans mention | Enregistré dans le channel. Il continue avec les agents que l'utilisateur a désignés dans son dernier message qui en désignait, voir plus bas, et va à personne s'il n'y en a pas. |
24-| Mention dans la réponse d'un agent | Rien, pour l'instant : les agents ne peuvent pas encore s'adresser les uns aux autres. |
34+| Mention dans la réponse d'un agent | Quand le tour de l'agent se termine normalement, l'agent mentionné est appelé avec cette réponse, dans la limite de la profondeur de chaîne. Un agent qui se mentionne lui-même, ou un nom qu'aucun agent ne porte, n'appelle personne. Voir [les agents qui s'appellent](../explanation/agents-qui-s-appellent.md). |
2535
26-L'agent reçoit le message exactement comme saisi, mention comprise, sans les espaces autour. Il ne reçoit pas encore les messages précédents du channel.
36+L'agent reçoit le message exactement comme saisi, mention comprise, sans les espaces autour, précédé des messages du channel qu'il n'a pas encore vus, quand il y en a. Voir [le contexte du channel](contexte-du-channel.md).
2737
2838 ## Continuer sans mentionner de nouveau
2939
@@ -36,13 +46,13 @@ Un message qui ne contient aucune mention va aux agents désignés par le dernie
3646 | Le dernier agent désigné a été supprimé | Le message ne va à personne. |
3747 | Un autre channel | Chaque channel a ses propres destinataires. |
3848
39-Seuls les messages de l'utilisateur comptent : une mention écrite par un agent ne change rien. Environ 200 messages précédents du channel sont regardés. Tant qu'il y a des destinataires, une ligne au-dessus de la zone de message dit à qui va un message simple.
49+Seuls les messages de l'utilisateur comptent : une mention écrite par un agent appelle cet agent, mais ne change pas à qui va le prochain message simple de l'utilisateur. Environ 200 messages précédents du channel sont regardés. Tant qu'il y a des destinataires, une ligne au-dessus de la zone de message dit à qui va un message simple.
4050
4151 Un message qui commence par une commande `/` suit ces règles : ses destinataires sont trouvés de la même façon, et les mentions devant la commande sont retirées de ce que reçoit l'agent. Voir les [commandes](commandes-et-fichiers.md).
4252
4353 ## Suggestions pendant la saisie
4454
45-Tant que le texte se termine par `@` suivi du début d'un nom, des boutons proposent les agents déclarés dont le nom commence par ces lettres, sans tenir compte de la casse, par ordre alphabétique. Un `@` seul propose tous les agents. La première proposition ressort. Cliquer sur une proposition, ou appuyer sur Tab, remplace le début par `@nom ` (une espace suit), place le curseur après, et les propositions disparaissent. Tab prend la première proposition, et seulement quand la zone de message a le focus : quand aucun agent n'est proposé, Tab fait ce qu'il fait d'habitude. Une mention suivie d'une espace, ou au milieu du texte, ne déclenche aucune proposition : seule la fin du texte est regardée.
55+Tant que le texte se termine par `@` suivi du début d'un nom, des boutons proposent les agents déclarés dont le nom commence par ces lettres, sans tenir compte de la casse, par ordre alphabétique. Un `@` seul propose tous les agents. La première proposition ressort, et les flèches déplacent la surbrillance (voir [le clavier dans les listes](commandes-et-fichiers.md)). Cliquer sur une proposition, ou appuyer sur Tab, remplace le début par `@nom ` (une espace suit), place le curseur après, et les propositions disparaissent. Tab prend la proposition en surbrillance, et seulement quand la zone de message a le focus : quand aucun agent n'est proposé, Tab fait ce qu'il fait d'habitude. Une mention suivie d'une espace, ou au milieu du texte, ne déclenche aucune proposition : seule la fin du texte est regardée.
4656
4757 ## Voir aussi
4858
@@ -14,16 +14,26 @@ Une mention s'adresse à un agent depuis un message : `@nom`.
14 | Casse | Ignorée pour la correspondance : `@BOB` s'adresse à l'agent déclaré `bob`. |14 | Casse | Ignorée pour la correspondance : `@BOB` s'adresse à l'agent déclaré `bob`. |
15 | Mentions répétées | Comptées une seule fois, dans l'ordre de première apparition, quelle que soit leur casse. |15 | Mentions répétées | Comptées une seule fois, dans l'ordre de première apparition, quelle que soit leur casse. |
16 16
17+## À qui s'adresse un message
18+
19+| Le message | Destinataires |
20+| --- | --- |
21+| Commence par des mentions (`@bob dis bonjour à @mouse`) | Seulement les mentions du début : `bob`. `@mouse` est seulement évoqué, et n'appelle personne. |
22+| Commence par plusieurs mentions (`@bob @mouse discutez-en`, `@bob, @mouse discutez-en`) | Chacune d'elles. Des espaces et des virgules peuvent les séparer. |
23+| Ne commence pas par une mention (`dis bonjour à @bob et @mouse`) | Chaque agent qu'il mentionne. |
24+
25+Les mentions du début s'arrêtent au premier mot qui n'est pas une mention : dans `@bob et @mouse qu'en pensez-vous`, seul `bob` est destinataire. Écrivez `@bob @mouse qu'en pensez-vous` pour viser les deux. La même règle s'applique aux réponses des agents (voir [les agents qui s'appellent](../explanation/agents-qui-s-appellent.md)) et aux messages qui décident à qui va un message simple.
26+
17 ## Ce que fait une mention27 ## Ce que fait une mention
18 28
19 | Cas | Effet |29 | Cas | Effet |
20 | --- | --- |30 | --- | --- |
21-| Nom d'un agent déclaré | L'agent reçoit le message. Un message avec plusieurs mentions atteint chaque agent une fois. |31+| Nom d'un agent déclaré que le message vise | L'agent reçoit le message. Un message qui vise plusieurs agents atteint chacun une fois. |
22-| Nom qu'aucun agent ne porte | Rien n'est envoyé. Le texte reste tel qu'écrit et une notice nomme les agents inconnus. |32+| Nom qu'aucun agent ne porte, parmi ceux que le message vise | Rien n'est envoyé. Le texte reste tel qu'écrit et une notice nomme les agents inconnus. Un nom seulement évoqué (`@bob salue @ghost`) ne déclenche aucune notice. |
23 | Message sans mention | Enregistré dans le channel. Il continue avec les agents que l'utilisateur a désignés dans son dernier message qui en désignait, voir plus bas, et va à personne s'il n'y en a pas. |33 | Message sans mention | Enregistré dans le channel. Il continue avec les agents que l'utilisateur a désignés dans son dernier message qui en désignait, voir plus bas, et va à personne s'il n'y en a pas. |
24-| Mention dans la réponse d'un agent | Rien, pour l'instant : les agents ne peuvent pas encore s'adresser les uns aux autres. |34+| Mention dans la réponse d'un agent | Quand le tour de l'agent se termine normalement, l'agent mentionné est appelé avec cette réponse, dans la limite de la profondeur de chaîne. Un agent qui se mentionne lui-même, ou un nom qu'aucun agent ne porte, n'appelle personne. Voir [les agents qui s'appellent](../explanation/agents-qui-s-appellent.md). |
25 35
26-L'agent reçoit le message exactement comme saisi, mention comprise, sans les espaces autour. Il ne reçoit pas encore les messages précédents du channel.36+L'agent reçoit le message exactement comme saisi, mention comprise, sans les espaces autour, précédé des messages du channel qu'il n'a pas encore vus, quand il y en a. Voir [le contexte du channel](contexte-du-channel.md).
27 37
28 ## Continuer sans mentionner de nouveau38 ## Continuer sans mentionner de nouveau
29 39
@@ -36,13 +46,13 @@ Un message qui ne contient aucune mention va aux agents désignés par le dernie
36 | Le dernier agent désigné a été supprimé | Le message ne va à personne. |46 | Le dernier agent désigné a été supprimé | Le message ne va à personne. |
37 | Un autre channel | Chaque channel a ses propres destinataires. |47 | Un autre channel | Chaque channel a ses propres destinataires. |
38 48
39-Seuls les messages de l'utilisateur comptent : une mention écrite par un agent ne change rien. Environ 200 messages précédents du channel sont regardés. Tant qu'il y a des destinataires, une ligne au-dessus de la zone de message dit à qui va un message simple.49+Seuls les messages de l'utilisateur comptent : une mention écrite par un agent appelle cet agent, mais ne change pas à qui va le prochain message simple de l'utilisateur. Environ 200 messages précédents du channel sont regardés. Tant qu'il y a des destinataires, une ligne au-dessus de la zone de message dit à qui va un message simple.
40 50
41 Un message qui commence par une commande `/` suit ces règles : ses destinataires sont trouvés de la même façon, et les mentions devant la commande sont retirées de ce que reçoit l'agent. Voir les [commandes](commandes-et-fichiers.md).51 Un message qui commence par une commande `/` suit ces règles : ses destinataires sont trouvés de la même façon, et les mentions devant la commande sont retirées de ce que reçoit l'agent. Voir les [commandes](commandes-et-fichiers.md).
42 52
43 ## Suggestions pendant la saisie53 ## Suggestions pendant la saisie
44 54
45-Tant que le texte se termine par `@` suivi du début d'un nom, des boutons proposent les agents déclarés dont le nom commence par ces lettres, sans tenir compte de la casse, par ordre alphabétique. Un `@` seul propose tous les agents. La première proposition ressort. Cliquer sur une proposition, ou appuyer sur Tab, remplace le début par `@nom ` (une espace suit), place le curseur après, et les propositions disparaissent. Tab prend la première proposition, et seulement quand la zone de message a le focus : quand aucun agent n'est proposé, Tab fait ce qu'il fait d'habitude. Une mention suivie d'une espace, ou au milieu du texte, ne déclenche aucune proposition : seule la fin du texte est regardée.55+Tant que le texte se termine par `@` suivi du début d'un nom, des boutons proposent les agents déclarés dont le nom commence par ces lettres, sans tenir compte de la casse, par ordre alphabétique. Un `@` seul propose tous les agents. La première proposition ressort, et les flèches déplacent la surbrillance (voir [le clavier dans les listes](commandes-et-fichiers.md)). Cliquer sur une proposition, ou appuyer sur Tab, remplace le début par `@nom ` (une espace suit), place le curseur après, et les propositions disparaissent. Tab prend la proposition en surbrillance, et seulement quand la zone de message a le focus : quand aucun agent n'est proposé, Tab fait ce qu'il fait d'habitude. Une mention suivie d'une espace, ou au milieu du texte, ne déclenche aucune proposition : seule la fin du texte est regardée.
46 56
47 ## Voir aussi57 ## Voir aussi
48 58
modified docs/fr/reference/methodes-acp.md +6 -6
@@ -8,11 +8,11 @@ ACP est du JSON-RPC sur l'entrée et la sortie standard du processus de l'agent.
88
99 | Méthode | Protocole | Synedrion |
1010 | --- | --- | --- |
11-| `initialize` | De base. Négocie les versions et échange les capacités. | Appelée une fois par processus d'agent. Synedrion ne définit aucune capacité client. |
11+| `initialize` | De base. Négocie les versions et échange les capacités. | Appelée une fois par processus d'agent. Synedrion n'annonce aucune capacité client, par décision : voir les [capacités du client](../explanation/capacites-du-client.md). |
1212 | `authenticate` | De base, utilisée si l'agent l'exige. | Non appelée. |
1313 | `session/new` | De base. Crée une session. | Appelée une fois par couple agent et channel, avec le dossier de travail de la déclaration, ou le dossier où Synedrion s'exécute. |
14-| `session/prompt` | De base. Envoie le prompt de l'utilisateur. | Appelée pour chaque message adressé à un agent, avec un bloc de texte (le message tel que saisi, ou la commande seule pour une commande `/`) suivi d'un bloc `resource_link` par fichier joint. |
15-| `session/cancel` | Notification, aucune réponse attendue. | Envoyée par le bouton **Stop**, pour chaque agent qui travaille dans le channel. |
14+| `session/prompt` | De base. Envoie le prompt de l'utilisateur. | Appelée pour chaque message adressé à un agent, avec un bloc de texte suivi d'un bloc `resource_link` par fichier joint. Le texte est le message tel que saisi, précédé du contexte du channel quand il y en a, ou la commande seule pour une commande `/`, ou, pour un agent appelé par un autre agent, la réponse de cet agent. |
15+| `session/cancel` | Notification, aucune réponse attendue. | Envoyée par le bouton **Stop**, pour chaque agent qui travaille dans le channel. Les réponses des tours annulés n'appellent personne. |
1616 | `session/load` | Optionnelle, exige la capacité `loadSession`. Reprend une session. | Non utilisée : les sessions ne survivent pas à un redémarrage de Synedrion. |
1717 | `session/set_mode` | Optionnelle. Change de mode de fonctionnement. | Non utilisée. |
1818 | `logout` | Optionnelle, exige `agentCapabilities.auth.logout`. | Non utilisée. |
@@ -22,15 +22,15 @@ ACP est du JSON-RPC sur l'entrée et la sortie standard du processus de l'agent.
2222 | Méthode | Protocole | Synedrion |
2323 | --- | --- | --- |
2424 | `session/request_permission` | De base. Demande à l'utilisateur d'autoriser un appel d'outil. | Affichée comme une carte dans le channel avec le titre et les options de l'agent. L'option choisie est renvoyée. **Dismiss** répond par une annulation, que l'agent prend pour un refus. Si le tour est annulé avant, la carte est retirée et l'agent reçoit une annulation. |
25-| `fs/read_text_file`, `fs/write_text_file` | Optionnelles, exigent les capacités `fs.readTextFile` et `fs.writeTextFile`. | Non offertes (non décidé, ticket #18). |
26-| `terminal/create`, `terminal/output`, `terminal/release`, `terminal/wait_for_exit`, `terminal/kill` | Optionnelles, exigent la capacité `terminal`. | Non offertes (non décidé, ticket #18). |
25+| `fs/read_text_file`, `fs/write_text_file` | Optionnelles, exigent les capacités `fs.readTextFile` et `fs.writeTextFile`. | Non offertes, par décision : voir les [capacités du client](../explanation/capacites-du-client.md). |
26+| `terminal/create`, `terminal/output`, `terminal/release`, `terminal/wait_for_exit`, `terminal/kill` | Optionnelles, exigent la capacité `terminal`. | Non offertes, par décision : voir les [capacités du client](../explanation/capacites-du-client.md). |
2727 | `elicitation/create` | Optionnelle, exige la capacité d'élicitation correspondante. | Non offerte. |
2828
2929 ## Notifications que l'agent envoie au client
3030
3131 | Notification | Protocole | Synedrion |
3232 | --- | --- | --- |
33-| `session/update` | Progression, morceaux de message, morceaux de raisonnement, appels d'outils, plans, commandes disponibles, changements de mode. | Le texte de la réponse de l'agent est mis bout à bout dans un seul message. Son raisonnement (morceaux de pensée) est affiché en direct dans une carte pendant que l'agent travaille, et n'est pas conservé. La liste des commandes disponibles alimente la liste de `/`. Tout le reste est ignoré pour l'instant (appels d'outils et plans : ticket #17). |
33+| `session/update` | Progression, morceaux de message, morceaux de raisonnement, appels d'outils, plans, commandes disponibles, changements de mode. | Le texte de la réponse de l'agent est mis bout à bout dans un seul message, et un nouveau message commence après un appel d'outil ou un plan. Son raisonnement (morceaux de pensée) est affiché en direct dans une carte pendant que l'agent travaille, et n'est pas conservé. Les appels d'outils et leurs mises à jour, et les plans, sont gardés dans le channel sous forme de cartes : voir [appels d'outils, plans, et ce qui ne peut pas être montré](appels-d-outils-et-plans.md). Les notices sont affichées. La liste des commandes disponibles alimente la liste de `/`. Un contenu qui ne peut pas être dessiné est montré comme une courte note, et une mise à jour d'un genre inconnu comme une notice. Les chiffres d'utilisation, les modes, les options de configuration, le titre de la session et l'écho du message de l'utilisateur ne sont pas montrés. |
3434 | `elicitation/complete` | Signale la fin d'une interaction par URL hors bande. | Ignorée. |
3535
3636 ## Raisons d'arrêt
@@ -8,11 +8,11 @@ ACP est du JSON-RPC sur l'entrée et la sortie standard du processus de l'agent.
8 8
9 | Méthode | Protocole | Synedrion |9 | Méthode | Protocole | Synedrion |
10 | --- | --- | --- |10 | --- | --- | --- |
11-| `initialize` | De base. Négocie les versions et échange les capacités. | Appelée une fois par processus d'agent. Synedrion ne définit aucune capacité client. |11+| `initialize` | De base. Négocie les versions et échange les capacités. | Appelée une fois par processus d'agent. Synedrion n'annonce aucune capacité client, par décision : voir les [capacités du client](../explanation/capacites-du-client.md). |
12 | `authenticate` | De base, utilisée si l'agent l'exige. | Non appelée. |12 | `authenticate` | De base, utilisée si l'agent l'exige. | Non appelée. |
13 | `session/new` | De base. Crée une session. | Appelée une fois par couple agent et channel, avec le dossier de travail de la déclaration, ou le dossier où Synedrion s'exécute. |13 | `session/new` | De base. Crée une session. | Appelée une fois par couple agent et channel, avec le dossier de travail de la déclaration, ou le dossier où Synedrion s'exécute. |
14-| `session/prompt` | De base. Envoie le prompt de l'utilisateur. | Appelée pour chaque message adressé à un agent, avec un bloc de texte (le message tel que saisi, ou la commande seule pour une commande `/`) suivi d'un bloc `resource_link` par fichier joint. |14+| `session/prompt` | De base. Envoie le prompt de l'utilisateur. | Appelée pour chaque message adressé à un agent, avec un bloc de texte suivi d'un bloc `resource_link` par fichier joint. Le texte est le message tel que saisi, précédé du contexte du channel quand il y en a, ou la commande seule pour une commande `/`, ou, pour un agent appelé par un autre agent, la réponse de cet agent. |
15-| `session/cancel` | Notification, aucune réponse attendue. | Envoyée par le bouton **Stop**, pour chaque agent qui travaille dans le channel. |15+| `session/cancel` | Notification, aucune réponse attendue. | Envoyée par le bouton **Stop**, pour chaque agent qui travaille dans le channel. Les réponses des tours annulés n'appellent personne. |
16 | `session/load` | Optionnelle, exige la capacité `loadSession`. Reprend une session. | Non utilisée : les sessions ne survivent pas à un redémarrage de Synedrion. |16 | `session/load` | Optionnelle, exige la capacité `loadSession`. Reprend une session. | Non utilisée : les sessions ne survivent pas à un redémarrage de Synedrion. |
17 | `session/set_mode` | Optionnelle. Change de mode de fonctionnement. | Non utilisée. |17 | `session/set_mode` | Optionnelle. Change de mode de fonctionnement. | Non utilisée. |
18 | `logout` | Optionnelle, exige `agentCapabilities.auth.logout`. | Non utilisée. |18 | `logout` | Optionnelle, exige `agentCapabilities.auth.logout`. | Non utilisée. |
@@ -22,15 +22,15 @@ ACP est du JSON-RPC sur l'entrée et la sortie standard du processus de l'agent.
22 | Méthode | Protocole | Synedrion |22 | Méthode | Protocole | Synedrion |
23 | --- | --- | --- |23 | --- | --- | --- |
24 | `session/request_permission` | De base. Demande à l'utilisateur d'autoriser un appel d'outil. | Affichée comme une carte dans le channel avec le titre et les options de l'agent. L'option choisie est renvoyée. **Dismiss** répond par une annulation, que l'agent prend pour un refus. Si le tour est annulé avant, la carte est retirée et l'agent reçoit une annulation. |24 | `session/request_permission` | De base. Demande à l'utilisateur d'autoriser un appel d'outil. | Affichée comme une carte dans le channel avec le titre et les options de l'agent. L'option choisie est renvoyée. **Dismiss** répond par une annulation, que l'agent prend pour un refus. Si le tour est annulé avant, la carte est retirée et l'agent reçoit une annulation. |
25-| `fs/read_text_file`, `fs/write_text_file` | Optionnelles, exigent les capacités `fs.readTextFile` et `fs.writeTextFile`. | Non offertes (non décidé, ticket #18). |25+| `fs/read_text_file`, `fs/write_text_file` | Optionnelles, exigent les capacités `fs.readTextFile` et `fs.writeTextFile`. | Non offertes, par décision : voir les [capacités du client](../explanation/capacites-du-client.md). |
26-| `terminal/create`, `terminal/output`, `terminal/release`, `terminal/wait_for_exit`, `terminal/kill` | Optionnelles, exigent la capacité `terminal`. | Non offertes (non décidé, ticket #18). |26+| `terminal/create`, `terminal/output`, `terminal/release`, `terminal/wait_for_exit`, `terminal/kill` | Optionnelles, exigent la capacité `terminal`. | Non offertes, par décision : voir les [capacités du client](../explanation/capacites-du-client.md). |
27 | `elicitation/create` | Optionnelle, exige la capacité d'élicitation correspondante. | Non offerte. |27 | `elicitation/create` | Optionnelle, exige la capacité d'élicitation correspondante. | Non offerte. |
28 28
29 ## Notifications que l'agent envoie au client29 ## Notifications que l'agent envoie au client
30 30
31 | Notification | Protocole | Synedrion |31 | Notification | Protocole | Synedrion |
32 | --- | --- | --- |32 | --- | --- | --- |
33-| `session/update` | Progression, morceaux de message, morceaux de raisonnement, appels d'outils, plans, commandes disponibles, changements de mode. | Le texte de la réponse de l'agent est mis bout à bout dans un seul message. Son raisonnement (morceaux de pensée) est affiché en direct dans une carte pendant que l'agent travaille, et n'est pas conservé. La liste des commandes disponibles alimente la liste de `/`. Tout le reste est ignoré pour l'instant (appels d'outils et plans : ticket #17). |33+| `session/update` | Progression, morceaux de message, morceaux de raisonnement, appels d'outils, plans, commandes disponibles, changements de mode. | Le texte de la réponse de l'agent est mis bout à bout dans un seul message, et un nouveau message commence après un appel d'outil ou un plan. Son raisonnement (morceaux de pensée) est affiché en direct dans une carte pendant que l'agent travaille, et n'est pas conservé. Les appels d'outils et leurs mises à jour, et les plans, sont gardés dans le channel sous forme de cartes : voir [appels d'outils, plans, et ce qui ne peut pas être montré](appels-d-outils-et-plans.md). Les notices sont affichées. La liste des commandes disponibles alimente la liste de `/`. Un contenu qui ne peut pas être dessiné est montré comme une courte note, et une mise à jour d'un genre inconnu comme une notice. Les chiffres d'utilisation, les modes, les options de configuration, le titre de la session et l'écho du message de l'utilisateur ne sont pas montrés. |
34 | `elicitation/complete` | Signale la fin d'une interaction par URL hors bande. | Ignorée. |34 | `elicitation/complete` | Signale la fin d'une interaction par URL hors bande. | Ignorée. |
35 35
36 ## Raisons d'arrêt36 ## Raisons d'arrêt
added docs/fr/reference/reglages.md +27 -0
new file mode 100644
@@ -0,0 +1,27 @@
1+# Référence : les réglages
2+
3+Le panneau **Settings** contient les deux réglages de la conversation. On l'ouvre avec le bouton de la barre qui porte des curseurs. Les deux réglages s'appliquent dès le message suivant, et sont conservés dans la base de données.
4+
5+| Réglage | Champ | Défaut | Valeurs permises | Signification |
6+| --- | --- | --- | --- | --- |
7+| Messages de contexte | `Messages of context` | 20 | 0 à 100 | Combien de messages, au plus, un agent connaît en plus de celui qui l'appelle : ceux envoyés dans le channel depuis son dernier tour. `0` ne lui donne rien de plus que le message. Voir [le contexte du channel](contexte-du-channel.md). |
8+| Profondeur de chaîne | `Chain depth` | 3 | 0 à 10 | Combien de fois de suite la réponse d'un agent peut appeler un autre agent. `0` interdit aux agents de s'appeler. Voir [les agents qui s'appellent](../explanation/agents-qui-s-appellent.md). |
9+
10+## Enregistrement
11+
12+| Action | Effet |
13+| --- | --- |
14+| **Save settings** avec deux nombres entiers dans les limites | Les enregistre, et une notice dit `Settings saved. They apply from the next message.` |
15+| Une valeur qui n'est pas un nombre entier (vide, des lettres, un signe moins, une virgule) | Rien n'est enregistré, et une notice dit `Chain depth must be a whole number, not "…"` ou la même chose pour `Messages of context`. |
16+| Une valeur au-dessus de la limite | Rien n'est enregistré, et une notice dit `… must be at most 100` ou `… at most 10`. |
17+| Les deux valeurs fausses | La première, dans l'ordre du tableau, est signalée. |
18+
19+Les espaces autour sont ignorés.
20+
21+## Où ils sont conservés
22+
23+Chaque réglage est une ligne de la table `setting`, avec les clés `context_messages` et `chain_depth`. Un réglage jamais enregistré a sa valeur par défaut. Une valeur stockée qui n'a pas de sens est signalée comme une erreur de stockage au démarrage au lieu d'être remplacée en silence. Voir [la base de données](base-de-donnees.md).
24+
25+## Voir aussi
26+
27+- Utiliser la profondeur de chaîne : [laisser les agents s'appeler entre eux](../how-to/laisser-les-agents-s-appeler.md)
new file mode 100644
@@ -0,0 +1,27 @@
1+# Référence : les réglages
2+
3+Le panneau **Settings** contient les deux réglages de la conversation. On l'ouvre avec le bouton de la barre qui porte des curseurs. Les deux réglages s'appliquent dès le message suivant, et sont conservés dans la base de données.
4+
5+| Réglage | Champ | Défaut | Valeurs permises | Signification |
6+| --- | --- | --- | --- | --- |
7+| Messages de contexte | `Messages of context` | 20 | 0 à 100 | Combien de messages, au plus, un agent connaît en plus de celui qui l'appelle : ceux envoyés dans le channel depuis son dernier tour. `0` ne lui donne rien de plus que le message. Voir [le contexte du channel](contexte-du-channel.md). |
8+| Profondeur de chaîne | `Chain depth` | 3 | 0 à 10 | Combien de fois de suite la réponse d'un agent peut appeler un autre agent. `0` interdit aux agents de s'appeler. Voir [les agents qui s'appellent](../explanation/agents-qui-s-appellent.md). |
9+
10+## Enregistrement
11+
12+| Action | Effet |
13+| --- | --- |
14+| **Save settings** avec deux nombres entiers dans les limites | Les enregistre, et une notice dit `Settings saved. They apply from the next message.` |
15+| Une valeur qui n'est pas un nombre entier (vide, des lettres, un signe moins, une virgule) | Rien n'est enregistré, et une notice dit `Chain depth must be a whole number, not "…"` ou la même chose pour `Messages of context`. |
16+| Une valeur au-dessus de la limite | Rien n'est enregistré, et une notice dit `… must be at most 100` ou `… at most 10`. |
17+| Les deux valeurs fausses | La première, dans l'ordre du tableau, est signalée. |
18+
19+Les espaces autour sont ignorés.
20+
21+## Où ils sont conservés
22+
23+Chaque réglage est une ligne de la table `setting`, avec les clés `context_messages` et `chain_depth`. Un réglage jamais enregistré a sa valeur par défaut. Une valeur stockée qui n'a pas de sens est signalée comme une erreur de stockage au démarrage au lieu d'être remplacée en silence. Voir [la base de données](base-de-donnees.md).
24+
25+## Voir aussi
26+
27+- Utiliser la profondeur de chaîne : [laisser les agents s'appeler entre eux](../how-to/laisser-les-agents-s-appeler.md)
modified docs/fr/reference/rendu-des-messages.md +2 -1
@@ -4,7 +4,8 @@
44 | --- | --- |
55 | Un agent | Du Markdown, par la vue Markdown de GPUI Kit. Le texte peut être sélectionné à la souris. |
66 | L'utilisateur | Du texte brut, tel que saisi. |
7-| Synedrion (notices) | Du texte brut, en italique. |
7+| Synedrion (notices) | Du texte brut, en italique. Une notice d'un agent est montrée de la même façon, signée `@nom:`. |
8+| Les appels d'outils et plans d'un agent | Des cartes, pas du texte : voir [appels d'outils, plans, et ce qui ne peut pas être montré](appels-d-outils-et-plans.md). |
89
910 Le texte de l'utilisateur n'est pas interprété, pour que des caractères comme `*` ou `_` ne soient jamais transformés en mise en forme par surprise. Le texte stocké dans la base est toujours ce que l'auteur a écrit : le Markdown n'est qu'une façon de le dessiner.
1011
@@ -4,7 +4,8 @@
4 | --- | --- |4 | --- | --- |
5 | Un agent | Du Markdown, par la vue Markdown de GPUI Kit. Le texte peut être sélectionné à la souris. |5 | Un agent | Du Markdown, par la vue Markdown de GPUI Kit. Le texte peut être sélectionné à la souris. |
6 | L'utilisateur | Du texte brut, tel que saisi. |6 | L'utilisateur | Du texte brut, tel que saisi. |
7-| Synedrion (notices) | Du texte brut, en italique. |7+| Synedrion (notices) | Du texte brut, en italique. Une notice d'un agent est montrée de la même façon, signée `@nom:`. |
8+| Les appels d'outils et plans d'un agent | Des cartes, pas du texte : voir [appels d'outils, plans, et ce qui ne peut pas être montré](appels-d-outils-et-plans.md). |
8 9
9 Le texte de l'utilisateur n'est pas interprété, pour que des caractères comme `*` ou `_` ne soient jamais transformés en mise en forme par surprise. Le texte stocké dans la base est toujours ce que l'auteur a écrit : le Markdown n'est qu'une façon de le dessiner.10 Le texte de l'utilisateur n'est pas interprété, pour que des caractères comme `*` ou `_` ne soient jamais transformés en mise en forme par surprise. Le texte stocké dans la base est toujours ce que l'auteur a écrit : le Markdown n'est qu'une façon de le dessiner.
10 11