You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by lu...@apache.org on 2026/10/10 10:49:18 UTC
(maka) branch feat/desktop-gpui-shell updated: feat(desktop-gpui): add the workbar, find, search and side chats
This is an automated email from the ASF dual-hosted git repository.
UncertaintyDeterminesYou4ndMe pushed a commit to branch feat/desktop-gpui-shell
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/feat/desktop-gpui-shell by this push:
new e2d4841f7a feat(desktop-gpui): add the workbar, find, search and side chats
e2d4841f7a is described below
commit e2d4841f7a2c0f40322d34c5a50683cb626c02cf
Author: Xun Lu <lu...@apache.org>
AuthorDate: Sat Oct 10 18:47:24 2026 +0800
feat(desktop-gpui): add the workbar, find, search and side chats
Bring apps/desktop-gpui up to date with the standalone workspace it
was imported from. It still speaks protocol epoch 197 (MAKA_PIN is
unchanged).
- The workbar turns the right panel into tool tabs:
- Changes: the task folder's Git changes for the whole branch, the
uncommitted work, one commit or one turn, with a card under each
settled turn's reply listing the files it edited.
- Files: the task's artifacts with previews. HTML pages render
without scripts or styles, or open in the default app.
- Trace: the task's trace, usage and context window, as Desktop's
Inspector shows them.
- Terminal: Host-owned PTYs drawn as Zed draws them.
- Side chat: a side conversation on a hidden fork of the task
(session.branch.create). A cleanup ledger removes forks that a
crash or quit leaves behind at the next launch.
- Find in the conversation (Cmd-F), with match case and whole word.
Each Chinese character counts as a word.
- Search every task (Shift-Cmd-F) through recall.query.
- Syntax colours in code blocks, diffs and file previews.
- Links in rendered text open only http, https and mailto addresses,
as in Desktop. Before, a file: link could start an application.
- docs/upstream-issues.md records that the Host restarts when a
terminal start goes over the shared PTY cap.
New files carry the ASF header. The two new icons are generated by
scripts/design-icons.py like the rest of the set.
Generated-by: Claude Code
---
apps/desktop-gpui/AGENTS.md | 14 +-
apps/desktop-gpui/CHANGELOG.md | 38 +
apps/desktop-gpui/Cargo.lock | 394 +++-
apps/desktop-gpui/Cargo.toml | 53 +-
apps/desktop-gpui/assets/icons/maka/activity.svg | 1 +
apps/desktop-gpui/assets/icons/maka/chat.svg | 1 +
apps/desktop-gpui/crates/app/Cargo.toml | 6 +
apps/desktop-gpui/crates/app/src/chrome_tests.rs | 14 +-
apps/desktop-gpui/crates/app/src/commands.rs | 56 +-
apps/desktop-gpui/crates/app/src/find_tests.rs | 253 +++
apps/desktop-gpui/crates/app/src/lib.rs | 70 +-
apps/desktop-gpui/crates/app/src/main.rs | 32 +-
apps/desktop-gpui/crates/app/src/palette.rs | 73 +-
apps/desktop-gpui/crates/app/src/review_tests.rs | 200 +-
apps/desktop-gpui/crates/app/src/search_tests.rs | 406 ++++
.../desktop-gpui/crates/app/src/side_chat_tests.rs | 338 ++++
apps/desktop-gpui/crates/app/src/sidebar_tests.rs | 11 +-
apps/desktop-gpui/crates/app/src/strip_tests.rs | 11 +-
apps/desktop-gpui/crates/app/src/tests.rs | 226 ++-
.../crates/app/src/turn_edits_tests.rs | 588 ++++++
apps/desktop-gpui/crates/app/src/workbar_tests.rs | 633 +++++++
apps/desktop-gpui/crates/app/src/workbench.rs | 296 ++-
.../crates/app/src/workbench/context_strip.rs | 114 +-
.../crates/app/src/workbench/review_pane.rs | 654 -------
.../crates/app/src/workbench/side_chats.rs | 436 +++++
.../crates/app/src/workbench/workbar.rs | 1972 ++++++++++++++++++++
apps/desktop-gpui/crates/automations/src/review.rs | 2 +
apps/desktop-gpui/crates/conversation/Cargo.toml | 6 +-
.../crates/conversation/src/composer.rs | 159 +-
.../desktop-gpui/crates/conversation/src/corpus.rs | 232 +++
.../crates/conversation/src/corpus/markdown.rs | 409 ++++
.../crates/conversation/src/edits_card.rs | 339 ++++
apps/desktop-gpui/crates/conversation/src/lib.rs | 30 +-
.../desktop-gpui/crates/conversation/src/paging.rs | 38 +
.../desktop-gpui/crates/conversation/src/quotes.rs | 193 ++
apps/desktop-gpui/crates/conversation/src/rows.rs | 226 ++-
.../crates/conversation/src/side_chat.rs | 635 +++++++
.../crates/conversation/src/side_chat/fork.rs | 325 ++++
.../crates/conversation/src/side_chat/ledger.rs | 892 +++++++++
.../crates/conversation/src/side_chat/panel.rs | 140 ++
apps/desktop-gpui/crates/conversation/src/state.rs | 471 ++++-
apps/desktop-gpui/crates/conversation/src/tests.rs | 21 +
.../crates/conversation/src/tests/attachments.rs | 2 +-
.../crates/conversation/src/tests/edits.rs | 253 +++
.../crates/conversation/src/tests/find.rs | 812 ++++++++
.../crates/conversation/src/tests/links.rs | 45 +
.../crates/conversation/src/tests/pty.rs | 173 ++
.../crates/conversation/src/tests/side_chat.rs | 1296 +++++++++++++
.../crates/conversation/src/tests/syntax.rs | 227 +++
.../crates/conversation/src/tests/turn_start.rs | 385 ++++
apps/desktop-gpui/crates/conversation/src/view.rs | 452 ++++-
.../crates/conversation/src/view/find.rs | 823 ++++++++
.../crates/conversation/src/view/landing.rs | 188 ++
.../crates/conversation/src/view/text_views.rs | 279 +++
.../crates/{conversation => files}/Cargo.toml | 9 +-
apps/desktop-gpui/crates/files/src/bench_tests.rs | 204 ++
apps/desktop-gpui/crates/files/src/desk.rs | 359 ++++
apps/desktop-gpui/crates/files/src/lib.rs | 107 ++
apps/desktop-gpui/crates/files/src/list.rs | 357 ++++
apps/desktop-gpui/crates/files/src/policy.rs | 655 +++++++
apps/desktop-gpui/crates/files/src/preview.rs | 1107 +++++++++++
apps/desktop-gpui/crates/files/src/read.rs | 260 +++
apps/desktop-gpui/crates/files/src/tests.rs | 546 ++++++
apps/desktop-gpui/crates/files/src/view.rs | 1245 ++++++++++++
apps/desktop-gpui/crates/files/src/view_tests.rs | 1015 ++++++++++
.../host-client/examples/capture_fixtures.rs | 690 ++++++-
apps/desktop-gpui/crates/host-client/src/tests.rs | 41 +-
.../fixtures/sequences/artifact_files.jsonl | 23 +
.../fixtures/sequences/inspector.jsonl | 20 +
.../host-protocol/fixtures/sequences/recall.jsonl | 4 +
.../fixtures/sequences/side_chat.jsonl | 28 +
.../fixtures/sequences/terminal.jsonl | 38 +
.../crates/host-protocol/src/artifact.rs | 406 +++-
.../crates/host-protocol/src/context.rs | 261 +++
.../crates/host-protocol/src/execution_inspect.rs | 571 ++++++
.../crates/host-protocol/src/fixture_tests.rs | 568 +++++-
.../crates/host-protocol/src/host_frame.rs | 7 +
apps/desktop-gpui/crates/host-protocol/src/lib.rs | 104 +-
.../crates/host-protocol/src/message.rs | 112 +-
.../crates/host-protocol/src/recall.rs | 548 ++++++
.../crates/host-protocol/src/runtime_resource.rs | 954 ++++++++++
.../crates/host-protocol/src/session_continuity.rs | 78 +-
.../crates/host-protocol/src/session_revision.rs | 177 ++
.../crates/host-protocol/src/session_turns.rs | 242 +++
.../crates/host-protocol/src/stored_message.rs | 4 +-
.../desktop-gpui/crates/host-protocol/src/usage.rs | 125 +-
.../crates/{conversation => inspector}/Cargo.toml | 11 +-
apps/desktop-gpui/crates/inspector/src/lib.rs | 66 +
apps/desktop-gpui/crates/inspector/src/model.rs | 762 ++++++++
.../crates/inspector/src/model_tests.rs | 535 ++++++
apps/desktop-gpui/crates/inspector/src/read.rs | 154 ++
apps/desktop-gpui/crates/inspector/src/state.rs | 520 ++++++
apps/desktop-gpui/crates/inspector/src/tests.rs | 766 ++++++++
apps/desktop-gpui/crates/inspector/src/view.rs | 1197 ++++++++++++
apps/desktop-gpui/crates/review/Cargo.toml | 5 +
apps/desktop-gpui/crates/review/src/bench_tests.rs | 2 +
apps/desktop-gpui/crates/review/src/git.rs | 6 +-
apps/desktop-gpui/crates/review/src/git_tests.rs | 5 +-
apps/desktop-gpui/crates/review/src/lib.rs | 13 +-
apps/desktop-gpui/crates/review/src/panel.rs | 897 ++++++---
.../desktop-gpui/crates/review/src/panel/scopes.rs | 568 ++++++
apps/desktop-gpui/crates/review/src/shown.rs | 13 +-
apps/desktop-gpui/crates/review/src/sync.rs | 195 +-
apps/desktop-gpui/crates/review/src/tests.rs | 241 ++-
.../crates/review/src/tests/geometry.rs | 348 ++++
apps/desktop-gpui/crates/review/src/tree.rs | 93 +-
apps/desktop-gpui/crates/review/src/turns.rs | 327 ++++
apps/desktop-gpui/crates/review/src/turns/net.rs | 631 +++++++
apps/desktop-gpui/crates/review/src/turns/patch.rs | 589 ++++++
apps/desktop-gpui/crates/review/src/turns_tests.rs | 643 +++++++
.../crates/{conversation => search}/Cargo.toml | 14 +-
apps/desktop-gpui/crates/search/src/find_bar.rs | 578 ++++++
apps/desktop-gpui/crates/search/src/lib.rs | 92 +
apps/desktop-gpui/crates/search/src/matching.rs | 293 +++
apps/desktop-gpui/crates/search/src/page.rs | 1087 +++++++++++
apps/desktop-gpui/crates/search/src/page_tests.rs | 545 ++++++
apps/desktop-gpui/crates/search/src/query.rs | 85 +
apps/desktop-gpui/crates/search/src/recall.rs | 773 ++++++++
apps/desktop-gpui/crates/search/src/searchable.rs | 100 +
apps/desktop-gpui/crates/search/src/tests.rs | 439 +++++
apps/desktop-gpui/crates/session/src/catalog.rs | 39 +-
apps/desktop-gpui/crates/session/src/page.rs | 34 +-
apps/desktop-gpui/crates/session/src/row.rs | 32 +-
apps/desktop-gpui/crates/session/src/sidebar.rs | 48 +-
.../crates/session/src/sidebar_tests.rs | 12 +-
.../crates/settings/src/general_page.rs | 42 +-
apps/desktop-gpui/crates/settings/src/lib.rs | 6 +-
.../crates/settings/src/notifications.rs | 15 +
.../crates/settings/src/preferences.rs | 201 +-
apps/desktop-gpui/crates/settings/src/section.rs | 3 +
apps/desktop-gpui/crates/settings/src/tests.rs | 53 +-
apps/desktop-gpui/crates/shared/Cargo.toml | 3 +
apps/desktop-gpui/crates/shared/src/assets.rs | 5 +-
apps/desktop-gpui/crates/shared/src/contrast.rs | 145 ++
apps/desktop-gpui/crates/shared/src/copy.rs | 21 +-
.../crates/shared/src/copy/commands.rs | 2 -
.../crates/shared/src/copy/conversation.rs | 41 +
apps/desktop-gpui/crates/shared/src/copy/files.rs | 237 +++
.../crates/shared/src/copy/inspector.rs | 324 ++++
apps/desktop-gpui/crates/shared/src/copy/review.rs | 48 +-
apps/desktop-gpui/crates/shared/src/copy/search.rs | 96 +
.../crates/shared/src/copy/settings.rs | 10 +
.../crates/shared/src/copy/side_chat.rs | 102 +
.../crates/shared/src/copy/terminal.rs | 104 ++
.../desktop-gpui/crates/shared/src/copy/workbar.rs | 45 +
apps/desktop-gpui/crates/shared/src/icons.rs | 24 +
apps/desktop-gpui/crates/shared/src/layout.rs | 19 +
apps/desktop-gpui/crates/shared/src/lib.rs | 7 +-
apps/desktop-gpui/crates/shared/src/links.rs | 91 +
apps/desktop-gpui/crates/shared/src/menu.rs | 3 +
apps/desktop-gpui/crates/shared/src/palette.rs | 285 ++-
apps/desktop-gpui/crates/shared/src/syntax.rs | 233 +++
apps/desktop-gpui/crates/shared/src/theme.rs | 408 ++++
apps/desktop-gpui/crates/shared/src/time.rs | 32 +
.../crates/{conversation => terminal}/Cargo.toml | 16 +-
apps/desktop-gpui/crates/terminal/src/controls.rs | 251 +++
apps/desktop-gpui/crates/terminal/src/emulator.rs | 535 ++++++
apps/desktop-gpui/crates/terminal/src/hydration.rs | 186 ++
apps/desktop-gpui/crates/terminal/src/input.rs | 429 +++++
apps/desktop-gpui/crates/terminal/src/lib.rs | 91 +
apps/desktop-gpui/crates/terminal/src/link.rs | 284 +++
apps/desktop-gpui/crates/terminal/src/owner.rs | 802 ++++++++
apps/desktop-gpui/crates/terminal/src/search.rs | 164 ++
apps/desktop-gpui/crates/terminal/src/terminal.rs | 1310 +++++++++++++
apps/desktop-gpui/crates/terminal/src/tests.rs | 1230 ++++++++++++
apps/desktop-gpui/crates/terminal/src/view.rs | 1307 +++++++++++++
.../desktop-gpui/crates/terminal/src/view/blink.rs | 140 ++
.../crates/terminal/src/view/box_drawing.rs | 579 ++++++
.../crates/terminal/src/view/element.rs | 509 +++++
apps/desktop-gpui/crates/terminal/src/view/find.rs | 277 +++
apps/desktop-gpui/crates/terminal/src/view/grid.rs | 835 +++++++++
.../desktop-gpui/crates/terminal/src/view/links.rs | 184 ++
.../crates/terminal/src/view/scrollbar.rs | 128 ++
.../desktop-gpui/crates/terminal/src/view_tests.rs | 813 ++++++++
.../crates/terminal/tests/live_host.rs | 361 ++++
.../crates/transcript-model/src/edits.rs | 853 +++++++++
.../crates/transcript-model/src/lib.rs | 1 +
.../crates/transcript-model/src/transcript.rs | 80 +
.../crates/transcript-model/tests/synthetic.rs | 231 +++
apps/desktop-gpui/crates/workspace/src/actions.rs | 27 +-
apps/desktop-gpui/docs/dev-host.md | 30 +
apps/desktop-gpui/docs/plan/phase-4-modules.md | 184 ++
apps/desktop-gpui/docs/upstream-issues.md | 107 ++
apps/desktop-gpui/scripts/design-icons.py | 7 +
184 files changed, 52649 insertions(+), 1473 deletions(-)
diff --git a/apps/desktop-gpui/AGENTS.md b/apps/desktop-gpui/AGENTS.md
index 4722fb766b..e45a16c1f4 100644
--- a/apps/desktop-gpui/AGENTS.md
+++ b/apps/desktop-gpui/AGENTS.md
@@ -41,7 +41,7 @@ phase plan is in `docs/plan/`.
```text
crates/
-├── app/ shell: main, windows, menus; composes feature crates
+├── app/ shell: main, windows, menus, the workbar's strip; composes feature crates
├── host-protocol/ wire types and frame codec; no GPUI, no I/O
├── host-client/ transport, handshake, request multiplexing, subscriptions,
│ reconnect, Host spawn
@@ -50,7 +50,17 @@ crates/
├── session/ session catalog, creation, switching, metadata
├── transcript-model/ pure logic: subscription frames -> transcript state; no GPUI
├── conversation/ transcript, streaming output, tool calls, permission prompts, composer
-├── review/ the task's Git changes, read on this machine, and the changes panel
+├── review/ the task's Git changes, read on this machine, and the workbar's
+│ Changes face
+├── search/ finding text: the Searchable seam, matching, the find bar, and the
+│ Search page over every task
+├── terminal/ a task's terminals: Host-owned PTYs driven through runtime resources,
+│ the emulator their output is parsed into, key and mouse tables, and
+│ the terminal view (the workbar's Terminal face) that paints them
+├── files/ a task's artifacts read from the Host: the workbar's Files face,
+│ its list, previews and actions
+├── inspector/ a task's trace, usage and context window read from the Host: the
+│ workbar's Trace face (Desktop's Inspector)
└── settings/ model connections, preferences
docs/
├── plan/ phase plans
diff --git a/apps/desktop-gpui/CHANGELOG.md b/apps/desktop-gpui/CHANGELOG.md
index c5ebcf7c9e..fbf01ce993 100644
--- a/apps/desktop-gpui/CHANGELOG.md
+++ b/apps/desktop-gpui/CHANGELOG.md
@@ -158,6 +158,38 @@ The version lives only in the workspace `Cargo.toml`. A release moves the
counted each second. While the Runtime retries a provider request the
line gives the reason and counts down to the attempt, or says the attempt
is under way.
+- A new task opens as a draft and is created with its first message; a
+ project's heading starts a task in that project; the thinking level is
+ chosen beside the model.
+- A long Tool output scrolls inside the transcript, a Write or Edit card
+ shows its diff, and a code cell's finished call shows what it did and
+ returned. Dragging the sidebar's edge past its narrowest width collapses
+ it.
+- The workbar: the right panel as tool tabs, opened beside the conversation,
+ dragged wide, or maximized in its place.
+ - Changes: the task folder's Git changes (the whole branch, what is
+ uncommitted, one commit, or one turn), every changed file beside the
+ selected file's diff. A card under a settled turn's reply lists the
+ files it edited and opens its changes; the task's folder, branch and
+ changes show over the composer.
+ - Files (⌘P): the task's files, with a preview of each and its actions.
+ HTML pages show rendered or as source (no scripts or styles) and open in
+ the default app.
+ - Trace: the task's trace, usage and context window, as Maka Desktop's
+ Inspector shows them.
+ - Terminal: terminals the Host runs for the task, drawn as Zed draws
+ them, with a scrollbar over the scrollback, ⌘-click on web links, a
+ blinking cursor, and Settings › Terminal (Option as Meta).
+ - Side chat (⌥⌘S): a side conversation about the task on a hidden fork
+ of it, which reads the task's history and does not change the task.
+ Text selected in the conversation goes in as a quote. Closing a side
+ chat or deleting its task removes the fork; forks a quit leaves behind
+ are removed at the next launch.
+- Find in the conversation (⌘F), with match case and whole word; each
+ Chinese character counts as a word.
+- Search every task (⇧⌘F, the sidebar's search button, or the palette): the
+ Search page, which opens a task at the passage it found.
+- Syntax colours in code blocks, diffs and file previews.
### Changed
@@ -167,3 +199,9 @@ The version lives only in the workspace `Cargo.toml`. A release moves the
- A connection to an endpoint Maka does not know is added as a Custom
connection with its API protocol (OpenAI Chat, OpenAI Responses, or
Anthropic Messages), replacing the three custom relay providers.
+
+### Security
+
+- A link in rendered text (a reply, a file in the Files face, the daily
+ review) opens only when it is a web or mail address, as in Maka Desktop.
+ Any address used to open, and a `file:` link could start an application.
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index ca670562e0..f3b444466f 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -131,6 +131,31 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "alacritty_terminal"
+version = "0.26.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bda177466b9524d59f1b12f0dd30b68696788e9992a7e959021c4a0ed96fcf59"
+dependencies = [
+ "base64 0.22.1",
+ "bitflags 2.13.2",
+ "home",
+ "libc",
+ "log",
+ "miow",
+ "parking_lot",
+ "piper",
+ "polling",
+ "regex-automata",
+ "rustix",
+ "rustix-openpty",
+ "serde",
+ "signal-hook",
+ "unicode-width",
+ "vte",
+ "windows-sys 0.59.0",
+]
+
[[package]]
name = "aligned"
version = "0.4.3"
@@ -193,23 +218,29 @@ version = "0.1.0"
dependencies = [
"async-channel",
"automations",
+ "base64 0.22.1",
"bots",
"conversation",
"extensions",
+ "files",
"futures-lite",
"gpui-kit",
"host-client",
"host-protocol",
+ "inspector",
"log",
"objc2 0.6.4",
"objc2-app-kit 0.3.2",
"objc2-foundation 0.3.2",
"pet",
"review",
+ "search",
"serde_json",
"session",
"settings",
"shared",
+ "terminal",
+ "transcript-model",
"workspace",
]
@@ -697,6 +728,9 @@ name = "bitflags"
version = "2.13.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+dependencies = [
+ "serde_core",
+]
[[package]]
name = "bitstream-io"
@@ -918,9 +952,9 @@ dependencies = [
[[package]]
name = "cc"
-version = "1.4.7"
+version = "1.2.67"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "54413ede23c2daf518f35156dfde027feb2374004d63bd497f983c8db9c0e313"
+checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38"
dependencies = [
"find-msvc-tools",
"jobserver",
@@ -1160,12 +1194,16 @@ version = "0.1.0"
dependencies = [
"async-channel",
"base64 0.22.1",
+ "blocking",
"futures-lite",
"gpui-kit",
"host-client",
"host-protocol",
"image",
"log",
+ "markdown",
+ "search",
+ "serde",
"serde_json",
"shared",
"transcript-model",
@@ -1452,6 +1490,12 @@ dependencies = [
"linktime-proc-macro",
]
+[[package]]
+name = "cursor-icon"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f"
+
[[package]]
name = "data-encoding"
version = "2.11.1"
@@ -1895,6 +1939,24 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "files"
+version = "0.1.0"
+dependencies = [
+ "async-channel",
+ "base64 0.22.1",
+ "dirs 6.0.0",
+ "futures-lite",
+ "gpui-kit",
+ "host-protocol",
+ "log",
+ "serde_json",
+ "shared",
+ "transcript-model",
+ "uuid",
+ "workspace",
+]
+
[[package]]
name = "find-msvc-tools"
version = "0.1.13"
@@ -2472,6 +2534,24 @@ dependencies = [
"smallvec",
"smol",
"tracing",
+ "tree-sitter",
+ "tree-sitter-bash",
+ "tree-sitter-c",
+ "tree-sitter-cpp",
+ "tree-sitter-css",
+ "tree-sitter-diff",
+ "tree-sitter-go",
+ "tree-sitter-html",
+ "tree-sitter-java",
+ "tree-sitter-javascript",
+ "tree-sitter-json",
+ "tree-sitter-md",
+ "tree-sitter-python",
+ "tree-sitter-rust",
+ "tree-sitter-sequel",
+ "tree-sitter-toml-ng",
+ "tree-sitter-typescript",
+ "tree-sitter-yaml",
"unicode-segmentation",
"unicode-width",
"uuid",
@@ -3490,6 +3570,15 @@ dependencies = [
"digest 0.10.7",
]
+[[package]]
+name = "home"
+version = "0.5.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "host-client"
version = "0.1.0"
@@ -3889,6 +3978,22 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "inspector"
+version = "0.1.0"
+dependencies = [
+ "async-channel",
+ "futures-lite",
+ "gpui-kit",
+ "host-client",
+ "host-protocol",
+ "log",
+ "serde",
+ "serde_json",
+ "shared",
+ "workspace",
+]
+
[[package]]
name = "instant"
version = "0.1.13"
@@ -4545,6 +4650,15 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "miow"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "536bfad37a309d62069485248eeaba1e8d9853aaf951caaeaed0585a95346f08"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "moxcms"
version = "0.8.1"
@@ -6226,10 +6340,15 @@ dependencies = [
"async-fs",
"async-io",
"async-process",
+ "base64 0.22.1",
"futures-lite",
"gpui-kit",
+ "host-protocol",
"log",
+ "serde_json",
"shared",
+ "similar",
+ "transcript-model",
]
[[package]]
@@ -6403,6 +6522,17 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "rustix-openpty"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1de16c7c59892b870a6336f185dc10943517f1327447096bbb7bb32cd85e2393"
+dependencies = [
+ "errno",
+ "libc",
+ "rustix",
+]
+
[[package]]
name = "rustls"
version = "0.23.45"
@@ -6613,6 +6743,21 @@ version = "4.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c107b6f4780854c8b126e228ea8869f4d7b71260f962fefb57b996b8959ba6b"
+[[package]]
+name = "search"
+version = "0.1.0"
+dependencies = [
+ "async-channel",
+ "futures-lite",
+ "gpui-kit",
+ "host-protocol",
+ "icu_normalizer",
+ "log",
+ "serde_json",
+ "shared",
+ "workspace",
+]
+
[[package]]
name = "security-framework"
version = "3.7.0"
@@ -6877,6 +7022,8 @@ version = "0.1.0"
dependencies = [
"chrono",
"gpui-kit",
+ "serde_json",
+ "url",
]
[[package]]
@@ -6900,6 +7047,16 @@ version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+[[package]]
+name = "signal-hook"
+version = "0.4.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b29ffa27d3d59a049bb328258de100f8012848d1b08d444e08bbc02ac468435e"
+dependencies = [
+ "libc",
+ "signal-hook-registry",
+]
+
[[package]]
name = "signal-hook-registry"
version = "1.4.8"
@@ -7088,6 +7245,12 @@ version = "0.4.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d08889ec5408683408db66ad89e0e1f93dff55c73a4ccc71c427d5b277ee47e6"
+[[package]]
+name = "streaming-iterator"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2b2231b7c3057d5e4ad0156fb3dc807d900806020c5ffa3ee6ff2c8c76fb8520"
+
[[package]]
name = "strict-num"
version = "0.1.1"
@@ -7393,7 +7556,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
- "getrandom 0.3.4",
+ "getrandom 0.4.3",
"once_cell",
"rustix",
"windows-sys 0.61.2",
@@ -7419,6 +7582,27 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "terminal"
+version = "0.1.0"
+dependencies = [
+ "alacritty_terminal",
+ "async-channel",
+ "conversation",
+ "futures-lite",
+ "gpui-kit",
+ "host-client",
+ "host-protocol",
+ "log",
+ "regex",
+ "search",
+ "serde_json",
+ "shared",
+ "url",
+ "uuid",
+ "workspace",
+]
+
[[package]]
name = "thiserror"
version = "1.0.69"
@@ -7789,6 +7973,196 @@ dependencies = [
"thiserror 2.0.21",
]
+[[package]]
+name = "tree-sitter"
+version = "0.26.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "17ebdd3a5a7e28a1890b876fdbd0c3c0fe0a6336cffaa104f11b9f720c9daa29"
+dependencies = [
+ "cc",
+ "regex",
+ "regex-syntax",
+ "serde_json",
+ "streaming-iterator",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-bash"
+version = "0.23.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "329a4d48623ac337d42b1df84e81a1c9dbb2946907c102ca72db158c1964a52e"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-c"
+version = "0.24.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9b2eb57a55fed6b00812912e730b7a275cf4fe98bfd6a5d76263d4438371728"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-cpp"
+version = "0.23.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df2196ea9d47b4ab4a31b9297eaa5a5d19a0b121dceb9f118f6790ad0ab94743"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-css"
+version = "0.23.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ad6489794d41350d12a7fbe520e5199f688618f43aace5443980d1ddcf1b29e"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-diff"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfe1e5ca280a65dfe5ba4205c1bcc84edf486464fed315db53dee6da9a335889"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-go"
+version = "0.23.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b13d476345220dbe600147dd444165c5791bf85ef53e28acbedd46112ee18431"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-html"
+version = "0.23.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "261b708e5d92061ede329babaaa427b819329a9d427a1d710abb0f67bbef63ee"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-java"
+version = "0.23.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0aa6cbcdc8c679b214e616fd3300da67da0e492e066df01bcf5a5921a71e90d6"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-javascript"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf40bf599e0416c16c125c3cec10ee5ddc7d1bb8b0c60fa5c4de249ad34dc1b1"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-json"
+version = "0.24.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4d727acca406c0020cffc6cf35516764f36c8e3dc4408e5ebe2cb35a947ec471"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-language"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0af592be68c579aa78a16846bd19422978c3c52e438523d45ff5d1bff1f9d4a"
+
+[[package]]
+name = "tree-sitter-md"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2efd398be546456c814598ee56c0f51769a77241511b4a58077815d120afa882"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-python"
+version = "0.23.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d065aaa27f3aaceaf60c1f0e0ac09e1cb9eb8ed28e7bcdaa52129cffc7f4b04"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-rust"
+version = "0.24.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "439e577dbe07423ec2582ac62c7531120dbfccfa6e5f92406f93dd271a120e45"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-sequel"
+version = "0.3.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d198ad3c319c02e43c21efa1ec796b837afcb96ffaef1a40c1978fbdcec7d17"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-toml-ng"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e9adc2c898ae49730e857d75be403da3f92bb81d8e37a2f918a08dd10de5ebb1"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-typescript"
+version = "0.23.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c5f76ed8d947a75cc446d5fccd8b602ebf0cde64ccf2ffa434d873d7a575eff"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
+[[package]]
+name = "tree-sitter-yaml"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53c223db85f05e34794f065454843b0668ebc15d240ada63e2b5939f43ce7c97"
+dependencies = [
+ "cc",
+ "tree-sitter-language",
+]
+
[[package]]
name = "triomphe"
version = "0.1.16"
@@ -8114,6 +8488,20 @@ dependencies = [
"libc",
]
+[[package]]
+name = "vte"
+version = "0.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd"
+dependencies = [
+ "arrayvec",
+ "bitflags 2.13.2",
+ "cursor-icon",
+ "log",
+ "memchr",
+ "serde",
+]
+
[[package]]
name = "wait-timeout"
version = "0.2.1"
diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml
index 8bb35aeec0..91db8e8bfa 100644
--- a/apps/desktop-gpui/Cargo.toml
+++ b/apps/desktop-gpui/Cargo.toml
@@ -23,13 +23,17 @@ members = [
"crates/bots",
"crates/conversation",
"crates/extensions",
+ "crates/files",
"crates/host-client",
"crates/host-protocol",
+ "crates/inspector",
"crates/pet",
"crates/review",
+ "crates/search",
"crates/session",
"crates/settings",
"crates/shared",
+ "crates/terminal",
"crates/transcript-model",
"crates/workspace",
]
@@ -50,15 +54,48 @@ workspace = { path = "crates/workspace" }
session = { path = "crates/session" }
conversation = { path = "crates/conversation" }
extensions = { path = "crates/extensions" }
+files = { path = "crates/files" }
+inspector = { path = "crates/inspector" }
automations = { path = "crates/automations" }
pet = { path = "crates/pet" }
review = { path = "crates/review" }
+search = { path = "crates/search" }
settings = { path = "crates/settings" }
+terminal = { path = "crates/terminal" }
bots = { path = "crates/bots" }
# Pinned to git main for the Diff component; back to the crates.io release when it ships (expected 2026-10-12).
-gpui-kit = { git = "https://github.com/longbridge/gpui-kit", rev = "1e41f17e27ea46589af9c6c428d18b5bf23ef4f6" }
+#
+# Syntax colours: the kit's highlighter colours nothing without its
+# `tree-sitter` feature (which brings JSON) and a grammar per language. The
+# grammars are a curated set, the languages a coding agent's transcript,
+# diffs and files mostly hold, not the kit's whole `tree-sitter-languages`
+# list: each grammar is a C parser compiled into the binary.
+gpui-kit = { git = "https://github.com/longbridge/gpui-kit", rev = "1e41f17e27ea46589af9c6c428d18b5bf23ef4f6", features = [
+ "tree-sitter",
+ "tree-sitter-bash",
+ "tree-sitter-c",
+ "tree-sitter-cpp",
+ "tree-sitter-css",
+ "tree-sitter-diff",
+ "tree-sitter-go",
+ "tree-sitter-html",
+ "tree-sitter-java",
+ "tree-sitter-javascript",
+ "tree-sitter-markdown",
+ "tree-sitter-python",
+ "tree-sitter-rust",
+ "tree-sitter-sql",
+ "tree-sitter-toml",
+ "tree-sitter-tsx",
+ "tree-sitter-typescript",
+ "tree-sitter-yaml",
+] }
+# The terminal emulator a terminal's Host output is parsed into (the
+# terminal crate): its grid, modes and vte parser only; the Host owns the
+# PTY, so its tty and event loop stay unused.
+alacritty_terminal = "0.26"
anyhow = "1"
async-channel = "2"
async-fs = "2"
@@ -80,17 +117,31 @@ futures-lite = "2"
# builds; no aws-lc.
futures-rustls = { version = "0.26", default-features = false, features = ["ring", "tls12"] }
getrandom = "0.4"
+# Unicode NFC, as the Host folds what recall matches (`foldForMatch`): the
+# Search page highlights matched terms by the same rule. Already in the
+# graph through url's IDNA, with its compiled data.
+icu_normalizer = { version = "2.3", default-features = false, features = ["compiled_data"] }
# Only the codecs attachments decode and encode (the conversation crate).
# GPUI already depends on this version with more of them.
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "gif", "webp", "tiff", "bmp"] }
log = "0.4"
+# The Markdown parser gpui-kit's text view uses (same version, already in
+# the graph): the find bar reads a reply's visible text with the same parse.
+markdown = { version = "1.0.0", default-features = false }
# QR codes for the chat bots' guided setup (the settings crate draws them);
# the module matrix only, no image or SVG renderer.
qrcode = { version = "0.14", default-features = false }
+# The web address pattern a terminal's links are found by (the terminal
+# crate). Already in the graph through GPUI and gpui-kit.
+regex = "1.13"
rustls-platform-verifier = "0.7"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
+# Line diffs of a turn's file before and after it (the review crate's turn
+# changes): the comparison only, no text helpers. Already in the graph
+# through gpui-kit's Diff component.
+similar = { version = "2.7", default-features = false }
# The system's preferred languages, for the Follow system interface language.
sys-locale = "0.3"
thiserror = "2"
diff --git a/apps/desktop-gpui/assets/icons/maka/activity.svg b/apps/desktop-gpui/assets/icons/maka/activity.svg
new file mode 100644
index 0000000000..5df5566b3d
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/maka/activity.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2.25 8h2.25l1.75-4.75 3.5 9.5L11.5 8h2.25"/></svg>
diff --git a/apps/desktop-gpui/assets/icons/maka/chat.svg b/apps/desktop-gpui/assets/icons/maka/chat.svg
new file mode 100644
index 0000000000..a4f60ca8d9
--- /dev/null
+++ b/apps/desktop-gpui/assets/icons/maka/chat.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5.4 13.12A5.75 5.75 0 1 0 2.88 10.6L2.25 13.75Z"/><path d="M6.35 6.45a1.7 1.7 0 1 1 2.4 1.55c-.45.22-.75.55-.75 1.05v.2"/><path d="M8 10.85h.01" stroke-width="2"/></svg>
diff --git a/apps/desktop-gpui/crates/app/Cargo.toml b/apps/desktop-gpui/crates/app/Cargo.toml
index d589038905..de933e0f35 100644
--- a/apps/desktop-gpui/crates/app/Cargo.toml
+++ b/apps/desktop-gpui/crates/app/Cargo.toml
@@ -35,15 +35,20 @@ automations.workspace = true
bots.workspace = true
conversation.workspace = true
extensions.workspace = true
+files.workspace = true
futures-lite.workspace = true
gpui-kit.workspace = true
host-protocol.workspace = true
+inspector.workspace = true
log.workspace = true
pet.workspace = true
review.workspace = true
+search.workspace = true
session.workspace = true
settings.workspace = true
shared.workspace = true
+terminal.workspace = true
+transcript-model.workspace = true
workspace.workspace = true
# The Dock tile's content view, for the app icon Settings chooses (see
@@ -65,6 +70,7 @@ objc2-foundation = { version = "0.3", default-features = false, features = ["std
[dev-dependencies]
async-channel.workspace = true
+base64.workspace = true
bots = { workspace = true, features = ["test-support"] }
gpui-kit = { workspace = true, features = ["test-support"] }
host-client.workspace = true
diff --git a/apps/desktop-gpui/crates/app/src/chrome_tests.rs b/apps/desktop-gpui/crates/app/src/chrome_tests.rs
index cb5863c7ba..8ed426ef50 100644
--- a/apps/desktop-gpui/crates/app/src/chrome_tests.rs
+++ b/apps/desktop-gpui/crates/app/src/chrome_tests.rs
@@ -828,13 +828,13 @@ fn escape_clears_the_query_then_closes_the_palette(cx: &mut TestAppContext) {
}
#[gpui_kit::test]
-fn the_palette_opens_a_task_by_title_from_the_sidebar_search(cx: &mut TestAppContext) {
+fn the_palette_opens_a_task_by_title(cx: &mut TestAppContext) {
let harness = Harness::open(vec![session("s1", "Alpha"), session("s2", "Beta release")], cx);
let draft = harness.draft_id(cx);
harness.with_window(cx, |window, cx| window.click(row("s1"), cx));
- harness.with_window(cx, |window, cx| window.click("command-palette-button", cx));
+ harness.with_window(cx, |window, cx| window.press("cmd-k", cx));
harness.with_window(cx, |window, cx| {
- assert!(window.find("command-palette").visible(), "the search button opens it");
+ assert!(window.find("command-palette").visible(), "⌘K opens it");
window.input("beta", cx);
});
harness.with_window(cx, |window, cx| window.press("enter", cx));
@@ -1313,8 +1313,11 @@ fn the_view_menu_zooms_with_its_keys_shown(cx: &mut TestAppContext) {
}
}
+/// ⌘F is each surface's own: a page's search, the settings' section
+/// search, and in the task view Find in conversation, which an empty task
+/// has nothing for (`find_tests` has the rest).
#[gpui_kit::test]
-fn command_f_finds_on_pages_and_in_settings_but_not_in_the_task_view(cx: &mut TestAppContext) {
+fn command_f_finds_on_pages_and_in_settings(cx: &mut TestAppContext) {
use gpui_kit::{Action as _, Focusable as _};
use workspace::actions::{FocusSearch, OpenExtensions};
let harness = Harness::open(vec![session("s1", "Alpha")], cx);
@@ -1324,7 +1327,8 @@ fn command_f_finds_on_pages_and_in_settings_but_not_in_the_task_view(cx: &mut Te
window.click(draft.clone(), cx);
window.input("hello", cx);
});
- // The task view leaves ⌘F unbound for now.
+ // The task view's ⌘F is Find in conversation; an empty task has
+ // nothing to find, and its draft keeps focus.
harness.with_window(cx, |window, cx| {
assert!(window.highest_precedence_binding_for_action(&FocusSearch).is_none());
window.press("secondary-f", cx);
diff --git a/apps/desktop-gpui/crates/app/src/commands.rs b/apps/desktop-gpui/crates/app/src/commands.rs
index e806ecf764..b175a0212d 100644
--- a/apps/desktop-gpui/crates/app/src/commands.rs
+++ b/apps/desktop-gpui/crates/app/src/commands.rs
@@ -36,16 +36,18 @@ use session::{
SelectNextSession, SelectPreviousSession,
};
use shared::copy::{
- self, Text, commands as words, conversation, extensions as pages, settings as settings_copy,
+ self, Text, commands as words, conversation, extensions as pages, search as find_words,
+ settings as settings_copy,
};
use shared::icons::MakaIcon;
use workspace::actions::{
- AddConnection, ArchiveTask, FlagTask, FocusComposer, GoBack, GoForward, NewSession,
- OpenCommandPalette, OpenExtensions, OpenProjectSettings, OpenScheduledTasks, OpenSettings,
- Reconnect, SendMessage, ShowKeyboardShortcuts, StopTurn, SwitchStateRoot, ToggleSidebar,
+ AddConnection, ArchiveTask, FindInConversation, FlagTask, FocusComposer, GoBack, GoForward,
+ NewSession, OpenCommandPalette, OpenExtensions, OpenProjectSettings, OpenScheduledTasks,
+ OpenSettings, Reconnect, SearchAllTasks, SendMessage, ShowKeyboardShortcuts, StopTurn,
+ SwitchStateRoot, ToggleSidebar,
};
-use crate::Quit;
+use crate::{Quit, TASK_VIEW_CONTEXT};
/// A group of commands, in the order the palette and the sheet list them.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
@@ -83,8 +85,9 @@ pub struct CommandSpec {
/// The key context the binding applies in; `None` for anywhere in the
/// window.
pub context: Option<&'static str>,
- /// Whether the palette offers it: window-wide commands, except the
- /// ones that open the palette's own neighbours.
+ /// Whether the palette offers it: the commands that act on the window
+ /// or the task, wherever focus is, except the ones that open the
+ /// palette's own neighbours; not the keys of a focused list.
pub palette: bool,
icon: fn() -> Icon,
action: fn() -> Box<dyn Action>,
@@ -145,6 +148,15 @@ pub static COMMANDS: &[CommandSpec] = &[
icon: || Icon::new(MakaIcon::Stop),
action: || Box::new(StopTurn),
},
+ CommandSpec {
+ id: "find-in-conversation",
+ label: find_words::FIND_IN_CONVERSATION,
+ group: CommandGroup::Task,
+ context: Some(TASK_VIEW_CONTEXT),
+ palette: true,
+ icon: || Icon::new(MakaIcon::Search),
+ action: || Box::new(FindInConversation),
+ },
CommandSpec {
id: "archive-task",
label: words::ARCHIVE_TASK,
@@ -208,6 +220,15 @@ pub static COMMANDS: &[CommandSpec] = &[
icon: || Icon::new(AssetIcon::Timer),
action: || Box::new(OpenScheduledTasks),
},
+ CommandSpec {
+ id: "search-all-tasks",
+ label: find_words::SEARCH_ALL_TASKS,
+ group: CommandGroup::View,
+ context: None,
+ palette: true,
+ icon: || Icon::new(MakaIcon::Search),
+ action: || Box::new(SearchAllTasks),
+ },
CommandSpec {
id: "command-palette",
label: words::OPEN_PALETTE,
@@ -370,11 +391,30 @@ pub static COMMANDS: &[CommandSpec] = &[
icon: || Icon::new(IconName::ArrowDown),
action: || Box::new(ScrollToBottom),
},
+ // While the find bar shows, anywhere in the task view.
+ CommandSpec {
+ id: "next-match",
+ label: find_words::NEXT_MATCH,
+ group: CommandGroup::Transcript,
+ context: Some(TASK_VIEW_CONTEXT),
+ palette: false,
+ icon: || Icon::new(MakaIcon::ChevronRight),
+ action: || Box::new(search::SelectNextMatch),
+ },
+ CommandSpec {
+ id: "previous-match",
+ label: find_words::PREVIOUS_MATCH,
+ group: CommandGroup::Transcript,
+ context: Some(TASK_VIEW_CONTEXT),
+ palette: false,
+ icon: || Icon::new(MakaIcon::ChevronLeft),
+ action: || Box::new(search::SelectPreviousMatch),
+ },
];
/// The commands the palette may list, in table order.
pub fn palette_commands() -> impl Iterator<Item = &'static CommandSpec> {
- COMMANDS.iter().filter(|command| command.palette && command.context.is_none())
+ COMMANDS.iter().filter(|command| command.palette)
}
/// The command whose key is `id`.
diff --git a/apps/desktop-gpui/crates/app/src/find_tests.rs b/apps/desktop-gpui/crates/app/src/find_tests.rs
new file mode 100644
index 0000000000..39b1239d43
--- /dev/null
+++ b/apps/desktop-gpui/crates/app/src/find_tests.rs
@@ -0,0 +1,253 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! Find in the conversation in the window: ⌘F in the task view, the bar's
+//! place over the transcript, and the command in the palette and the
+//! keyboard shortcuts sheet.
+
+use base64::Engine as _;
+use gpui_kit::component::kbd::Kbd;
+use gpui_kit::test::TestWindowExt as _;
+use gpui_kit::{AsKeystroke as _, Focusable as _, KeyContext, TestAppContext, px, size};
+use shared::domain_element_id;
+
+use crate::TASK_VIEW_CONTEXT;
+use crate::chrome_tests::row;
+use crate::tests::{EPOCH, Harness, ScriptedHost, session, settle};
+use serde_json::{Value, json};
+
+/// Task `s1`'s `subscription.open`: one settled turn in its tail.
+fn open_with_a_turn() -> Value {
+ let rows = [
+ json!({"type": "user", "id": "t1", "turnId": "t1", "ts": 1, "text": "Where is the needle?"}),
+ json!({"type": "assistant", "id": "t1-a", "turnId": "t1", "ts": 2,
+ "text": "The **needle** is here.", "contentOrder": ["text"], "modelId": "m"}),
+ json!({"type": "turn_state", "id": "t1-end", "turnId": "t1", "ts": 3,
+ "status": "completed"}),
+ ];
+ let fragments: Vec<Value> = rows
+ .iter()
+ .enumerate()
+ .rev()
+ .map(|(ix, row)| {
+ let bytes = serde_json::to_vec(row).expect("row");
+ json!({
+ "sequence": ix + 1, "byteOffset": 0, "totalBytes": bytes.len(),
+ "payloadDigest": null,
+ "data": base64::engine::general_purpose::STANDARD.encode(&bytes)
+ })
+ })
+ .collect();
+ json!({
+ "hostEpoch": EPOCH, "subscriptionId": "sub-s1", "nextSequence": 1,
+ "snapshot": {
+ "schemaVersion": 5,
+ "session": {"sessionId": "s1", "metadataRevision": 1, "status": "active",
+ "createdAt": 1, "isArchived": false},
+ "projectionRevision": 1, "rootTurn": null, "goal": null,
+ "queue": {"hostEpoch": EPOCH, "queueRevision": 0, "steering": [], "followup": []},
+ "interactions": {"pending": []}
+ },
+ "activeAssistantStreams": [],
+ "transcript": {"durable": {
+ "kind": "page", "sessionId": "s1", "direction": "older", "throughSequence": 3,
+ "rawBytes": 0, "fragments": fragments, "nextCursor": null,
+ "endsAtTurnBoundary": true
+ }}
+ })
+}
+
+/// Task `s1` selected, a turn in it, and "hello" in its draft.
+fn task_with_a_turn(cx: &mut TestAppContext) -> Harness {
+ let transport = ScriptedHost::new(vec![session("s1", "Alpha", "/work/demo", "active")]);
+ transport.reply("subscription.open", Ok(open_with_a_turn()));
+ let harness = Harness::with_transport(transport, cx);
+ harness.with_window(cx, |window, cx| window.click(row("s1"), cx));
+ let draft = harness.draft_id(cx);
+ harness.with_window(cx, |window, cx| {
+ window.click(draft.clone(), cx);
+ window.input("hello", cx);
+ });
+ harness
+}
+
+fn find_open(harness: &Harness, cx: &mut TestAppContext) -> bool {
+ harness
+ .workbench
+ .read_with(cx, |workbench, cx| workbench.conversation().read(cx).is_find_open())
+}
+
+/// Whether the bar's query has keyboard focus.
+fn query_focused(harness: &Harness, cx: &mut TestAppContext) -> bool {
+ let bar = harness
+ .workbench
+ .read_with(cx, |workbench, cx| workbench.conversation().read(cx).find_bar().cloned())
+ .expect("the bar was shown");
+ harness.with_window(cx, |window, cx| {
+ bar.read(cx).query().read(cx).focus_handle(cx).is_focused(window)
+ })
+}
+
+/// The bar over the transcript: under the plate's header, inside the
+/// transcript's edges, at most about 360 pt wide.
+fn assert_placed(harness: &Harness, cx: &mut TestAppContext) {
+ harness.with_window(cx, |window, _| {
+ let header = window.find("main-header").bounds();
+ let transcript = window.find("conversation-transcript").bounds();
+ let bar = window.find("find-bar").bounds();
+ assert!(bar.top() >= header.bottom(), "under the header: {bar:?} {header:?}");
+ assert!(bar.top() >= transcript.top() && bar.top() <= transcript.top() + px(12.));
+ assert!(bar.left() >= transcript.left() && bar.right() <= transcript.right(), "{bar:?}");
+ assert!(bar.size.width <= px(360.5), "{bar:?}");
+ assert!(transcript.right() - bar.right() <= px(16.), "at the top right: {bar:?}");
+ // One row of controls, all inside the bar, the query widest.
+ let query = window.find("find-query").bounds();
+ let close = window.find("find-close").bounds();
+ assert!(query.left() >= bar.left() && close.right() <= bar.right(), "{query:?} {close:?}");
+ assert!(query.top() < close.bottom() && close.top() < query.bottom(), "one row");
+ assert!(query.size.width >= px(80.), "room to type: {query:?}");
+ });
+}
+
+#[gpui_kit::test]
+fn command_f_in_the_task_view_opens_the_bar_and_escape_returns_to_the_draft(
+ cx: &mut TestAppContext,
+) {
+ let harness = task_with_a_turn(cx);
+ let draft = harness.draft_id(cx);
+ harness.with_window(cx, |window, cx| window.press("cmd-f", cx));
+ assert!(find_open(&harness, cx));
+ assert!(query_focused(&harness, cx), "the query has focus");
+ assert_eq!(harness.draft(cx), "hello", "the draft keeps its text");
+ assert_placed(&harness, cx);
+ harness.with_window(cx, |window, _| {
+ let bar = window.find("find-bar").bounds();
+ assert!((bar.size.width - px(360.)).abs() < px(1.), "360 pt in a wide window: {bar:?}");
+ });
+ // ⌘F again selects the query; Escape closes the bar and gives focus
+ // back to the draft.
+ harness.with_window(cx, |window, cx| window.input("needle", cx));
+ harness.with_window(cx, |window, cx| window.press("cmd-f", cx));
+ harness.with_window(cx, |window, cx| window.input("other", cx));
+ let query = harness.workbench.read_with(cx, |workbench, cx| {
+ let bar = workbench.conversation().read(cx).find_bar().cloned().expect("bar");
+ bar.read(cx).query().read(cx).value().to_string()
+ });
+ assert_eq!(query, "other", "the existing query was selected and replaced");
+ harness.with_window(cx, |window, cx| window.press("escape", cx));
+ assert!(!find_open(&harness, cx));
+ harness.with_window(cx, |window, _| {
+ assert!(window.try_find("find-bar").is_none());
+ assert_eq!(window.find(draft.clone()).focused(), Some(true), "back in the draft");
+ });
+}
+
+/// Lets the changes panel's read of the task folder (a real `git` on a
+/// background thread) finish.
+#[allow(clippy::disallowed_methods)] // A test waiting on a real subprocess.
+fn wait_for_the_panel(harness: &Harness, cx: &mut TestAppContext) {
+ let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
+ loop {
+ settle(cx);
+ let busy = harness.workbench.read_with(cx, |workbench, cx| {
+ let panel = workbench.review_panel().read(cx);
+ panel.is_loading() || panel.turn_changes().read(cx).is_computing()
+ });
+ if !busy || std::time::Instant::now() > deadline {
+ break;
+ }
+ std::thread::sleep(std::time::Duration::from_millis(5));
+ }
+ harness.with_window(cx, |_, _| {});
+}
+
+#[gpui_kit::test]
+fn the_bar_fits_beside_the_changes_panel_and_in_a_narrow_window(cx: &mut TestAppContext) {
+ cx.executor().allow_parking();
+ let harness = task_with_a_turn(cx);
+ harness.with_window(cx, |window, cx| window.click("review-toggle", cx));
+ wait_for_the_panel(&harness, cx);
+ harness.with_window(cx, |window, cx| window.press("cmd-f", cx));
+ assert!(find_open(&harness, cx));
+ assert_placed(&harness, cx);
+ harness.with_window(cx, |window, _| {
+ assert!(window.find("review-panel").visible(), "the panel stays open");
+ });
+ cx.simulate_window_resize(harness.window.into(), size(px(560.), px(700.)));
+ harness.with_window(cx, |_, _| {});
+ assert_placed(&harness, cx);
+}
+
+#[gpui_kit::test]
+fn the_palette_and_the_shortcuts_sheet_offer_find_in_conversation(cx: &mut TestAppContext) {
+ let harness = task_with_a_turn(cx);
+ let entry = domain_element_id("palette-entry", "command:find-in-conversation");
+ harness.with_window(cx, |window, cx| window.press("cmd-k", cx));
+ harness.with_window(cx, |window, cx| window.input("find in conversation", cx));
+ // The line shows the key that runs it in the task view.
+ let keys = harness.with_window(cx, |window, _| {
+ assert!(window.find(entry.clone()).visible());
+ let context = KeyContext::parse(TASK_VIEW_CONTEXT).expect("context");
+ let action = workspace::actions::FindInConversation;
+ window
+ .bindings_for_action_in_context(&action, context)
+ .iter()
+ .filter_map(|binding| binding.keystrokes().first())
+ .map(|keystroke| Kbd::format(keystroke.as_keystroke()))
+ .collect::<Vec<_>>()
+ });
+ assert_eq!(keys, ["⌘F"]);
+ harness.with_window(cx, |window, cx| window.press("enter", cx));
+ assert!(find_open(&harness, cx), "choosing it opens the bar");
+ assert!(query_focused(&harness, cx));
+ harness.with_window(cx, |window, cx| window.press("escape", cx));
+
+ harness.with_window(cx, |window, cx| window.press("cmd-/", cx));
+ harness.with_window(cx, |window, _| {
+ for (id, keys) in
+ [("find-in-conversation", "⌘F"), ("next-match", "⌘G"), ("previous-match", "⇧⌘G")]
+ {
+ let line = window.find(domain_element_id("shortcut", id));
+ let label = line.label().expect("label");
+ assert!(label.ends_with(keys), "{id}: {label}");
+ }
+ });
+}
+
+#[gpui_kit::test]
+fn an_empty_task_has_nothing_to_find(cx: &mut TestAppContext) {
+ let harness = Harness::open(vec![session("s1", "Alpha", "/work/demo", "active")], cx);
+ harness.with_window(cx, |window, cx| window.click(row("s1"), cx));
+ let draft = harness.draft_id(cx);
+ harness.with_window(cx, |window, cx| {
+ window.click(draft.clone(), cx);
+ window.press("cmd-f", cx);
+ });
+ assert!(!find_open(&harness, cx));
+ harness.with_window(cx, |window, _| {
+ assert_eq!(window.find(draft.clone()).focused(), Some(true), "the draft keeps focus");
+ });
+ let listed = harness.workbench.read_with(cx, |workbench, cx| {
+ workbench
+ .palette_entries(cx)
+ .iter()
+ .any(|entry| entry.key.as_ref() == "command:find-in-conversation")
+ });
+ assert!(!listed, "the palette offers it only with a conversation to find in");
+}
diff --git a/apps/desktop-gpui/crates/app/src/lib.rs b/apps/desktop-gpui/crates/app/src/lib.rs
index 0407fb5f2f..1914288a89 100644
--- a/apps/desktop-gpui/crates/app/src/lib.rs
+++ b/apps/desktop-gpui/crates/app/src/lib.rs
@@ -42,9 +42,10 @@ use settings::FontSizeStep;
use shared::copy::{self, Locale};
use shared::theme::{BODY_LINE_HEIGHT, BODY_TEXT_REMS};
use workspace::actions::{
- AddConnection, FocusComposer, GoBack, GoForward, NewSession, OpenCommandPalette, OpenSettings,
- Reconnect, ResetZoom, SendMessage, ShowKeyboardShortcuts, StopTurn, SwitchStateRoot,
- ToggleReview, ToggleSidebar, ZoomIn, ZoomOut,
+ AddConnection, FindInConversation, FocusComposer, GoBack, GoForward, NewSession,
+ OpenCommandPalette, OpenSettings, Reconnect, ResetZoom, SearchAllTasks, SendMessage,
+ ShowKeyboardShortcuts, StopTurn, SwitchStateRoot, ToggleFiles, ToggleReview, ToggleSideChat,
+ ToggleSidebar, ToggleTerminal, ZoomIn, ZoomOut,
};
pub use bot_link::link_bots;
@@ -57,7 +58,8 @@ pub use state_root_dialog::{
show_workbench, show_workbench_on,
};
pub use workbench::{
- CHROME_HEIGHT_REMS, PassivePointer, SIDEBAR_OVERLAY_CONTEXT, SIDEBAR_RESIZE_CONTEXT, Workbench,
+ CHROME_HEIGHT_REMS, PassivePointer, SIDEBAR_OVERLAY_CONTEXT, SIDEBAR_RESIZE_CONTEXT,
+ TASK_VIEW_CONTEXT, Workbench,
};
gpui_kit::actions!(
@@ -92,6 +94,10 @@ pub fn init(cx: &mut App) {
extensions::init(cx);
automations::init(cx);
review::init(cx);
+ search::init(cx);
+ terminal::init(cx);
+ files::init(cx);
+ inspector::init(cx);
// Bindings first: `set_menus` copies each item's shortcut from the keymap.
cx.bind_keys([
KeyBinding::new("secondary-n", NewSession, None),
@@ -109,6 +115,8 @@ pub fn init(cx: &mut App) {
KeyBinding::new("secondary-shift-p", OpenCommandPalette, Some(MENU_SKIPS)),
KeyBinding::new("secondary-k", OpenCommandPalette, None),
KeyBinding::new("secondary-/", ShowKeyboardShortcuts, None),
+ // Search every task, wherever focus is (Zed's project search key).
+ KeyBinding::new("secondary-shift-f", SearchAllTasks, None),
KeyBinding::new("secondary-q", Quit, None),
// Zoom: + takes Shift on most layouts, so ⌘= and ⌘+ both zoom in,
// with Shift or without. The menu bar shows a command's first
@@ -119,9 +127,15 @@ pub fn init(cx: &mut App) {
KeyBinding::new("secondary-shift-=", ZoomIn, None),
KeyBinding::new("secondary--", ZoomOut, None),
KeyBinding::new("secondary-0", ResetZoom, None),
- // The changes panel: Desktop's `ctrl+shift+g`, the Control key on
- // every platform, macOS included.
+ // The workbar's tools: Desktop's `ctrl+shift+g` for the changes and
+ // `ctrl+\`` for the terminal, the Control key on every platform,
+ // macOS included, and its ⌘P for the files. They reach no
+ // terminal's program, and the menu bar shows none of them.
KeyBinding::new("ctrl-shift-g", ToggleReview, None),
+ KeyBinding::new("ctrl-`", ToggleTerminal, None),
+ KeyBinding::new("secondary-p", ToggleFiles, None),
+ // Desktop's `mod+alt+s` for the side chat.
+ KeyBinding::new("secondary-alt-s", ToggleSideChat, None),
]);
// The sidebar's edge, while its handle has focus (Desktop's separator
// keys).
@@ -135,15 +149,26 @@ pub fn init(cx: &mut App) {
// The sidebar over the plate.
KeyBinding::new("escape", workbench::CloseSidebarOverlay, Some(SIDEBAR_OVERLAY_CONTEXT)),
]);
- // The changes panel's edge, while its handle has focus: Left moves the
- // edge toward the plate, widening the panel.
- let review = Some(workbench::REVIEW_RESIZE_CONTEXT);
+ // Find in the conversation, anywhere in the task view (the transcript,
+ // its find bar, the composer, the header): ⌘F opens the bar; while it
+ // shows, ⌘G and ⇧⌘G move through its matches. A page binds ⌘F in its
+ // own context (its search field); a view in the task view with a find
+ // of its own takes ⌘F in its deeper context.
+ let task_view = Some(TASK_VIEW_CONTEXT);
cx.bind_keys([
- KeyBinding::new("left", workbench::WidenReviewStep, review),
- KeyBinding::new("right", workbench::NarrowReviewStep, review),
- KeyBinding::new("shift-left", workbench::WidenReviewLargeStep, review),
- KeyBinding::new("shift-right", workbench::NarrowReviewLargeStep, review),
- KeyBinding::new("enter", workbench::ResetReviewWidth, review),
+ KeyBinding::new("secondary-f", FindInConversation, task_view),
+ KeyBinding::new("secondary-g", search::SelectNextMatch, task_view),
+ KeyBinding::new("secondary-shift-g", search::SelectPreviousMatch, task_view),
+ ]);
+ // The workbar's edge, while its handle has focus: Left moves the edge
+ // toward the plate, widening the panel.
+ let workbar = Some(workbench::WORKBAR_RESIZE_CONTEXT);
+ cx.bind_keys([
+ KeyBinding::new("left", workbench::WidenWorkbarStep, workbar),
+ KeyBinding::new("right", workbench::NarrowWorkbarStep, workbar),
+ KeyBinding::new("shift-left", workbench::WidenWorkbarLargeStep, workbar),
+ KeyBinding::new("shift-right", workbench::NarrowWorkbarLargeStep, workbar),
+ KeyBinding::new("enter", workbench::ResetWorkbarWidth, workbar),
]);
cx.on_action(|_: &Quit, cx| cx.quit());
// The UI font size is the app's, so every window zooms from here,
@@ -170,8 +195,13 @@ pub fn init(cx: &mut App) {
fallback(cx, Workbench::show_keyboard_shortcuts);
fallback(cx, Workbench::open_extensions);
fallback(cx, Workbench::open_scheduled_tasks);
+ fallback(cx, Workbench::search_all_tasks);
fallback(cx, Workbench::toggle_review);
- fallback(cx, Workbench::toggle_review_maximized);
+ fallback(cx, Workbench::toggle_terminal);
+ fallback(cx, Workbench::toggle_files);
+ fallback(cx, Workbench::toggle_side_chat);
+ fallback(cx, Workbench::toggle_workbar_maximized);
+ fallback(cx, Workbench::find_in_conversation);
cx.set_menus(menus(cx));
// The menu bar is the platform's copy of the menus: rebuild it in the
// new language.
@@ -240,6 +270,8 @@ mod chrome_tests;
#[cfg(test)]
mod draft_tests;
#[cfg(test)]
+mod find_tests;
+#[cfg(test)]
mod font_size_tests;
#[cfg(test)]
mod host_blocked_tests;
@@ -250,6 +282,10 @@ mod pet_tests;
#[cfg(test)]
mod review_tests;
#[cfg(test)]
+mod search_tests;
+#[cfg(test)]
+mod side_chat_tests;
+#[cfg(test)]
mod sidebar_tests;
#[cfg(test)]
mod state_root_tests;
@@ -257,3 +293,7 @@ mod state_root_tests;
mod strip_tests;
#[cfg(test)]
mod tests;
+#[cfg(test)]
+mod turn_edits_tests;
+#[cfg(test)]
+mod workbar_tests;
diff --git a/apps/desktop-gpui/crates/app/src/main.rs b/apps/desktop-gpui/crates/app/src/main.rs
index c82c05b2ac..35c1a48295 100644
--- a/apps/desktop-gpui/crates/app/src/main.rs
+++ b/apps/desktop-gpui/crates/app/src/main.rs
@@ -290,6 +290,9 @@ fn main() {
cx.set_app_identity(BUNDLE_IDENTIFIER, shared::copy::APP_NAME.en());
gpui_kit::init(cx);
app::init(cx);
+ // The copies of a task's files that open in the default app: this
+ // launch's directory, and those of launches that ended removed.
+ files::install_temp_files(cx);
// Keep system awake applies from launch, as in Maka Desktop.
automations::KeepSystemAwake::init_global(cx);
// The Runtime Hosts every window can talk to; the window opens on the
@@ -310,7 +313,21 @@ fn main() {
// the chosen appearance instead of switching after its first frame.
let preferences_store = preferences_store(passive);
let load = preferences_store.as_ref().map(|store| store.load());
+ // The side chats' forks are written down in the client's config
+ // directory, so a run that ends before removing one leaves it to
+ // the next; its file is in place before the window opens, so no
+ // fork is asked for before it is on disk. A passive launch keeps
+ // them in memory, as it does its preferences.
+ let ledger = (!passive).then(conversation::LedgerFile::open_default);
cx.spawn(async move |cx| {
+ if let Some(ledger) = ledger
+ && let Some(file) = ledger.await
+ {
+ cx.update(|cx| {
+ conversation::SideChatLedger::global(cx)
+ .update(cx, |ledger, cx| ledger.restore(Rc::new(file), cx))
+ });
+ }
let preferences = match load {
Some(load) => load.await.unwrap_or_else(|error| {
log::warn!("could not read the preferences: {error}");
@@ -500,9 +517,17 @@ fn build_workbench(
workbench.read_changes_with(std::sync::Arc::new(review::git::SystemGit), cx);
});
let catalog = workbench.read(cx).sidebar().read(cx).catalog().clone();
+ let names = catalog.clone();
let task_names: TaskNames =
- Rc::new(move |id, cx| catalog.read(cx).row(id).map(|row| row.name.clone()));
+ Rc::new(move |id, cx| names.read(cx).row(id).map(|row| row.name.clone()));
let notifier = cx.new(|cx| RunNotifier::new(host, task_names, window, cx));
+ // A side chat's fork is no task: its turns post nothing.
+ notifier.update(cx, |notifier, _| {
+ notifier.set_hidden_sessions(Rc::new(move |id, cx| {
+ catalog.read(cx).is_side_conversation(id)
+ || conversation::SideChatLedger::global(cx).read(cx).holds(id)
+ }))
+ });
cx.observe_release(&workbench, move |_, _| drop(notifier)).detach();
app::link_bots(&workbench, cx);
workbench
@@ -1089,9 +1114,10 @@ fn parse_args(args: impl Iterator<Item = String>) -> Result<Args, String> {
}
"--group-by-project" => group_by_project = true,
"--open-page" => {
- let value = args.next().ok_or("--open-page needs extensions or scheduled-tasks")?;
+ let value =
+ args.next().ok_or("--open-page needs extensions, scheduled-tasks or search")?;
page = Some(SidebarPage::from_key(&value).ok_or_else(|| {
- format!("--open-page {value:?}: extensions or scheduled-tasks")
+ format!("--open-page {value:?}: extensions, scheduled-tasks or search")
})?);
}
"--open-model-menu" => open = Some(Opening::ModelMenu),
diff --git a/apps/desktop-gpui/crates/app/src/palette.rs b/apps/desktop-gpui/crates/app/src/palette.rs
index 216cf79f43..43e8f1eb22 100644
--- a/apps/desktop-gpui/crates/app/src/palette.rs
+++ b/apps/desktop-gpui/crates/app/src/palette.rs
@@ -37,6 +37,7 @@ use gpui_kit::{
TestSupportExt as _, WeakEntity, Window, div, px, rems,
};
use host_protocol::PermissionMode;
+use search::matching::fuzzy_score;
use settings::{Appearance, Language, SettingsSection};
use shared::copy::{Text, commands as words};
use shared::domain_element_id;
@@ -120,8 +121,9 @@ pub(crate) struct PaletteEntry {
pub(crate) keywords: Vec<SharedString>,
pub(crate) icon: Icon,
pub(crate) checked: bool,
- /// The Action whose key binding the line shows.
- pub(crate) shortcut: Option<Box<dyn Action>>,
+ /// The Action whose key binding the line shows, and the key context
+ /// that binding applies in (`None` for anywhere).
+ pub(crate) shortcut: Option<(Box<dyn Action>, Option<&'static str>)>,
pub(crate) command: PaletteCommand,
}
@@ -155,8 +157,12 @@ impl PaletteEntry {
self
}
- pub(crate) fn shortcut(mut self, action: Box<dyn Action>) -> Self {
- self.shortcut = Some(action);
+ pub(crate) fn shortcut(
+ mut self,
+ action: Box<dyn Action>,
+ context: Option<&'static str>,
+ ) -> Self {
+ self.shortcut = Some((action, context));
self
}
@@ -293,10 +299,9 @@ fn item(entries: &Rc<Vec<PaletteEntry>>, ix: usize) -> CommandItem {
let entries = entries.clone();
CommandItem::new().label(entry.label.clone()).checked(entry.checked).child(move |window, cx| {
let entry = &entries[ix];
- let shortcut = entry
- .shortcut
- .as_ref()
- .and_then(|action| Kbd::binding_for_action(action.as_ref(), None, window));
+ let shortcut = entry.shortcut.as_ref().and_then(|(action, context)| {
+ Kbd::binding_for_action(action.as_ref(), *context, window)
+ });
h_flex()
.id(domain_element_id("palette-entry", &entry.key))
.test_support()
@@ -335,35 +340,6 @@ fn filter(entries: &[PaletteEntry], query: &str) -> Vec<(Section, Vec<usize>)> {
.collect()
}
-/// A fuzzy match of `query` in `text`, ignoring case and the query's
-/// spaces: every query character must appear in order. Higher is better:
-/// each match scores, more when it continues the previous one, starts a
-/// word, or starts the text; each skipped character costs a little. `None`
-/// when a character is missing.
-pub(crate) fn fuzzy_score(query: &str, text: &str) -> Option<i32> {
- let text: Vec<char> = text.chars().flat_map(char::to_lowercase).collect();
- let mut score = 0;
- let mut position = 0;
- let mut previous: Option<usize> = None;
- for wanted in query.chars().filter(|c| !c.is_whitespace()).flat_map(char::to_lowercase) {
- let found = (position..text.len()).find(|&ix| text[ix] == wanted)?;
- score += 10;
- if previous.is_some_and(|previous| previous + 1 == found) {
- score += 15;
- }
- let word_start = found == 0 || !text[found - 1].is_alphanumeric();
- if found == 0 {
- score += 20;
- } else if word_start {
- score += 12;
- }
- score -= (found - position).min(10) as i32;
- previous = Some(found);
- position = found + 1;
- }
- Some(score)
-}
-
/// Opens the palette over `window` with `entries`, its query field
/// focused. Escape clears a query, then closes the palette; focus returns
/// to what had it.
@@ -389,26 +365,3 @@ pub(crate) fn open_palette(
state.update(cx, |state, cx| state.focus(window, cx));
palette
}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn a_fuzzy_match_needs_every_character_in_order() {
- assert!(fuzzy_score("tgsb", "Toggle sidebar").is_some());
- assert!(fuzzy_score("sidebar", "Toggle sidebar").is_some());
- assert!(fuzzy_score("bs", "Toggle sidebar").is_none(), "out of order");
- assert!(fuzzy_score("xyz", "Toggle sidebar").is_none());
- assert!(fuzzy_score("任务", "新任务").is_some());
- assert_eq!(fuzzy_score("", "anything"), Some(0));
- }
-
- #[test]
- fn prefixes_and_word_starts_beat_scattered_matches() {
- let score = |query, text| fuzzy_score(query, text).expect("match");
- assert!(score("new", "New task") > score("new", "Renew the key"));
- assert!(score("st", "Stop turn") > score("st", "Toggle sidebar list"));
- assert!(score("dark", "Dark") > score("dark", "Dim background, dark mode"));
- }
-}
diff --git a/apps/desktop-gpui/crates/app/src/review_tests.rs b/apps/desktop-gpui/crates/app/src/review_tests.rs
index 262cf517fb..cac979cc0e 100644
--- a/apps/desktop-gpui/crates/app/src/review_tests.rs
+++ b/apps/desktop-gpui/crates/app/src/review_tests.rs
@@ -117,7 +117,7 @@ impl Panel {
}
fn shown(&self, cx: &mut TestAppContext) -> bool {
- self.harness.with_window(cx, |window, _| window.try_find("review-pane").is_some())
+ self.harness.with_window(cx, |window, _| window.try_find("workbar-pane").is_some())
}
fn target(&self, cx: &mut TestAppContext) -> Option<String> {
@@ -175,7 +175,7 @@ fn the_button_and_its_shortcut_toggle_the_changes_panel(cx: &mut TestAppContext)
assert!(panel.shown(cx), "and opens it");
// The panel's own close button closes it too.
- panel.harness.with_window(cx, |window, cx| window.click("review-close", cx));
+ panel.harness.with_window(cx, |window, cx| window.click("workbar-close", cx));
panel.settle(cx);
assert!(!panel.shown(cx));
}
@@ -234,18 +234,18 @@ fn the_changes_panel_sits_beside_the_plate_at_its_width(cx: &mut TestAppContext)
let panel = Panel::open(&["s1"], 1600., cx);
panel.harness.with_window(cx, |window, cx| window.press("ctrl-shift-g", cx));
panel.settle(cx);
- let (main, pane) = (panel.bounds("main-pane", cx), panel.bounds("review-pane", cx));
+ let (main, pane) = (panel.bounds("main-pane", cx), panel.bounds("workbar-pane", cx));
assert_eq!(pane.size.width, px(480.));
assert_eq!(pane.left(), main.right() + px(8.), "the canvas margin between the plates");
assert_eq!(pane.top(), main.top());
panel.harness.with_window(cx, |window, cx| {
- let start = window.find("review-resize").bounds().center();
+ let start = window.find("workbar-resize").bounds().center();
window.drag(start, gpui_kit::point(start.x + px(80.), start.y), cx);
});
cx.executor().advance_clock(Duration::from_millis(300));
settle(cx);
- assert_eq!(panel.bounds("review-pane", cx).size.width, px(400.));
+ assert_eq!(panel.bounds("workbar-pane", cx).size.width, px(400.));
assert_eq!(cx.update(|cx| AppPreferences::current(cx).review_width), 400);
}
@@ -261,7 +261,7 @@ fn a_narrow_window_puts_the_changes_panel_below(cx: &mut TestAppContext) {
panel.harness.workbench.read_with(cx, |workbench, _| workbench.sidebar_form())
};
assert_eq!(form(cx), SidebarForm::Expanded, "1200 px keeps the sidebar");
- let (main, pane) = (panel.bounds("main-pane", cx), panel.bounds("review-pane", cx));
+ let (main, pane) = (panel.bounds("main-pane", cx), panel.bounds("workbar-pane", cx));
assert_eq!(pane.top(), main.bottom() + px(8.), "below the plate");
assert_eq!((pane.left(), pane.size.width), (main.left(), main.size.width));
assert!(pane.size.height <= px(360.));
@@ -270,7 +270,7 @@ fn a_narrow_window_puts_the_changes_panel_below(cx: &mut TestAppContext) {
cx.simulate_window_resize(panel.harness.window.into(), size(px(1000.), px(800.)));
panel.settle(cx);
assert_ne!(form(cx), SidebarForm::Expanded, "the sidebar collapses at its breakpoint");
- let (main, pane) = (panel.bounds("main-pane", cx), panel.bounds("review-pane", cx));
+ let (main, pane) = (panel.bounds("main-pane", cx), panel.bounds("workbar-pane", cx));
assert!(pane.top() > main.top(), "still below");
}
@@ -284,17 +284,17 @@ fn the_changes_panel_drags_wide_until_the_conversation_keeps_its_least(cx: &mut
panel.settle(cx);
let drag = |by: f32, cx: &mut TestAppContext| {
panel.harness.with_window(cx, |window, cx| {
- let start = window.find("review-resize").bounds().center();
+ let start = window.find("workbar-resize").bounds().center();
window.drag(start, gpui_kit::point(start.x - px(by), start.y), cx);
});
cx.executor().advance_clock(Duration::from_millis(300));
settle(cx);
};
drag(300., cx);
- assert_eq!(panel.bounds("review-pane", cx).size.width, px(780.), "past 600");
+ assert_eq!(panel.bounds("workbar-pane", cx).size.width, px(780.), "past 600");
drag(1000., cx);
// 1600 less the 256 px sidebar, the 8 px margins and gap, and 400.
- assert_eq!(panel.bounds("review-pane", cx).size.width, px(920.));
+ assert_eq!(panel.bounds("workbar-pane", cx).size.width, px(920.));
let main = panel.bounds("main-pane", cx);
assert_eq!(main.size.width, px(400.), "the conversation keeps its least");
assert_eq!(cx.update(|cx| AppPreferences::current(cx).review_width), 920);
@@ -320,22 +320,24 @@ fn the_changes_panel_maximizes_in_the_conversations_place(cx: &mut TestAppContex
draft.update(cx, |draft, cx| draft.set_value("half a thought", window, cx));
});
let maximized = |cx: &mut TestAppContext| {
- workbench.read_with(cx, |workbench, cx| workbench.review_maximized(cx))
+ workbench.read_with(cx, |workbench, cx| workbench.workbar_maximized(cx))
};
let composer_shown = |cx: &mut TestAppContext| {
panel.harness.with_window(cx, |window, _| window.try_find("composer").is_some())
};
let sidebar = panel.bounds("main-pane", cx).left();
- panel.harness.with_window(cx, |window, cx| window.click("review-maximize", cx));
+ panel.harness.with_window(cx, |window, cx| window.click("workbar-maximize", cx));
panel.settle(cx);
assert!(maximized(cx));
- let (main, pane) = (panel.bounds("main-pane", cx), panel.bounds("review-pane", cx));
+ let (main, pane) = (panel.bounds("main-pane", cx), panel.bounds("workbar-pane", cx));
assert_eq!(main.left(), sidebar, "the sidebar stays");
assert_eq!((pane.left(), pane.size.width), (main.left(), main.size.width), "the plate's width");
assert_eq!(pane.bottom(), main.bottom());
assert!(!composer_shown(cx), "the composer leaves the plate");
- assert!(!panel.harness.with_window(cx, |window, _| window.try_find("review-resize").is_some()));
+ assert!(
+ !panel.harness.with_window(cx, |window, _| window.try_find("workbar-resize").is_some())
+ );
let remembered = cx.update(|cx| AppPreferences::current(cx).review_maximized);
assert!(remembered.contains("s1"), "{remembered:?}");
@@ -359,7 +361,7 @@ fn the_changes_panel_maximizes_in_the_conversations_place(cx: &mut TestAppContex
assert!(!maximized(cx), "and opens beside the conversation");
panel.select("s1", cx);
assert!(maximized(cx), "the first task's panel is still maximized");
- panel.harness.with_window(cx, |window, cx| window.click("review-maximize", cx));
+ panel.harness.with_window(cx, |window, cx| window.click("workbar-maximize", cx));
panel.settle(cx);
assert!(!maximized(cx), "its button restores it");
panel.harness.with_window(cx, |window, cx| window.press("shift-escape", cx));
@@ -380,9 +382,175 @@ fn the_changes_panel_maximizes_in_the_conversations_place(cx: &mut TestAppContex
panel.settle(cx);
let focused = panel.harness.with_window(cx, |window, _| window.find("review-panel").focused());
assert_eq!(focused, Some(true), "maximizing moves the focus into the panel");
- panel.harness.with_window(cx, |window, cx| window.click("review-close", cx));
+ panel.harness.with_window(cx, |window, cx| window.click("workbar-close", cx));
panel.settle(cx);
assert!(!panel.shown(cx));
let focused = panel.harness.with_window(cx, |window, _| window.find(draft).focused());
assert_eq!(focused, Some(true), "the composer takes the focus");
}
+
+/// Runs `git` in `dir`, as a test author with no hooks or signing.
+fn git(dir: &Path, args: &[&str]) {
+ let output = std::process::Command::new("git")
+ .arg("-C")
+ .arg(dir)
+ .args(["-c", "user.name=Review Test", "-c", "user.email=review@example.invalid"])
+ .args(["-c", "commit.gpgsign=false", "-c", "core.hooksPath=/dev/null"])
+ .args(args)
+ .env("LC_ALL", "C")
+ .output()
+ .expect("git");
+ assert!(output.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&output.stderr));
+}
+
+/// Makes the task folder `dir` a repository with thirty files of sixty
+/// lines on `main`, three commits on `feature`, and every file changed
+/// since: the panel's tree, its scopes and its diff all scroll.
+fn fill_repository(dir: &Path) {
+ std::fs::remove_dir_all(dir.join(".git")).expect("folder");
+ git(dir, &["init", "-q", "-b", "main"]);
+ let write = |pass: usize| {
+ for file in 0..30 {
+ let text: String = (0..60)
+ .map(|line| {
+ if line % 7 == pass % 7 {
+ format!("{pass} {line}\n")
+ } else {
+ format!("line {line}\n")
+ }
+ })
+ .collect();
+ std::fs::write(dir.join(format!("file{file:02}.txt")), text).expect("write");
+ }
+ };
+ write(0);
+ git(dir, &["add", "."]);
+ git(dir, &["commit", "-q", "-m", "start"]);
+ git(dir, &["checkout", "-q", "-b", "feature"]);
+ for pass in 1..=3 {
+ write(pass);
+ git(dir, &["commit", "-q", "-am", &format!("Pass {pass}")]);
+ }
+ write(4);
+}
+
+/// The squares of `plate`'s radius at its corners.
+fn corner_squares(plate: gpui_kit::Bounds<Pixels>) -> [gpui_kit::Bounds<Pixels>; 4] {
+ use gpui_kit::{Bounds, point};
+ let radius = shared::theme::RADIUS_MODAL;
+ let side = size(radius, radius);
+ let (left, right) = (plate.left(), plate.right() - radius);
+ let (top, bottom) = (plate.top(), plate.bottom() - radius);
+ [
+ Bounds::new(point(left, top), side),
+ Bounds::new(point(right, top), side),
+ Bounds::new(point(left, bottom), side),
+ Bounds::new(point(right, bottom), side),
+ ]
+}
+
+impl Panel {
+ /// Asserts that nothing the panel scrolls paints into a corner square
+ /// of its plate: its lists' clips and every row in them as far as the
+ /// clip shows it, and the diff's viewport and every line in it.
+ fn assert_clear_of_corners(&self, when: &str, cx: &mut TestAppContext) {
+ use gpui_kit::{Bounds, Role};
+ let painted = |bounds: Bounds<Pixels>, clip: Bounds<Pixels>| {
+ let part = bounds.intersect(&clip);
+ (part.size.width > px(0.) && part.size.height > px(0.)).then_some(part)
+ };
+ let plate = self.bounds("review-panel", cx);
+ let parts = self.harness.with_window(cx, |window, _| {
+ let mut parts: Vec<(String, Bounds<Pixels>)> = Vec::new();
+ for (list, role) in
+ [("review-files", Role::TreeItem), ("review-scopes", Role::ListItem)]
+ {
+ let clip = window.find(list).bounds();
+ parts.extend(painted(clip, plate).map(|part| (list.to_owned(), part)));
+ for row in window.within(list).find_all_by_role(role) {
+ let name = format!("{list} row {:?}", row.label());
+ parts.extend(painted(row.bounds(), clip).map(|part| (name, part)));
+ }
+ }
+ let viewport = window.find("review-diff").bounds();
+ parts.extend(painted(viewport, plate).map(|part| ("the diff".to_owned(), part)));
+ for line in window.find_all("source") {
+ let name = format!("diff line {:?}", line.label());
+ parts.extend(painted(line.bounds(), viewport).map(|part| (name, part)));
+ }
+ parts
+ });
+ assert!(parts.iter().any(|(name, _)| name.starts_with("diff line")), "{when}: lines drawn");
+ for (name, part) in parts {
+ for corner in corner_squares(plate) {
+ assert!(
+ painted(part, corner).is_none(),
+ "{when}: {name} at {part:?} reaches the corner {corner:?} of {plate:?}"
+ );
+ }
+ }
+ }
+
+ /// Turns the wheel over each of the panel's lists and its diff
+ /// `times` times, `step` px down each.
+ fn scroll_all(&self, times: usize, step: f32, cx: &mut TestAppContext) {
+ for id in ["review-files", "review-scopes", "diff-body"] {
+ for _ in 0..times {
+ self.harness.with_window(cx, |window, cx| {
+ let delta = gpui_kit::ScrollDelta::Pixels(gpui_kit::point(px(0.), px(-step)));
+ window.scroll(id, delta, cx);
+ });
+ }
+ }
+ self.settle(cx);
+ }
+}
+
+/// Beside the conversation, below it and in its place, the changes panel
+/// is one rounded plate: at the top of its lists, part way down and at
+/// the end, nothing it scrolls reaches into its corners.
+#[gpui_kit::test]
+fn the_changes_panel_keeps_its_corners_clear_in_every_place(cx: &mut TestAppContext) {
+ let panel = Panel::open(&["s1"], 1600., cx);
+ fill_repository(&panel.folders[0]);
+ panel.harness.workbench.update(cx, |workbench, cx| {
+ workbench.review_panel().update(cx, |panel, _| {
+ panel.set_git_runner(Arc::new(review::git::SystemGit));
+ });
+ });
+ panel.harness.with_window(cx, |window, cx| window.press("ctrl-shift-g", cx));
+ panel.settle(cx);
+ for (width, maximized, place) in
+ [(1600., false, "beside"), (1200., false, "below"), (1600., true, "maximized")]
+ {
+ cx.simulate_window_resize(panel.harness.window.into(), size(px(width), px(800.)));
+ panel.settle(cx);
+ if maximized {
+ panel.harness.with_window(cx, |window, cx| window.click("workbar-maximize", cx));
+ panel.settle(cx);
+ }
+ let (main, pane) = (panel.bounds("main-pane", cx), panel.bounds("workbar-pane", cx));
+ match place {
+ "beside" => assert_eq!(pane.left(), main.right() + px(8.)),
+ "below" => assert_eq!(pane.top(), main.bottom() + px(8.)),
+ _ => assert_eq!(pane.bottom(), main.bottom()),
+ }
+ panel.scroll_all(12, -1000., cx);
+ panel.assert_clear_of_corners(&format!("{place}, at the top"), cx);
+ panel.scroll_all(3, 100., cx);
+ panel.assert_clear_of_corners(&format!("{place}, part way down"), cx);
+ panel.scroll_all(12, 1000., cx);
+ panel.assert_clear_of_corners(&format!("{place}, at the end"), cx);
+ }
+}
+
+/// The header's changes button puts its glyph's ink on the plate's 16 px
+/// line, as the panel's bar does.
+#[gpui_kit::test]
+fn the_headers_changes_button_inks_on_the_plates_line(cx: &mut TestAppContext) {
+ let panel = Panel::open(&["s1"], 1600., cx);
+ let (main, button) = (panel.bounds("main-pane", cx), panel.bounds("review-toggle", cx));
+ assert_eq!(button.size, size(px(28.), px(28.)));
+ let ink = button.center().x + px(8.) - px(16. * shared::icons::ink::FILE_DIFF);
+ assert!((main.right() - px(16.) - ink).abs() < px(0.5), "{ink:?} in {main:?}");
+}
diff --git a/apps/desktop-gpui/crates/app/src/search_tests.rs b/apps/desktop-gpui/crates/app/src/search_tests.rs
new file mode 100644
index 0000000000..885502cd3e
--- /dev/null
+++ b/apps/desktop-gpui/crates/app/src/search_tests.rs
@@ -0,0 +1,406 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! The Search page in the window: ⇧⌘F, the sidebar's search button and
+//! the palette open it with its field focused, a selection seeds it, a
+//! result opens its task at its message, and Back returns to the page as
+//! it was.
+
+use base64::Engine as _;
+use gpui_kit::test::TestWindowExt as _;
+use gpui_kit::{Focusable as _, ScrollDelta, TestAppContext, point, px};
+use serde_json::{Value, json};
+use session::SidebarPage;
+use shared::copy::search as copy;
+
+use crate::chrome_tests::row;
+use crate::tests::{EPOCH, Harness, ScriptedHost, session, settle};
+
+/// The rows of settled turn `turn`, from sequence `first`: a prompt and a
+/// reply that holds a needle.
+fn needle_turn(turn: &str, first: u64) -> Vec<(u64, Value)> {
+ vec![
+ (
+ first,
+ json!({"type": "user", "id": turn, "turnId": turn, "ts": first,
+ "text": "Where is it?"}),
+ ),
+ (
+ first + 1,
+ json!({"type": "assistant", "id": format!("{turn}-a"), "turnId": turn,
+ "ts": first + 1, "text": "The needle is in the hay.",
+ "contentOrder": ["text"], "modelId": "m"}),
+ ),
+ (
+ first + 2,
+ json!({"type": "turn_state", "id": format!("{turn}-end"), "turnId": turn,
+ "ts": first + 2, "status": "completed"}),
+ ),
+ ]
+}
+
+/// An older page of task `id` holding `rows`, older history behind `next`.
+fn page_of(id: &str, rows: &[(u64, Value)], next: Option<&str>) -> Value {
+ let fragments: Vec<Value> = rows
+ .iter()
+ .rev()
+ .map(|(sequence, row)| {
+ let bytes = serde_json::to_vec(row).expect("row");
+ json!({
+ "sequence": sequence, "byteOffset": 0, "totalBytes": bytes.len(),
+ "payloadDigest": null,
+ "data": base64::engine::general_purpose::STANDARD.encode(&bytes)
+ })
+ })
+ .collect();
+ json!({
+ "kind": "page", "sessionId": id, "direction": "older", "throughSequence": 99,
+ "rawBytes": 0, "fragments": fragments, "nextCursor": next, "endsAtTurnBoundary": true
+ })
+}
+
+/// `subscription.open` of task `id`: one settled turn whose reply holds a
+/// needle.
+pub(crate) fn open_with_a_needle(id: &str) -> Value {
+ open_with_tail(id, page_of(id, &needle_turn("t1", 1), None))
+}
+
+fn open_with_tail(id: &str, tail: Value) -> Value {
+ json!({
+ "hostEpoch": EPOCH, "subscriptionId": format!("sub-{id}"), "nextSequence": 1,
+ "snapshot": {
+ "schemaVersion": 5,
+ "session": {"sessionId": id, "metadataRevision": 1, "status": "active",
+ "createdAt": 1, "isArchived": false},
+ "projectionRevision": 1, "rootTurn": null, "goal": null,
+ "queue": {"hostEpoch": EPOCH, "queueRevision": 0, "steering": [], "followup": []},
+ "interactions": {"pending": []}
+ },
+ "activeAssistantStreams": [],
+ "transcript": {"durable": tail}
+ })
+}
+
+fn passage(session: &str, anchor: &str, text: &str) -> Value {
+ json!({
+ "sessionId": session, "sessionTitle": "", "turnId": "t1", "anchorMessageId": anchor,
+ "sequence": 1,
+ "messages": [{"messageId": anchor, "role": "assistant", "matchKind": "assistant_message",
+ "text": text, "timestamp": 2, "isAnchor": true}],
+ "matchedTerms": ["needle"], "score": 1.0, "lastMessageAt": 2,
+ "hasMoreBefore": false, "hasMoreAfter": false
+ })
+}
+
+/// A recall answer: the needle in `s2`'s reply first, then a dozen in `s1`
+/// (enough to scroll the page).
+fn needles() -> Value {
+ let mut passages = vec![passage("s2", "t1-a", "The needle is in the hay.")];
+ passages.extend((0..12).map(|ix| passage("s1", &format!("a{ix}"), "Another needle.")));
+ json!({"ok": true, "facts": [], "passages": passages, "gaps": "",
+ "searchedEverySession": true})
+}
+
+fn two_tasks() -> std::sync::Arc<ScriptedHost> {
+ ScriptedHost::new(vec![
+ session("s1", "Alpha", "/work/demo", "active"),
+ session("s2", "Beta", "/work/demo", "active"),
+ ])
+}
+
+fn page(harness: &Harness, cx: &mut TestAppContext) -> Option<SidebarPage> {
+ harness.workbench.read_with(cx, |workbench, _| workbench.page())
+}
+
+/// The Search page's field: whether it has focus, and its text.
+fn field(harness: &Harness, cx: &mut TestAppContext) -> (bool, String) {
+ let view = harness
+ .workbench
+ .read_with(cx, |workbench, _| workbench.search_view().cloned())
+ .expect("the page was shown");
+ let query = view.read_with(cx, |view, _| view.query().clone());
+ let focused =
+ harness.with_window(cx, |window, cx| query.read(cx).focus_handle(cx).is_focused(window));
+ (focused, query.read_with(cx, |query, _| query.value().to_string()))
+}
+
+#[gpui_kit::test]
+fn command_shift_f_the_search_button_and_the_palette_open_the_page_focused(
+ cx: &mut TestAppContext,
+) {
+ let harness = Harness::with_transport(two_tasks(), cx);
+ harness.with_window(cx, |window, cx| window.click(row("s1"), cx));
+ harness.with_window(cx, |window, cx| window.press("cmd-shift-f", cx));
+ assert_eq!(page(&harness, cx), Some(SidebarPage::Search));
+ assert_eq!(field(&harness, cx), (true, String::new()));
+ harness.with_window(cx, |window, _| {
+ assert_eq!(window.find("page-title").label(), Some(copy::SEARCH.en()));
+ assert_eq!(
+ window.find("search-status").label(),
+ Some(copy::SEARCH_HINT.en()),
+ "a hint while nothing is typed"
+ );
+ });
+
+ // Back in the task, the sidebar's button opens it again.
+ harness.with_window(cx, |window, cx| window.click(row("s2"), cx));
+ assert_eq!(page(&harness, cx), None);
+ harness.with_window(cx, |window, cx| window.click("search-button", cx));
+ assert_eq!(page(&harness, cx), Some(SidebarPage::Search));
+ assert!(field(&harness, cx).0);
+
+ // And the palette's command; ⌘K stays the palette.
+ harness.with_window(cx, |window, cx| window.click(row("s1"), cx));
+ harness.with_window(cx, |window, cx| window.press("cmd-k", cx));
+ harness.with_window(cx, |window, cx| window.input("search all tasks", cx));
+ harness.with_window(cx, |window, cx| window.press("enter", cx));
+ assert_eq!(page(&harness, cx), Some(SidebarPage::Search));
+ assert!(field(&harness, cx).0);
+}
+
+#[gpui_kit::test]
+fn a_selection_seeds_the_query_and_is_searched_at_once(cx: &mut TestAppContext) {
+ let transport = two_tasks();
+ transport.reply("recall.query", Ok(needles()));
+ let harness = Harness::with_transport(transport.clone(), cx);
+ harness.with_window(cx, |window, cx| window.click(row("s1"), cx));
+ let draft = harness.draft_id(cx);
+ harness.with_window(cx, |window, cx| {
+ window.click(draft.clone(), cx);
+ window.input("the needle\nhere", cx);
+ window.press("cmd-a", cx);
+ });
+ harness.with_window(cx, |window, cx| window.press("cmd-shift-f", cx));
+ assert_eq!(field(&harness, cx), (true, "the needle here".to_owned()));
+ let requests = transport.requests("recall.query");
+ assert_eq!(requests.len(), 1);
+ assert_eq!(requests[0]["terms"], json!(["the", "needle", "here"]));
+ assert_eq!(harness.draft(cx), "the needle\nhere", "the draft keeps its text");
+}
+
+#[gpui_kit::test]
+fn a_passage_opens_its_task_at_its_message_and_back_returns_to_the_page(cx: &mut TestAppContext) {
+ let transport = two_tasks();
+ transport.reply("recall.query", Ok(needles()));
+ // The window opens on s1, the newest task; the passage is in s2.
+ transport.reply("subscription.open", Ok(open_with_a_needle("s1")));
+ transport.reply("subscription.open", Ok(open_with_a_needle("s2")));
+ let harness = Harness::with_transport(transport.clone(), cx);
+ harness.with_window(cx, |window, cx| window.press("cmd-shift-f", cx));
+ harness.with_window(cx, |window, cx| window.input("needle", cx));
+ settle(cx);
+ let s2 = search::passage_element_id("s2", "t1-a");
+ harness.with_window(cx, |window, _| {
+ assert!(window.find(s2.clone()).visible(), "the results show");
+ });
+ // The cursor on the first passage, then the page scrolled by hand.
+ harness.with_window(cx, |window, cx| window.press("down", cx));
+ harness.with_window(cx, |window, cx| {
+ window.scroll("search-body", ScrollDelta::Pixels(point(px(0.), px(-240.))), cx);
+ });
+ let offset = |harness: &Harness, cx: &mut TestAppContext| {
+ harness.workbench.read_with(cx, |workbench, cx| {
+ workbench.search_view().expect("page").read(cx).scroll_handle().offset().y
+ })
+ };
+ let scrolled = offset(&harness, cx);
+ assert!(scrolled < px(0.), "scrolled: {scrolled:?}");
+
+ harness.with_window(cx, |window, cx| window.press("enter", cx));
+ settle(cx);
+ harness.with_window(cx, |_, _| {});
+ assert_eq!(page(&harness, cx), None, "the task shows");
+ let selected = harness.workbench.read_with(cx, |workbench, cx| {
+ workbench.sidebar().read(cx).catalog().read(cx).selected_id().cloned()
+ });
+ assert_eq!(selected.as_deref(), Some("s2"));
+ let (open, query) = harness.workbench.read_with(cx, |workbench, cx| {
+ let view = workbench.conversation().read(cx);
+ let query = view.find_bar().map(|bar| bar.read(cx).query().read(cx).value().to_string());
+ (view.is_find_open(), query)
+ });
+ assert!(open, "the find bar shows");
+ assert_eq!(query.as_deref(), Some("needle"));
+ harness.with_window(cx, |window, _| {
+ assert_eq!(window.find("find-count").label(), Some("1/1"), "its match is active");
+ });
+
+ // Back: the page as it was.
+ harness.with_window(cx, |window, cx| window.press("cmd-[", cx));
+ assert_eq!(page(&harness, cx), Some(SidebarPage::Search));
+ assert_eq!(field(&harness, cx).1, "needle");
+ harness.with_window(cx, |window, _| {
+ assert!(window.try_find(s2.clone()).is_some(), "the results stay");
+ });
+ assert_eq!(offset(&harness, cx), scrolled, "and where they were scrolled");
+ assert_eq!(transport.requests("recall.query").len(), 1, "nothing searched again");
+}
+
+#[gpui_kit::test]
+fn escape_clears_the_query_then_leaves_for_the_task(cx: &mut TestAppContext) {
+ let transport = two_tasks();
+ transport.reply("recall.query", Ok(needles()));
+ let harness = Harness::with_transport(transport, cx);
+ harness.with_window(cx, |window, cx| window.click(row("s1"), cx));
+ harness.with_window(cx, |window, cx| window.press("cmd-shift-f", cx));
+ harness.with_window(cx, |window, cx| window.input("needle", cx));
+ harness.with_window(cx, |window, cx| window.press("escape", cx));
+ assert_eq!(page(&harness, cx), Some(SidebarPage::Search));
+ assert_eq!(field(&harness, cx), (true, String::new()));
+ harness.with_window(cx, |window, cx| window.press("escape", cx));
+ assert_eq!(page(&harness, cx), None, "the task view, as the other pages leave");
+ let draft = harness.draft_id(cx);
+ harness.with_window(cx, |window, _| {
+ assert_eq!(window.find(draft.clone()).focused(), Some(true), "ready to write");
+ });
+ harness.with_window(cx, |window, cx| window.press("cmd-[", cx));
+ assert_eq!(page(&harness, cx), Some(SidebarPage::Search), "Back returns to it");
+}
+
+#[gpui_kit::test]
+fn text_selected_in_a_reply_seeds_the_query(cx: &mut TestAppContext) {
+ let transport = two_tasks();
+ transport.reply("subscription.open", Ok(open_with_a_needle("s1")));
+ transport.reply("recall.query", Ok(needles()));
+ let harness = Harness::with_transport(transport.clone(), cx);
+ settle(cx);
+ let reply =
+ conversation::item_element_id("t1", &transcript_model::ItemKey::Text("t1-a".into()));
+ harness.with_window(cx, |window, cx| {
+ let bounds = window.find(reply.clone()).bounds();
+ let y = bounds.top() + px(10.);
+ window.drag(point(bounds.left() + px(2.), y), point(bounds.right() - px(2.), y), cx);
+ });
+ harness.with_window(cx, |window, cx| window.press("cmd-shift-f", cx));
+ let (focused, query) = field(&harness, cx);
+ assert!(focused);
+ assert!(query.contains("needle"), "{query:?}");
+ assert_eq!(transport.requests("recall.query").len(), 1);
+}
+
+#[gpui_kit::test]
+fn a_search_without_a_connection_runs_again_once_connected(cx: &mut TestAppContext) {
+ let transport = two_tasks();
+ transport.reply("recall.query", Err(workspace::HostRequestError::NotConnected));
+ transport.reply("recall.query", Ok(needles()));
+ let harness = Harness::with_transport(transport.clone(), cx);
+ harness.with_window(cx, |window, cx| window.press("cmd-shift-f", cx));
+ harness.with_window(cx, |window, cx| window.input("needle", cx));
+ settle(cx);
+ harness.with_window(cx, |window, _| {
+ let failure = window.find("search-failure");
+ assert_eq!(failure.label(), Some(copy::FAILED_NOT_CONNECTED.en()));
+ });
+ harness
+ .feed(host_client::ConnectionEvent::Connected { accepted: crate::tests::accepted() }, cx);
+ harness.with_window(cx, |_, _| {});
+ assert_eq!(transport.requests("recall.query").len(), 2, "searched again");
+ harness.with_window(cx, |window, _| {
+ assert!(window.try_find("search-failure").is_none());
+ assert!(window.find(search::passage_element_id("s2", "t1-a")).visible());
+ });
+}
+
+/// Back to the page while the passage's task is still read back to its
+/// message: the passage no longer waits, and its find bar never opens
+/// over the task.
+#[gpui_kit::test]
+fn leaving_before_a_passage_is_read_back_forgets_it(cx: &mut TestAppContext) {
+ let transport = two_tasks();
+ let mut answer = needles();
+ answer["passages"][0]["anchorMessageId"] = json!("t0-a");
+ answer["passages"][0]["turnId"] = json!("t0");
+ transport.reply("recall.query", Ok(answer));
+ transport.reply("subscription.open", Ok(open_with_a_needle("s1")));
+ let tail = page_of("s2", &needle_turn("t1", 10), Some("c1"));
+ transport.reply("subscription.open", Ok(open_with_tail("s2", tail)));
+ let page_read = transport.hold("session.transcript.page");
+ let harness = Harness::with_transport(transport.clone(), cx);
+ harness.with_window(cx, |window, cx| window.press("cmd-shift-f", cx));
+ harness.with_window(cx, |window, cx| window.input("needle", cx));
+ settle(cx);
+ harness.with_window(cx, |window, cx| window.press("down", cx));
+ harness.with_window(cx, |window, cx| window.press("enter", cx));
+ settle(cx);
+ assert_eq!(page(&harness, cx), None);
+ assert_eq!(transport.requests("session.transcript.page").len(), 1, "reading back to it");
+ harness.with_window(cx, |window, cx| window.press("cmd-[", cx));
+ assert_eq!(page(&harness, cx), Some(SidebarPage::Search));
+ page_read.try_send(Ok(page_of("s2", &needle_turn("t0", 1), None))).expect("release");
+ settle(cx);
+ harness.with_window(cx, |_, _| {});
+ let open = harness
+ .workbench
+ .read_with(cx, |workbench, cx| workbench.conversation().read(cx).is_find_open());
+ assert!(!open, "no find bar opened behind the page");
+ let focused = harness.with_window(cx, |window, cx| {
+ let view = harness.workbench.read(cx).search_view().cloned().expect("page");
+ let list = gpui_kit::Focusable::focus_handle(view.read(cx), cx);
+ list.is_focused(window)
+ });
+ assert!(focused, "the page keeps focus, on its results");
+}
+
+/// A side chat's fork of task `source`, as the catalog lists it: the
+/// source's name, its parent, the side-conversation label.
+fn fork_of(id: &str, source: &str) -> Value {
+ let mut fork = session(id, "Forked words", "/work/demo", "active");
+ fork["parentSessionId"] = json!(source);
+ fork["branchOfTurnId"] = json!("t1");
+ fork["labels"] = json!(["mode:side_conversation"]);
+ fork
+}
+
+#[gpui_kit::test]
+fn a_side_chat_fork_is_hidden_from_the_sidebar_the_palette_and_the_search_page(
+ cx: &mut TestAppContext,
+) {
+ let transport = ScriptedHost::new(vec![
+ session("s1", "Alpha", "/work/demo", "active"),
+ fork_of("f1", "s1"),
+ session("s2", "Beta", "/work/demo", "active"),
+ ]);
+ let mut answer = needles();
+ answer["passages"]
+ .as_array_mut()
+ .expect("passages")
+ .insert(0, passage("f1", "f-a", "The forked needle."));
+ transport.reply("recall.query", Ok(answer));
+ let harness = Harness::with_transport(transport, cx);
+ harness.with_window(cx, |window, _| {
+ assert!(window.try_find(row("s1")).is_some() && window.try_find(row("s2")).is_some());
+ assert!(window.try_find(row("f1")).is_none(), "no row for the fork");
+ });
+ let keys: Vec<String> = harness.workbench.read_with(cx, |workbench, cx| {
+ workbench.palette_entries(cx).iter().map(|entry| entry.key.to_string()).collect()
+ });
+ assert!(keys.iter().any(|key| key.ends_with("s1")), "{keys:?}");
+ assert!(!keys.iter().any(|key| key.ends_with("f1")), "no palette line for the fork: {keys:?}");
+
+ harness.with_window(cx, |window, cx| window.press("cmd-shift-f", cx));
+ harness.with_window(cx, |window, cx| window.input("needle", cx));
+ settle(cx);
+ harness.with_window(cx, |window, _| {
+ assert!(window.find(search::passage_element_id("s2", "t1-a")).visible());
+ assert!(
+ window.try_find(search::passage_element_id("f1", "f-a")).is_none(),
+ "the fork's passage is left out"
+ );
+ });
+}
diff --git a/apps/desktop-gpui/crates/app/src/side_chat_tests.rs b/apps/desktop-gpui/crates/app/src/side_chat_tests.rs
new file mode 100644
index 0000000000..a6fd0c513d
--- /dev/null
+++ b/apps/desktop-gpui/crates/app/src/side_chat_tests.rs
@@ -0,0 +1,338 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! The workbar's Side chat in the window: opened from [+] and ⌥⌘S, kept
+//! across task switches, closed with Desktop's confirmation, gone with its
+//! deleted task (not an archived one), and fed quotes from a selection in
+//! the task's conversation by ⌥⌘S and the transcript's context menu.
+
+use gpui_kit::test::TestWindowExt as _;
+use gpui_kit::{ElementId, Entity, TestAppContext, point, px};
+use serde_json::{Value, json};
+use settings::AppPreferences;
+use shared::copy::side_chat as copy;
+
+use conversation::{SideChat, SideChatLedger};
+
+use crate::chrome_tests::row;
+use crate::search_tests::open_with_a_needle;
+use crate::tests::{Harness, ScriptedHost, frame, session, settle};
+
+/// A settled Turn of a task, as `session.turns.query` lists it.
+fn completed(turn: &str, first: u64) -> Value {
+ json!({
+ "turnId": turn, "firstSequence": first,
+ "latestState": {"sequence": first + 2, "message": {
+ "type": "turn_state", "id": format!("{turn}-end"), "turnId": turn, "ts": first + 2,
+ "status": "completed"
+ }},
+ "userPromptPreview": null
+ })
+}
+
+/// Tasks s1 and s2; s1's reply holds a needle, and its Turn t1 completed.
+fn bench(cx: &mut TestAppContext) -> Harness {
+ let transport = ScriptedHost::new(vec![
+ session("s1", "Alpha", "/work/demo", "active"),
+ session("s2", "Beta", "/work/demo", "active"),
+ ]);
+ transport.answer_gets();
+ transport.set_turns("s1", vec![completed("t1", 1)]);
+ transport.reply("subscription.open", Ok(open_with_a_needle("s1")));
+ let harness = Harness::with_transport(transport, cx);
+ harness.with_window(cx, |window, cx| window.click(row("s1"), cx));
+ harness
+}
+
+fn side_chats(harness: &Harness, cx: &mut TestAppContext) -> Vec<Entity<SideChat>> {
+ harness.workbench.read_with(cx, |workbench, cx| workbench.side_chats(cx))
+}
+
+/// The strip's side chat tabs: key, name, showing. (The task's Changes
+/// face is open too, as it is by default.)
+fn tabs(harness: &Harness, cx: &mut TestAppContext) -> Vec<(String, String, bool)> {
+ let tabs = harness.workbench.read_with(cx, |workbench, cx| workbench.strip_tabs(cx));
+ tabs.into_iter().filter(|(key, _, _)| key.starts_with("side-chat:")).collect()
+}
+
+/// The draft of side chat `chat`'s composer.
+fn side_draft(harness: &Harness, chat: &Entity<SideChat>, cx: &mut TestAppContext) -> ElementId {
+ let id = chat.read_with(cx, |chat, _| chat.id().clone());
+ harness.workbench.read_with(cx, |workbench, cx| {
+ let panel = workbench.side_chat_panel(&id, cx).expect("a panel");
+ let draft = panel.read(cx).composer().read(cx).draft().entity_id();
+ ("input", draft).into()
+ })
+}
+
+/// Opens a side chat from the workbar's [+] menu.
+fn add_side_chat(harness: &Harness, cx: &mut TestAppContext) {
+ if !harness.workbench.read_with(cx, |workbench, cx| workbench.workbar_shown(cx)) {
+ harness.with_window(cx, |window, cx| window.press("cmd-alt-s", cx));
+ return;
+ }
+ harness.with_window(cx, |window, cx| window.click("workbar-add", cx));
+ harness.with_window(cx, |window, cx| window.click("menu-item:workbar-tool-side-chat", cx));
+}
+
+/// Types `text` in `chat`'s composer and presses Enter.
+fn send_in(harness: &Harness, chat: &Entity<SideChat>, text: &str, cx: &mut TestAppContext) {
+ let draft = side_draft(harness, chat, cx);
+ harness.with_window(cx, |window, cx| {
+ window.click(draft.clone(), cx);
+ window.input(text, cx);
+ });
+ harness.with_window(cx, |window, cx| window.press("enter", cx));
+ settle(cx);
+}
+
+fn fork_of(chat: &Entity<SideChat>, cx: &mut TestAppContext) -> Option<String> {
+ chat.read_with(cx, |chat, _| chat.fork_id().map(ToString::to_string))
+}
+
+/// The catalog changed: the window reads it again.
+fn catalog_changed(harness: &Harness, cx: &mut TestAppContext) {
+ harness.push(
+ frame(json!({"kind": "session.catalog.changed", "revision": 9, "sessionId": "s1"})),
+ cx,
+ );
+ harness.with_window(cx, |_, _| {});
+}
+
+#[gpui_kit::test]
+fn command_option_s_opens_a_side_chat_and_toggles_it(cx: &mut TestAppContext) {
+ let harness = bench(cx);
+ harness.with_window(cx, |window, cx| window.press("cmd-alt-s", cx));
+ let chats = side_chats(&harness, cx);
+ assert_eq!(chats.len(), 1);
+ assert_eq!(
+ tabs(&harness, cx),
+ [(
+ format!("side-chat:{}", chats[0].read_with(cx, |chat, _| chat.id().clone())),
+ copy::SIDE_CHAT.en().to_owned(),
+ true
+ )]
+ );
+ let draft = side_draft(&harness, &chats[0], cx);
+ harness.with_window(cx, |window, _| {
+ assert_eq!(window.find(draft.clone()).focused(), Some(true), "ready to write");
+ assert!(window.find("side-chat-empty").visible(), "nothing of its own yet");
+ });
+ // Again: the panel hides; again: the same side chat shows.
+ harness.with_window(cx, |window, cx| window.press("cmd-alt-s", cx));
+ assert!(!harness.workbench.read_with(cx, |workbench, cx| workbench.workbar_shown(cx)));
+ harness.with_window(cx, |window, cx| window.press("cmd-alt-s", cx));
+ assert_eq!(side_chats(&harness, cx), chats, "the same side chat, not a new one");
+ // [+] adds a second, numbered.
+ add_side_chat(&harness, cx);
+ let names: Vec<String> = tabs(&harness, cx).into_iter().map(|(_, name, _)| name).collect();
+ assert_eq!(names, ["Side chat", "Side chat 2"]);
+}
+
+#[gpui_kit::test]
+fn the_new_tasks_draft_has_no_side_chat(cx: &mut TestAppContext) {
+ let harness = bench(cx);
+ harness.with_window(cx, |window, cx| window.press("cmd-n", cx));
+ assert!(harness.drafting(cx));
+ harness.with_window(cx, |window, cx| window.press("cmd-alt-s", cx));
+ assert!(side_chats(&harness, cx).is_empty());
+ harness.with_window(cx, |window, _| {
+ let note = window.find_all("notification");
+ assert!(!note.is_empty(), "a note says why");
+ });
+}
+
+#[gpui_kit::test]
+fn switching_tasks_keeps_a_side_chat_and_coming_back_shows_it(cx: &mut TestAppContext) {
+ let harness = bench(cx);
+ add_side_chat(&harness, cx);
+ let chat = side_chats(&harness, cx).remove(0);
+ send_in(&harness, &chat, "What is the needle for?", cx);
+ let fork = fork_of(&chat, cx).expect("the first send made the fork");
+ // A draft left behind in it.
+ let draft = side_draft(&harness, &chat, cx);
+ harness.with_window(cx, |window, cx| {
+ window.click(draft.clone(), cx);
+ window.input("and then", cx);
+ });
+
+ harness.with_window(cx, |window, cx| window.click(row("s2"), cx));
+ assert!(side_chats(&harness, cx).is_empty(), "s2 has none");
+ assert!(tabs(&harness, cx).iter().all(|(key, _, _)| !key.starts_with("side-chat:")));
+ // The fork lives on meanwhile, hidden from the list.
+ harness.with_window(cx, |window, _| {
+ assert!(window.try_find(row(&fork)).is_none());
+ });
+ assert!(harness.transport.requests("session.remove").is_empty());
+
+ harness.with_window(cx, |window, cx| window.click(row("s1"), cx));
+ let back = side_chats(&harness, cx);
+ assert_eq!(back, std::slice::from_ref(&chat), "the same side chat");
+ assert_eq!(fork_of(&chat, cx).as_deref(), Some(fork.as_str()));
+ let shown: Vec<bool> = tabs(&harness, cx).into_iter().map(|(_, _, shown)| shown).collect();
+ assert_eq!(shown, [true], "its face shows");
+ let text = harness.workbench.read_with(cx, |workbench, cx| {
+ let id = chat.read(cx).id().clone();
+ let panel = workbench.side_chat_panel(&id, cx).expect("panel");
+ panel.read(cx).composer().read(cx).draft().read(cx).value().to_string()
+ });
+ assert_eq!(text, "and then", "its draft kept");
+}
+
+#[gpui_kit::test]
+fn closing_a_side_chat_with_a_conversation_asks_then_removes_its_fork(cx: &mut TestAppContext) {
+ let harness = bench(cx);
+ add_side_chat(&harness, cx);
+ let chat = side_chats(&harness, cx).remove(0);
+ send_in(&harness, &chat, "Explain", cx);
+ let fork = fork_of(&chat, cx).expect("fork");
+ let key = format!("side-chat:{}", chat.read_with(cx, |chat, _| chat.id().clone()));
+ let close = shared::domain_element_id("workbar-tab-close", &key);
+
+ harness.with_window(cx, |window, cx| window.click(close.clone(), cx));
+ harness.with_window(cx, |window, _| {
+ assert_eq!(
+ window.find(shared::dialog::DIALOG_TITLE_ID).label(),
+ Some(copy::CLOSE_TITLE.en())
+ );
+ });
+ // Cancel keeps it.
+ harness.with_window(cx, |window, cx| window.click("cancel", cx));
+ assert_eq!(side_chats(&harness, cx).len(), 1);
+ assert!(harness.transport.requests("session.remove").is_empty());
+
+ harness.with_window(cx, |window, cx| window.click(close.clone(), cx));
+ harness.with_window(cx, |window, cx| window.click("side-chat-dont-ask", cx));
+ harness.with_window(cx, |window, cx| window.click("ok", cx));
+ settle(cx);
+ assert!(side_chats(&harness, cx).is_empty(), "its tab went");
+ assert_eq!(
+ harness.transport.requests("session.remove"),
+ [json!({"sessionId": fork, "expectedRevision": 2})],
+ "its fork removed"
+ );
+ let held = cx.update(|cx| SideChatLedger::global(cx).read(cx).holds(&fork));
+ assert!(!held, "the ledger settled it");
+ assert!(cx.update(|cx| AppPreferences::current(cx).side_chat_close_unconfirmed));
+
+ // Not asked again.
+ add_side_chat(&harness, cx);
+ let second = side_chats(&harness, cx).remove(0);
+ send_in(&harness, &second, "Again", cx);
+ let key = format!("side-chat:{}", second.read_with(cx, |chat, _| chat.id().clone()));
+ harness.with_window(cx, |window, cx| {
+ window.click(shared::domain_element_id("workbar-tab-close", &key), cx)
+ });
+ settle(cx);
+ assert!(side_chats(&harness, cx).is_empty());
+ assert_eq!(harness.transport.requests("session.remove").len(), 2);
+}
+
+#[gpui_kit::test]
+fn deleting_the_task_disposes_of_its_side_chats_and_archiving_does_not(cx: &mut TestAppContext) {
+ let harness = bench(cx);
+ add_side_chat(&harness, cx);
+ let chat = side_chats(&harness, cx).remove(0);
+ send_in(&harness, &chat, "Explain", cx);
+ let fork = fork_of(&chat, cx).expect("fork");
+
+ // Archived, the task is still listed: its side chat stays.
+ let mut sessions = harness.transport.sessions();
+ for session in &mut sessions {
+ if session["id"] == "s1" {
+ session["isArchived"] = json!(true);
+ }
+ }
+ harness.transport.set_sessions(sessions.clone());
+ catalog_changed(&harness, cx);
+ assert!(harness.transport.requests("session.remove").is_empty());
+ assert!(!chat.read_with(cx, |chat, _| chat.is_disposed()));
+
+ // Deleted: it goes with its fork.
+ sessions.retain(|session| session["id"] != "s1");
+ harness.transport.set_sessions(sessions);
+ catalog_changed(&harness, cx);
+ settle(cx);
+ assert!(chat.read_with(cx, |chat, _| chat.is_disposed()));
+ assert_eq!(
+ harness.transport.requests("session.remove"),
+ [json!({"sessionId": fork, "expectedRevision": 2})]
+ );
+}
+
+/// Drags across the needle reply of s1.
+fn select_the_reply(harness: &Harness, cx: &mut TestAppContext) -> ElementId {
+ let reply: ElementId =
+ conversation::item_element_id("t1", &transcript_model::ItemKey::Text("t1-a".into()));
+ harness.with_window(cx, |window, cx| {
+ let bounds = window.find(reply.clone()).bounds();
+ let y = bounds.top() + px(10.);
+ window.drag(point(bounds.left() + px(2.), y), point(bounds.right() - px(2.), y), cx);
+ });
+ reply
+}
+
+#[gpui_kit::test]
+fn command_option_s_with_a_selection_stages_a_quote_and_the_send_carries_it(
+ cx: &mut TestAppContext,
+) {
+ let harness = bench(cx);
+ settle(cx);
+ select_the_reply(&harness, cx);
+ harness.with_window(cx, |window, cx| window.press("cmd-alt-s", cx));
+ let chats = side_chats(&harness, cx);
+ assert_eq!(chats.len(), 1, "a side chat opened for the quote");
+ let quotes: Vec<(String, Option<String>)> = chats[0].read_with(cx, |chat, _| {
+ chat.quotes()
+ .iter()
+ .map(|staged| (staged.quote.text.clone(), staged.quote.source_turn_id.clone()))
+ .collect()
+ });
+ assert_eq!(quotes.len(), 1);
+ assert!(quotes[0].0.contains("needle"), "{quotes:?}");
+ assert_eq!(quotes[0].1.as_deref(), Some("t1"), "the selection lies in t1's reply");
+ harness.with_window(cx, |window, _| {
+ assert!(window.find("composer-quotes").visible(), "a chip above its draft");
+ });
+ send_in(&harness, &chats[0], "Why?", cx);
+ let submits = harness.transport.requests("turn.message.submit");
+ let submit = submits.last().expect("a send");
+ assert_eq!(submit["content"]["text"], "Why?");
+ assert_eq!(submit["content"]["quotes"][0]["sourceTurnId"], "t1");
+ assert!(
+ submit["content"]["quotes"][0]["text"].as_str().is_some_and(|text| text.contains("needle"))
+ );
+ assert!(chats[0].read_with(cx, |chat, _| chat.quotes().is_empty()), "the Host took it");
+}
+
+#[gpui_kit::test]
+fn the_transcripts_context_menu_asks_about_the_selection_in_the_side_chat(cx: &mut TestAppContext) {
+ let harness = bench(cx);
+ settle(cx);
+ let reply = select_the_reply(&harness, cx);
+ harness.with_window(cx, |window, cx| window.right_click(reply.clone(), cx));
+ harness.with_window(cx, |window, cx| window.press("down", cx));
+ harness.with_window(cx, |window, cx| window.press("enter", cx));
+ let chats = side_chats(&harness, cx);
+ assert_eq!(chats.len(), 1);
+ let texts: Vec<String> = chats[0].read_with(cx, |chat, _| {
+ chat.quotes().iter().map(|staged| staged.quote.text.clone()).collect()
+ });
+ assert!(texts.len() == 1 && texts[0].contains("needle"), "{texts:?}");
+}
diff --git a/apps/desktop-gpui/crates/app/src/sidebar_tests.rs b/apps/desktop-gpui/crates/app/src/sidebar_tests.rs
index c491726b5e..cd79a9ce67 100644
--- a/apps/desktop-gpui/crates/app/src/sidebar_tests.rs
+++ b/apps/desktop-gpui/crates/app/src/sidebar_tests.rs
@@ -335,7 +335,7 @@ fn the_rail_holds_new_task_the_pages_search_the_host_and_settings(cx: &mut TestA
("rail-new-task".into(), shared::copy::NEW_TASK.en()),
(rail_page("extensions"), session::SidebarPage::Extensions.title().en()),
(rail_page("scheduled-tasks"), session::SidebarPage::ScheduledTasks.title().en()),
- ("rail-search".into(), shared::copy::commands::SEARCH.en()),
+ ("rail-search".into(), shared::copy::search::SEARCH_ALL_TASKS.en()),
("rail-settings".into(), shared::copy::settings::SETTINGS.en()),
];
let mut above = px(0.);
@@ -365,10 +365,11 @@ fn the_rail_holds_new_task_the_pages_search_the_host_and_settings(cx: &mut TestA
Some(session::SidebarPage::Extensions)
);
harness.with_window(cx, |window, cx| window.click("rail-search", cx));
- harness.with_window(cx, |window, cx| {
- assert!(window.find("command-palette").visible(), "search opens the palette");
- window.press("escape", cx);
- });
+ assert_eq!(
+ harness.workbench.read_with(cx, |workbench, _| workbench.page()),
+ Some(session::SidebarPage::Search),
+ "search opens the Search page"
+ );
harness.with_window(cx, |window, cx| window.click("rail-host-status", cx));
assert!(harness.workbench.read_with(cx, |workbench, _| workbench.footer_menu_open()));
harness.with_window(cx, |window, cx| window.press("escape", cx));
diff --git a/apps/desktop-gpui/crates/app/src/strip_tests.rs b/apps/desktop-gpui/crates/app/src/strip_tests.rs
index f3bd9f0b3e..cc209e60cb 100644
--- a/apps/desktop-gpui/crates/app/src/strip_tests.rs
+++ b/apps/desktop-gpui/crates/app/src/strip_tests.rs
@@ -199,7 +199,7 @@ impl Strip {
}
fn panel_shown(&self, cx: &mut TestAppContext) -> bool {
- self.exists("review-pane", cx)
+ self.exists("workbar-pane", cx)
}
}
@@ -233,6 +233,15 @@ fn the_strip_shows_the_task_its_branch_and_its_changes(cx: &mut TestAppContext)
);
assert!(name.right() <= branch.left() && branch.right() < chip.left(), "name, branch, chip");
assert!(chip.right() <= bar.right());
+ // No fill of its own: the folder is a 28 px chip that hugs its glyph,
+ // name and chevron, its glyph over the composer's "+" glyph; the
+ // changes chip ends where the composer's controls do.
+ assert_eq!(name.size.height, px(28.));
+ assert!(name.size.width < bar.size.width / 2., "it hugs its content: {name:?}");
+ let (glyph, attach) =
+ (strip.bounds("context-strip-folder", cx), strip.bounds("composer-attach", cx));
+ assert_eq!(glyph.center().x, attach.center().x, "{glyph:?} over {attach:?}");
+ assert_eq!(chip.right(), composer.right() - px(12.));
assert!(!strip.panel_shown(cx));
strip.click("context-strip-changes", cx);
diff --git a/apps/desktop-gpui/crates/app/src/tests.rs b/apps/desktop-gpui/crates/app/src/tests.rs
index 419a056e3b..5d99e7321b 100644
--- a/apps/desktop-gpui/crates/app/src/tests.rs
+++ b/apps/desktop-gpui/crates/app/src/tests.rs
@@ -63,6 +63,16 @@ pub(crate) struct ScriptedHost {
replies: Mutex<HashMap<String, VecDeque<Reply>>>,
held: Mutex<HashMap<String, VecDeque<async_channel::Receiver<Reply>>>>,
pub(crate) requests: Mutex<Vec<(String, Value)>>,
+ /// Each task's terminals as `runtime.resource.query` lists them; a
+ /// start adds a running one.
+ terminals: Mutex<HashMap<String, Vec<Value>>>,
+ starts: Mutex<usize>,
+ /// Each task's files as `artifact.query` lists them, and the revision
+ /// of the list (moved by every change).
+ artifacts: Mutex<HashMap<String, Vec<Value>>>,
+ artifact_revision: Mutex<u64>,
+ /// Each task's Turns as `session.turns.query` lists them.
+ turns: Mutex<HashMap<String, Vec<Value>>>,
}
impl ScriptedHost {
@@ -82,6 +92,38 @@ impl ScriptedHost {
sender
}
+ /// Answers `get` with the listed session (see `answers_get`).
+ pub(crate) fn answer_gets(&self) {
+ *self.answers_get.lock().expect("answers_get") = true;
+ }
+
+ /// Sets the Turns `session.turns.query` lists for task `session`.
+ pub(crate) fn set_turns(&self, session: &str, turns: Vec<Value>) {
+ self.turns.lock().expect("turns").insert(session.to_owned(), turns);
+ }
+
+ /// Sets the sessions the catalog lists.
+ pub(crate) fn set_sessions(&self, sessions: Vec<Value>) {
+ *self.sessions.lock().expect("sessions") = sessions;
+ }
+
+ /// The sessions the catalog lists now.
+ pub(crate) fn sessions(&self) -> Vec<Value> {
+ self.sessions.lock().expect("sessions").clone()
+ }
+
+ /// Sets the terminals task `session` lists.
+ pub(crate) fn set_terminals(&self, session: &str, names: &[&str]) {
+ let resources = names.iter().map(|name| terminal_resource(session, name)).collect();
+ self.terminals.lock().expect("terminals").insert(session.to_owned(), resources);
+ }
+
+ /// Sets the files task `session` lists, moving the list's revision.
+ pub(crate) fn set_artifacts(&self, session: &str, artifacts: Vec<Value>) {
+ self.artifacts.lock().expect("artifacts").insert(session.to_owned(), artifacts);
+ *self.artifact_revision.lock().expect("revision") += 1;
+ }
+
pub(crate) fn requests(&self, operation: &str) -> Vec<Value> {
let requests = self.requests.lock().expect("requests");
requests.iter().filter(|(op, _)| op == operation).map(|(_, input)| input.clone()).collect()
@@ -153,19 +195,174 @@ impl HostTransport for ScriptedHost {
"skillInvocation": {"loaded": [], "failed": [], "receipts": []}
})),
(None, "session.remove") => {
+ // A side chat's fork leaves the catalog with its removal.
+ self.sessions.lock().expect("sessions").retain(|session| {
+ session["id"] != input["sessionId"]
+ || !session["labels"]
+ .as_array()
+ .is_some_and(|labels| labels.contains(&json!("mode:side_conversation")))
+ });
Ok(json!({"kind": "removed", "sessionId": input["sessionId"]}))
}
+ (None, "session.turns.query") => {
+ let session = input["sessionId"].as_str().expect("session");
+ let turns = self.turns.lock().expect("turns").get(session).cloned();
+ Ok(json!({"sessionId": session, "throughSequence": 40,
+ "contributions": turns.unwrap_or_default(), "nextPosition": null}))
+ }
+ // A side chat's fork: the source's projection with the label
+ // and the parent, listed from now on.
+ (None, "session.branch.create") => {
+ let source = input["sourceSessionId"].as_str().expect("source");
+ let target = input["targetSessionId"].as_str().expect("target");
+ let mut sessions = self.sessions.lock().expect("sessions");
+ let Some(mut fork) =
+ sessions.iter().find(|session| session["id"] == source).cloned()
+ else {
+ return Box::pin(async move {
+ Err(HostRequestError::Operation {
+ operation: "session.branch.create",
+ code: host_protocol::HostOperationErrorCode::NotFound,
+ message: "Source Session does not exist".into(),
+ })
+ });
+ };
+ fork["id"] = json!(target);
+ fork["revision"] = json!(2);
+ fork["labels"] = json!(["mode:side_conversation"]);
+ fork["parentSessionId"] = json!(source);
+ if let Some(turn) = input["sourceTurnId"].as_str() {
+ fork["branchOfTurnId"] = json!(turn);
+ }
+ if !sessions.iter().any(|session| session["id"] == target) {
+ sessions.push(fork.clone());
+ }
+ Ok(json!({"kind": "committed", "session": fork}))
+ }
(None, "turn.stop") => Ok(json!({
"sessionId": input["sessionId"], "turnId": input["turnId"],
"runId": input["runId"], "status": "cancelled", "terminalEventId": "end",
"abortSource": "renderer.stop_button"
})),
+ (None, "subscription.pty_interest.set") => {
+ Ok(json!({"subscriptionId": input["subscriptionId"]}))
+ }
+ (None, "runtime.resource.query") if input["kind"] == "list_start" => {
+ let session = input["sessionId"].as_str().expect("session");
+ let terminals = self.terminals.lock().expect("terminals");
+ let resources = terminals.get(session).cloned().unwrap_or_default();
+ Ok(json!({"kind": "page", "sessionId": session, "revision": "sha256:00",
+ "resources": resources, "nextCursor": null}))
+ }
+ (None, "runtime.resource.start") => {
+ let session = input["sessionId"].as_str().expect("session").to_owned();
+ let name = {
+ let mut starts = self.starts.lock().expect("starts");
+ *starts += 1;
+ format!("started-{starts}")
+ };
+ let resource = terminal_resource(&session, &name);
+ self.terminals
+ .lock()
+ .expect("terminals")
+ .entry(session)
+ .or_default()
+ .push(resource.clone());
+ Ok(json!({"resource": resource["result"]}))
+ }
+ (None, "runtime.resource.controller.acquire") => Ok(json!({
+ "controllerId": input["controllerId"], "nextSequence": 1,
+ "pty": {"sessionId": input["sessionId"], "ref": input["ref"], "sequence": 0,
+ "buffer": "", "size": {"cols": 80, "rows": 24}}
+ })),
+ (None, "runtime.resource.controller.control") => {
+ Ok(json!({"controllerId": input["controllerId"], "sequence": input["sequence"]}))
+ }
+ (None, "runtime.resource.controller.release") => {
+ Ok(json!({"controllerId": input["controllerId"], "released": true}))
+ }
+ (None, "runtime.resource.stop") => {
+ let session = input["sessionId"].as_str().expect("session");
+ let reference = input["ref"].as_str().expect("ref");
+ if let Some(terminals) = self.terminals.lock().expect("terminals").get_mut(session)
+ {
+ terminals.retain(|terminal| terminal["result"]["ref"] != reference);
+ }
+ Ok(json!({}))
+ }
+ (None, "artifact.query")
+ if matches!(input["kind"].as_str(), Some("list_start" | "get")) =>
+ {
+ let session = input["sessionId"].as_str().expect("session");
+ let artifacts = self.artifacts.lock().expect("artifacts");
+ let listed = artifacts.get(session).cloned().unwrap_or_default();
+ let revision =
+ format!("sha256:{:064x}", *self.artifact_revision.lock().expect("revision"));
+ if input["kind"] == "get" {
+ Ok(json!({"kind": "artifact", "sessionId": session, "revision": revision,
+ "artifact": null}))
+ } else {
+ Ok(json!({"kind": "page", "sessionId": session, "revision": revision,
+ "artifacts": listed, "nextCursor": null}))
+ }
+ }
+ // The Trace face's reads: a task that has not run.
+ (None, "execution.inspect.query") => Ok(json!({
+ "kind": "session_trace_page", "schemaVersion": 1,
+ "sessionId": input["sessionId"], "turns": [],
+ "coverage": {"modelCalls": "none", "turnsMissingModelCalls": [],
+ "turnsWithFewerModelCallsThanSteps": [], "unreadableRecords": 0,
+ "oversizedRuns": 0},
+ "nextCursor": null
+ })),
+ (None, "context.diagnostics.query") => {
+ Ok(json!({"status": "unavailable", "reason": "no_completed_request"}))
+ }
+ (None, "usage.query") if input["kind"] == "summary" => Ok(json!({
+ "kind": "summary",
+ "summary": {"range": {"from": 0, "to": 1}, "totalRequests": 0, "totalCostUsd": 0,
+ "totalTokens": {"input": 0, "output": 0, "cacheMiss": 0, "cacheRead": 0,
+ "cacheWrite": 0, "reasoning": 0, "total": 0},
+ "cacheHitRequests": 0, "cacheCreateRequests": 0, "errorRequests": 0,
+ "totalDurationMs": 0},
+ "provenance": {"coverage": {"attempts": 0, "pricedAttempts": 0,
+ "unpricedAttempts": 0, "usageReportedAttempts": 0, "usagePartialAttempts": 0,
+ "usageMissingAttempts": 0}, "legacyRecords": 0, "unreadableRecords": 0,
+ "pendingRepairs": 0}
+ })),
(None, other) => Err(HostRequestError::Transport(format!("unexpected {other}").into())),
};
Box::pin(async move { result })
}
}
+/// A file of task `session` a subagent wrote back, as `artifact.query`
+/// lists it.
+pub(crate) fn artifact(session: &str, id: &str, name: &str) -> Value {
+ json!({
+ "id": id, "sessionId": session, "turnId": "t1", "createdAt": 1, "name": name,
+ "kind": "file", "sizeBytes": 3, "source": "subagent_writeback"
+ })
+}
+
+/// The ref of the terminal `name`.
+pub(crate) fn terminal_ref(name: &str) -> String {
+ format!("maka://runtime/background-tasks/{name}")
+}
+
+/// A running terminal of task `session`, as `runtime.resource.query` lists
+/// it.
+pub(crate) fn terminal_resource(session: &str, name: &str) -> Value {
+ json!({
+ "sessionId": session, "ownership": {"kind": "local"},
+ "sourceTurnId": format!("desktop-terminal-{name}"),
+ "sourceToolCallId": format!("desktop-terminal-{name}"),
+ "result": {"kind": "shell_run", "ref": terminal_ref(name), "mode": "pty",
+ "status": "running", "cwd": "/w", "cmd": "exec \"$SHELL\" -l",
+ "startedAt": 1, "updatedAt": 2, "revision": 2}
+ })
+}
+
/// The one project the Host lists: new tasks go into it.
pub(crate) const DEMO_PATH: &str = "/work/demo";
@@ -224,7 +421,7 @@ fn open_result(session_id: &str) -> Value {
})
}
-fn accepted() -> HostAccepted {
+pub(crate) fn accepted() -> HostAccepted {
serde_json::from_value(json!({
"kind": "accepted", "rootId": "r", "hostEpoch": EPOCH, "connectionId": "c",
"selectedProtocol": 0, "compatibilityEpoch": 197, "compositionId": "maka.interactive",
@@ -301,7 +498,7 @@ impl Harness {
settle(cx);
}
- fn push(&self, frame: PushFrame, cx: &mut TestAppContext) {
+ pub(crate) fn push(&self, frame: PushFrame, cx: &mut TestAppContext) {
self.host.update(cx, |host, cx| host.handle_host_event(HostEvent::Push(frame), cx));
settle(cx);
}
@@ -320,6 +517,25 @@ impl Harness {
self.push(frame(value), cx);
}
+ /// Sends the next `session_domain_changed` of `session_id`'s
+ /// subscription, for `domain`.
+ pub(crate) fn domain_changed(
+ &mut self,
+ session_id: &str,
+ domain: &str,
+ cx: &mut TestAppContext,
+ ) {
+ let subscription = format!("sub-{session_id}");
+ let (sequence, _) = self.sequences.entry(subscription.clone()).or_insert((1, 1));
+ let value = json!({
+ "kind": "subscription.session_domain_changed", "hostEpoch": EPOCH,
+ "subscriptionId": subscription, "sequence": *sequence, "sessionId": session_id,
+ "domain": domain
+ });
+ *sequence += 1;
+ self.push(frame(value), cx);
+ }
+
pub(crate) fn with_window<R>(
&self,
cx: &mut TestAppContext,
@@ -371,7 +587,7 @@ pub(crate) fn settle(cx: &mut TestAppContext) {
cx.run_until_parked();
}
-fn frame(value: Value) -> PushFrame {
+pub(crate) fn frame(value: Value) -> PushFrame {
match HostFrame::decode(value).expect("frame") {
HostFrame::Push(frame) => frame,
other => panic!("not a push frame: {other:?}"),
@@ -756,9 +972,9 @@ fn tab_walks_the_sidebar_then_the_composer(cx: &mut TestAppContext) {
}
window.press("shift-tab", cx);
assert_eq!(window.find("new-session").focused(), Some(true), "Extensions → New task");
- // The app name row's search button opens the command palette.
+ // The app name row's search button opens the Search page.
window.press("shift-tab", cx);
- let search = window.find("command-palette-button");
+ let search = window.find("search-button");
assert_eq!(search.focused(), Some(true), "New task → search");
// Before the sidebar's rows come the window controls in its top
// strip; Back and Forward are disabled, so the toggle is next.
diff --git a/apps/desktop-gpui/crates/app/src/turn_edits_tests.rs b/apps/desktop-gpui/crates/app/src/turn_edits_tests.rs
new file mode 100644
index 0000000000..097fc19d5e
--- /dev/null
+++ b/apps/desktop-gpui/crates/app/src/turn_edits_tests.rs
@@ -0,0 +1,588 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! UI integration tests of what a turn edited, in the window: the card
+//! under the settled turn with each file's net lines, worked out from the
+//! files on this machine, and its buttons opening the changes panel on the
+//! turn. The task's folder is in the system's temporary folder, in no
+//! repository, as a task's folder may be.
+
+// Setup writes the files the turn's tools edited; the settle loop waits on
+// the work that reads them on the blocking pool.
+#![allow(clippy::disallowed_methods)]
+
+use std::path::PathBuf;
+use std::time::{Duration, Instant};
+
+use base64::Engine as _;
+use gpui_kit::TestAppContext;
+use gpui_kit::test::TestWindowExt as _;
+use serde_json::{Value, json};
+
+use crate::tests::{EPOCH, Harness, ScriptedHost, session, settle};
+
+/// The task's folder, removed when dropped.
+struct Folder(PathBuf);
+
+impl Folder {
+ fn new(name: &str) -> Self {
+ let dir =
+ std::env::temp_dir().join(format!("app-turn-edits-{name}-{}", std::process::id()));
+ std::fs::remove_dir_all(&dir).ok();
+ std::fs::create_dir_all(&dir).expect("folder");
+ Self(dir)
+ }
+
+ fn path(&self, name: &str) -> String {
+ self.0.join(name).to_string_lossy().into_owned()
+ }
+}
+
+impl Drop for Folder {
+ fn drop(&mut self) {
+ std::fs::remove_dir_all(&self.0).ok();
+ }
+}
+
+/// Turn `t1`: `Edit` twice on `report.py` (its third and eighth lines), a
+/// `Write` creating `notes.md`, a `Bash` call, and `apply_patch` updating
+/// `data.txt` and deleting `old.txt`, then its reply. The folder holds the
+/// files as the turn left them.
+fn turn_rows(folder: &Folder) -> Vec<Value> {
+ std::fs::write(folder.0.join("report.py"), "a1\na2\nA3\na4\na5\na6\na7\nA8\na9\na10\n")
+ .expect("write");
+ std::fs::write(folder.0.join("notes.md"), "# Notes\n\nfirst\n").expect("write");
+ std::fs::write(folder.0.join("data.txt"), "x\nY\nz\n").expect("write");
+ let (report, notes) = (folder.path("report.py"), folder.path("notes.md"));
+ let diff = |path: &str, hunks: &str| {
+ json!({"kind": "file_diff", "paths": [path],
+ "diff": format!("--- a/{path}\n+++ b/{path}\n{hunks}")})
+ };
+ let call = |id: &str, tool: &str, args: Value| {
+ json!({"type": "tool_call", "id": id, "turnId": "t1", "ts": 2, "toolName": tool,
+ "args": args, "stepId": "s1"})
+ };
+ let result = |id: &str, content: Value| {
+ json!({"type": "tool_result", "id": format!("r-{id}"), "turnId": "t1", "ts": 3,
+ "toolUseId": id, "isError": false, "content": content})
+ };
+ let patch = "*** Begin Patch\n*** Update File: data.txt\n@@\n x\n-y\n+Y\n z\n\
+ *** Delete File: old.txt\n*** End Patch";
+ vec![
+ json!({"type": "user", "id": "t1", "turnId": "t1", "ts": 1, "text": "Build the report"}),
+ call("c1", "Edit", json!({"path": "report.py"})),
+ result("c1", diff(&report, "@@ -1,6 +1,6 @@\n a1\n a2\n-a3\n+A3\n a4\n a5\n a6")),
+ call("c2", "Edit", json!({"path": "report.py"})),
+ result("c2", diff(&report, "@@ -5,6 +5,6 @@\n a5\n a6\n a7\n-a8\n+A8\n a9\n a10")),
+ call("c3", "Write", json!({"path": "notes.md", "content": "# Notes\n\nfirst\n"})),
+ result(
+ "c3",
+ json!({"kind": "file_diff", "paths": [notes], "diff": format!(
+ "--- /dev/null\n+++ b/{notes}\n@@ -0,0 +1,3 @@\n+# Notes\n+\n+first")}),
+ ),
+ call("c4", "Bash", json!({"command": "python report.py"})),
+ result("c4", json!({"kind": "text", "text": ""})),
+ call("c5", "apply_patch", json!(patch)),
+ result("c5", json!({"kind": "json", "value": {"status": "completed"}})),
+ json!({"type": "assistant", "id": "s1", "turnId": "t1", "ts": 4, "text": "Done.",
+ "contentOrder": ["tools", "text"], "modelId": "m"}),
+ json!({"type": "turn_state", "id": "e1", "turnId": "t1", "ts": 5, "status": "completed"}),
+ ]
+}
+
+/// Turn `t1` in Code Mode, as a real Host stores it at epoch 197: a step,
+/// then one code cell (`exec`) whose script writes `notes.md` (new), edits
+/// `report.py`'s eighth line and runs a command, each call a row of its own
+/// (`<exec id>:nested:<id>`, origin `code_mode`, the `exec` its parent),
+/// then the reply. The folder holds the files as the turn left them.
+fn code_cell_rows(folder: &Folder) -> Vec<Value> {
+ std::fs::write(folder.0.join("report.py"), "a1\na2\na3\na4\na5\na6\na7\nA8\na9\na10\n")
+ .expect("write");
+ std::fs::write(folder.0.join("notes.md"), "# Notes\n\nfirst\n").expect("write");
+ let (report, notes) = (folder.path("report.py"), folder.path("notes.md"));
+ let step = |id: &str, text: &str| {
+ json!({"type": "assistant", "id": id, "turnId": "t1", "ts": 2, "text": text,
+ "thinking": {"text": "Plan the next step."},
+ "contentOrder": ["thinking", "text", "tools"], "modelId": "m"})
+ };
+ let nested = |row: Value| {
+ let mut row = row;
+ row["origin"] = json!("code_mode");
+ row["modelVisibility"] = json!("hidden");
+ row["parentToolCallId"] = json!("call_e1");
+ row["parentOperationId"] = json!("op-exec");
+ row
+ };
+ let call = |id: &str, tool: &str, args: Value| {
+ nested(json!({"type": "tool_call", "id": format!("call_e1:nested:{id}"), "turnId": "t1",
+ "ts": 3, "toolName": tool, "args": args, "stepId": "call_e1:nested"}))
+ };
+ let result = |id: &str, content: Value| {
+ nested(json!({"type": "tool_result", "id": format!("op-{id}_response"), "turnId": "t1",
+ "ts": 3, "toolUseId": format!("call_e1:nested:{id}"), "isError": false,
+ "content": content}))
+ };
+ vec![
+ json!({"type": "user", "id": "t1", "turnId": "t1", "ts": 1, "text": "Write the notes"}),
+ step("s1", ""),
+ json!({"type": "tool_call", "id": "call_e1", "turnId": "t1", "ts": 2, "toolName": "exec",
+ "stepId": "s1", "origin": "provider", "modelVisibility": "visible",
+ "args": {"code": "await tools.Write({path: \"notes.md\", content: \"…\"});"}}),
+ call("u1", "Write", json!({"path": "notes.md", "content": "# Notes\n\nfirst\n"})),
+ result(
+ "u1",
+ json!({"kind": "file_diff", "paths": [notes], "diff": format!(
+ "--- /dev/null\n+++ b/{notes}\n@@ -0,0 +1,3 @@\n+# Notes\n+\n+first")}),
+ ),
+ call("u2", "Edit", json!({"path": "report.py", "old_string": "a8", "new_string": "A8"})),
+ result(
+ "u2",
+ json!({"kind": "file_diff", "paths": [report], "diff": format!(
+ "--- a/{report}\n+++ b/{report}\n\
+ @@ -5,6 +5,6 @@\n a5\n a6\n a7\n-a8\n+A8\n a9\n a10")}),
+ ),
+ call("u3", "Bash", json!({"command": "python report.py"})),
+ result("u3", json!({"kind": "text", "text": ""})),
+ json!({"type": "tool_result", "id": "op-exec_response", "turnId": "t1", "ts": 4,
+ "toolUseId": "call_e1", "isError": false, "origin": "provider",
+ "modelVisibility": "visible", "content": {"kind": "json", "value": {"ok": true}}}),
+ step("s2", "Done."),
+ json!({"type": "turn_state", "id": "e1", "turnId": "t1", "ts": 5, "status": "completed"}),
+ ]
+}
+
+/// Session `s1`'s `subscription.open`, its durable tail `rows`.
+fn open_with(rows: &[Value]) -> Value {
+ open_with_tail(older_page(rows, 1, rows.len(), None))
+}
+
+/// An `older` page of session `s1` read at `through`: `rows`, numbered from
+/// `first`, newest first as the Host sends them. With a cursor `next` to
+/// older rows, it stops inside a turn.
+fn older_page(rows: &[Value], first: usize, through: usize, next: Option<&str>) -> Value {
+ let fragments: Vec<Value> = rows
+ .iter()
+ .enumerate()
+ .rev()
+ .map(|(ix, row)| {
+ let bytes = serde_json::to_vec(row).expect("row");
+ json!({
+ "sequence": first + ix, "byteOffset": 0, "totalBytes": bytes.len(),
+ "payloadDigest": null,
+ "data": base64::engine::general_purpose::STANDARD.encode(&bytes)
+ })
+ })
+ .collect();
+ json!({
+ "kind": "page", "sessionId": "s1", "direction": "older", "throughSequence": through,
+ "rawBytes": 0, "fragments": fragments, "nextCursor": next,
+ "endsAtTurnBoundary": next.is_none()
+ })
+}
+
+/// Session `s1`'s `subscription.open` with the durable tail `tail`.
+fn open_with_tail(tail: Value) -> Value {
+ json!({
+ "hostEpoch": EPOCH, "subscriptionId": "sub-s1", "nextSequence": 1,
+ "snapshot": {
+ "schemaVersion": 5,
+ "session": {"sessionId": "s1", "metadataRevision": 1, "status": "active",
+ "createdAt": 1, "isArchived": false},
+ "projectionRevision": 1, "rootTurn": null, "goal": null,
+ "queue": {"hostEpoch": EPOCH, "queueRevision": 0, "steering": [], "followup": []},
+ "interactions": {"pending": []}
+ },
+ "activeAssistantStreams": [],
+ "transcript": {"durable": tail}
+ })
+}
+
+/// The window on task `s1` in `folder`, whose transcript holds the turn.
+fn open(folder: &Folder, cx: &mut TestAppContext) -> Harness {
+ cx.executor().allow_parking();
+ let path = folder.0.to_string_lossy().into_owned();
+ let transport = ScriptedHost::new(vec![session("s1", "Alpha", &path, "active")]);
+ transport.reply("subscription.open", Ok(open_with(&turn_rows(folder))));
+ let harness = Harness::with_transport(transport, cx);
+ wait(&harness, cx);
+ harness
+}
+
+/// Runs the window's work to its end: the turns' changes, and the panel's
+/// reads.
+fn wait(harness: &Harness, cx: &mut TestAppContext) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ loop {
+ settle(cx);
+ let busy = harness.workbench.read_with(cx, |workbench, cx| {
+ let panel = workbench.review_panel().read(cx);
+ panel.is_loading() || panel.turn_changes().read(cx).is_computing()
+ });
+ if !busy || Instant::now() > deadline {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ harness.with_window(cx, |_, _| {});
+}
+
+fn label(
+ harness: &Harness,
+ within: gpui_kit::ElementId,
+ id: impl Into<gpui_kit::ElementId>,
+ cx: &mut TestAppContext,
+) -> Option<String> {
+ let id = id.into();
+ harness.with_window(cx, |window, _| {
+ window.within(within).try_find(id).and_then(|element| element.label().map(str::to_owned))
+ })
+}
+
+fn file_id(path: &str) -> gpui_kit::ElementId {
+ shared::domain_element_id("turn-edits-file", path)
+}
+
+/// The card under the turn lists its four files in the order it first
+/// edited them, the two Edits of `report.py` as one net change; the file it
+/// deleted, unknown before, says so.
+#[gpui_kit::test]
+fn the_card_lists_the_turns_files_with_their_net_lines(cx: &mut TestAppContext) {
+ let folder = Folder::new("card");
+ let harness = open(&folder, cx);
+ let card = conversation::edits_element_id("t1");
+ assert_eq!(
+ label(&harness, card.clone(), "turn-edits-title", cx).as_deref(),
+ Some("Edited 4 files")
+ );
+ assert_eq!(
+ label(&harness, card.clone(), "turn-edits-counts", cx).as_deref(),
+ Some("6 lines added, 3 lines deleted")
+ );
+ let rows: Vec<Option<String>> = ["report.py", "notes.md", "data.txt", "old.txt"]
+ .iter()
+ .map(|path| label(&harness, card.clone(), file_id(path), cx))
+ .collect();
+ assert_eq!(
+ rows,
+ [
+ Some("report.py, 2 lines added, 2 lines deleted".to_owned()),
+ Some("notes.md, 3 lines added, 0 lines deleted".to_owned()),
+ Some("data.txt, 1 line added, 1 line deleted".to_owned()),
+ None,
+ ]
+ );
+ harness.with_window(cx, |window, cx| window.within(card.clone()).click("turn-edits-more", cx));
+ assert_eq!(
+ label(&harness, card.clone(), file_id("old.txt"), cx).as_deref(),
+ Some("old.txt, Deleted")
+ );
+}
+
+/// "View changes" opens the changes panel on the turn, which a folder in no
+/// repository shows instead of saying so; a file's row shows that file.
+#[gpui_kit::test]
+fn view_changes_opens_the_panel_on_the_turn(cx: &mut TestAppContext) {
+ let folder = Folder::new("panel");
+ let harness = open(&folder, cx);
+ let card = conversation::edits_element_id("t1");
+ assert!(harness.with_window(cx, |window, _| window.try_find("workbar-pane").is_none()));
+ harness.with_window(cx, |window, cx| window.within(card.clone()).click("turn-edits-view", cx));
+ wait(&harness, cx);
+ let (shown, failure) = harness.with_window(cx, |window, _| {
+ (
+ window.try_find("review-turn-label").and_then(|label| label.label().map(str::to_owned)),
+ window
+ .try_find(shared::domain_element_id("settings-status", "review-failure"))
+ .is_some(),
+ )
+ });
+ assert_eq!(shown.as_deref(), Some("Build the report"), "the panel opens on the turn");
+ assert!(!failure, "no repository is no failure where the turn shows");
+ let turn = harness.workbench.read_with(cx, |workbench, cx| {
+ workbench.review_panel().read(cx).shown_turn().map(ToString::to_string)
+ });
+ assert_eq!(turn.as_deref(), Some("t1"));
+
+ harness
+ .with_window(cx, |window, cx| window.within(card.clone()).click(file_id("data.txt"), cx));
+ wait(&harness, cx);
+ let selected = harness.workbench.read_with(cx, |workbench, cx| {
+ workbench.review_panel().read(cx).selected_file().map(ToString::to_string)
+ });
+ assert_eq!(selected.as_deref(), Some("data.txt"));
+ let header = shared::domain_element_id("review-file-header", "data.txt");
+ assert!(harness.with_window(cx, |window, _| window.try_find(header).is_some()));
+}
+
+/// A Code Mode turn too large for the transcript's 16 KiB tail: the window
+/// opens on its reply, reads the rest of it as older history, and then
+/// cards the files its code cell wrote, as it would had the turn been read
+/// whole (F29: the card never showed, the turn's edits read once from the
+/// tail alone).
+#[gpui_kit::test]
+fn the_card_counts_a_code_cell_turn_the_tail_cut(cx: &mut TestAppContext) {
+ let folder = Folder::new("cut");
+ let rows = code_cell_rows(&folder);
+ // The tail starts at the `exec`'s result; the older page has the rest.
+ let (older, tail) = rows.split_at(9);
+ cx.executor().allow_parking();
+ let path = folder.0.to_string_lossy().into_owned();
+ let transport = ScriptedHost::new(vec![session("s1", "Alpha", &path, "active")]);
+ let tail = older_page(tail, older.len() + 1, rows.len(), Some("c1"));
+ transport.reply("subscription.open", Ok(open_with_tail(tail)));
+ transport.reply("session.transcript.page", Ok(older_page(older, 1, rows.len(), None)));
+ let harness = Harness::with_transport(transport.clone(), cx);
+ wait(&harness, cx);
+ assert_eq!(
+ transport.requests("session.transcript.page").len(),
+ 1,
+ "the rest of the turn was read as older history"
+ );
+ let card = conversation::edits_element_id("t1");
+ assert_eq!(
+ label(&harness, card.clone(), "turn-edits-title", cx).as_deref(),
+ Some("Edited 2 files")
+ );
+ let rows: Vec<Option<String>> = ["notes.md", "report.py"]
+ .iter()
+ .map(|path| label(&harness, card.clone(), file_id(path), cx))
+ .collect();
+ assert_eq!(
+ rows,
+ [
+ Some("notes.md, 3 lines added, 0 lines deleted".to_owned()),
+ Some("report.py, 1 line added, 1 line deleted".to_owned()),
+ ]
+ );
+}
+
+/// Turn `t1` of [`turn_rows`] with a reply taller than the window, so a
+/// tail of its last rows fills the transcript.
+fn turn_rows_long_reply(folder: &Folder) -> Vec<Value> {
+ let mut rows = turn_rows(folder);
+ let reply: String =
+ (1..=40).map(|n| format!("Paragraph {n} on how the report was built.\n\n")).collect();
+ rows[11]["text"] = json!(reply);
+ rows
+}
+
+/// The window on task `s1` whose transcript tail is `rows` from
+/// `tail_from` on, cut inside turn `t1` (older history behind cursor `c1`).
+/// The first read of older history waits for the returned sender.
+fn open_cut(
+ folder: &Folder,
+ rows: &[Value],
+ tail_from: usize,
+ cx: &mut TestAppContext,
+) -> (Harness, async_channel::Sender<Result<Value, workspace::HostRequestError>>) {
+ cx.executor().allow_parking();
+ let path = folder.0.to_string_lossy().into_owned();
+ let transport = ScriptedHost::new(vec![session("s1", "Alpha", &path, "active")]);
+ let tail = older_page(&rows[tail_from..], tail_from + 1, rows.len(), Some("c1"));
+ transport.reply("subscription.open", Ok(open_with_tail(tail)));
+ let page = transport.hold("session.transcript.page");
+ let harness = Harness::with_transport(transport, cx);
+ wait(&harness, cx);
+ (harness, page)
+}
+
+fn has_card(harness: &Harness, cx: &mut TestAppContext) -> bool {
+ harness.with_window(cx, |window, _| {
+ window.try_find(conversation::edits_element_id("t1")).is_some()
+ })
+}
+
+fn footer_top(harness: &Harness, cx: &mut TestAppContext) -> gpui_kit::Pixels {
+ harness.with_window(cx, |window, _| {
+ window.find(conversation::footer_element_id("t1")).bounds().top()
+ })
+}
+
+/// The card lists all four files of turn `t1`, the first of them edited at
+/// the turn's start.
+fn assert_whole_card(harness: &Harness, cx: &mut TestAppContext) {
+ let card = conversation::edits_element_id("t1");
+ assert_eq!(
+ label(harness, card.clone(), "turn-edits-title", cx).as_deref(),
+ Some("Edited 4 files")
+ );
+ assert_eq!(
+ label(harness, card.clone(), "turn-edits-counts", cx).as_deref(),
+ Some("6 lines added, 3 lines deleted")
+ );
+ assert_eq!(
+ label(harness, card, file_id("report.py"), cx).as_deref(),
+ Some("report.py, 2 lines added, 2 lines deleted")
+ );
+}
+
+/// A task whose last turn is larger than the tail opens on the turn's
+/// reply, which fills the transcript: no card, because the turn's start
+/// and its edits are older history. The window reads it on its own, in the
+/// background, and then cards the whole turn, its end where it was.
+#[gpui_kit::test]
+fn a_turn_larger_than_the_tail_cards_once_its_start_is_read(cx: &mut TestAppContext) {
+ let folder = Folder::new("whole");
+ let rows = turn_rows_long_reply(&folder);
+ // The tail holds the reply and the end; every call is older.
+ let (harness, page) = open_cut(&folder, &rows, 11, cx);
+ let reads = harness.transport.requests("session.transcript.page");
+ assert_eq!(reads.len(), 1, "the turn's end shows: its start is read on its own");
+ assert_eq!(reads[0]["maxBytes"], conversation::BACKGROUND_PAGE_BYTES);
+ assert!(!has_card(&harness, cx), "no card for half a turn");
+ let before = footer_top(&harness, cx);
+
+ page.try_send(Ok(older_page(&rows[..11], 1, rows.len(), None))).expect("release");
+ wait(&harness, cx);
+ assert_whole_card(&harness, cx);
+ assert_eq!(harness.transport.requests("session.transcript.page").len(), 1);
+ let after = footer_top(&harness, cx);
+ assert!(f32::from((after - before).abs()) < 1., "the turn's end stayed: {before:?} {after:?}");
+}
+
+/// Every edit of the turn is in the tail, only its prompt older: the card
+/// still waits for the turn's start, then lists the same files.
+#[gpui_kit::test]
+fn a_turn_whose_edits_are_all_in_the_tail_waits_for_its_start(cx: &mut TestAppContext) {
+ let folder = Folder::new("tail-edits");
+ let rows = turn_rows_long_reply(&folder);
+ let (harness, page) = open_cut(&folder, &rows, 1, cx);
+ assert_eq!(harness.transport.requests("session.transcript.page").len(), 1);
+ assert!(!has_card(&harness, cx), "the edits are here, the start is not");
+ harness.workbench.read_with(cx, |workbench, cx| {
+ let turns = workbench.review_panel().read(cx).turn_changes().read(cx).turns().len();
+ assert_eq!(turns, 0, "nor is the turn a scope of the panel");
+ });
+
+ page.try_send(Ok(older_page(&rows[..1], 1, rows.len(), None))).expect("release");
+ wait(&harness, cx);
+ assert_whole_card(&harness, cx);
+}
+
+/// Turn `turn` writing `name`, a new file of two lines, then a reply
+/// of `paragraphs` paragraphs.
+fn writing_turn(folder: &Folder, turn: &str, name: &str, paragraphs: usize) -> Vec<Value> {
+ let content = "one\ntwo\n";
+ std::fs::write(folder.0.join(name), content).expect("write");
+ let path = folder.path(name);
+ let call = format!("{turn}-c1");
+ let reply: String = (1..=paragraphs).map(|n| format!("Paragraph {n}.\n\n")).collect();
+ vec![
+ json!({"type": "user", "id": turn, "turnId": turn, "ts": 1,
+ "text": format!("Write {name}")}),
+ json!({"type": "tool_call", "id": call, "turnId": turn, "ts": 2, "toolName": "Write",
+ "args": {"path": name, "content": content}, "stepId": format!("{turn}-s1")}),
+ json!({"type": "tool_result", "id": format!("{call}-r"), "turnId": turn, "ts": 3,
+ "toolUseId": call, "isError": false,
+ "content": {"kind": "file_diff", "paths": [path], "diff": format!(
+ "--- /dev/null\n+++ b/{path}\n@@ -0,0 +1,2 @@\n+one\n+two")}}),
+ json!({"type": "assistant", "id": format!("{turn}-s1"), "turnId": turn, "ts": 4,
+ "text": reply, "contentOrder": ["tools", "text"], "modelId": "m"}),
+ json!({"type": "turn_state", "id": format!("{turn}-end"), "turnId": turn, "ts": 5,
+ "status": "completed"}),
+ ]
+}
+
+fn listed_turns(harness: &Harness, cx: &mut TestAppContext) -> Vec<String> {
+ harness.workbench.read_with(cx, |workbench, cx| {
+ let panel = workbench.review_panel().read(cx);
+ panel.turn_list().iter().map(|turn| turn.turn_id().to_string()).collect()
+ })
+}
+
+fn reading_line(harness: &Harness, cx: &mut TestAppContext) -> Option<String> {
+ harness.with_window(cx, |window, _| {
+ window.try_find("review-turns-reading").and_then(|line| line.label().map(str::to_owned))
+ })
+}
+
+/// Three turns, each writing a file; the tail holds only the newest. The
+/// changes panel opened on the task reads the rest of the history in the
+/// background, saying so under the turns meanwhile, and then lists every
+/// turn's scope.
+#[gpui_kit::test]
+fn the_panel_lists_every_turn_once_the_history_is_read(cx: &mut TestAppContext) {
+ cx.executor().allow_parking();
+ let folder = Folder::new("history");
+ let (t1, t2) = (writing_turn(&folder, "t1", "a.md", 1), writing_turn(&folder, "t2", "b.md", 1));
+ let t3 = writing_turn(&folder, "t3", "c.md", 40);
+ let through = t1.len() + t2.len() + t3.len();
+ let path = folder.0.to_string_lossy().into_owned();
+ let transport = ScriptedHost::new(vec![session("s1", "Alpha", &path, "active")]);
+ // The tail ends between turns: no turn is cut, older ones exist.
+ let mut tail = older_page(&t3, t1.len() + t2.len() + 1, through, Some("c1"));
+ tail["endsAtTurnBoundary"] = json!(true);
+ transport.reply("subscription.open", Ok(open_with_tail(tail)));
+ let page = transport.hold("session.transcript.page");
+ let mut second = older_page(&t1, 1, through, None);
+ second["endsAtTurnBoundary"] = json!(true);
+ transport.reply("session.transcript.page", Ok(second));
+ let harness = Harness::with_transport(transport, cx);
+ wait(&harness, cx);
+ assert!(
+ harness.transport.requests("session.transcript.page").is_empty(),
+ "nothing is read while the panel is closed and no turn is cut"
+ );
+
+ harness.with_window(cx, |window, cx| window.click("review-toggle", cx));
+ wait(&harness, cx);
+ let reads = harness.transport.requests("session.transcript.page");
+ assert_eq!(reads.len(), 1, "opening the panel reads the earlier history");
+ assert_eq!(reads[0]["maxBytes"], conversation::BACKGROUND_PAGE_BYTES);
+ assert_eq!(listed_turns(&harness, cx), ["t3"]);
+ assert_eq!(reading_line(&harness, cx).as_deref(), Some("Reading earlier turns"));
+
+ let mut first = older_page(&t2, t1.len() + 1, through, Some("c2"));
+ first["endsAtTurnBoundary"] = json!(true);
+ page.try_send(Ok(first)).expect("release");
+ wait(&harness, cx);
+ assert_eq!(harness.transport.requests("session.transcript.page").len(), 2);
+ assert_eq!(listed_turns(&harness, cx), ["t1", "t2", "t3"]);
+ assert_eq!(reading_line(&harness, cx), None, "the history is whole");
+}
+
+/// The panel opened while a turn runs reads nothing; once the turn ends,
+/// it reads the earlier history.
+#[gpui_kit::test]
+fn the_panel_reads_no_history_while_a_turn_runs(cx: &mut TestAppContext) {
+ cx.executor().allow_parking();
+ let folder = Folder::new("running");
+ let t1 = writing_turn(&folder, "t1", "a.md", 1);
+ let t2 = writing_turn(&folder, "t2", "b.md", 40);
+ let through = t1.len() + t2.len();
+ let path = folder.0.to_string_lossy().into_owned();
+ let transport = ScriptedHost::new(vec![session("s1", "Alpha", &path, "active")]);
+ let mut tail = older_page(&t2, t1.len() + 1, through, Some("c1"));
+ tail["endsAtTurnBoundary"] = json!(true);
+ transport.reply("subscription.open", Ok(open_with_tail(tail)));
+ transport.reply("session.transcript.page", Ok(older_page(&t1, 1, through, None)));
+ let mut harness = Harness::with_transport(transport, cx);
+ wait(&harness, cx);
+ harness.project("s1", crate::tests::root("t3", "run-3", "running"), cx);
+ harness.with_window(cx, |window, cx| window.click("review-toggle", cx));
+ wait(&harness, cx);
+ assert!(harness.transport.requests("session.transcript.page").is_empty(), "a turn runs");
+ assert_eq!(reading_line(&harness, cx), None);
+ assert_eq!(listed_turns(&harness, cx), ["t2"]);
+
+ harness.project("s1", crate::tests::root("t3", "run-3", "completed"), cx);
+ wait(&harness, cx);
+ assert_eq!(harness.transport.requests("session.transcript.page").len(), 1);
+ assert_eq!(listed_turns(&harness, cx), ["t1", "t2"]);
+}
diff --git a/apps/desktop-gpui/crates/app/src/workbar_tests.rs b/apps/desktop-gpui/crates/app/src/workbar_tests.rs
new file mode 100644
index 0000000000..0b03acd4e5
--- /dev/null
+++ b/apps/desktop-gpui/crates/app/src/workbar_tests.rs
@@ -0,0 +1,633 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! UI integration tests of the workbar in the window: its [+] menu, its
+//! tabs and their ×, the strip overflowing, Ctrl+`, its tabs through
+//! placement changes and maximize, terminals following the selected task,
+//! their controllers held only while their face shows, the app's keys
+//! around a focused terminal, and the Terminal settings taking effect; the
+//! Files face from [+] and ⌘P, its Escape, and its list read again when a
+//! turn settles; the Trace face from [+], read and refreshed only while it
+//! shows.
+
+// The changes' read checks the task folder on the blocking pool, which the
+// settle loop waits on.
+#![allow(clippy::disallowed_methods)]
+
+use std::path::Path;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use futures_lite::FutureExt as _;
+use futures_lite::future::Boxed;
+use gpui_kit::test::TestWindowExt as _;
+use gpui_kit::{Context, TestAppContext, px, size};
+use review::git::{GitError, GitOutput, GitRunner};
+use serde_json::json;
+use settings::AppPreferences;
+
+use crate::tests::{EPOCH, Harness, ScriptedHost, artifact, frame, session, settle, terminal_ref};
+
+/// Git that fails at once: the changes' face shows its failure, and no
+/// read waits on a subprocess.
+struct NoGit;
+
+impl GitRunner for NoGit {
+ fn run(&self, _: &Path, _: &[String]) -> Boxed<Result<GitOutput, GitError>> {
+ async { Err(GitError::Failed("fatal: nothing here".to_owned())) }.boxed()
+ }
+}
+
+struct Bench {
+ harness: Harness,
+}
+
+impl Bench {
+ /// The window with tasks `ids`, the first selected; each task's
+ /// terminals as `terminals` lists them.
+ fn open(ids: &[&str], terminals: &[(&str, &[&str])], cx: &mut TestAppContext) -> Self {
+ let transport =
+ ScriptedHost::new(ids.iter().map(|id| session(id, id, "/work/a", "active")).collect());
+ for (task, names) in terminals {
+ transport.set_terminals(task, names);
+ }
+ cx.executor().allow_parking();
+ let harness = Harness::with_transport(transport, cx);
+ harness.workbench.update(cx, |workbench, cx| {
+ workbench.review_panel().update(cx, |panel, _| panel.set_git_runner(Arc::new(NoGit)));
+ });
+ let bench = Self { harness };
+ bench.select(ids[0], cx);
+ bench
+ }
+
+ fn select(&self, id: &str, cx: &mut TestAppContext) {
+ self.harness.workbench.update(cx, |workbench, cx| {
+ let catalog = workbench.sidebar().read(cx).catalog().clone();
+ catalog.update(cx, |catalog, cx| catalog.select(Some(id), cx));
+ });
+ self.frame(cx);
+ }
+
+ /// Draws a frame and lets what it set off (the changes' read among it)
+ /// run to its end.
+ fn frame(&self, cx: &mut TestAppContext) {
+ let deadline = Instant::now() + Duration::from_secs(10);
+ loop {
+ self.harness.with_window(cx, |_, _| {});
+ settle(cx);
+ let loading = self
+ .harness
+ .workbench
+ .read_with(cx, |workbench, cx| workbench.review_panel().read(cx).is_loading());
+ if !loading || Instant::now() > deadline {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(5));
+ }
+ self.harness.with_window(cx, |_, _| {});
+ }
+
+ /// The × of a tab that does not show appears under the pointer.
+ fn close_tab(&self, key: &str, cx: &mut TestAppContext) {
+ let wrapper = shared::domain_element_id("workbar-tab", key);
+ self.harness.with_window(cx, |window, cx| window.hover(wrapper, cx));
+ self.frame(cx);
+ self.click(close(key), cx);
+ }
+
+ /// Changes the preferences, as a switch in Settings does.
+ fn set_preferences(
+ &self,
+ change: impl FnOnce(&mut AppPreferences, &mut Context<AppPreferences>),
+ cx: &mut TestAppContext,
+ ) {
+ cx.update(|cx| AppPreferences::global(cx).update(cx, change));
+ self.frame(cx);
+ }
+
+ fn press(&self, keys: &str, cx: &mut TestAppContext) {
+ for key in keys.split(' ') {
+ self.harness.with_window(cx, |window, cx| window.press(key, cx));
+ self.frame(cx);
+ }
+ }
+
+ fn click(&self, id: impl Into<gpui_kit::ElementId>, cx: &mut TestAppContext) {
+ let id = id.into();
+ self.harness.with_window(cx, |window, cx| window.click(id, cx));
+ self.frame(cx);
+ }
+
+ fn exists(&self, id: impl Into<gpui_kit::ElementId>, cx: &mut TestAppContext) -> bool {
+ let id = id.into();
+ self.harness.with_window(cx, |window, _| window.try_find(id).is_some())
+ }
+
+ fn focused(&self, id: &'static str, cx: &mut TestAppContext) -> bool {
+ self.harness.with_window(cx, |window, _| {
+ window.try_find(id).and_then(|element| element.focused()) == Some(true)
+ })
+ }
+
+ /// The strip's tabs: key, name and whether it shows.
+ fn tabs(&self, cx: &mut TestAppContext) -> Vec<(String, String, bool)> {
+ self.harness.workbench.read_with(cx, |workbench, cx| workbench.strip_tabs(cx))
+ }
+
+ fn open_workbar(&self, cx: &mut TestAppContext) -> bool {
+ self.harness.workbench.read_with(cx, |workbench, cx| workbench.workbar_shown(cx))
+ }
+
+ fn starts(&self) -> usize {
+ self.harness.transport.requests("runtime.resource.start").len()
+ }
+
+ /// Everything typed into terminals so far.
+ fn typed(&self) -> String {
+ self.harness
+ .transport
+ .requests("runtime.resource.controller.control")
+ .iter()
+ .filter_map(|input| input["control"]["input"].as_str().map(str::to_owned))
+ .collect()
+ }
+
+ /// The rows of each resize sent.
+ fn resizes(&self) -> Vec<u64> {
+ self.harness
+ .transport
+ .requests("runtime.resource.controller.control")
+ .iter()
+ .filter(|input| input["control"]["kind"] == "resize")
+ .map(|input| input["control"]["rows"].as_u64().expect("rows"))
+ .collect()
+ }
+
+ fn menu_item(&self, key: &str, cx: &mut TestAppContext) -> Option<bool> {
+ let id = shared::domain_element_id("menu-item", key);
+ self.harness.with_window(cx, |window, _| {
+ window.try_find(id).map(|item| item.checked() == Some(true))
+ })
+ }
+
+ /// Output of terminal `name` of task `session`.
+ fn output(
+ &mut self,
+ task: &str,
+ name: &str,
+ sequence: u64,
+ data: &str,
+ cx: &mut TestAppContext,
+ ) {
+ self.harness.push(
+ frame(json!({
+ "kind": "subscription.runtime_resource_pty_data", "hostEpoch": EPOCH,
+ "subscriptionId": format!("sub-{task}"), "sessionId": task,
+ "ref": terminal_ref(name), "ptySequence": sequence, "data": data
+ })),
+ cx,
+ );
+ self.frame(cx);
+ }
+}
+
+fn tab(key: &str) -> gpui_kit::ElementId {
+ shared::domain_element_id("workbar-tab-button", key)
+}
+
+fn close(key: &str) -> gpui_kit::ElementId {
+ shared::domain_element_id("workbar-tab-close", key)
+}
+
+#[gpui_kit::test]
+fn the_add_menu_opens_changes_and_terminals_and_marks_the_open_ones(cx: &mut TestAppContext) {
+ let bench = Bench::open(&["s1"], &[], cx);
+ bench.click("review-toggle", cx);
+ assert_eq!(bench.tabs(cx), [("changes".into(), "Changes".into(), true)]);
+
+ bench.click("workbar-add", cx);
+ assert_eq!(bench.menu_item("workbar-tool-changes", cx), Some(true), "Changes is open");
+ assert_eq!(bench.menu_item("workbar-tool-terminal", cx), Some(false));
+ bench.click(shared::domain_element_id("menu-item", "workbar-tool-terminal"), cx);
+ assert_eq!(bench.starts(), 1);
+ let started = terminal_ref("started-1");
+ assert_eq!(
+ bench.tabs(cx),
+ [("changes".into(), "Changes".into(), false), (started.clone(), "Terminal".into(), true)],
+ "the new terminal shows, after Changes"
+ );
+ assert!(bench.exists("terminal-face", cx));
+ assert!(bench.focused("terminal-grid", cx), "and has the focus");
+
+ // Terminal always adds one; both are marked open now.
+ bench.click("workbar-add", cx);
+ assert_eq!(bench.menu_item("workbar-tool-changes", cx), Some(true));
+ assert_eq!(bench.menu_item("workbar-tool-terminal", cx), Some(true));
+ bench.click(shared::domain_element_id("menu-item", "workbar-tool-terminal"), cx);
+ assert_eq!(bench.starts(), 2);
+ assert_eq!(bench.tabs(cx).len(), 3);
+ // Unmarking Changes closes its face.
+ bench.click("workbar-add", cx);
+ bench.click(shared::domain_element_id("menu-item", "workbar-tool-changes"), cx);
+ let keys: Vec<String> = bench.tabs(cx).into_iter().map(|(key, _, _)| key).collect();
+ assert_eq!(keys, [started, terminal_ref("started-2")]);
+ bench.click("workbar-add", cx);
+ assert_eq!(bench.menu_item("workbar-tool-changes", cx), Some(false));
+}
+
+#[gpui_kit::test]
+fn a_tabs_close_button_closes_its_face_and_the_last_one_hides_the_panel(cx: &mut TestAppContext) {
+ let bench = Bench::open(&["s1"], &[("s1", &["r1"])], cx);
+ bench.click("review-toggle", cx);
+ let r1 = terminal_ref("r1");
+ assert_eq!(bench.tabs(cx).len(), 2, "Changes and the task's terminal");
+ // The shown tab's ×: Changes closes and the terminal shows.
+ bench.click(close("changes"), cx);
+ assert_eq!(bench.tabs(cx), [(r1.clone(), "Terminal".into(), true)]);
+ assert!(bench.open_workbar(cx));
+ // The terminal's ×: its shell stops, without asking, and the tab goes
+ // when the Host confirms; it was the last, so the panel hides.
+ let stop = bench.harness.transport.hold("runtime.resource.stop");
+ bench.click(close(&r1), cx);
+ assert_eq!(bench.harness.transport.requests("runtime.resource.stop").len(), 1);
+ assert!(bench.exists(shared::domain_element_id("workbar-tab-closing", &r1), cx));
+ stop.try_send(Ok(json!({}))).expect("stop");
+ bench.frame(cx);
+ assert!(bench.tabs(cx).is_empty());
+ assert!(!bench.open_workbar(cx), "the last face closed hides the panel");
+}
+
+#[gpui_kit::test]
+fn inactive_tabs_drop_their_labels_when_the_strip_overflows(cx: &mut TestAppContext) {
+ let names = ["a1", "a2", "a3", "a4", "a5", "a6", "a7"];
+ let bench = Bench::open(&["s1"], &[("s1", &names)], cx);
+ bench.click("review-toggle", cx);
+ bench.frame(cx);
+ let label = |key: &str| shared::domain_element_id("workbar-tab-label", key);
+ // Changes shows: every other tab is bare, its name kept for assistive
+ // technology and a tooltip.
+ assert!(bench.exists(label("changes"), cx));
+ for name in names {
+ assert!(!bench.exists(label(&terminal_ref(name)), cx), "{name} drops its label");
+ }
+ let spoken = bench.harness.with_window(cx, |window, _| {
+ window.find(tab(&terminal_ref("a2"))).label().map(str::to_owned)
+ });
+ assert_eq!(spoken.as_deref(), Some("Terminal 2"));
+ // The active one keeps its label.
+ bench.click(tab(&terminal_ref("a3")), cx);
+ assert!(bench.exists(label(&terminal_ref("a3")), cx));
+ assert!(!bench.exists(label("changes"), cx));
+ // With room again every label returns: no horizontal scrolling.
+ bench.close_tab("changes", cx);
+ for name in &names[3..] {
+ bench.close_tab(&terminal_ref(name), cx);
+ }
+ bench.frame(cx);
+ for name in &names[..3] {
+ assert!(bench.exists(label(&terminal_ref(name)), cx), "{name} has its label");
+ }
+}
+
+#[gpui_kit::test]
+fn ctrl_backtick_shows_starts_focuses_and_hides_the_terminal(cx: &mut TestAppContext) {
+ let bench = Bench::open(&["s1"], &[], cx);
+ assert!(!bench.open_workbar(cx));
+ // From the composer: the panel opens on a new terminal, focused.
+ bench.press("ctrl-`", cx);
+ assert!(bench.open_workbar(cx));
+ assert_eq!(bench.starts(), 1, "the task had none: one starts");
+ let started = terminal_ref("started-1");
+ assert_eq!(
+ bench.tabs(cx),
+ [("changes".into(), "Changes".into(), false), (started.clone(), "Terminal".into(), true)]
+ );
+ assert!(bench.focused("terminal-grid", cx));
+ // With the terminal focused: the panel hides, its terminal kept.
+ bench.press("ctrl-`", cx);
+ assert!(!bench.open_workbar(cx));
+ assert!(bench.harness.transport.requests("runtime.resource.stop").is_empty());
+ // Again: the same terminal, focused; nothing new starts.
+ bench.press("ctrl-`", cx);
+ assert!(bench.open_workbar(cx));
+ assert_eq!(bench.starts(), 1);
+ assert!(bench.focused("terminal-grid", cx));
+ // On Changes, with the focus elsewhere: back to the terminal.
+ bench.click(tab("changes"), cx);
+ bench.harness.with_window(cx, |window, cx| {
+ window.dispatch_action(Box::new(workspace::actions::FocusComposer), cx);
+ });
+ bench.press("ctrl-`", cx);
+ assert_eq!(bench.tabs(cx)[1], (started, "Terminal".into(), true));
+ assert!(bench.focused("terminal-grid", cx));
+}
+
+#[gpui_kit::test]
+fn tabs_survive_placement_changes_and_maximize(cx: &mut TestAppContext) {
+ let bench = Bench::open(&["s1"], &[("s1", &["r1"])], cx);
+ bench.press("ctrl-`", cx);
+ let r1 = terminal_ref("r1");
+ let tabs = bench.tabs(cx);
+ assert_eq!(tabs.len(), 2);
+ let acquires = || bench.harness.transport.requests("runtime.resource.controller.acquire").len();
+ let attached = acquires();
+ assert_eq!(attached, 1);
+ bench.click("workbar-maximize", cx);
+ assert!(bench.harness.workbench.read_with(cx, |workbench, cx| workbench.workbar_maximized(cx)));
+ assert_eq!(bench.tabs(cx), tabs, "maximized, the same tabs");
+ assert!(bench.exists("terminal-grid", cx));
+ bench.press("shift-escape", cx);
+ assert!(
+ !bench.harness.workbench.read_with(cx, |workbench, cx| workbench.workbar_maximized(cx))
+ );
+ // Below the plate in a narrow window, and back beside it.
+ cx.simulate_window_resize(bench.harness.window.into(), size(px(860.), px(700.)));
+ bench.frame(cx);
+ assert_eq!(bench.tabs(cx), tabs);
+ cx.simulate_window_resize(bench.harness.window.into(), size(px(1400.), px(800.)));
+ bench.frame(cx);
+ assert_eq!(bench.tabs(cx), tabs);
+ assert_eq!(acquires(), attached, "the terminal stayed attached throughout");
+ assert!(bench.harness.transport.requests("runtime.resource.controller.release").is_empty());
+ assert_eq!(bench.tabs(cx)[1].0, r1);
+}
+
+#[gpui_kit::test]
+fn switching_tasks_swaps_terminals_and_returning_attaches_again(cx: &mut TestAppContext) {
+ let bench = Bench::open(&["s1", "s2"], &[("s1", &["r1"]), ("s2", &["o1", "o2"])], cx);
+ bench.press("ctrl-`", cx);
+ let keys = |bench: &Bench, cx: &mut TestAppContext| -> Vec<String> {
+ bench.tabs(cx).into_iter().map(|(key, _, _)| key).collect()
+ };
+ assert_eq!(keys(&bench, cx), ["changes".to_owned(), terminal_ref("r1")]);
+ bench.select("s2", cx);
+ assert!(!bench.open_workbar(cx), "each task its own workbar");
+ let released = bench.harness.transport.requests("runtime.resource.controller.release");
+ assert_eq!(released.len(), 1, "r1's controller is let go; its shell runs on");
+ bench.press("ctrl-`", cx);
+ assert_eq!(keys(&bench, cx), ["changes".to_owned(), terminal_ref("o1"), terminal_ref("o2")]);
+ assert_eq!(bench.starts(), 0, "s2 had terminals: none starts");
+ bench.select("s1", cx);
+ assert_eq!(keys(&bench, cx), ["changes".to_owned(), terminal_ref("r1")]);
+ let acquired: Vec<String> = bench
+ .harness
+ .transport
+ .requests("runtime.resource.controller.acquire")
+ .iter()
+ .map(|input| input["ref"].as_str().expect("ref").to_owned())
+ .collect();
+ assert_eq!(
+ acquired.iter().filter(|name| **name == terminal_ref("r1")).count(),
+ 2,
+ "attached again"
+ );
+}
+
+/// The terminals hold their controllers only while their face shows: on
+/// another face their output still streams in for their tabs, and back on
+/// their face they are taken again, each with its snapshot.
+#[gpui_kit::test]
+fn the_terminals_hold_their_controllers_only_while_their_face_shows(cx: &mut TestAppContext) {
+ let mut bench = Bench::open(&["s1"], &[("s1", &["r1", "r2"])], cx);
+ let count = |bench: &Bench, operation: &str| bench.harness.transport.requests(operation).len();
+ let interest = |bench: &Bench| {
+ let sets = bench.harness.transport.requests("subscription.pty_interest.set");
+ sets.last().map(|input| input["refs"].clone())
+ };
+ let both = json!([terminal_ref("r1"), terminal_ref("r2")]);
+ bench.press("ctrl-`", cx);
+ assert_eq!(count(&bench, "runtime.resource.controller.acquire"), 2);
+ assert_eq!(interest(&bench).as_ref(), Some(&both));
+
+ // Changes takes the panel: both seats go, the output still comes.
+ bench.click(tab("changes"), cx);
+ assert_eq!(count(&bench, "runtime.resource.controller.release"), 2);
+ assert_eq!(interest(&bench).as_ref(), Some(&both));
+ bench.output("s1", "r2", 1, "\x07", cx);
+ let bell = bench
+ .harness
+ .workbench
+ .read_with(cx, |workbench, cx| workbench.terminal_view().read(cx).tabs(cx)[1].bell);
+ assert!(bell, "r2's bell reaches its tab");
+
+ // Back to a terminal: both are taken again, and typing reaches it.
+ bench.click(tab(&terminal_ref("r1")), cx);
+ assert_eq!(count(&bench, "runtime.resource.controller.acquire"), 4);
+ assert_eq!(count(&bench, "runtime.resource.controller.release"), 2);
+ bench.output("s1", "r1", 1, "$ ", cx);
+ bench.press("l s enter", cx);
+ assert_eq!(bench.typed(), "ls\r");
+}
+
+#[gpui_kit::test]
+fn a_focused_terminal_gets_its_keys_and_the_apps_shortcuts_still_work(cx: &mut TestAppContext) {
+ let mut bench = Bench::open(&["s1"], &[("s1", &["r1"])], cx);
+ bench.press("ctrl-`", cx);
+ bench.output("s1", "r1", 1, "$ ", cx);
+ bench.press("escape up ctrl-c tab enter", cx);
+ assert_eq!(bench.typed(), "\x1b\x1b[A\x03\t\r");
+ assert!(bench.focused("terminal-grid", cx), "Tab kept the focus in the terminal");
+ // ⌘K is the palette's, not a clear.
+ bench.press("cmd-k", cx);
+ assert!(bench.exists("command-palette", cx));
+ bench.press("escape", cx);
+ assert_eq!(bench.typed(), "\x1b\x1b[A\x03\t\r", "the palette's keys stayed out of it");
+}
+
+#[gpui_kit::test]
+fn the_terminal_settings_take_effect_in_the_terminal(cx: &mut TestAppContext) {
+ let mut bench = Bench::open(&["s1"], &[("s1", &["r1"])], cx);
+ bench.press("ctrl-`", cx);
+ bench.output("s1", "r1", 1, "$ ", cx);
+ // Option as Meta off: ⌥B is Option's character, not Meta-B.
+ bench.press("alt-b", cx);
+ assert!(!bench.typed().contains("\x1bb"), "{:?}", bench.typed());
+ bench.set_preferences(|preferences, cx| preferences.set_terminal_option_as_meta(true, cx), cx);
+ bench.press("alt-b", cx);
+ assert!(bench.typed().ends_with("\x1bb"), "Meta-B: {:?}", bench.typed());
+ bench.set_preferences(|preferences, cx| preferences.set_terminal_option_as_meta(false, cx), cx);
+ bench.press("alt-b", cx);
+ assert!(bench.typed().ends_with("\x1bb") && bench.typed().matches("\x1bb").count() == 1);
+
+ // Blinking cursor: the terminal's cursor blinks by default, and not
+ // once the setting is off.
+ let blinking = |cx: &mut TestAppContext| {
+ bench.harness.workbench.read_with(cx, |workbench, cx| {
+ let terminal = workbench.terminal_view().read(cx).active_terminal(cx).expect("r1");
+ terminal.read(cx).content().cursor.blinking
+ })
+ };
+ assert!(blinking(cx));
+ bench.set_preferences(|preferences, cx| preferences.set_terminal_cursor_blink(false, cx), cx);
+ assert!(!blinking(cx));
+}
+
+#[gpui_kit::test]
+fn zooming_recomputes_a_terminals_grid(cx: &mut TestAppContext) {
+ let bench = Bench::open(&["s1"], &[("s1", &["r1"])], cx);
+ cx.simulate_window_resize(bench.harness.window.into(), size(px(1600.), px(900.)));
+ bench.press("ctrl-`", cx);
+ let before = *bench.resizes().last().expect("the grid from the bounds");
+ bench.press("cmd-=", cx);
+ let after = *bench.resizes().last().expect("resized");
+ // The panel's width zooms with the cells; its height is the window's.
+ assert!(after < before, "larger cells, fewer rows: {before} → {after}");
+}
+
+/// The Files face: between Changes and Terminal in [+], opened there and
+/// with ⌘P, its tab remembered for the task, and its list read as it
+/// shows.
+#[gpui_kit::test]
+fn files_open_from_the_add_menu_and_cmd_p_between_changes_and_terminal(cx: &mut TestAppContext) {
+ let bench = Bench::open(&["s1", "s2"], &[], cx);
+ bench.harness.transport.set_artifacts("s1", vec![artifact("s1", "a1", "brief.md")]);
+ bench.click("review-toggle", cx);
+ bench.click("workbar-add", cx);
+ assert_eq!(bench.menu_item("workbar-tool-files", cx), Some(false));
+ let tops = bench.harness.with_window(cx, |window, _| {
+ ["workbar-tool-changes", "workbar-tool-files", "workbar-tool-terminal"]
+ .map(|key| window.find(shared::domain_element_id("menu-item", key)).bounds().top())
+ });
+ assert!(tops[0] < tops[1] && tops[1] < tops[2], "Files between Changes and Terminal");
+ bench.click(shared::domain_element_id("menu-item", "workbar-tool-files"), cx);
+ assert_eq!(
+ bench.tabs(cx),
+ [("changes".into(), "Changes".into(), false), ("files".into(), "Files".into(), true)]
+ );
+ assert!(bench.exists(shared::domain_element_id("files-row", "a1"), cx), "read as it shows");
+ assert!(bench.focused("files-list", cx));
+ let open = |cx: &mut TestAppContext| {
+ cx.update(|cx| AppPreferences::global(cx).read(cx).is_files_face_open("s1"))
+ };
+ assert!(open(cx), "the task remembers its Files face");
+
+ // ⌘P while the files show hides the panel; again shows them, focused.
+ bench.press("cmd-p", cx);
+ assert!(!bench.open_workbar(cx));
+ bench.press("cmd-p", cx);
+ assert!(bench.open_workbar(cx));
+ assert_eq!(bench.tabs(cx)[1], ("files".into(), "Files".into(), true));
+ assert!(bench.focused("files-list", cx));
+ // On Changes, ⌘P comes back to the files.
+ bench.click(tab("changes"), cx);
+ bench.press("cmd-p", cx);
+ assert_eq!(bench.tabs(cx)[1], ("files".into(), "Files".into(), true));
+ // Another task has its own files; its face is not open.
+ bench.select("s2", cx);
+ assert_eq!(bench.tabs(cx), [("changes".into(), "Changes".into(), true)]);
+ bench.press("cmd-p", cx);
+ assert!(bench.exists("files-empty", cx), "s2 has none");
+ // Unmarking it in [+] closes the face.
+ bench.click("workbar-add", cx);
+ bench.click(shared::domain_element_id("menu-item", "workbar-tool-files"), cx);
+ assert_eq!(bench.tabs(cx), [("changes".into(), "Changes".into(), true)]);
+ assert!(!cx.update(|cx| AppPreferences::global(cx).read(cx).is_files_face_open("s2")));
+}
+
+#[gpui_kit::test]
+fn escape_in_the_file_list_gives_the_composer_its_place_back(cx: &mut TestAppContext) {
+ let bench = Bench::open(&["s1"], &[], cx);
+ bench.press("cmd-p", cx);
+ assert!(bench.open_workbar(cx));
+ assert!(bench.focused("files-list", cx));
+ bench.press("escape", cx);
+ assert!(!bench.open_workbar(cx));
+ let draft = bench.harness.draft_id(cx);
+ let focused = bench.harness.with_window(cx, |window, _| window.find(draft).focused());
+ assert_eq!(focused, Some(true));
+}
+
+#[gpui_kit::test]
+fn a_settled_turn_reads_the_files_again(cx: &mut TestAppContext) {
+ let mut bench = Bench::open(&["s1"], &[], cx);
+ bench.press("cmd-p", cx);
+ let lists = |bench: &Bench| {
+ bench
+ .harness
+ .transport
+ .requests("artifact.query")
+ .iter()
+ .filter(|input| input["kind"] == "list_start")
+ .count()
+ };
+ let before = lists(&bench);
+ bench.harness.project("s1", crate::tests::root("t1", "r1", "running"), cx);
+ bench.frame(cx);
+ assert_eq!(lists(&bench), before);
+ bench.harness.transport.set_artifacts("s1", vec![artifact("s1", "a1", "late.md")]);
+ bench.harness.project("s1", crate::tests::root("t1", "r1", "completed"), cx);
+ bench.frame(cx);
+ assert_eq!(lists(&bench), before + 1);
+ assert!(bench.exists(shared::domain_element_id("files-row", "a1"), cx));
+}
+
+/// The Trace face: after Files in [+], with no shortcut, opened there and
+/// remembered for the task; read as it shows; a usage change of the task
+/// refreshes its summary while it shows and not once it is hidden behind
+/// another tab; Escape in it gives the composer its place back.
+#[gpui_kit::test]
+fn the_trace_opens_from_the_add_menu_after_files(cx: &mut TestAppContext) {
+ let mut bench = Bench::open(&["s1", "s2"], &[], cx);
+ bench.click("review-toggle", cx);
+ bench.click("workbar-add", cx);
+ assert_eq!(bench.menu_item("workbar-tool-inspector", cx), Some(false));
+ let tops = bench.harness.with_window(cx, |window, _| {
+ ["workbar-tool-files", "workbar-tool-inspector", "workbar-tool-terminal"]
+ .map(|key| window.find(shared::domain_element_id("menu-item", key)).bounds().top())
+ });
+ assert!(tops[0] < tops[1] && tops[1] < tops[2], "Trace between Files and Terminal");
+ bench.click(shared::domain_element_id("menu-item", "workbar-tool-inspector"), cx);
+ assert_eq!(
+ bench.tabs(cx),
+ [("changes".into(), "Changes".into(), false), ("inspector".into(), "Trace".into(), true)]
+ );
+ assert!(bench.exists("inspector-face", cx));
+ assert!(bench.exists("inspector-empty", cx), "s1 has not run");
+ assert!(bench.focused("inspector-face", cx));
+ let summaries = |bench: &Bench| bench.harness.transport.requests("usage.query").len();
+ assert_eq!(summaries(&bench), 1, "read as it shows");
+ assert!(cx.update(|cx| AppPreferences::global(cx).read(cx).is_inspector_face_open("s1")));
+
+ bench.harness.domain_changed("s1", "usage", cx);
+ cx.executor().advance_clock(inspector::REFRESH_DEBOUNCE * 2);
+ bench.frame(cx);
+ assert_eq!(summaries(&bench), 2, "the task's usage changed while the face shows");
+
+ // Behind the Changes tab the face is hidden: nothing refreshes.
+ bench.click(tab("changes"), cx);
+ bench.harness.domain_changed("s1", "usage", cx);
+ cx.executor().advance_clock(inspector::REFRESH_DEBOUNCE * 2);
+ bench.frame(cx);
+ assert_eq!(summaries(&bench), 2);
+
+ // Escape in the face hides the panel and focuses the composer.
+ bench.click(tab("inspector"), cx);
+ bench.press("escape", cx);
+ assert!(!bench.open_workbar(cx));
+
+ // Unmarking it in [+] closes the face; another task's is not open.
+ bench.click("review-toggle", cx);
+ bench.click("workbar-add", cx);
+ assert_eq!(bench.menu_item("workbar-tool-inspector", cx), Some(true));
+ bench.click(shared::domain_element_id("menu-item", "workbar-tool-inspector"), cx);
+ assert_eq!(bench.tabs(cx), [("changes".into(), "Changes".into(), true)]);
+ bench.select("s2", cx);
+ assert!(!cx.update(|cx| AppPreferences::global(cx).read(cx).is_inspector_face_open("s2")));
+}
diff --git a/apps/desktop-gpui/crates/app/src/workbench.rs b/apps/desktop-gpui/crates/app/src/workbench.rs
index 91b2c62b5e..aaa246628e 100644
--- a/apps/desktop-gpui/crates/app/src/workbench.rs
+++ b/apps/desktop-gpui/crates/app/src/workbench.rs
@@ -34,6 +34,7 @@ use conversation::{
};
use extensions::{ExtensionsContext, ExtensionsView};
use gpui_kit::assets::IconName as AssetIcon;
+use gpui_kit::base::TextSelection;
use gpui_kit::base::animation::{EffectTransition, ease_in_out_cubic};
use gpui_kit::component::button::{Button, ButtonVariants as _};
use gpui_kit::component::clipboard::Clipboard;
@@ -49,6 +50,7 @@ use gpui_kit::{
Render, Role, SharedString, StatefulInteractiveElement as _, Styled as _, Subscription, Task,
TestSupportExt as _, Window, div, prelude::FluentBuilder as _, px, rems,
};
+use search::{SearchPageEvent, SearchView, TaskEntry};
use session::{
Place, SessionCatalog, SessionCatalogEvent, SessionHistory, SessionSidebar, SidebarEvent,
SidebarPage,
@@ -60,12 +62,16 @@ use settings::{
};
use shared::copy::commands as palette_words;
use shared::copy::extensions as pages_copy;
+use shared::copy::search as search_copy;
use shared::copy::settings as settings_copy;
use shared::copy::{self, Locale};
use shared::domain_element_id;
use shared::hop::Hops;
-use shared::icons::MakaIcon;
-use shared::layout::{COLUMN_GUTTER_REMS, COLUMN_MAX_WIDTH_REMS, PAGE_MAX_WIDTH_REMS};
+use shared::icons::{MakaIcon, ink};
+use shared::layout::{
+ COLUMN_GUTTER_REMS, COLUMN_MAX_WIDTH_REMS, ICON_BUTTON_REMS, ICON_GLYPH_REMS,
+ PAGE_MAX_WIDTH_REMS, PLATE_LINE_REMS, ink_padding,
+};
use shared::menu::{
Menu, MenuEntry, MenuHeading, MenuItem, MenuPlacement, MenuSlot, menu_layer, reopens_on,
};
@@ -74,6 +80,8 @@ use shared::theme::{
quiet_button,
};
+use terminal::Terminals;
+
use crate::commands::palette_commands;
use crate::empty_state::EmptyState;
use crate::host_blocked::HostBlockedScreen;
@@ -84,19 +92,20 @@ use crate::sidebar_layout::{SidebarForm, SidebarLayout};
use crate::state_root_dialog::{StateRootSetup, open_state_root_dialog, show_workbench_on};
mod context_strip;
-mod review_pane;
+mod side_chats;
+mod workbar;
use context_strip::ContextStrip;
-use review_pane::ReviewPane;
-pub use review_pane::{
- NarrowReviewLargeStep, NarrowReviewStep, REVIEW_RESIZE_CONTEXT, ResetReviewWidth,
- WidenReviewLargeStep, WidenReviewStep,
+use workbar::Workbar;
+pub use workbar::{
+ NarrowWorkbarLargeStep, NarrowWorkbarStep, ResetWorkbarWidth, WORKBAR_RESIZE_CONTEXT,
+ WidenWorkbarLargeStep, WidenWorkbarStep,
};
use workspace::actions::{
- AddConnection, ArchiveTask, FlagTask, FocusComposer, GoBack, GoForward, NewSession,
- OpenCommandPalette, OpenExtensions, OpenProjectSettings, OpenScheduledTasks, OpenSettings,
- Reconnect, SendMessage, ShowKeyboardShortcuts, StopTurn, SwitchHost, SwitchStateRoot,
- ToggleSidebar,
+ AddConnection, ArchiveTask, FindInConversation, FlagTask, FocusComposer, GoBack, GoForward,
+ NewSession, OpenCommandPalette, OpenExtensions, OpenProjectSettings, OpenScheduledTasks,
+ OpenSettings, Reconnect, SearchAllTasks, SendMessage, ShowKeyboardShortcuts, StopTurn,
+ SwitchHost, SwitchStateRoot, ToggleSidebar,
};
use workspace::{
ConnectionCatalog, ConnectionStatus, HostDirectory, HostSession, ProjectCatalogSource,
@@ -233,6 +242,15 @@ pub const SIDEBAR_RESIZE_CONTEXT: &str = "SidebarResize";
/// Key context of the sidebar while it lies over the plate.
pub const SIDEBAR_OVERLAY_CONTEXT: &str = "SidebarOverlay";
+/// Key context of the task view (the plate while it shows the selected
+/// task: its header, the conversation and the composer), which owns ⌘F,
+/// Find in conversation. A page or settings in the plate's place have
+/// contexts of their own.
+pub const TASK_VIEW_CONTEXT: &str = "TaskView";
+
+/// The most of a selection ⇧⌘F takes as the Search page's query.
+const SEARCH_SEED_MAX_CHARS: usize = 200;
+
/// How long the sidebar takes to change width, eased in and out: the kit
/// sidebar's transition (`SIDEBAR_TRANSITION_DURATION` and
/// `ease_in_out_cubic` in gpui-component's sidebar).
@@ -420,6 +438,9 @@ pub struct Workbench {
pet: Entity<PetWatch>,
/// The Scheduled tasks page, from the first time it shows.
automations: Option<Entity<AutomationsView>>,
+ /// The Search page, from the first time it shows: its query, results
+ /// and scroll stay for Back.
+ search: Option<Entity<SearchView>>,
/// The task Back or Forward is selecting: its selection change is not
/// a visit.
navigating: Option<SharedString>,
@@ -442,7 +463,7 @@ pub struct Workbench {
/// How Open project folder opens it.
folder_opener: FolderOpener,
/// The changes panel beside the plate, and its width.
- review: ReviewPane,
+ workbar: Workbar,
/// The context strip over the composer.
strip: ContextStrip,
_subscriptions: Vec<Subscription>,
@@ -475,6 +496,9 @@ impl Workbench {
});
let scheduled = cx.new(|cx| ScheduledTasks::new(host.clone(), cx));
let pet = cx.new(|cx| PetWatch::new(&host, &catalog, &state, cx));
+ // The window's terminals, beside the conversation state whose
+ // Session subscription carries their output, following its task.
+ let terminals = cx.new(|cx| Terminals::new(host.clone(), state.clone(), cx));
let subscriptions = vec![
// The sidebar's Scheduled tasks entry counts the active tasks.
cx.observe(&scheduled, |this, scheduled, cx| {
@@ -496,8 +520,10 @@ impl Workbench {
window.set_window_title(
&this.title(cx).unwrap_or_else(|| copy::APP_NAME.get(cx).into()),
);
- // The changes panel follows the selected task.
+ // The workbar's changes follow the selected task.
this.sync_review_target(window, cx);
+ // The Search page names and matches the tasks listed.
+ this.sync_search_tasks(cx);
cx.notify();
}),
cx.subscribe_in(&catalog, window, {
@@ -551,8 +577,12 @@ impl Workbench {
cx.notify();
}
}),
- // The header's folder button names the selected task's project.
- cx.observe(&projects, |_, _, cx| cx.notify()),
+ // The header's folder button names the selected task's project,
+ // and the Search page each task's.
+ cx.observe(&projects, |this, _, cx| {
+ this.sync_search_tasks(cx);
+ cx.notify();
+ }),
// While settings show, the section list takes it instead, and
// on a page the page.
cx.on_focus_lost(window, |this, window, cx| this.focus_main(window, cx)),
@@ -577,6 +607,7 @@ impl Workbench {
}
}),
];
+ let workbar = Workbar::new(terminals, host.clone(), window, cx);
let mut this = Self {
host,
catalog,
@@ -608,6 +639,7 @@ impl Workbench {
scheduled,
pet,
automations: None,
+ search: None,
navigating: None,
state_root_setup: None,
settings: None,
@@ -616,7 +648,7 @@ impl Workbench {
footer_menu_closed_at: None,
project_menu: MenuSlot::new(MenuPlacement::BelowStart),
folder_opener: Rc::new(|path, cx| cx.open_with_system(path)),
- review: ReviewPane::new(window, cx),
+ workbar,
strip: ContextStrip::new(cx),
_subscriptions: subscriptions,
};
@@ -627,7 +659,7 @@ impl Workbench {
this.layout = SidebarLayout::new(this.window_is_narrow());
this.shown_form = this.layout.form(narrow_sidebar(cx));
window.set_window_title(&this.title(cx).unwrap_or_else(|| copy::APP_NAME.get(cx).into()));
- this.watch_review(window, cx);
+ this.watch_workbar(window, cx);
this
}
@@ -785,9 +817,7 @@ impl Workbench {
match &self.settings {
Some(settings) => settings.view.update(cx, |view, cx| view.focus_nav(window, cx)),
None if self.page.is_some() => self.focus_page(window, cx),
- None if self.review_maximized(cx) => {
- self.review_panel().update(cx, |panel, cx| panel.focus_files(window, cx));
- }
+ None if self.workbar_maximized(cx) => self.focus_workbar_face(window, cx),
None => self.composer.update(cx, |composer, cx| composer.focus(window, cx)),
}
}
@@ -1114,6 +1144,11 @@ impl Workbench {
self.extensions.as_ref()
}
+ /// The Search page, once it has shown.
+ pub fn search_view(&self) -> Option<&Entity<SearchView>> {
+ self.search.as_ref()
+ }
+
/// The Host's scheduled tasks.
pub fn scheduled_tasks(&self) -> &Entity<ScheduledTasks> {
&self.scheduled
@@ -1154,6 +1189,106 @@ impl Workbench {
self.show_page(SidebarPage::ScheduledTasks, window, cx);
}
+ /// ⇧⌘F: shows the Search page and focuses its field, its text
+ /// selected; text selected in the window (in a reply, or in the draft)
+ /// becomes the query and is searched at once. From settings, it leaves
+ /// them first.
+ pub(crate) fn search_all_tasks(
+ &mut self,
+ _: &SearchAllTasks,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let seed = self.selection_seed(window, cx);
+ self.show_page(SidebarPage::Search, window, cx);
+ if let Some(view) = &self.search {
+ view.update(cx, |view, cx| match &seed {
+ Some(seed) => view.search_for(seed, window, cx),
+ None => view.focus_query(window, cx),
+ });
+ }
+ }
+
+ /// The text selected in the window, as a query: the transcript's
+ /// selection, else the draft's while it has focus, its whitespace
+ /// folded and cut to [`SEARCH_SEED_MAX_CHARS`].
+ fn selection_seed(&self, window: &mut Window, cx: &mut App) -> Option<String> {
+ let mut text = TextSelection::selected_text(window, cx);
+ if text.trim().is_empty() {
+ let draft = self.composer.read(cx).draft().read(cx);
+ if draft.focus_handle(cx).is_focused(window) {
+ text = draft.selected_value().to_string();
+ }
+ }
+ let folded = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ (!folded.is_empty()).then(|| folded.chars().take(SEARCH_SEED_MAX_CHARS).collect())
+ }
+
+ /// Hands the Search page the tasks the catalog lists, as the sidebar
+ /// names them, with their projects.
+ fn sync_search_tasks(&mut self, cx: &mut Context<Self>) {
+ let Some(view) = self.search.clone() else { return };
+ let locale = Locale::current(cx);
+ let projects = self.projects.read(cx);
+ let tasks: Vec<TaskEntry> = self
+ .catalog
+ .read(cx)
+ .rows()
+ .iter()
+ .map(|row| {
+ let project = projects
+ .registered_project(row.project_id.as_deref())
+ .map(|project| project.label())
+ .filter(|label| !label.is_empty());
+ TaskEntry::new(row.id.clone(), copy::task_title(locale, &row.name).to_owned())
+ .with_project(project)
+ .archived(row.is_archived)
+ .with_activity_at(row.activity_at)
+ })
+ .collect();
+ // Side chats' forks copy their task's words; their passages go: those
+ // the catalog lists, and this client's own before it lists them.
+ let mut hidden: std::collections::HashSet<SharedString> =
+ self.catalog.read(cx).side_conversations().cloned().collect();
+ let ledger = conversation::SideChatLedger::global(cx);
+ hidden.extend(
+ ledger.read(cx).entries().iter().map(|entry| entry.target_session_id.clone().into()),
+ );
+ view.update(cx, |view, cx| {
+ view.set_tasks(tasks, cx);
+ view.set_hidden_sessions(hidden, cx);
+ });
+ }
+
+ /// What the Search page asks of the window: a task by its title, as
+ /// the sidebar opens one; a passage's task, at its message with the
+ /// find bar on its term; or, Escape with nothing typed, the task view.
+ /// Back returns to the page as it was.
+ fn search_event(
+ &mut self,
+ _: &Entity<SearchView>,
+ event: &SearchPageEvent,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ match event {
+ SearchPageEvent::OpenTask(id) => {
+ self.leave_page(Some(id.clone()), window, cx);
+ self.catalog.update(cx, |catalog, cx| catalog.select_when_listed(id.clone(), cx));
+ self.composer.update(cx, |composer, cx| composer.focus(window, cx));
+ }
+ SearchPageEvent::OpenPassage(target) => {
+ let id = target.session_id().clone();
+ self.leave_page(Some(id.clone()), window, cx);
+ self.catalog.update(cx, |catalog, cx| catalog.select_when_listed(id, cx));
+ self.conversation
+ .update(cx, |view, cx| view.open_at_passage(target.clone(), window, cx));
+ }
+ SearchPageEvent::Leave => self.focus_composer(&FocusComposer, window, cx),
+ _ => {}
+ }
+ }
+
/// Puts `page` (or the task view) on the plate without recording a
/// visit; the sidebar marks its entry. The Extensions page is made the
/// first time and reads its catalog then.
@@ -1179,7 +1314,20 @@ impl Workbench {
if let (Some(SidebarPage::ScheduledTasks), Some(view)) = (page, &self.automations) {
view.update(cx, |view, cx| view.activate(cx));
}
+ if page == Some(SidebarPage::Search) && self.search.is_none() {
+ let view = cx.new(|cx| SearchView::new(self.host.clone(), window, cx));
+ self._subscriptions.push(cx.observe(&view, |_, _, cx| cx.notify()));
+ self._subscriptions.push(cx.subscribe_in(&view, window, Self::search_event));
+ self.search = Some(view);
+ }
self.page = page;
+ if page.is_some() {
+ // A passage still being read for the task view waits no more.
+ self.conversation.update(cx, |view, _| view.cancel_landing());
+ }
+ if page == Some(SidebarPage::Search) {
+ self.sync_search_tasks(cx);
+ }
self.sidebar.update(cx, |sidebar, cx| sidebar.set_open_page(page, cx));
window.set_window_title(&self.title(cx).unwrap_or_else(|| copy::APP_NAME.get(cx).into()));
cx.notify();
@@ -1212,6 +1360,11 @@ impl Workbench {
(Some(SidebarPage::ScheduledTasks), _, Some(view)) => {
view.update(cx, |view, cx| view.focus(window, cx))
}
+ (Some(SidebarPage::Search), _, _) => {
+ if let Some(view) = &self.search {
+ view.update(cx, |view, cx| view.focus(window, cx));
+ }
+ }
_ => {}
}
}
@@ -1274,7 +1427,7 @@ impl Workbench {
self.close_settings(window, cx);
self.leave_page(None, window, cx);
self.close_sidebar_overlay(window, cx);
- self.restore_review(window, cx);
+ self.restore_workbar(window, cx);
self.composer.update(cx, |composer, cx| composer.focus(window, cx));
}
@@ -1286,7 +1439,7 @@ impl Workbench {
window: &mut Window,
cx: &mut Context<Self>,
) {
- if self.settings.is_none() && self.page.is_none() && !self.review_maximized(cx) {
+ if self.settings.is_none() && self.page.is_none() && !self.workbar_maximized(cx) {
self.composer.update(cx, |composer, cx| composer.send(window, cx));
}
}
@@ -1378,7 +1531,10 @@ impl Workbench {
// A task the Usage page's activity log names: leave settings
// for it, as the Scheduled tasks page does.
cx.subscribe_in(&view, window, |this, _, event: &settings::OpenTask, window, cx| {
+ // A side chat's fork is no task the window shows: its row
+ // opens the task it forks.
let id = event.session_id.clone();
+ let id = this.catalog.read(cx).side_conversation_source(&id).cloned().unwrap_or(id);
this.close_settings(window, cx);
this.leave_page(Some(id.clone()), window, cx);
this.catalog.update(cx, |catalog, cx| catalog.select(Some(&id), cx));
@@ -1605,6 +1761,55 @@ impl Workbench {
});
}
+ /// ⌘F: shows the find bar over the conversation and focuses its query,
+ /// while the plate shows a conversation to find in.
+ pub(crate) fn find_in_conversation(
+ &mut self,
+ _: &FindInConversation,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.shows_conversation(cx) {
+ self.conversation.update(cx, |view, cx| view.open_find(window, cx));
+ }
+ }
+
+ /// ⌘G and ⇧⌘G from the rest of the task view (the composer): the next
+ /// or previous match while the find bar shows; else the key goes on.
+ fn select_next_match(
+ &mut self,
+ _: &search::SelectNextMatch,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !self.conversation.update(cx, |view, cx| view.step_find(true, window, cx)) {
+ cx.propagate();
+ }
+ }
+
+ fn select_previous_match(
+ &mut self,
+ _: &search::SelectPreviousMatch,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !self.conversation.update(cx, |view, cx| view.step_find(false, window, cx)) {
+ cx.propagate();
+ }
+ }
+
+ /// Whether the plate shows the selected task's conversation: no
+ /// settings, page, Host blocker, maximized changes panel or empty state
+ /// in its place.
+ fn shows_conversation(&self, cx: &App) -> bool {
+ self.settings.is_none()
+ && self.page.is_none()
+ && self.host.read(cx).blocker().is_none()
+ && !self.workbar_maximized(cx)
+ && !self.shows_empty_state(cx)
+ && self.conversation.read(cx).has_rows()
+ }
+
/// Archives the selected task, or unarchives it.
pub(crate) fn archive_task(&mut self, _: &ArchiveTask, _: &mut Window, cx: &mut Context<Self>) {
let Some(row) = self.catalog.read(cx).selected_row() else {
@@ -1674,6 +1879,7 @@ impl Workbench {
conversation::ComposerAction::Send { enabled: true, .. }
),
"switch-state-root" => self.state_root_setup.is_some(),
+ "find-in-conversation" => self.shows_conversation(cx),
_ => true,
};
if !runs {
@@ -1689,7 +1895,7 @@ impl Workbench {
PaletteCommand::Action(spec.action()),
)
.keywords([english(label), english(spec.label), english(heading)])
- .shortcut(spec.action()),
+ .shortcut(spec.action(), spec.context),
);
}
if composer.model_switchable(cx) {
@@ -2044,12 +2250,16 @@ impl Workbench {
// The changes panel's button ends the task view's header.
let review = (!chrome_only).then(|| self.render_review_button(cx)).flatten();
// The plate shows through: a header fill would paint square corners
- // over the plate's rounded ones. No divider under it.
+ // over the plate's rounded ones. No divider under it. The changes
+ // panel's button at its end puts its glyph's ink on the plate's 16 px
+ // line, as the panel's own bar does.
+ let trailing =
+ ink_padding(PLATE_LINE_REMS, ICON_BUTTON_REMS, ICON_GLYPH_REMS, ink::FILE_DIFF);
div().id("main-header").test_support().child(
TitleBar::new()
.h(rems(CHROME_HEIGHT_REMS))
.when(self.shown_form != SidebarForm::Hidden || settings, |this| this.pl_5())
- .pr_4()
+ .pr(rems(trailing))
.bg(cx.theme().transparent)
.border_b_0()
.child(h_flex().flex_1().min_w_0().gap_2().children(controls).map(|this| {
@@ -2426,7 +2636,7 @@ impl Workbench {
.on_click(cx.listener(|this, _, window, cx| this.new_session(&NewSession, window, cx)));
let new_task = self.rail_hop("new-task", new_task, cx);
let mut pages = Vec::new();
- for page in SidebarPage::ALL {
+ for page in SidebarPage::LISTED {
let title: SharedString = page.title().get(cx).into();
let id = domain_element_id("rail-page", page.key());
let button = self
@@ -2436,12 +2646,13 @@ impl Workbench {
.on_click(move |_, window, cx| window.dispatch_action(page.action(), cx));
pages.push(self.rail_hop(page.key(), button, cx));
}
- let search: SharedString = palette_words::SEARCH.get(cx).into();
+ let search: SharedString = search_copy::SEARCH_ALL_TASKS.get(cx).into();
let magnifier = Icon::new(MakaIcon::Search);
let search = self
.rail_button("rail-search".into(), "search", magnifier, search.clone(), window, cx)
- .tooltip_with_action(search, &OpenCommandPalette, None)
- .on_click(|_, window, cx| window.dispatch_action(OpenCommandPalette.boxed_clone(), cx));
+ .tooltip_with_action(search, &SearchAllTasks, None)
+ .selected(self.page == Some(SidebarPage::Search))
+ .on_click(|_, window, cx| window.dispatch_action(SearchAllTasks.boxed_clone(), cx));
let search = self.rail_hop("search", search, cx);
let (label, dot) = self.host_status(cx);
let host = Button::new("rail-host-status")
@@ -2653,6 +2864,9 @@ impl Workbench {
(Some(SidebarPage::ScheduledTasks), _, Some(view)) => {
view.update(cx, |view, cx| view.render_page(window, cx))
}
+ (Some(SidebarPage::Search), _, _) if let Some(view) = &self.search => {
+ view.update(cx, |view, cx| view.render_page(window, cx))
+ }
_ => div().flex_1().min_h_0().into_any_element(),
}
}
@@ -2890,6 +3104,7 @@ impl Render for Workbench {
let maka = cx.maka();
// While settings show, their navigation takes the sidebar's place and
// their page the plate's; the task view's entities keep their state.
+ let mut task_view = false;
let (column, plate): (Option<AnyElement>, Vec<AnyElement>) = match self.settings_view() {
Some(settings) => (
Some(self.render_settings_column(&settings, window, cx).into_any_element()),
@@ -2913,13 +3128,14 @@ impl Render for Workbench {
}
// The changes panel maximized for the task: the conversation and
// the composer keep their state and leave the plate to it.
- None if self.review_maximized(cx) => {
+ None if self.workbar_maximized(cx) => {
let mut plate = vec![self.render_header(cx).into_any_element()];
plate.extend(self.render_connection_strip(COLUMN_MAX_WIDTH_REMS, cx));
- plate.push(self.render_review_maximized());
+ plate.push(self.render_workbar_maximized(window, cx));
(self.render_column(window, cx), plate)
}
None => {
+ task_view = true;
// The conversation keeps its slot; the empty state stands in
// for it while there is nothing to read.
let body = if self.shows_empty_state(cx) {
@@ -2953,6 +3169,7 @@ impl Render for Workbench {
let main = v_flex()
.id("main-pane")
.test_support()
+ .when(task_view, |this| this.key_context(TASK_VIEW_CONTEXT))
.size_full()
.bg(maka.plate)
.rounded(RADIUS_MODAL)
@@ -2960,8 +3177,8 @@ impl Render for Workbench {
.into_any_element();
// Beside the task view, the selected task's changes panel, unless
// it fills the plate.
- let beside = self.review_shown(cx) && !self.review_maximized(cx);
- let review = if beside { self.with_review(main, window, cx) } else { main };
+ let beside = self.workbar_shown(cx) && !self.workbar_maximized(cx);
+ let review = if beside { self.with_workbar(main, window, cx) } else { main };
h_flex()
.id("workbench")
.size_full()
@@ -2987,18 +3204,25 @@ impl Render for Workbench {
.on_action(cx.listener(Self::show_keyboard_shortcuts))
.on_action(cx.listener(Self::open_extensions))
.on_action(cx.listener(Self::open_scheduled_tasks))
+ .on_action(cx.listener(Self::search_all_tasks))
.on_action(cx.listener(Self::close_overlay_action))
.on_action(cx.listener(Self::toggle_review))
- .on_action(cx.listener(Self::toggle_review_maximized))
+ .on_action(cx.listener(Self::toggle_terminal))
+ .on_action(cx.listener(Self::toggle_files))
+ .on_action(cx.listener(Self::toggle_side_chat))
+ .on_action(cx.listener(Self::toggle_workbar_maximized))
+ .on_action(cx.listener(Self::find_in_conversation))
+ .on_action(cx.listener(Self::select_next_match))
+ .on_action(cx.listener(Self::select_previous_match))
.on_drag_move(cx.listener(Self::drag_sidebar_edge))
- .on_drag_move(cx.listener(Self::drag_review_edge))
+ .on_drag_move(cx.listener(Self::drag_workbar_edge))
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, _, _, cx| {
if std::mem::take(&mut this.resizing) {
cx.notify();
}
- this.end_review_drag(cx);
+ this.end_workbar_drag(cx);
}),
)
.children(column)
diff --git a/apps/desktop-gpui/crates/app/src/workbench/context_strip.rs b/apps/desktop-gpui/crates/app/src/workbench/context_strip.rs
index 571a53d8a8..c48864ff1c 100644
--- a/apps/desktop-gpui/crates/app/src/workbench/context_strip.rs
+++ b/apps/desktop-gpui/crates/app/src/workbench/context_strip.rs
@@ -17,14 +17,15 @@
* under the License.
*/
-//! The context strip over the composer, as Claude Code's: a quiet bar the
+//! The context strip over the composer, as Claude Code's: a line the
//! composer's width directly above it, in an existing task (the new task's
-//! draft keeps its project picker in the composer instead). On the left
-//! the task's folder name, which opens the project menu above it (the
-//! header's folder button's entries), and the current branch, muted, in
-//! mono; on the right the lines all the task's changes add and delete,
-//! "+N −M" in the diff colours, in a chip that opens the changes panel, or
-//! focuses it while open.
+//! draft keeps its project picker in the composer instead), with no fill
+//! of its own. On the left the task's folder, a chip that hugs its folder
+//! glyph, its name and a chevron and opens the project menu above it (the
+//! header's folder button's entries), its glyph over the composer's "+"
+//! glyph; then the current branch, muted, in mono; on the right the lines
+//! all the task's changes add and delete, "+N −M" in the diff colours, in
+//! a chip that opens the changes panel, or focuses it while open.
//!
//! The counts are the changes panel's All changes against its base: the
//! window's [`ChangeSummary`] reads them as the panel does, off the main
@@ -43,10 +44,8 @@
use std::sync::Arc;
-use gpui_kit::component::button::{Button, ButtonVariants as _};
-use gpui_kit::component::{
- ActiveTheme as _, Selectable as _, Sizable as _, StyledExt as _, h_flex,
-};
+use gpui_kit::component::button::{Button, ButtonCustomVariant, ButtonVariants as _};
+use gpui_kit::component::{ActiveTheme as _, Icon, Selectable as _, StyledExt as _, h_flex};
use gpui_kit::{
AnyElement, AppContext as _, ClickEvent, Context, Entity, InteractiveElement as _, IntoElement,
ParentElement as _, StatefulInteractiveElement as _, Styled as _, TestSupportExt as _, Window,
@@ -56,6 +55,7 @@ use review::git::GitRunner;
use review::{ChangeSummary, ChangeTotals};
use shared::copy::review as review_copy;
use shared::copy::{self, Locale};
+use shared::icons::MakaIcon;
use shared::layout::COLUMN_MAX_WIDTH_REMS;
use shared::menu::{MenuPlacement, MenuSlot};
use shared::theme::{ActiveMakaPalette as _, tabular_nums, tinted_button};
@@ -63,6 +63,14 @@ use workspace::actions::ToggleReview;
use super::{PROJECT_MENU_MIN_WIDTH_REMS, Workbench};
+/// The composer's padding (the conversation's dock, 12 px): the strip's
+/// chips start and end where the composer's controls do.
+const COMPOSER_INSET_REMS: f32 = 0.75;
+/// The composer's "+": a 28 px button, its glyph 16 px in its middle. The
+/// folder chip's glyph sits in a 16 px slot as far into the chip as the
+/// "+" glyph is into its button, so the two glyphs share a centre line.
+const ATTACH_GLYPH_INSET_REMS: f32 = (1.75 - 1.) / 2.;
+
/// The strip's state in the window.
pub(crate) struct ContextStrip {
/// What the strip says of the selected task's repository.
@@ -100,12 +108,10 @@ impl Workbench {
self.strip.menu.is_open()
}
- /// The strip's chip: opens the selected task's changes panel and gives
- /// it the focus, or only the focus while it is open.
+ /// The strip's chip: shows the selected task's changes in the workbar
+ /// and gives them the focus.
fn open_changes_from_strip(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- if !self.review_open(cx) {
- self.set_review_open(true, window, cx);
- }
+ self.show_changes(window, cx);
self.review_panel().update(cx, |panel, cx| panel.focus_files(window, cx));
cx.notify();
}
@@ -116,10 +122,6 @@ impl Workbench {
self.catalog.read(cx).selected_id()?;
let maka = cx.maka();
let locale = Locale::current(cx);
- // The composer's surface sunk a step, as the segmented track is:
- // in dark the ink wash, not the sunken tier, which would be the
- // darkest surface on screen.
- let fill = if cx.theme().is_dark() { maka.wash } else { maka.sunken };
let totals = self.strip.summary.read(cx).totals().cloned();
let name = self.task_folder(cx).map(|folder| folder.name);
let branch = totals.as_ref().and_then(|totals| totals.current_branch.clone());
@@ -131,13 +133,8 @@ impl Workbench {
.max_w(rems(COLUMN_MAX_WIDTH_REMS))
.mx_auto()
.h_8()
- .px_1()
+ .px(rems(COMPOSER_INSET_REMS))
.gap_1()
- // The composer's radius, 28 at the spec's scale: over half this
- // one line's height at every zoom, so the ends are round, as
- // the buttons inside them are 4 in.
- .rounded_full()
- .bg(fill)
.text_xs()
.children(name.map(|name| self.render_strip_name(name, cx)))
.when_some(branch, |this, branch| {
@@ -206,8 +203,11 @@ impl Workbench {
)
}
- /// The task's folder name, the first thing the strip gives up width
- /// for: a quiet button that opens the project menu above it.
+ /// The task's folder, the first thing the strip gives up width for: a
+ /// 28 px chip that hugs the folder glyph, the name and a chevron and
+ /// opens the project menu above it. It sits on the composer's surface
+ /// sunk a step, as the segmented track is: in dark the ink wash, not
+ /// the sunken tier, which would be the darkest surface on screen.
fn render_strip_name(
&self,
name: gpui_kit::SharedString,
@@ -215,16 +215,30 @@ impl Workbench {
) -> AnyElement {
let maka = cx.maka();
let tip = copy::PROJECT_INFO.get(cx);
+ let (fill, hover, press) = if cx.theme().is_dark() {
+ let fill = maka.wash;
+ (fill, maka.ink.opacity(fill.a + 0.05), maka.ink.opacity(fill.a + 0.1))
+ } else {
+ (maka.sunken, maka.sunken.blend(maka.hover), maka.sunken.blend(maka.selected))
+ };
div()
.relative()
.min_w_0()
.flex_shrink(1.)
.child(
Button::new("context-strip-project")
- .ghost()
- .xsmall()
- .h_6()
- .px_2()
+ .custom(
+ ButtonCustomVariant::new(cx)
+ .color(fill)
+ .foreground(maka.ink)
+ .hover(hover)
+ .active(press)
+ .shadow(false),
+ )
+ .bg(fill)
+ .h_7()
+ .pl(rems(ATTACH_GLYPH_INSET_REMS))
+ .pr_2()
.min_w_0()
.max_w_full()
.rounded_full()
@@ -244,13 +258,37 @@ impl Workbench {
);
}))
.child(
- div()
+ h_flex()
.min_w_0()
- .truncate()
- .text_xs()
- .font_medium()
- .text_color(maka.ink)
- .child(name),
+ .gap_1p5()
+ .child(
+ h_flex()
+ .id("context-strip-folder")
+ .test_support()
+ .flex_none()
+ .size_4()
+ .justify_center()
+ .child(
+ Icon::new(MakaIcon::Folder)
+ .size_3p5()
+ .text_color(maka.ink_muted),
+ ),
+ )
+ .child(
+ div()
+ .min_w_0()
+ .truncate()
+ .text_xs()
+ .font_medium()
+ .text_color(maka.ink)
+ .child(name),
+ )
+ .child(
+ Icon::new(MakaIcon::ChevronDown)
+ .size_3p5()
+ .flex_none()
+ .text_color(maka.ink_muted),
+ ),
),
)
.children(self.strip.menu.layer())
diff --git a/apps/desktop-gpui/crates/app/src/workbench/review_pane.rs b/apps/desktop-gpui/crates/app/src/workbench/review_pane.rs
deleted file mode 100644
index dcde8ab246..0000000000
--- a/apps/desktop-gpui/crates/app/src/workbench/review_pane.rs
+++ /dev/null
@@ -1,654 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing,
- * software distributed under the License is distributed on an
- * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
- * KIND, either express or implied. See the License for the
- * specific language governing permissions and limitations
- * under the License.
- */
-
-//! The changes panel beside the plate: Maka Desktop's right Workbar with
-//! its `review` tool (`features/workbar`), for the selected task.
-//!
-//! Like Desktop's Workbar it is open or closed per task, remembered with
-//! its width in the preferences; it follows the selected task, and a draft
-//! (no task) has nothing to review. On a window with room it is its own
-//! plate on the right, `width` wide (Desktop's 480 at first, from 340,
-//! scaling with the UI font as the sidebar does), with a handle on its
-//! edge that drags it as wide as leaves the conversation its least width,
-//! Desktop's 400 px (`--maka-conversation-min-width`), which keeps the
-//! composer's controls on one row and the transcript readable. When the
-//! window cannot keep the composer's whole column beside the panel's
-//! narrowest width, the panel goes below the plate, as Desktop's Workbar
-//! goes below the conversation on a narrow window, 42% of the window's
-//! height up to 360 px, with no handle. The sidebar's own rules (F13) are
-//! untouched: it collapses at its breakpoint as before.
-//!
-//! Maximized (its bar's button, or ⇧Esc), the panel fills the plate below
-//! the plate's header in the conversation's and the composer's place, which
-//! keep their state, not drawn; the button, ⇧Esc or Esc in the panel give
-//! them their place back. Each task remembers it with the panel's other
-//! state.
-
-use std::collections::BTreeSet;
-use std::sync::Arc;
-
-use conversation::ConversationEvent;
-use gpui_kit::component::button::{Button, ButtonVariants as _};
-use gpui_kit::component::{Icon, Selectable as _, Sizable as _, ThemeStyled as _};
-use gpui_kit::{
- AnyElement, App, AppContext as _, ClickEvent, Context, DragMoveEvent, Empty, Entity,
- FocusHandle, InteractiveElement as _, IntoElement, ParentElement as _, Render, Role,
- StatefulInteractiveElement as _, Styled as _, Task, TestSupportExt as _, Window, div,
- prelude::FluentBuilder as _, px, rems,
-};
-use review::git::{ReviewScope, SystemGit};
-use review::{ReviewPanel, ReviewPanelEvent, ReviewTarget, ToggleMaximized};
-use session::LoadState;
-use settings::{AppPreferences, DEFAULT_REVIEW_WIDTH, REVIEW_WIDTHS, clamp_review_width};
-use shared::copy::review as copy;
-use shared::icons::MakaIcon;
-use shared::theme::{ActiveMakaPalette as _, RADIUS_MODAL};
-use workspace::actions::ToggleReview;
-
-use super::{
- DESIGN_PX_PER_REM, PLATE_INSET_REMS, PLATE_MIN_REMS, RESIZE_HANDLE_WIDTH, RESIZE_LARGE_STEP,
- RESIZE_STEP, WIDTH_SAVE_DELAY, Workbench,
-};
-
-/// Key context of the panel's edge while it has focus.
-pub const REVIEW_RESIZE_CONTEXT: &str = "ReviewResize";
-
-gpui_kit::actions!(
- maka_review,
- [
- /// Move the changes panel's edge 10 px toward the plate.
- WidenReviewStep,
- /// Move the changes panel's edge 10 px away from the plate.
- NarrowReviewStep,
- /// Move the changes panel's edge 50 px toward the plate.
- WidenReviewLargeStep,
- /// Move the changes panel's edge 50 px away from the plate.
- NarrowReviewLargeStep,
- /// Give the changes panel its default width.
- ResetReviewWidth,
- ]
-);
-
-/// The least the plate keeps beside the panel when the panel is dragged
-/// wide: Desktop's `--maka-conversation-min-width`, 400 px, and the canvas
-/// margin on either side of the plate (as in `PLATE_MIN_REMS`).
-const PLATE_LEAST_REMS: f32 = 400. / DESIGN_PX_PER_REM + 2. * PLATE_INSET_REMS;
-
-/// The height of the panel below the plate: Desktop's `min(42dvh, 360px)`.
-const BELOW_HEIGHT_SHARE: f32 = 0.42;
-const BELOW_MAX_HEIGHT_REMS: f32 = 360. / DESIGN_PX_PER_REM;
-
-/// Where the panel goes.
-#[derive(Debug, Clone, Copy, PartialEq)]
-pub(crate) enum ReviewPlacement {
- /// On the right of the plate, this many rems wide.
- Beside(f32),
- /// Below the plate, the plate's width.
- Below,
-}
-
-impl ReviewPlacement {
- /// For a window `window_rems` wide whose sidebar column takes
- /// `column_rems`, a panel `width` wide (the preferences' pixels): beside
- /// the plate when its narrowest width leaves the plate the composer's
- /// whole column, at its width up to what leaves the conversation its
- /// least; else below.
- pub(crate) fn of(window_rems: f32, column_rems: f32, width: u16) -> Self {
- let beside = window_rems - column_rems - PLATE_INSET_REMS;
- let narrowest = f32::from(*REVIEW_WIDTHS.start()) / DESIGN_PX_PER_REM;
- if beside - PLATE_MIN_REMS < narrowest {
- return Self::Below;
- }
- Self::Beside((f32::from(width) / DESIGN_PX_PER_REM).min(beside - PLATE_LEAST_REMS))
- }
-}
-
-/// What a drag of the panel's edge carries: nothing; its moves set the
-/// width.
-#[derive(Debug, Clone, Copy)]
-pub(crate) struct ReviewResize;
-
-impl Render for ReviewResize {
- fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
- Empty
- }
-}
-
-/// The panel and what the window keeps about it.
-pub(crate) struct ReviewPane {
- panel: Entity<ReviewPanel>,
- /// The width in the preferences' pixels, as dragged.
- width: u16,
- resizing: bool,
- /// The edge's handle, a Tab stop.
- resize_focus: FocusHandle,
- /// Whether a turn of the selected task ran at the last commit.
- turn_running: bool,
- _save_width: Option<Task<()>>,
-}
-
-impl ReviewPane {
- pub(crate) fn new(window: &mut Window, cx: &mut Context<Workbench>) -> Self {
- Self {
- panel: cx.new(|cx| ReviewPanel::new(Arc::new(SystemGit), window, cx)),
- width: AppPreferences::current(cx).review_width,
- resizing: false,
- resize_focus: cx.focus_handle().tab_stop(true).tab_index(1),
- turn_running: false,
- _save_width: None,
- }
- }
-}
-
-impl Workbench {
- /// Follows the panel's requests and what should read it again: the
- /// selected task's turn ending, and the window coming back to the
- /// front.
- pub(super) fn watch_review(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- let panel = self.review.panel.clone();
- let subscriptions = [
- cx.subscribe_in(&panel, window, |this, _, event: &ReviewPanelEvent, window, cx| {
- match event {
- ReviewPanelEvent::BaseBranchChanged { session_id, base_branch } => {
- let (id, branch) = (session_id.to_string(), base_branch.clone());
- AppPreferences::global(cx).update(cx, |preferences, cx| {
- preferences.set_review_base_branch(&id, branch.clone(), cx);
- });
- // The strip counts against the same base: from the
- // panel's next read of All changes, or its own.
- let summary = this.strip.summary.clone();
- summary.update(cx, |summary, _| summary.set_base_branch(branch));
- if !this.review_feeds_strip(cx) {
- summary.update(cx, |summary, cx| summary.refresh(cx));
- }
- }
- ReviewPanelEvent::ChangesRead { session_id, totals } => {
- let (id, totals) = (session_id.clone(), totals.clone());
- this.strip
- .summary
- .update(cx, |summary, cx| summary.accept(&id, totals, cx));
- }
- ReviewPanelEvent::CloseRequested => this.set_review_open(false, window, cx),
- ReviewPanelEvent::MaximizeRequested(maximized) => {
- this.set_review_maximized(*maximized, window, cx);
- }
- _ => {}
- }
- }),
- cx.subscribe_in(
- &self.state.clone(),
- window,
- |this, state, _: &ConversationEvent, window, cx| {
- let running = !matches!(
- state.read(cx).turn_activity(),
- conversation::TurnActivity::Idle | conversation::TurnActivity::Unavailable
- );
- let ended =
- std::mem::replace(&mut this.review.turn_running, running) && !running;
- if ended {
- this.refresh_review(window, cx);
- }
- },
- ),
- cx.observe(&self.strip.summary.clone(), |_, _, cx| cx.notify()),
- cx.observe_window_activation(window, |this, window, cx| {
- if window.is_window_active() {
- this.refresh_review(window, cx);
- }
- }),
- // Desktop's `retain-sessions`: once the catalog is read, the
- // panel state of tasks it no longer lists goes.
- cx.observe(&self.catalog.clone(), |_, catalog, cx| {
- let catalog = catalog.read(cx);
- if *catalog.load_state() != LoadState::Loaded {
- return;
- }
- let ids: BTreeSet<String> =
- catalog.rows().iter().map(|row| row.id.to_string()).collect();
- AppPreferences::global(cx)
- .update(cx, |preferences, cx| preferences.retain_review_tasks(&ids, cx));
- }),
- ];
- self._subscriptions.extend(subscriptions);
- self.sync_review_target(window, cx);
- }
-
- /// The changes panel.
- pub fn review_panel(&self) -> &Entity<ReviewPanel> {
- &self.review.panel
- }
-
- /// Whether the selected task's changes panel is open.
- pub fn review_open(&self, cx: &App) -> bool {
- self.catalog
- .read(cx)
- .selected_id()
- .is_some_and(|id| AppPreferences::global(cx).read(cx).is_review_open(id))
- }
-
- /// Whether the panel shows: open, beside the task view (not settings,
- /// a page, or a blocked Host's screen).
- pub(super) fn review_shown(&self, cx: &App) -> bool {
- self.settings.is_none()
- && self.page.is_none()
- && self.host.read(cx).blocker().is_none()
- && self.review_open(cx)
- }
-
- /// The panel's width in the preferences' pixels.
- pub fn review_width(&self) -> u16 {
- self.review.width
- }
-
- /// Where the panel goes in this window.
- pub(super) fn review_placement(&self, cx: &App) -> ReviewPlacement {
- let column = self.form_rems(self.shown_form, cx);
- ReviewPlacement::of(self.window_rems, column, self.review.width)
- }
-
- /// Opens the selected task's changes panel, or closes it (the header
- /// button, ⌃⇧G, Desktop's `toggleTool('review')`). With no task, or
- /// while settings cover the window, it does nothing, as Desktop's
- /// shortcut does without an active Session or behind the settings.
- pub(crate) fn toggle_review(
- &mut self,
- _: &ToggleReview,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- if self.settings.is_some() || self.catalog.read(cx).selected_id().is_none() {
- return;
- }
- let open = !self.review_open(cx);
- if open && self.page.is_some() {
- let selected = self.catalog.read(cx).selected_id().cloned();
- self.leave_page(selected, window, cx);
- }
- self.set_review_open(open, window, cx);
- }
-
- /// Opens or closes the selected task's panel, remembering it for the
- /// task; opening reads its changes.
- pub(super) fn set_review_open(
- &mut self,
- open: bool,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- let Some(id) = self.catalog.read(cx).selected_id().cloned() else { return };
- AppPreferences::global(cx)
- .update(cx, |preferences, cx| preferences.set_review_open(&id, open, cx));
- if open {
- self.sync_review_target(window, cx);
- self.refresh_review(window, cx);
- }
- cx.notify();
- }
-
- /// Points the panel and the context strip at the selected task (its
- /// folder, or a Host elsewhere), with the base branch remembered for
- /// it, and reads it if it is a different task (the panel only while it
- /// shows).
- pub(super) fn sync_review_target(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- let remote = self.host.read(cx).is_remote();
- let target = self.catalog.read(cx).selected_row().map(|row| {
- if remote {
- ReviewTarget::remote(row.id.clone())
- } else {
- ReviewTarget::local(row.id.clone(), row.workspace_path.as_ref())
- }
- });
- let panel = self.review.panel.clone();
- self.sync_review_maximized(cx);
- if panel.read(cx).target() == target.as_ref() {
- return;
- }
- let base = target.as_ref().and_then(|target| {
- AppPreferences::global(cx).read(cx).review_base_branch(target.session_id())
- });
- self.strip.summary.update(cx, |summary, cx| {
- summary.set_target(target.clone(), base.clone(), cx);
- });
- panel.update(cx, |panel, cx| panel.set_target(target, base, window, cx));
- self.refresh_review(window, cx);
- }
-
- /// Whether the selected task's panel shows filling the plate, in the
- /// conversation's place: open, shown, and maximized for the task.
- pub fn review_maximized(&self, cx: &App) -> bool {
- self.review_shown(cx) && self.review_maximized_for_task(cx)
- }
-
- /// Whether the selected task's panel is maximized when it shows.
- fn review_maximized_for_task(&self, cx: &App) -> bool {
- self.catalog
- .read(cx)
- .selected_id()
- .is_some_and(|id| AppPreferences::global(cx).read(cx).is_review_maximized(id))
- }
-
- /// ⇧Esc: the shown panel fills the plate, or gives the conversation its
- /// place back. With the panel closed it does nothing.
- pub(crate) fn toggle_review_maximized(
- &mut self,
- _: &ToggleMaximized,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- if self.review_shown(cx) {
- let maximized = !self.review_maximized(cx);
- self.set_review_maximized(maximized, window, cx);
- }
- }
-
- /// Maximizes the selected task's panel or restores it, remembering it
- /// for the task. Maximizing moves focus into the panel's file list, as
- /// the conversation and the composer leave the window (their state
- /// stays: they are only not drawn).
- pub(crate) fn set_review_maximized(
- &mut self,
- maximized: bool,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- let Some(id) = self.catalog.read(cx).selected_id().cloned() else { return };
- AppPreferences::global(cx)
- .update(cx, |preferences, cx| preferences.set_review_maximized(&id, maximized, cx));
- self.sync_review_maximized(cx);
- if maximized {
- self.review.panel.update(cx, |panel, cx| panel.focus_files(window, cx));
- }
- cx.notify();
- }
-
- /// Tells the panel whether it is maximized, for its button.
- fn sync_review_maximized(&mut self, cx: &mut Context<Self>) {
- let maximized = self.review_maximized_for_task(cx);
- self.review.panel.update(cx, |panel, cx| panel.set_maximized(maximized, cx));
- }
-
- /// Gives the conversation its place back, for a command that needs the
- /// composer.
- pub(super) fn restore_review(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- if self.review_maximized(cx) {
- self.set_review_maximized(false, window, cx);
- }
- }
-
- /// The panel filling the plate below its header, in the conversation's
- /// and the composer's place.
- pub(super) fn render_review_maximized(&self) -> AnyElement {
- div()
- .id("review-pane")
- .test_support()
- .flex_1()
- .min_h_0()
- .w_full()
- .child(self.review.panel.clone())
- .into_any_element()
- }
-
- /// Reads the panel's changes again while it shows, and the context
- /// strip's, unless the panel's read of All changes gives them.
- fn refresh_review(&mut self, window: &mut Window, cx: &mut Context<Self>) {
- if self.review_shown(cx) {
- self.review.panel.update(cx, |panel, cx| panel.refresh(window, cx));
- }
- if !self.review_feeds_strip(cx) {
- self.strip.summary.update(cx, |summary, cx| summary.refresh(cx));
- }
- }
-
- /// Whether the panel's reads tell the context strip its counts: while
- /// it shows All changes.
- fn review_feeds_strip(&self, cx: &App) -> bool {
- self.review_shown(cx) && *self.review.panel.read(cx).scope() == ReviewScope::All
- }
-
- /// The header's button for the panel: Desktop's `file-diff` glyph,
- /// pressed while the panel is open, named and tipped with its shortcut.
- pub(super) fn render_review_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
- self.catalog.read(cx).selected_id()?;
- let label = copy::CHANGES.get(cx);
- let open = self.review_open(cx);
- Some(
- Button::new("review-toggle")
- .ghost()
- .small()
- .size_7()
- .flex_shrink_0()
- .icon(Icon::new(MakaIcon::FileDiff).size_4().text_color(cx.maka().ink_muted))
- .accessibility_label(label)
- .tooltip_with_action(label, &ToggleReview, None)
- .selected(open)
- .on_click(cx.listener(|this, _, window, cx| {
- this.toggle_review(&ToggleReview, window, cx);
- }))
- .into_any_element(),
- )
- }
-
- /// The panel's own plate.
- pub(super) fn render_review_plate(&self, cx: &App) -> AnyElement {
- div()
- .id("review-pane")
- .test_support()
- .size_full()
- .min_w_0()
- .bg(cx.maka().plate)
- .rounded(RADIUS_MODAL)
- .child(self.review.panel.clone())
- .into_any_element()
- }
-
- /// `main` (the plate) with the panel beside it or below it.
- pub(super) fn with_review(
- &self,
- main: AnyElement,
- window: &Window,
- cx: &mut Context<Self>,
- ) -> AnyElement {
- let gap = rems(PLATE_INSET_REMS);
- match self.review_placement(cx) {
- ReviewPlacement::Beside(width) => gpui_kit::component::h_flex()
- .size_full()
- .items_stretch()
- .child(div().flex_1().min_w_0().h_full().child(main))
- .child(
- div()
- .w(gap)
- .h_full()
- .flex_shrink_0()
- .relative()
- .child(self.render_review_handle(window, cx)),
- )
- .child(
- div()
- .w(rems(width))
- .h_full()
- .flex_shrink_0()
- .child(self.render_review_plate(cx)),
- )
- .into_any_element(),
- ReviewPlacement::Below => {
- let rem = window.rem_size();
- let height = (window.viewport_size().height / rem * BELOW_HEIGHT_SHARE)
- .min(BELOW_MAX_HEIGHT_REMS);
- gpui_kit::component::v_flex()
- .size_full()
- .child(div().flex_1().min_h_0().w_full().child(main))
- .child(div().h(gap).flex_shrink_0())
- .child(
- div()
- .h(rems(height))
- .w_full()
- .flex_shrink_0()
- .child(self.render_review_plate(cx)),
- )
- .into_any_element()
- }
- }
- }
-
- /// The handle on the panel's edge, in the gap between the plates, as
- /// the sidebar's: a 6 px hit area below the chrome band with the
- /// column-resize cursor, Desktop's grip on hover, focus or drag. A drag
- /// moves the edge from the narrowest width to what leaves the
- /// conversation its least; a double-click restores the default.
- /// Focused, Left and Right move the edge by 10 (Shift: 50), Enter
- /// restores it.
- fn render_review_handle(&self, window: &Window, cx: &mut Context<Self>) -> AnyElement {
- let maka = cx.maka();
- let dragging = self.review.resizing && cx.has_active_drag();
- let keyboard =
- self.review.resize_focus.is_focused(window) && window.last_input_was_keyboard();
- let pill = div()
- .w(px(3.))
- .h(rems(2.))
- .rounded_full()
- .bg(if dragging { maka.border_strong } else { maka.border })
- .when(!dragging && !keyboard, |this| {
- this.invisible().group_hover("review-resize", |this| this.visible())
- });
- div()
- .id("review-resize")
- .test_support()
- .role(Role::Splitter)
- .aria_label(copy::RESIZE_PANEL.get(cx))
- .track_focus(&self.review.resize_focus)
- .key_context(REVIEW_RESIZE_CONTEXT)
- .on_action(cx.listener(|this, _: &WidenReviewStep, window, cx| {
- this.step_review_width(RESIZE_STEP, window, cx);
- }))
- .on_action(cx.listener(|this, _: &NarrowReviewStep, window, cx| {
- this.step_review_width(-RESIZE_STEP, window, cx);
- }))
- .on_action(cx.listener(|this, _: &WidenReviewLargeStep, window, cx| {
- this.step_review_width(RESIZE_LARGE_STEP, window, cx);
- }))
- .on_action(cx.listener(|this, _: &NarrowReviewLargeStep, window, cx| {
- this.step_review_width(-RESIZE_LARGE_STEP, window, cx);
- }))
- .on_action(cx.listener(|this, _: &ResetReviewWidth, window, cx| {
- this.set_review_width(DEFAULT_REVIEW_WIDTH, window, cx);
- }))
- .absolute()
- .top(rems(super::CHROME_HEIGHT_REMS))
- .bottom_0()
- .left(window.rem_size() * (PLATE_INSET_REMS / 2.) - px(RESIZE_HANDLE_WIDTH / 2.))
- .w(px(RESIZE_HANDLE_WIDTH))
- .flex()
- .items_center()
- .justify_center()
- .group("review-resize")
- .cursor_col_resize()
- .when(keyboard, |this| this.focus_ring_style(window, cx))
- .on_drag(ReviewResize, |drag, _, _, cx| cx.new(|_| *drag))
- .on_click(cx.listener(|this, event: &ClickEvent, window, cx| {
- if event.click_count() >= 2 {
- this.set_review_width(DEFAULT_REVIEW_WIDTH, window, cx);
- }
- }))
- .child(pill)
- .into_any_element()
- }
-
- /// A drag of the panel's edge to the pointer, which holds the handle in
- /// the middle of the gap between the plates.
- pub(super) fn drag_review_edge(
- &mut self,
- event: &DragMoveEvent<ReviewResize>,
- window: &mut Window,
- cx: &mut Context<Self>,
- ) {
- let rem = window.rem_size();
- let right = window.viewport_size().width - rem * PLATE_INSET_REMS;
- let edge = event.event.position.x + rem * (PLATE_INSET_REMS / 2.);
- let width = ((right - edge) / rem * DESIGN_PX_PER_REM).round().max(0.);
- self.review.resizing = true;
- // Within u16 once clamped.
- let width = width.min(f32::from(u16::MAX)) as u16;
- self.set_review_width(width, window, cx);
- cx.notify();
- }
-
- /// A drag of the edge ended.
- pub(super) fn end_review_drag(&mut self, cx: &mut Context<Self>) {
- if std::mem::take(&mut self.review.resizing) {
- cx.notify();
- }
- }
-
- /// Moves the edge by `step` of the preferences' pixels; a positive
- /// step widens the panel.
- fn step_review_width(&mut self, step: i32, window: &Window, cx: &mut Context<Self>) {
- let width = (i32::from(self.review.width) + step).clamp(0, i32::from(u16::MAX));
- // Within u16 once clamped.
- self.set_review_width(width as u16, window, cx);
- }
-
- /// Sets the panel's width, from its narrowest to what leaves the
- /// conversation its least width beside it, and saves it once it has
- /// stayed a moment.
- pub fn set_review_width(&mut self, width: u16, window: &Window, cx: &mut Context<Self>) {
- let rem = window.rem_size();
- let column = self.form_rems(self.shown_form, cx);
- let room =
- window.viewport_size().width / rem - column - PLATE_LEAST_REMS - PLATE_INSET_REMS;
- let room = (room * DESIGN_PX_PER_REM).floor().clamp(0., f32::from(u16::MAX));
- // Within u16 once clamped.
- let width = clamp_review_width(width.min(room as u16));
- if width == self.review.width {
- return;
- }
- self.review.width = width;
- cx.notify();
- self.review._save_width = Some(cx.spawn(async move |this, cx| {
- cx.background_executor().timer(WIDTH_SAVE_DELAY).await;
- this.update(cx, |this, cx| {
- let width = this.review.width;
- AppPreferences::global(cx)
- .update(cx, |preferences, cx| preferences.set_review_width(width, cx));
- })
- .ok();
- }));
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- /// At the default font: the plate with the composer's column takes 49
- /// rems (784 px), with the least conversation 26 (400 px), the gap
- /// 0.5; both count the plate's margins.
- #[test]
- fn the_panel_goes_below_when_the_plate_would_lose_the_composers_width() {
- // A 1440 px window beside a 256 px sidebar: the panel takes its
- // 30 rems, up to the 47.5 that leave a 400 px conversation.
- assert_eq!(ReviewPlacement::of(90., 16., 480), ReviewPlacement::Beside(30.));
- assert_eq!(ReviewPlacement::of(90., 16., 1200), ReviewPlacement::Beside(47.5));
- assert_eq!(ReviewPlacement::of(120., 16., 1200), ReviewPlacement::Beside(75.));
- // Less room than the narrowest 340 px (21.25 rems) beside the
- // composer's column: below.
- assert_eq!(ReviewPlacement::of(85., 16., 480), ReviewPlacement::Below);
- // A collapsed sidebar gives the panel its room back.
- assert_eq!(ReviewPlacement::of(85., 0., 480), ReviewPlacement::Beside(30.));
- }
-}
diff --git a/apps/desktop-gpui/crates/app/src/workbench/side_chats.rs b/apps/desktop-gpui/crates/app/src/workbench/side_chats.rs
new file mode 100644
index 0000000000..42beca1440
--- /dev/null
+++ b/apps/desktop-gpui/crates/app/src/workbench/side_chats.rs
@@ -0,0 +1,436 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! The workbar's Side chat faces: each task's side chats
+//! ([`conversation::SideChat`]), how they open, show, close and go with
+//! their task (Desktop's `side-chat` tool, `use-workbar-controller.ts`).
+//!
+//! A side chat belongs to the task it talks about and lives while the app
+//! runs: switching tasks keeps it (only the selected task's side chats
+//! have tabs), and coming back shows it as it was. It goes when its tab
+//! closes (asking first when it has a conversation, unless the person said
+//! not to ask again) and when its task is deleted, not archived: its fork's
+//! runs are stopped and the fork removed. Tabs are numbered as Desktop's:
+//! "Side chat", "Side chat 2", one past the highest the task's open side
+//! chats carry.
+//!
+//! ⌥⌘S shows the task's side chat (the one last shown, or a new one when
+//! the task has none) or hides the panel while it shows one; with text
+//! selected in the task's conversation it stages the text as a quote in
+//! that side chat instead, as the transcript's "Ask in side chat" does.
+//! A task with no message yet (the new task's draft) has nothing to fork:
+//! it says so (Desktop's `sideChatUnavailable`).
+
+use std::cell::Cell;
+use std::collections::{BTreeSet, HashMap};
+use std::rc::Rc;
+
+use conversation::{SideChat, SideChatLedger, SideChatPanel};
+use gpui_kit::base::TextSelection;
+use gpui_kit::component::checkbox::Checkbox;
+use gpui_kit::component::notification::Notification;
+use gpui_kit::component::{WindowExt as _, v_flex};
+use gpui_kit::{
+ App, AppContext as _, Context, Entity, ParentElement as _, SharedString, Styled as _, Window,
+};
+use host_protocol::QuoteRef;
+use session::LoadState;
+use settings::AppPreferences;
+use shared::copy::{self as shell_copy, side_chat as copy};
+use shared::dialog::{DialogHeader, DialogHeaderExt as _};
+use workspace::HostSessionEvent;
+use workspace::actions::ToggleSideChat;
+
+use super::Workbench;
+use super::workbar::ToolKind;
+
+/// A side chat's tab: its id and its number among its task's.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct SideChatTab {
+ pub(crate) id: SharedString,
+ pub(crate) ordinal: usize,
+}
+
+struct Entry {
+ chat: Entity<SideChat>,
+ panel: Entity<SideChatPanel>,
+ ordinal: usize,
+}
+
+/// Every task's side chats, in the order they opened, and the one each
+/// task's panel shows on its Side chat face.
+#[derive(Default)]
+pub(crate) struct SideChats {
+ entries: Vec<Entry>,
+ shown: HashMap<SharedString, SharedString>,
+}
+
+impl SideChats {
+ fn of<'a>(&'a self, task: &str, cx: &App) -> Vec<&'a Entry> {
+ self.entries.iter().filter(|entry| entry.chat.read(cx).source().as_ref() == task).collect()
+ }
+
+ fn get<'a>(&'a self, id: &str, cx: &App) -> Option<&'a Entry> {
+ self.entries.iter().find(|entry| entry.chat.read(cx).id().as_ref() == id)
+ }
+
+ /// Task `task`'s tabs, in the order they opened.
+ pub(crate) fn tabs_of(&self, task: &str, cx: &App) -> Vec<SideChatTab> {
+ self.of(task, cx)
+ .into_iter()
+ .map(|entry| SideChatTab {
+ id: entry.chat.read(cx).id().clone(),
+ ordinal: entry.ordinal,
+ })
+ .collect()
+ }
+
+ /// The side chat task `task`'s panel shows: the one last shown, else its
+ /// newest.
+ fn shown_of<'a>(&'a self, task: &str, cx: &App) -> Option<&'a Entry> {
+ let shown = self.shown.get(task);
+ let of = self.of(task, cx);
+ of.iter()
+ .find(|entry| Some(entry.chat.read(cx).id()) == shown)
+ .or_else(|| of.last())
+ .copied()
+ }
+}
+
+impl Workbench {
+ /// The selected task's side chats, in the order they opened.
+ pub fn side_chats(&self, cx: &App) -> Vec<Entity<SideChat>> {
+ let Some(task) = self.selected_task(cx) else { return Vec::new() };
+ self.workbar.side_chats.of(&task, cx).into_iter().map(|entry| entry.chat.clone()).collect()
+ }
+
+ /// The panel of side chat `id`.
+ pub fn side_chat_panel(&self, id: &str, cx: &App) -> Option<Entity<SideChatPanel>> {
+ self.workbar.side_chats.get(id, cx).map(|entry| entry.panel.clone())
+ }
+
+ /// Whether the selected task has a side chat.
+ pub(super) fn side_chat_face_open(&self, cx: &App) -> bool {
+ self.selected_task(cx).is_some_and(|task| !self.workbar.side_chats.of(&task, cx).is_empty())
+ }
+
+ /// The id of the side chat the selected task's panel shows on its Side
+ /// chat face.
+ pub(super) fn shown_side_chat_id(&self, cx: &App) -> Option<SharedString> {
+ let task = self.selected_task(cx)?;
+ self.workbar.side_chats.shown_of(&task, cx).map(|entry| entry.chat.read(cx).id().clone())
+ }
+
+ /// Its panel.
+ pub(super) fn shown_side_chat_panel(&self, cx: &App) -> Option<Entity<SideChatPanel>> {
+ let task = self.selected_task(cx)?;
+ self.workbar.side_chats.shown_of(&task, cx).map(|entry| entry.panel.clone())
+ }
+
+ /// Gives the shown side chat's composer the focus.
+ pub(super) fn focus_side_chat(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if let Some(panel) = self.shown_side_chat_panel(cx) {
+ panel.update(cx, |panel, cx| panel.focus(window, cx));
+ }
+ }
+
+ /// Opens a new side chat about the selected task and shows it, its
+ /// composer focused. Nothing without a task.
+ pub(super) fn new_side_chat(
+ &mut self,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Option<Entity<SideChat>> {
+ let task = self.selected_task(cx)?;
+ let host = self.host.clone();
+ let chat = cx.new(|cx| SideChat::new(task.clone(), host, cx));
+ let (connections, projects) = (self.connections.clone(), self.projects.clone());
+ let panel =
+ cx.new(|cx| SideChatPanel::new(chat.clone(), connections, projects, window, cx));
+ // Desktop's `reserveOrdinal`: one past the highest the task's open
+ // side chats carry.
+ let ordinal = self
+ .workbar
+ .side_chats
+ .of(&task, cx)
+ .iter()
+ .map(|entry| entry.ordinal)
+ .max()
+ .unwrap_or(0)
+ + 1;
+ self._subscriptions.push(cx.observe(&chat, |_, _, cx| cx.notify()));
+ let id = chat.read(cx).id().clone();
+ self.workbar.side_chats.entries.push(Entry { chat: chat.clone(), panel, ordinal });
+ self.show_side_chat(&id, window, cx);
+ Some(chat)
+ }
+
+ /// Shows side chat `id` of the selected task, the panel open and its
+ /// composer focused.
+ pub(super) fn show_side_chat(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ let Some(task) = self.selected_task(cx) else { return };
+ if self.workbar.side_chats.get(id, cx).is_none() {
+ return;
+ }
+ if self.page.is_some() {
+ self.leave_page(Some(task.clone()), window, cx);
+ }
+ self.workbar.side_chats.shown.insert(task, id.to_owned().into());
+ self.set_workbar_face(ToolKind::SideChat, cx);
+ if !self.workbar_open(cx) {
+ self.set_workbar_open(true, window, cx);
+ }
+ self.focus_side_chat(window, cx);
+ cx.notify();
+ }
+
+ /// ⌥⌘S (Desktop's `toggleTool('side-chat')`): with text selected in
+ /// the task's conversation, stages it as a quote in the task's side
+ /// chat; otherwise shows the task's side chat (a new one when it has
+ /// none), or hides the panel while it shows one. Behind settings,
+ /// nothing; for the new task's draft, a note that a side chat needs a
+ /// task first.
+ pub(crate) fn toggle_side_chat(
+ &mut self,
+ _: &ToggleSideChat,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.settings.is_some() {
+ return;
+ }
+ if self.selected_task(cx).is_none() {
+ window.push_notification(
+ Notification::info(copy::UNAVAILABLE_BODY.get(cx)).title(copy::UNAVAILABLE.get(cx)),
+ cx,
+ );
+ return;
+ }
+ if self.page.is_none()
+ && let Some((text, turn)) = self.conversation_selection(window, cx)
+ {
+ TextSelection::clear(window, cx);
+ self.stage_side_quote(text, turn, window, cx);
+ return;
+ }
+ if self.workbar_shown(cx) && self.shown_face(cx) == ToolKind::SideChat {
+ self.set_workbar_open(false, window, cx);
+ self.composer.update(cx, |composer, cx| composer.focus(window, cx));
+ return;
+ }
+ match self.shown_side_chat_id(cx) {
+ Some(id) => self.show_side_chat(&id, window, cx),
+ None => {
+ self.new_side_chat(window, cx);
+ }
+ }
+ }
+
+ /// The text selected in the task's conversation, its whitespace folded
+ /// (Desktop's `normalizeQuoteText`), and the Turn whose replies hold
+ /// all of it; `None` unless the conversation's replies hold the
+ /// window's selection (text selected in a side chat, the Files face or
+ /// anywhere else is not a quote of the task).
+ fn conversation_selection(
+ &self,
+ window: &mut Window,
+ cx: &mut App,
+ ) -> Option<(String, Option<SharedString>)> {
+ if !self.conversation.read(cx).holds_selection(cx) {
+ return None;
+ }
+ let selected = TextSelection::selected_text(window, cx);
+ let folded = selected.split_whitespace().collect::<Vec<_>>().join(" ");
+ if folded.is_empty() {
+ return None;
+ }
+ let turn = self.conversation.read(cx).selection_turn(&selected, cx);
+ Some((folded, turn))
+ }
+
+ /// Stages `text` (from Turn `turn`, when one Turn's replies hold it) as
+ /// a quote in the selected task's side chat (the one shown, else a new
+ /// one), and shows it with its composer focused (Desktop's
+ /// `openSideChatWithQuote`).
+ pub(super) fn stage_side_quote(
+ &mut self,
+ text: String,
+ turn: Option<SharedString>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(task) = self.selected_task(cx) else { return };
+ let chat = match self.workbar.side_chats.shown_of(&task, cx) {
+ Some(entry) => entry.chat.clone(),
+ None => match self.new_side_chat(window, cx) {
+ Some(chat) => chat,
+ None => return,
+ },
+ };
+ let quote = QuoteRef::new(text).with_source_turn_id(turn.map(|turn| turn.to_string()));
+ chat.update(cx, |chat, cx| chat.stage_quote(quote, cx));
+ let id = chat.read(cx).id().clone();
+ self.show_side_chat(&id, window, cx);
+ }
+
+ /// A side chat's ×: one with a conversation asks first (Desktop's
+ /// close confirmation, with its "Don't ask again"), unless asked not
+ /// to; then it goes.
+ pub(super) fn close_side_chat(
+ &mut self,
+ id: &str,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(entry) = self.workbar.side_chats.get(id, cx) else { return };
+ let asks = entry.chat.read(cx).has_content()
+ && !AppPreferences::global(cx).read(cx).is_side_chat_close_unconfirmed();
+ if !asks {
+ self.dispose_side_chat(id, window, cx);
+ return;
+ }
+ let locale = shell_copy::Locale::current(cx);
+ let workbench = cx.entity().downgrade();
+ let id: SharedString = id.to_owned().into();
+ let skip = Rc::new(Cell::new(false));
+ window.open_alert_dialog(cx, move |alert, _, cx| {
+ let (workbench, id, skip) = (workbench.clone(), id.clone(), skip.clone());
+ let checked = skip.get();
+ let toggle = skip.clone();
+ shared::theme::floating_surface(alert, cx)
+ .with_header(DialogHeader::new(copy::CLOSE_TITLE.in_locale(locale)))
+ .description(
+ v_flex()
+ .gap_3()
+ .child(shared::dialog::confirmation_text(
+ copy::CLOSE_BODY.in_locale(locale),
+ ))
+ .child(
+ Checkbox::new("side-chat-dont-ask")
+ .label(copy::DONT_ASK_AGAIN.in_locale(locale))
+ .checked(checked)
+ .on_click(move |checked, window, _| {
+ toggle.set(*checked);
+ window.refresh();
+ }),
+ ),
+ )
+ .footer(shared::dialog::confirmation_answers(
+ shell_copy::CANCEL.in_locale(locale),
+ copy::CLOSE_CONFIRM.in_locale(locale),
+ true,
+ cx,
+ ))
+ .on_ok(move |_, window, cx| {
+ if skip.get() {
+ AppPreferences::global(cx).update(cx, |preferences, cx| {
+ preferences.set_side_chat_close_unconfirmed(true, cx)
+ });
+ }
+ workbench
+ .update(cx, |workbench, cx| workbench.dispose_side_chat(&id, window, cx))
+ .ok();
+ true
+ })
+ });
+ }
+
+ /// Side chat `id` goes: its tab, and its fork (stopped, then removed).
+ /// The last face gone hides the panel.
+ pub(super) fn dispose_side_chat(
+ &mut self,
+ id: &str,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ self.drop_side_chat(id, cx);
+ self.hide_empty_workbar(window, cx);
+ cx.notify();
+ }
+
+ fn drop_side_chat(&mut self, id: &str, cx: &mut Context<Self>) {
+ let Some(ix) = self
+ .workbar
+ .side_chats
+ .entries
+ .iter()
+ .position(|entry| entry.chat.read(cx).id().as_ref() == id)
+ else {
+ return;
+ };
+ let entry = self.workbar.side_chats.entries.remove(ix);
+ let task = entry.chat.read(cx).source().clone();
+ if self.workbar.side_chats.shown.get(&task).is_some_and(|shown| shown.as_ref() == id) {
+ self.workbar.side_chats.shown.remove(&task);
+ }
+ entry.chat.update(cx, |chat, cx| chat.dispose(cx)).detach();
+ }
+
+ /// Tells the app's ledger of side chats' forks about each connection of
+ /// this window's Host, so it settles what an ended run left on that
+ /// State Root.
+ pub(super) fn watch_side_chat_ledger(&mut self, cx: &mut Context<Self>) {
+ let subscription = cx.subscribe(&self.host, |this, _, event: &HostSessionEvent, cx| {
+ if matches!(event, HostSessionEvent::Connected { .. }) {
+ this.connect_side_chat_ledger(cx);
+ }
+ });
+ self._subscriptions.push(subscription);
+ // The Search page leaves out the forks the ledger holds.
+ let ledger = SideChatLedger::global(cx);
+ self._subscriptions.push(cx.observe(&ledger, |this, _, cx| this.sync_search_tasks(cx)));
+ self.connect_side_chat_ledger(cx);
+ }
+
+ fn connect_side_chat_ledger(&self, cx: &mut Context<Self>) {
+ let host = self.host.read(cx);
+ let Some(root) = host
+ .accepted()
+ .filter(|_| host.is_connected())
+ .map(|accepted| accepted.root_id.clone())
+ else {
+ return;
+ };
+ let requester = host.requester();
+ SideChatLedger::global(cx).update(cx, |ledger, cx| ledger.connected(&root, requester, cx));
+ }
+
+ /// Once the catalog is read, the side chats of tasks it no longer lists
+ /// (deleted; an archived task is still listed) go with their forks
+ /// (Desktop's `retireDeletedSessionSideChats`).
+ pub(super) fn retire_side_chats_of_deleted_tasks(&mut self, cx: &mut Context<Self>) {
+ let catalog = self.catalog.read(cx);
+ if *catalog.load_state() != LoadState::Loaded {
+ return;
+ }
+ let listed: BTreeSet<&SharedString> = catalog.rows().iter().map(|row| &row.id).collect();
+ let gone: Vec<SharedString> = self
+ .workbar
+ .side_chats
+ .entries
+ .iter()
+ .filter(|entry| !listed.contains(entry.chat.read(cx).source()))
+ .map(|entry| entry.chat.read(cx).id().clone())
+ .collect();
+ for id in gone {
+ log::info!("side chat {id}: its task is gone");
+ self.drop_side_chat(&id, cx);
+ }
+ }
+}
diff --git a/apps/desktop-gpui/crates/app/src/workbench/workbar.rs b/apps/desktop-gpui/crates/app/src/workbench/workbar.rs
new file mode 100644
index 0000000000..ce7493fb9e
--- /dev/null
+++ b/apps/desktop-gpui/crates/app/src/workbench/workbar.rs
@@ -0,0 +1,1972 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! The workbar: the panel of tools beside the plate, Maka Desktop's task
+//! workbar (`features/workbar`), for the selected task. It holds faces:
+//! the changes ([`review::ReviewPanel`]), the task's files
+//! ([`files::FilesView`]), the task's trace ([`inspector::InspectorView`],
+//! Desktop's Inspector), the task's side chats
+//! ([`conversation::SideChatPanel`], see [`super::side_chats`]) and the
+//! task's terminals ([`terminal::TerminalView`]), one shown at a time under
+//! a strip of tabs.
+//!
+//! The shell is here: the registry of tools ([`TOOLS`], Desktop's
+//! `WORKBAR_TOOL_DEFINITIONS`), the strip (a tab per open face, the [+]
+//! menu of every tool, maximize and close), where the panel goes, and what
+//! each task remembers. The faces are entities of their own and keep their
+//! state whether shown or not; the changes' key contexts stay on its own
+//! root, and a terminal face is drawn beside it, never inside it.
+//!
+//! Like Desktop's workbar it is open or closed per task, remembered with
+//! its width and, per task, the face it shows and whether its Changes,
+//! Files and Trace faces are open; terminals are the Host's, read from its inventory when a task
+//! is selected, never from these preferences (a task whose remembered face
+//! is a terminal shows its first live one). On a window with room it is its
+//! own plate on the right, `width` wide (Desktop's 480 at first, from 340,
+//! scaling with the UI font as the sidebar does), with a handle on its edge
+//! that drags it as wide as leaves the conversation its least width,
+//! Desktop's 400 px (`--maka-conversation-min-width`), which keeps the
+//! composer's controls on one row and the transcript readable. When the
+//! window cannot keep the composer's whole column beside the panel's
+//! narrowest width, the panel goes below the plate, as Desktop's goes below
+//! the conversation on a narrow window, 42% of the window's height up to
+//! 360 px, with no handle.
+//!
+//! The changes work out what each turn of the task edited
+//! ([`review::turns`]): the window hands them the session's edits as the
+//! transcript moves on, and hands the conversation what they worked out for
+//! the card under each settled turn, whose buttons open the panel on the
+//! turn. While the changes show, the conversation reads the task's whole
+//! history in the background, so they list every turn.
+//!
+//! Maximized (the strip's button, or ⇧Esc), the panel fills the plate below
+//! the plate's header in the conversation's and the composer's place, which
+//! keep their state, not drawn; the button or ⇧Esc (Esc in the changes)
+//! give them their place back. Each task remembers it.
+//!
+//! The terminals' output streams in while the panel shows, whichever face
+//! it shows, so their tabs keep their titles and bells; they hold their
+//! controllers only while their face shows, leaving them to another window
+//! or Maka Desktop meanwhile. Hidden, they let both go and their shells run
+//! on. The files are read while their face shows and polled while it
+//! stays, as Desktop's are; a settled turn and a subagent's writeback read
+//! them again. The trace is read while its face shows and refreshed from
+//! the task's own signals while it stays.
+
+use std::cell::Cell;
+use std::collections::BTreeSet;
+use std::rc::Rc;
+use std::sync::Arc;
+
+use conversation::{ConversationEvent, ConversationViewEvent};
+use files::{FilesView, FilesViewEvent};
+use gpui_kit::assets::IconName as AssetIcon;
+use gpui_kit::component::button::{Button, ButtonCustomVariant, ButtonVariants as _};
+use gpui_kit::component::spinner::Spinner;
+use gpui_kit::component::{
+ Icon, Selectable as _, Sizable as _, StyledExt as _, ThemeStyled as _, h_flex, v_flex,
+};
+use gpui_kit::{
+ Action, AnyElement, App, AppContext as _, ClickEvent, Context, DragMoveEvent, Empty, Entity,
+ FocusHandle, Hsla, InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Render,
+ Role, SharedString, StatefulInteractiveElement as _, Styled as _, Task, TestSupportExt as _,
+ TextRun, Window, canvas, div, prelude::FluentBuilder as _, px, rems,
+};
+use inspector::{InspectorView, InspectorViewEvent};
+use review::git::{ReviewScope, SystemGit};
+use review::{ReviewPanel, ReviewPanelEvent, ReviewTarget, ToggleMaximized};
+use session::LoadState;
+use settings::{
+ AppPreferences, DEFAULT_REVIEW_WIDTH, REVIEW_WIDTHS, WorkbarFace, clamp_review_width,
+};
+use shared::copy::side_chat as side_chat_copy;
+use shared::copy::{
+ self as shell_copy, Locale, Text, files as files_copy, inspector as inspector_copy,
+ review as review_copy, terminal as terminal_copy, workbar as copy,
+};
+use shared::domain_element_id;
+use shared::icons::{MakaIcon, ink};
+use shared::layout::{ICON_BUTTON_REMS, ICON_GLYPH_REMS, PLATE_LINE_REMS, ink_padding};
+use shared::menu::{MenuEntry, MenuItem, MenuPlacement, MenuSlot};
+use shared::theme::{
+ ActiveMakaPalette as _, BODY_TEXT_REMS, RADIUS_CONTROL, RADIUS_MODAL, selectable_row,
+};
+use terminal::{
+ CloseState, TerminalTab, TerminalView, TerminalViewEvent, Terminals, TerminalsShown,
+};
+use transcript_model::edits::{EditsKey, session_edits};
+use workspace::HostSession;
+use workspace::actions::{ToggleFiles, ToggleReview, ToggleSideChat, ToggleTerminal};
+
+use super::side_chats::{SideChatTab, SideChats};
+use super::{
+ DESIGN_PX_PER_REM, PLATE_INSET_REMS, PLATE_MIN_REMS, RESIZE_HANDLE_WIDTH, RESIZE_LARGE_STEP,
+ RESIZE_STEP, WIDTH_SAVE_DELAY, Workbench,
+};
+
+/// Key context of the workbar's edge while it has focus.
+pub const WORKBAR_RESIZE_CONTEXT: &str = "WorkbarResize";
+
+gpui_kit::actions!(
+ maka_workbar,
+ [
+ /// Move the workbar's edge 10 px toward the plate.
+ WidenWorkbarStep,
+ /// Move the workbar's edge 10 px away from the plate.
+ NarrowWorkbarStep,
+ /// Move the workbar's edge 50 px toward the plate.
+ WidenWorkbarLargeStep,
+ /// Move the workbar's edge 50 px away from the plate.
+ NarrowWorkbarLargeStep,
+ /// Give the workbar its default width.
+ ResetWorkbarWidth,
+ ]
+);
+
+/// The least the plate keeps beside the panel when the panel is dragged
+/// wide: Desktop's `--maka-conversation-min-width`, 400 px, and the canvas
+/// margin on either side of the plate (as in `PLATE_MIN_REMS`).
+const PLATE_LEAST_REMS: f32 = 400. / DESIGN_PX_PER_REM + 2. * PLATE_INSET_REMS;
+
+/// The height of the panel below the plate: Desktop's `min(42dvh, 360px)`.
+const BELOW_HEIGHT_SHARE: f32 = 0.42;
+const BELOW_MAX_HEIGHT_REMS: f32 = 360. / DESIGN_PX_PER_REM;
+
+/// The strip's height, as the changes' own bar under it.
+const STRIP_HEIGHT_REMS: f32 = 3.;
+
+/// A tab's parts, for working out whether the strip holds every label:
+/// its fill's padding before the icon and after the ×, the icon, the gaps
+/// between the parts, a mark, and the × button.
+const TAB_LEADING_REMS: f32 = 0.5;
+const TAB_TRAILING_REMS: f32 = 0.125;
+const TAB_ICON_REMS: f32 = 1.;
+const TAB_GAP_REMS: f32 = 0.25;
+const TAB_MARK_REMS: f32 = 0.75;
+const TAB_CLOSE_REMS: f32 = 1.25;
+/// The gap between tabs.
+const TABS_GAP_REMS: f32 = 0.125;
+/// A label's widest: a long title ends in an ellipsis there (the whole of
+/// it in the tab's accessible name).
+const TAB_LABEL_MAX_REMS: f32 = 12.;
+/// The [+] menu's least width.
+const ADD_MENU_WIDTH_REMS: f32 = 14.;
+
+/// One of the workbar's tools.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum ToolKind {
+ Changes,
+ Files,
+ Inspector,
+ SideChat,
+ Terminal,
+}
+
+/// A tool as the registry defines it (Desktop's `WorkbarToolDefinition`):
+/// the strip, the [+] menu, the shortcuts and the preferences all read it.
+#[derive(Clone, Copy)]
+pub(crate) struct ToolDefinition {
+ pub(crate) kind: ToolKind,
+ pub(crate) label: Text,
+ pub(crate) icon: MakaIcon,
+ /// The action of its shortcut, which the [+] menu shows; none for a
+ /// tool Desktop gives none.
+ pub(crate) shortcut: Option<fn() -> Box<dyn Action>>,
+ /// Whether a task remembers its face being open.
+ pub(crate) persisted: bool,
+ /// One face (choosing it in [+] opens or closes it), or several
+ /// (choosing it adds another).
+ pub(crate) singleton: bool,
+}
+
+/// Every tool, in the order the [+] menu lists them and the strip shows
+/// their faces.
+pub(crate) const TOOLS: [ToolDefinition; 5] = [
+ ToolDefinition {
+ kind: ToolKind::Changes,
+ label: review_copy::CHANGES,
+ icon: MakaIcon::FileDiff,
+ shortcut: Some(|| Box::new(ToggleReview)),
+ persisted: true,
+ singleton: true,
+ },
+ ToolDefinition {
+ kind: ToolKind::Files,
+ label: files_copy::FILES,
+ icon: MakaIcon::Folder,
+ shortcut: Some(|| Box::new(ToggleFiles)),
+ persisted: true,
+ singleton: true,
+ },
+ // Desktop's `inspector` tool: persisted, one face, no shortcut, the
+ // `activity` glyph.
+ ToolDefinition {
+ kind: ToolKind::Inspector,
+ label: inspector_copy::TRACE,
+ icon: MakaIcon::Activity,
+ shortcut: None,
+ persisted: true,
+ singleton: true,
+ },
+ // Desktop's `side-chat` tool: not persisted, several faces, its
+ // `mod+alt+s`, the chat glyph (Desktop's `message-circle-question`).
+ // After Trace here, where Desktop lists it first.
+ ToolDefinition {
+ kind: ToolKind::SideChat,
+ label: side_chat_copy::SIDE_CHAT,
+ icon: MakaIcon::Chat,
+ shortcut: Some(|| Box::new(ToggleSideChat)),
+ persisted: false,
+ singleton: false,
+ },
+ ToolDefinition {
+ kind: ToolKind::Terminal,
+ label: terminal_copy::TERMINAL,
+ icon: MakaIcon::ToolTerminal,
+ shortcut: Some(|| Box::new(ToggleTerminal)),
+ persisted: false,
+ singleton: false,
+ },
+];
+
+fn tool(kind: ToolKind) -> &'static ToolDefinition {
+ TOOLS.iter().find(|tool| tool.kind == kind).unwrap_or(&TOOLS[0])
+}
+
+/// Where the panel goes.
+#[derive(Debug, Clone, Copy, PartialEq)]
+pub(crate) enum WorkbarPlacement {
+ /// On the right of the plate, this many rems wide.
+ Beside(f32),
+ /// Below the plate, the plate's width.
+ Below,
+}
+
+impl WorkbarPlacement {
+ /// For a window `window_rems` wide whose sidebar column takes
+ /// `column_rems`, a panel `width` wide (the preferences' pixels): beside
+ /// the plate when its narrowest width leaves the plate the composer's
+ /// whole column, at its width up to what leaves the conversation its
+ /// least; else below.
+ pub(crate) fn of(window_rems: f32, column_rems: f32, width: u16) -> Self {
+ let beside = window_rems - column_rems - PLATE_INSET_REMS;
+ let narrowest = f32::from(*REVIEW_WIDTHS.start()) / DESIGN_PX_PER_REM;
+ if beside - PLATE_MIN_REMS < narrowest {
+ return Self::Below;
+ }
+ Self::Beside((f32::from(width) / DESIGN_PX_PER_REM).min(beside - PLATE_LEAST_REMS))
+ }
+}
+
+/// What a drag of the panel's edge carries: nothing; its moves set the
+/// width.
+#[derive(Debug, Clone, Copy)]
+pub(crate) struct WorkbarResize;
+
+impl Render for WorkbarResize {
+ fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
+ Empty
+ }
+}
+
+/// A face the strip shows a tab for.
+#[derive(Debug, Clone, PartialEq)]
+pub(super) enum Face {
+ Changes,
+ Files,
+ Inspector,
+ SideChat(SideChatTab),
+ Terminal(TerminalTab),
+}
+
+impl Face {
+ /// Stable within the strip: the tab's element ids derive from it.
+ fn key(&self) -> SharedString {
+ match self {
+ Self::Changes => "changes".into(),
+ Self::Files => "files".into(),
+ Self::Inspector => "inspector".into(),
+ Self::SideChat(tab) => format!("side-chat:{}", tab.id).into(),
+ Self::Terminal(tab) => tab.resource_ref.clone(),
+ }
+ }
+
+ fn kind(&self) -> ToolKind {
+ match self {
+ Self::Changes => ToolKind::Changes,
+ Self::Files => ToolKind::Files,
+ Self::Inspector => ToolKind::Inspector,
+ Self::SideChat(_) => ToolKind::SideChat,
+ Self::Terminal(_) => ToolKind::Terminal,
+ }
+ }
+
+ fn name(&self, cx: &App) -> SharedString {
+ match self {
+ Self::Changes => review_copy::CHANGES.get(cx).into(),
+ Self::Files => files_copy::FILES.get(cx).into(),
+ Self::Inspector => inspector_copy::TRACE.get(cx).into(),
+ Self::SideChat(tab) => {
+ side_chat_copy::numbered(Locale::current(cx), tab.ordinal).into()
+ }
+ Self::Terminal(tab) => tab.title.clone(),
+ }
+ }
+}
+
+/// The panel, its faces and what the window keeps about it.
+pub(crate) struct Workbar {
+ panel: Entity<ReviewPanel>,
+ terminals: Entity<Terminals>,
+ terminal: Entity<TerminalView>,
+ files: Entity<FilesView>,
+ inspector: Entity<InspectorView>,
+ /// The files the selected task's last turn said a subagent wrote back,
+ /// by task and turn: more of them reads the files again.
+ artifact_mentions: Option<(String, String, usize)>,
+ /// The width in the preferences' pixels, as dragged.
+ width: u16,
+ resizing: bool,
+ /// The edge's handle, a Tab stop.
+ resize_focus: FocusHandle,
+ /// Whether a turn of the selected task ran at the last commit.
+ turn_running: bool,
+ add_menu: MenuSlot,
+ /// The width the tabs had at the last frame: whether every label fits.
+ tabs_width: Rc<Cell<Pixels>>,
+ /// Every task's side chats, alive across task switches.
+ pub(super) side_chats: SideChats,
+ _save_width: Option<Task<()>>,
+}
+
+impl Workbar {
+ pub(crate) fn new(
+ terminals: Entity<Terminals>,
+ host: Entity<HostSession>,
+ window: &mut Window,
+ cx: &mut Context<Workbench>,
+ ) -> Self {
+ let terminal = cx.new(|cx| TerminalView::new(terminals.clone(), window, cx));
+ Self {
+ panel: cx.new(|cx| ReviewPanel::new(Arc::new(SystemGit), window, cx)),
+ terminals,
+ terminal,
+ files: cx.new(|cx| FilesView::new(host.clone(), window, cx)),
+ inspector: cx.new(|cx| InspectorView::new(host, window, cx)),
+ artifact_mentions: None,
+ width: AppPreferences::current(cx).review_width,
+ resizing: false,
+ resize_focus: cx.focus_handle().tab_stop(true).tab_index(1),
+ turn_running: false,
+ add_menu: MenuSlot::new(MenuPlacement::BelowStart),
+ tabs_width: Rc::new(Cell::new(Pixels::ZERO)),
+ side_chats: SideChats::default(),
+ _save_width: None,
+ }
+ }
+}
+
+impl Workbench {
+ /// Follows the faces' requests and what should read the changes again:
+ /// the selected task's turn ending, and the window coming back to the
+ /// front.
+ pub(super) fn watch_workbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let panel = self.workbar.panel.clone();
+ let terminal = self.workbar.terminal.clone();
+ let files = self.workbar.files.clone();
+ let inspector = self.workbar.inspector.clone();
+ let subscriptions = [
+ cx.subscribe_in(&panel, window, |this, _, event: &ReviewPanelEvent, window, cx| {
+ match event {
+ ReviewPanelEvent::BaseBranchChanged { session_id, base_branch } => {
+ let (id, branch) = (session_id.to_string(), base_branch.clone());
+ AppPreferences::global(cx).update(cx, |preferences, cx| {
+ preferences.set_review_base_branch(&id, branch.clone(), cx);
+ });
+ // The strip counts against the same base: from the
+ // panel's next read of All changes, or its own.
+ let summary = this.strip.summary.clone();
+ summary.update(cx, |summary, _| summary.set_base_branch(branch));
+ if !this.review_feeds_strip(cx) {
+ summary.update(cx, |summary, cx| summary.refresh(cx));
+ }
+ }
+ ReviewPanelEvent::ChangesRead { session_id, totals } => {
+ let (id, totals) = (session_id.clone(), totals.clone());
+ this.strip
+ .summary
+ .update(cx, |summary, cx| summary.accept(&id, totals, cx));
+ }
+ ReviewPanelEvent::MaximizeRequested(maximized) => {
+ this.set_workbar_maximized(*maximized, window, cx);
+ }
+ _ => {}
+ }
+ }),
+ cx.subscribe_in(&terminal, window, |this, _, event: &TerminalViewEvent, window, cx| {
+ match event {
+ // A terminal this window started: its face shows, with
+ // the focus.
+ TerminalViewEvent::Started => {
+ if this.catalog.read(cx).selected_id().is_some() {
+ this.set_workbar_face(ToolKind::Terminal, cx);
+ this.set_workbar_open(true, window, cx);
+ this.workbar.terminal.update(cx, |view, cx| view.focus(window, cx));
+ }
+ }
+ TerminalViewEvent::TabsChanged => {
+ this.hide_empty_workbar(window, cx);
+ cx.notify();
+ }
+ _ => {}
+ }
+ }),
+ cx.subscribe_in(
+ &self.state.clone(),
+ window,
+ |this, state, _: &ConversationEvent, window, cx| {
+ this.sync_turn_edits(cx);
+ this.sync_history_reading(cx);
+ let running = !matches!(
+ state.read(cx).turn_activity(),
+ conversation::TurnActivity::Idle | conversation::TurnActivity::Unavailable
+ );
+ let ended =
+ std::mem::replace(&mut this.workbar.turn_running, running) && !running;
+ if ended {
+ this.refresh_review(window, cx);
+ this.workbar.files.update(cx, |files, cx| files.refresh(cx));
+ }
+ this.sync_artifact_mentions(cx);
+ },
+ ),
+ // Escape in the file list gives the conversation its place
+ // back: a maximized panel restored, else the panel hidden and
+ // the composer focused.
+ cx.subscribe_in(&files, window, |this, _, event: &FilesViewEvent, window, cx| {
+ if matches!(event, FilesViewEvent::Dismiss) {
+ if this.workbar_maximized(cx) {
+ this.set_workbar_maximized(false, window, cx);
+ } else {
+ this.set_workbar_open(false, window, cx);
+ this.composer.update(cx, |composer, cx| composer.focus(window, cx));
+ }
+ }
+ }),
+ // Escape in the trace does what it does in the file list.
+ cx.subscribe_in(
+ &inspector,
+ window,
+ |this, _, event: &InspectorViewEvent, window, cx| {
+ if matches!(event, InspectorViewEvent::Dismiss) {
+ if this.workbar_maximized(cx) {
+ this.set_workbar_maximized(false, window, cx);
+ } else {
+ this.set_workbar_open(false, window, cx);
+ this.composer.update(cx, |composer, cx| composer.focus(window, cx));
+ }
+ }
+ },
+ ),
+ cx.observe(&self.strip.summary.clone(), |_, _, cx| cx.notify()),
+ // The card under each settled turn lists what the panel worked
+ // out for it.
+ cx.observe(&panel.read(cx).turn_changes().clone(), |this, changes, cx| {
+ let edited = changes.read(cx).edited_turns();
+ this.conversation.update(cx, |view, cx| view.set_edited_turns(edited, cx));
+ }),
+ cx.subscribe_in(
+ &self.conversation.clone(),
+ window,
+ |this, _, event: &ConversationViewEvent, window, cx| match event {
+ ConversationViewEvent::ShowTurnChanges { turn_id, path } => {
+ this.show_turn_changes(turn_id.clone(), path.clone(), window, cx);
+ }
+ // The transcript's "Ask in side chat": the selection
+ // as the menu opened on it.
+ ConversationViewEvent::AskInSideChat { text, turn_id } => {
+ let folded = text.split_whitespace().collect::<Vec<_>>().join(" ");
+ if !folded.is_empty() {
+ this.stage_side_quote(folded, turn_id.clone(), window, cx);
+ }
+ }
+ _ => {}
+ },
+ ),
+ cx.observe_window_activation(window, |this, window, cx| {
+ let active = window.is_window_active();
+ if active {
+ this.refresh_review(window, cx);
+ }
+ // The files are polled only while the window is active.
+ this.workbar.files.update(cx, |files, cx| files.set_window_active(active, cx));
+ }),
+ // Desktop's `retain-sessions`: once the catalog is read, the
+ // workbar state of tasks it no longer lists goes, and so do the
+ // side chats of a deleted task.
+ cx.observe(&self.catalog.clone(), |this, catalog, cx| {
+ this.retire_side_chats_of_deleted_tasks(cx);
+ let catalog = catalog.read(cx);
+ if *catalog.load_state() != LoadState::Loaded {
+ return;
+ }
+ let ids: BTreeSet<String> =
+ catalog.rows().iter().map(|row| row.id.to_string()).collect();
+ AppPreferences::global(cx)
+ .update(cx, |preferences, cx| preferences.retain_review_tasks(&ids, cx));
+ }),
+ // The Terminal group of Settings: Option as Meta and the
+ // blinking cursor.
+ cx.observe(&AppPreferences::global(cx), |this, preferences, cx| {
+ let preferences = preferences.read(cx);
+ let option_as_meta = preferences.terminal_option_as_meta();
+ let cursor_blink = preferences.terminal_cursor_blink();
+ this.workbar.terminal.update(cx, |view, cx| {
+ view.set_option_as_meta(option_as_meta);
+ view.set_cursor_blink(cursor_blink, cx);
+ });
+ }),
+ // Whatever moved the panel or a face in or out of sight (it
+ // opened or closed, another face or task, a page or settings
+ // over it), the terminals follow, streaming while it shows and
+ // attached while their face does, the files, read and polled
+ // while their face shows, and the trace, read and refreshed
+ // while its face shows.
+ cx.observe_self(|this, cx| {
+ this.sync_terminals_shown(cx);
+ this.sync_files_shown(cx);
+ this.sync_inspector_shown(cx);
+ }),
+ ];
+ self._subscriptions.extend(subscriptions);
+ // The task's conversation offers "Ask in side chat" on a right-click.
+ self.conversation.update(cx, |view, _| view.set_side_chat_menu(true));
+ self.watch_side_chat_ledger(cx);
+ let preferences = AppPreferences::current(cx);
+ terminal.update(cx, |view, cx| {
+ view.set_option_as_meta(preferences.terminal_option_as_meta);
+ view.set_cursor_blink(preferences.terminal_cursor_blink, cx);
+ });
+ let active = window.is_window_active();
+ self.workbar.files.update(cx, |files, cx| files.set_window_active(active, cx));
+ self.sync_review_target(window, cx);
+ self.sync_terminals_shown(cx);
+ self.sync_files_shown(cx);
+ self.sync_inspector_shown(cx);
+ }
+
+ /// The changes panel.
+ pub fn review_panel(&self) -> &Entity<ReviewPanel> {
+ &self.workbar.panel
+ }
+
+ /// The terminal face.
+ pub fn terminal_view(&self) -> &Entity<TerminalView> {
+ &self.workbar.terminal
+ }
+
+ /// The window's terminals.
+ pub fn terminals(&self) -> &Entity<Terminals> {
+ &self.workbar.terminals
+ }
+
+ /// The files face.
+ pub fn files_view(&self) -> &Entity<FilesView> {
+ &self.workbar.files
+ }
+
+ /// The trace face.
+ pub fn inspector_view(&self) -> &Entity<InspectorView> {
+ &self.workbar.inspector
+ }
+
+ /// The strip's tabs: each face's key and name, and whether it shows.
+ #[cfg(test)]
+ pub(crate) fn strip_tabs(&self, cx: &App) -> Vec<(String, String, bool)> {
+ let shown = self.shown_face(cx);
+ let active = self.workbar.terminal.read(cx).active_ref(cx);
+ self.faces(cx)
+ .iter()
+ .map(|face| {
+ let showing = match face {
+ Face::Changes => shown == ToolKind::Changes,
+ Face::Files => shown == ToolKind::Files,
+ Face::Inspector => shown == ToolKind::Inspector,
+ Face::SideChat(tab) => {
+ shown == ToolKind::SideChat
+ && self.shown_side_chat_id(cx).as_ref() == Some(&tab.id)
+ }
+ Face::Terminal(tab) => {
+ shown == ToolKind::Terminal && active.as_ref() == Some(&tab.resource_ref)
+ }
+ };
+ (face.key().to_string(), face.name(cx).to_string(), showing)
+ })
+ .collect()
+ }
+
+ /// Whether the selected task's workbar is open.
+ pub fn workbar_open(&self, cx: &App) -> bool {
+ self.catalog
+ .read(cx)
+ .selected_id()
+ .is_some_and(|id| AppPreferences::global(cx).read(cx).is_review_open(id))
+ }
+
+ /// Whether the panel shows: open, beside the task view (not settings,
+ /// a page, or a blocked Host's screen).
+ pub fn workbar_shown(&self, cx: &App) -> bool {
+ self.settings.is_none()
+ && self.page.is_none()
+ && self.host.read(cx).blocker().is_none()
+ && self.workbar_open(cx)
+ }
+
+ /// The terminals' output streams in while the panel shows, for their
+ /// tabs; they take their controllers only while their face shows.
+ fn sync_terminals_shown(&mut self, cx: &mut Context<Self>) {
+ let shown = if !self.workbar_shown(cx) {
+ TerminalsShown::Hidden
+ } else if self.shown_face(cx) == ToolKind::Terminal {
+ TerminalsShown::Face
+ } else {
+ TerminalsShown::Tabs
+ };
+ if self.workbar.terminals.read(cx).shown() != shown {
+ self.workbar.terminals.update(cx, |terminals, cx| terminals.set_shown(shown, cx));
+ }
+ }
+
+ /// The files follow the selected task, and are read and polled while
+ /// their face shows.
+ fn sync_files_shown(&mut self, cx: &mut Context<Self>) {
+ let session = self.selected_task(cx);
+ let shown = self.workbar_shown(cx) && self.shown_face(cx) == ToolKind::Files;
+ self.workbar.files.update(cx, |files, cx| {
+ files.set_session(session, cx);
+ files.set_shown(shown, cx);
+ });
+ }
+
+ /// The trace follows the selected task, and is read and refreshed while
+ /// its face shows.
+ fn sync_inspector_shown(&mut self, cx: &mut Context<Self>) {
+ let session = self.selected_task(cx);
+ let shown = self.workbar_shown(cx) && self.shown_face(cx) == ToolKind::Inspector;
+ self.workbar.inspector.update(cx, |inspector, cx| inspector.follow(session, shown, cx));
+ }
+
+ /// Reads the files again when the selected task's last turn says a
+ /// subagent wrote more back (`subagent` and `agent_swarm` results'
+ /// `artifactIds`): writebacks land while the turn runs.
+ fn sync_artifact_mentions(&mut self, cx: &mut Context<Self>) {
+ let (session, turn, count) = {
+ let state = self.state.read(cx);
+ let Some(transcript) = state.transcript() else { return };
+ let Some(turn) = transcript.turns().last() else { return };
+ (
+ transcript.session_id().to_owned(),
+ turn.turn_id.clone(),
+ files::policy::artifact_mentions(turn),
+ )
+ };
+ let previous =
+ self.workbar.artifact_mentions.replace((session.clone(), turn.clone(), count));
+ let more =
+ match previous {
+ Some((was_session, was_turn, was)) if was_session == session => {
+ if was_turn == turn { count > was } else { count > 0 }
+ }
+ _ => false,
+ };
+ if more {
+ self.workbar.files.update(cx, |files, cx| files.refresh(cx));
+ }
+ }
+
+ /// The panel's width in the preferences' pixels.
+ pub fn workbar_width(&self) -> u16 {
+ self.workbar.width
+ }
+
+ /// Where the panel goes in this window.
+ pub(super) fn workbar_placement(&self, cx: &App) -> WorkbarPlacement {
+ let column = self.form_rems(self.shown_form, cx);
+ WorkbarPlacement::of(self.window_rems, column, self.workbar.width)
+ }
+
+ // The faces.
+
+ pub(super) fn selected_task(&self, cx: &App) -> Option<SharedString> {
+ self.catalog.read(cx).selected_id().cloned()
+ }
+
+ /// Whether the selected task's Changes face is open.
+ fn changes_face_open(&self, cx: &App) -> bool {
+ self.selected_task(cx)
+ .is_some_and(|id| AppPreferences::global(cx).read(cx).is_changes_face_open(&id))
+ }
+
+ /// Whether the selected task's Files face is open.
+ fn files_face_open(&self, cx: &App) -> bool {
+ self.selected_task(cx)
+ .is_some_and(|id| AppPreferences::global(cx).read(cx).is_files_face_open(&id))
+ }
+
+ /// Whether the selected task's Trace face is open.
+ fn inspector_face_open(&self, cx: &App) -> bool {
+ self.selected_task(cx)
+ .is_some_and(|id| AppPreferences::global(cx).read(cx).is_inspector_face_open(&id))
+ }
+
+ /// The faces the strip shows a tab for, in the registry's order (each
+ /// tool's faces in the order they opened).
+ fn faces(&self, cx: &App) -> Vec<Face> {
+ let mut faces = Vec::new();
+ for tool in &TOOLS {
+ match tool.kind {
+ ToolKind::Changes if self.changes_face_open(cx) => faces.push(Face::Changes),
+ ToolKind::Files if self.files_face_open(cx) => faces.push(Face::Files),
+ ToolKind::Inspector if self.inspector_face_open(cx) => {
+ faces.push(Face::Inspector);
+ }
+ ToolKind::SideChat => faces.extend(
+ self.selected_task(cx)
+ .map(|task| self.workbar.side_chats.tabs_of(&task, cx))
+ .unwrap_or_default()
+ .into_iter()
+ .map(Face::SideChat),
+ ),
+ ToolKind::Terminal => faces.extend(
+ self.workbar.terminal.read(cx).tabs(cx).into_iter().map(Face::Terminal),
+ ),
+ _ => {}
+ }
+ }
+ faces
+ }
+
+ /// Whether the terminal face has anything to show: a terminal, or the
+ /// task's terminals being read, a start under way or refused.
+ fn terminal_face_open(&self, cx: &App) -> bool {
+ let view = self.workbar.terminal.read(cx);
+ view.has_terminals(cx) || view.has_pending_state(cx)
+ }
+
+ /// The face the panel shows: the one the task remembers while it has
+ /// something to show (the terminal face too while no other is open),
+ /// else the first open one in the registry's order.
+ pub(crate) fn shown_face(&self, cx: &App) -> ToolKind {
+ let changes = self.changes_face_open(cx);
+ let files = self.files_face_open(cx);
+ let inspector = self.inspector_face_open(cx);
+ let side_chat = self.side_chat_face_open(cx);
+ let remembered = match self
+ .selected_task(cx)
+ .map(|id| AppPreferences::global(cx).read(cx).workbar_face(&id))
+ .unwrap_or_default()
+ {
+ WorkbarFace::Changes => ToolKind::Changes,
+ WorkbarFace::Files => ToolKind::Files,
+ WorkbarFace::Inspector => ToolKind::Inspector,
+ WorkbarFace::SideChat => ToolKind::SideChat,
+ _ => ToolKind::Terminal,
+ };
+ let open = match remembered {
+ ToolKind::Changes => changes,
+ ToolKind::Files => files,
+ ToolKind::Inspector => inspector,
+ ToolKind::SideChat => side_chat,
+ ToolKind::Terminal => {
+ self.terminal_face_open(cx) || (!changes && !files && !inspector && !side_chat)
+ }
+ };
+ if open {
+ remembered
+ } else if changes {
+ ToolKind::Changes
+ } else if files {
+ ToolKind::Files
+ } else if inspector {
+ ToolKind::Inspector
+ } else if side_chat {
+ ToolKind::SideChat
+ } else {
+ ToolKind::Terminal
+ }
+ }
+
+ /// Remembers which face the selected task's panel shows.
+ pub(super) fn set_workbar_face(&mut self, kind: ToolKind, cx: &mut Context<Self>) {
+ let Some(id) = self.selected_task(cx) else { return };
+ let face = match kind {
+ ToolKind::Changes => WorkbarFace::Changes,
+ ToolKind::Files => WorkbarFace::Files,
+ ToolKind::Inspector => WorkbarFace::Inspector,
+ ToolKind::SideChat => WorkbarFace::SideChat,
+ ToolKind::Terminal => WorkbarFace::Terminal,
+ };
+ AppPreferences::global(cx)
+ .update(cx, |preferences, cx| preferences.set_workbar_face(&id, face, cx));
+ // The whole history is read only while the changes show.
+ self.sync_history_reading(cx);
+ cx.notify();
+ }
+
+ /// Opens or closes the selected task's Changes face; only a persisted
+ /// tool's face is remembered.
+ fn set_changes_face_open(&mut self, open: bool, cx: &mut Context<Self>) {
+ let Some(id) = self.selected_task(cx) else { return };
+ if tool(ToolKind::Changes).persisted {
+ AppPreferences::global(cx)
+ .update(cx, |preferences, cx| preferences.set_changes_face_open(&id, open, cx));
+ }
+ cx.notify();
+ }
+
+ /// Opens or closes the selected task's Files face, remembered for the
+ /// task (a persisted tool).
+ fn set_files_face_open(&mut self, open: bool, cx: &mut Context<Self>) {
+ let Some(id) = self.selected_task(cx) else { return };
+ if tool(ToolKind::Files).persisted {
+ AppPreferences::global(cx)
+ .update(cx, |preferences, cx| preferences.set_files_face_open(&id, open, cx));
+ }
+ cx.notify();
+ }
+
+ /// Opens or closes the selected task's Trace face, remembered for the
+ /// task (a persisted tool).
+ fn set_inspector_face_open(&mut self, open: bool, cx: &mut Context<Self>) {
+ let Some(id) = self.selected_task(cx) else { return };
+ if tool(ToolKind::Inspector).persisted {
+ AppPreferences::global(cx)
+ .update(cx, |preferences, cx| preferences.set_inspector_face_open(&id, open, cx));
+ }
+ cx.notify();
+ }
+
+ /// Hides the panel once no face is left in it (its last tab closed, or a
+ /// task shown again whose remembered terminals are gone).
+ pub(super) fn hide_empty_workbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.workbar_open(cx)
+ && !self.changes_face_open(cx)
+ && !self.files_face_open(cx)
+ && !self.inspector_face_open(cx)
+ && !self.side_chat_face_open(cx)
+ && !self.terminal_face_open(cx)
+ {
+ self.set_workbar_open(false, window, cx);
+ }
+ }
+
+ /// Shows the files: their face opened, shown, the panel open, and the
+ /// focus on their list.
+ fn show_files(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.set_files_face_open(true, cx);
+ self.set_workbar_face(ToolKind::Files, cx);
+ if !self.workbar_open(cx) {
+ self.set_workbar_open(true, window, cx);
+ }
+ self.sync_files_shown(cx);
+ self.workbar.files.update(cx, |files, cx| files.focus(window, cx));
+ cx.notify();
+ }
+
+ /// Shows the trace: its face opened, shown, the panel open, and the
+ /// focus in it.
+ fn show_inspector(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.set_inspector_face_open(true, cx);
+ self.set_workbar_face(ToolKind::Inspector, cx);
+ if !self.workbar_open(cx) {
+ self.set_workbar_open(true, window, cx);
+ }
+ self.sync_inspector_shown(cx);
+ self.workbar.inspector.update(cx, |inspector, cx| inspector.focus(window, cx));
+ cx.notify();
+ }
+
+ /// ⌘P (Desktop's `toggleTool('files')`): opens the selected task's
+ /// files and focuses them, or hides the panel while it shows them.
+ /// With no task, or behind settings, nothing.
+ pub(crate) fn toggle_files(
+ &mut self,
+ _: &ToggleFiles,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.settings.is_some() || self.selected_task(cx).is_none() {
+ return;
+ }
+ if self.workbar_shown(cx) && self.shown_face(cx) == ToolKind::Files {
+ self.set_workbar_open(false, window, cx);
+ return;
+ }
+ if self.page.is_some() {
+ let selected = self.selected_task(cx);
+ self.leave_page(selected, window, cx);
+ }
+ self.show_files(window, cx);
+ }
+
+ /// Shows the changes: their face opened, shown, and the panel open.
+ pub(super) fn show_changes(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ self.set_changes_face_open(true, cx);
+ self.set_workbar_face(ToolKind::Changes, cx);
+ if !self.workbar_open(cx) {
+ self.set_workbar_open(true, window, cx);
+ } else {
+ self.sync_history_reading(cx);
+ self.refresh_review(window, cx);
+ }
+ }
+
+ /// Opens the selected task's changes, or hides the panel while it shows
+ /// them (the header button, ⌃⇧G, Desktop's `toggleTool('review')`).
+ /// With no task, or while settings cover the window, it does nothing,
+ /// as Desktop's shortcut does without an active Session or behind the
+ /// settings.
+ pub(crate) fn toggle_review(
+ &mut self,
+ _: &ToggleReview,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.settings.is_some() || self.selected_task(cx).is_none() {
+ return;
+ }
+ if self.workbar_shown(cx) && self.shown_face(cx) == ToolKind::Changes {
+ self.set_workbar_open(false, window, cx);
+ return;
+ }
+ if self.page.is_some() {
+ let selected = self.selected_task(cx);
+ self.leave_page(selected, window, cx);
+ }
+ self.show_changes(window, cx);
+ }
+
+ /// Ctrl+`: with the panel hidden or on another face, shows the most
+ /// recently active terminal (starting one when the task has none) and
+ /// focuses it; with a terminal focused, hides the panel, its faces
+ /// kept. With no task, or behind settings, nothing.
+ pub(crate) fn toggle_terminal(
+ &mut self,
+ _: &ToggleTerminal,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.settings.is_some() || self.selected_task(cx).is_none() {
+ return;
+ }
+ let focused = self.workbar.terminal.read(cx).is_focused(window, cx);
+ if focused && self.workbar_shown(cx) {
+ self.set_workbar_open(false, window, cx);
+ self.composer.update(cx, |composer, cx| composer.focus(window, cx));
+ return;
+ }
+ if self.page.is_some() {
+ let selected = self.selected_task(cx);
+ self.leave_page(selected, window, cx);
+ }
+ self.set_workbar_face(ToolKind::Terminal, cx);
+ self.workbar.terminal.update(cx, |view, cx| view.ensure_terminal(cx));
+ if !self.workbar_open(cx) {
+ self.set_workbar_open(true, window, cx);
+ }
+ self.workbar.terminal.update(cx, |view, cx| view.focus(window, cx));
+ cx.notify();
+ }
+
+ /// A tool chosen in the [+] menu: Changes, Files and Trace open or
+ /// close (one face each), Terminal always adds a terminal.
+ fn choose_tool(&mut self, kind: ToolKind, window: &mut Window, cx: &mut Context<Self>) {
+ let definition = tool(kind);
+ match kind {
+ ToolKind::Changes if definition.singleton && self.changes_face_open(cx) => {
+ self.close_face(&Face::Changes, window, cx);
+ }
+ ToolKind::Changes => self.show_changes(window, cx),
+ ToolKind::Files if definition.singleton && self.files_face_open(cx) => {
+ self.close_face(&Face::Files, window, cx);
+ }
+ ToolKind::Files => self.show_files(window, cx),
+ ToolKind::Inspector if definition.singleton && self.inspector_face_open(cx) => {
+ self.close_face(&Face::Inspector, window, cx);
+ }
+ ToolKind::Inspector => self.show_inspector(window, cx),
+ ToolKind::SideChat => {
+ self.new_side_chat(window, cx);
+ }
+ ToolKind::Terminal => {
+ self.set_workbar_face(ToolKind::Terminal, cx);
+ self.workbar.terminal.update(cx, |view, cx| view.new_terminal(cx));
+ self.workbar.terminal.update(cx, |view, cx| view.focus(window, cx));
+ }
+ }
+ cx.notify();
+ }
+
+ /// A tab chosen: its face shows; a terminal's takes the focus.
+ fn activate_face(&mut self, face: &Face, window: &mut Window, cx: &mut Context<Self>) {
+ match face {
+ Face::Changes => {
+ self.set_workbar_face(ToolKind::Changes, cx);
+ self.refresh_review(window, cx);
+ }
+ Face::Files => {
+ self.set_workbar_face(ToolKind::Files, cx);
+ self.sync_files_shown(cx);
+ self.workbar.files.update(cx, |files, cx| files.focus(window, cx));
+ }
+ Face::Inspector => {
+ self.set_workbar_face(ToolKind::Inspector, cx);
+ self.sync_inspector_shown(cx);
+ self.workbar.inspector.update(cx, |inspector, cx| inspector.focus(window, cx));
+ }
+ Face::SideChat(tab) => self.show_side_chat(&tab.id, window, cx),
+ Face::Terminal(tab) => {
+ self.set_workbar_face(ToolKind::Terminal, cx);
+ let resource_ref = tab.resource_ref.clone();
+ self.workbar.terminal.update(cx, |view, cx| {
+ view.activate(&resource_ref, cx);
+ view.focus(window, cx);
+ });
+ }
+ }
+ cx.notify();
+ }
+
+ /// A tab's ×, or unmarking it in [+]: the Changes face closes; a
+ /// terminal stops (no confirmation: the model cannot see what runs in
+ /// it) and its tab goes once the Host confirms. The last face closed
+ /// hides the panel.
+ fn close_face(&mut self, face: &Face, window: &mut Window, cx: &mut Context<Self>) {
+ match face {
+ Face::Changes => {
+ self.set_changes_face_open(false, cx);
+ self.sync_history_reading(cx);
+ self.hide_empty_workbar(window, cx);
+ }
+ Face::Files => {
+ self.set_files_face_open(false, cx);
+ self.hide_empty_workbar(window, cx);
+ }
+ Face::Inspector => {
+ self.set_inspector_face_open(false, cx);
+ self.hide_empty_workbar(window, cx);
+ }
+ Face::SideChat(tab) => self.close_side_chat(&tab.id, window, cx),
+ Face::Terminal(tab) => {
+ let resource_ref = tab.resource_ref.clone();
+ self.workbar.terminal.update(cx, |view, cx| view.close(&resource_ref, cx));
+ }
+ }
+ cx.notify();
+ }
+
+ /// Opens or closes the selected task's panel, remembering it for the
+ /// task; opening reads its changes.
+ pub(super) fn set_workbar_open(
+ &mut self,
+ open: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(id) = self.selected_task(cx) else { return };
+ AppPreferences::global(cx)
+ .update(cx, |preferences, cx| preferences.set_review_open(&id, open, cx));
+ if open {
+ self.sync_review_target(window, cx);
+ self.refresh_review(window, cx);
+ }
+ self.sync_history_reading(cx);
+ cx.notify();
+ }
+
+ /// Points the panel and the context strip at the selected task (its
+ /// folder, or a Host elsewhere), with the base branch remembered for
+ /// it, and reads it if it is a different task (the panel only while it
+ /// shows).
+ pub(super) fn sync_review_target(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let remote = self.host.read(cx).is_remote();
+ let target = self.catalog.read(cx).selected_row().map(|row| {
+ if remote {
+ ReviewTarget::remote(row.id.clone()).with_task_folder(row.workspace_path.as_ref())
+ } else {
+ ReviewTarget::local(row.id.clone(), row.workspace_path.as_ref())
+ }
+ });
+ let panel = self.workbar.panel.clone();
+ self.sync_workbar_maximized(cx);
+ self.sync_files_shown(cx);
+ self.sync_inspector_shown(cx);
+ if panel.read(cx).target() == target.as_ref() {
+ return;
+ }
+ let base = target.as_ref().and_then(|target| {
+ AppPreferences::global(cx).read(cx).review_base_branch(target.session_id())
+ });
+ self.strip.summary.update(cx, |summary, cx| {
+ summary.set_target(target.clone(), base.clone(), cx);
+ });
+ panel.update(cx, |panel, cx| panel.set_target(target, base, window, cx));
+ self.sync_turn_edits(cx);
+ self.sync_history_reading(cx);
+ self.refresh_review(window, cx);
+ }
+
+ /// Whether the changes show: the panel shows, on its Changes face.
+ fn changes_shown(&self, cx: &App) -> bool {
+ self.workbar_shown(cx) && self.shown_face(cx) == ToolKind::Changes
+ }
+
+ /// While the changes show the selected task, has the conversation read
+ /// the task's whole history in the background, so they list every turn
+ /// and not only those of the transcript's tail (the Host has no cheaper
+ /// way: `session.turns.query` and `session.turn_landmarks.query` list
+ /// turns and where they lie, not what their calls edited); and tells
+ /// the panel while earlier turns are being read.
+ fn sync_history_reading(&mut self, cx: &mut Context<Self>) {
+ let followed =
+ self.workbar.panel.read(cx).target().map(|target| target.session_id().clone());
+ let wanted = self.changes_shown(cx)
+ && followed.is_some()
+ && self.state.read(cx).session_id() == followed.as_ref();
+ self.state.update(cx, |state, cx| state.set_whole_history_wanted(wanted, cx));
+ let reading = self.state.read(cx).is_reading_whole_history();
+ self.workbar.panel.update(cx, |panel, cx| panel.set_reading_turns(reading, cx));
+ }
+
+ /// Hands the panel the session's edits when the transcript moved on
+ /// since it last had them (another row, turn, or turn state); the panel
+ /// keeps them only for the task it follows.
+ fn sync_turn_edits(&mut self, cx: &mut Context<Self>) {
+ let changes = self.workbar.panel.read(cx).turn_changes().clone();
+ let (key, edits) = {
+ let state = self.state.read(cx);
+ let Some(transcript) = state.transcript() else { return };
+ let key = EditsKey::of(transcript);
+ if changes.read(cx).key() == Some(&key) {
+ return;
+ }
+ (key, session_edits(transcript))
+ };
+ changes.update(cx, |changes, cx| changes.set_edits(key, edits, cx));
+ }
+
+ /// Shows the selected task's changes on turn `turn_id`'s, at the file
+ /// at `path` when given: the card under the turn.
+ fn show_turn_changes(
+ &mut self,
+ turn_id: SharedString,
+ path: Option<SharedString>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if !self.changes_shown(cx) {
+ self.show_changes(window, cx);
+ }
+ self.workbar.panel.update(cx, |panel, cx| panel.show_turn(turn_id, path, cx));
+ cx.notify();
+ }
+
+ /// Whether the selected task's panel shows filling the plate, in the
+ /// conversation's place: open, shown, and maximized for the task.
+ pub fn workbar_maximized(&self, cx: &App) -> bool {
+ self.workbar_shown(cx) && self.workbar_maximized_for_task(cx)
+ }
+
+ /// Whether the selected task's panel is maximized when it shows.
+ fn workbar_maximized_for_task(&self, cx: &App) -> bool {
+ self.catalog
+ .read(cx)
+ .selected_id()
+ .is_some_and(|id| AppPreferences::global(cx).read(cx).is_review_maximized(id))
+ }
+
+ /// ⇧Esc: the shown panel fills the plate, or gives the conversation its
+ /// place back. With the panel closed it does nothing.
+ pub(crate) fn toggle_workbar_maximized(
+ &mut self,
+ _: &ToggleMaximized,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ if self.workbar_shown(cx) {
+ let maximized = !self.workbar_maximized(cx);
+ self.set_workbar_maximized(maximized, window, cx);
+ }
+ }
+
+ /// Maximizes the selected task's panel or restores it, remembering it
+ /// for the task. Maximizing moves focus into the face it shows, as the
+ /// conversation and the composer leave the window (their state stays:
+ /// they are only not drawn).
+ pub(crate) fn set_workbar_maximized(
+ &mut self,
+ maximized: bool,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let Some(id) = self.selected_task(cx) else { return };
+ AppPreferences::global(cx)
+ .update(cx, |preferences, cx| preferences.set_review_maximized(&id, maximized, cx));
+ self.sync_workbar_maximized(cx);
+ if maximized {
+ self.focus_workbar_face(window, cx);
+ }
+ cx.notify();
+ }
+
+ /// Gives the face the panel shows the focus: the changes' file list, or
+ /// the terminal.
+ pub(super) fn focus_workbar_face(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ match self.shown_face(cx) {
+ ToolKind::Changes => {
+ self.workbar.panel.update(cx, |panel, cx| panel.focus_files(window, cx));
+ }
+ ToolKind::Files => {
+ self.workbar.files.update(cx, |files, cx| files.focus(window, cx));
+ }
+ ToolKind::Inspector => {
+ self.workbar.inspector.update(cx, |inspector, cx| inspector.focus(window, cx));
+ }
+ ToolKind::SideChat => self.focus_side_chat(window, cx),
+ ToolKind::Terminal => {
+ self.workbar.terminal.update(cx, |view, cx| view.focus(window, cx));
+ }
+ }
+ }
+
+ /// Tells the changes whether the panel is maximized, for Esc.
+ fn sync_workbar_maximized(&mut self, cx: &mut Context<Self>) {
+ let maximized = self.workbar_maximized_for_task(cx);
+ self.workbar.panel.update(cx, |panel, cx| panel.set_maximized(maximized, cx));
+ }
+
+ /// Gives the conversation its place back, for a command that needs the
+ /// composer.
+ pub(super) fn restore_workbar(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.workbar_maximized(cx) {
+ self.set_workbar_maximized(false, window, cx);
+ }
+ }
+
+ /// Reads the changes again while they show, and the context strip's,
+ /// unless the changes' read of All changes gives them.
+ fn refresh_review(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ if self.changes_shown(cx) {
+ self.workbar.panel.update(cx, |panel, cx| panel.refresh(window, cx));
+ }
+ if !self.review_feeds_strip(cx) {
+ self.strip.summary.update(cx, |summary, cx| summary.refresh(cx));
+ }
+ }
+
+ /// Whether the changes' reads tell the context strip its counts: while
+ /// they show All changes.
+ fn review_feeds_strip(&self, cx: &App) -> bool {
+ self.changes_shown(cx) && *self.workbar.panel.read(cx).scope() == ReviewScope::All
+ }
+
+ /// The header's button for the changes: Desktop's `file-diff` glyph,
+ /// pressed while the panel shows them, named and tipped with its
+ /// shortcut.
+ pub(super) fn render_review_button(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
+ self.catalog.read(cx).selected_id()?;
+ let label = review_copy::CHANGES.get(cx);
+ let shown = self.workbar_open(cx) && self.shown_face(cx) == ToolKind::Changes;
+ Some(
+ Button::new("review-toggle")
+ .ghost()
+ .small()
+ .size_7()
+ .flex_shrink_0()
+ .icon(Icon::new(MakaIcon::FileDiff).size_4().text_color(cx.maka().ink_muted))
+ .accessibility_label(label)
+ .tooltip_with_action(label, &ToggleReview, None)
+ .selected(shown)
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.toggle_review(&ToggleReview, window, cx);
+ }))
+ .into_any_element(),
+ )
+ }
+
+ // Rendering.
+
+ /// The panel filling the plate below its header, in the conversation's
+ /// and the composer's place.
+ pub(super) fn render_workbar_maximized(
+ &self,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> AnyElement {
+ div().flex_1().min_h_0().w_full().child(self.render_workbar(window, cx)).into_any_element()
+ }
+
+ /// The panel: the strip of tabs over the face it shows, on its own
+ /// plate wherever it sits.
+ fn render_workbar(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
+ let face: AnyElement = match self.shown_face(cx) {
+ ToolKind::Changes => self.workbar.panel.clone().into_any_element(),
+ ToolKind::Files => self.workbar.files.clone().into_any_element(),
+ ToolKind::Inspector => self.workbar.inspector.clone().into_any_element(),
+ ToolKind::SideChat => match self.shown_side_chat_panel(cx) {
+ Some(panel) => panel.into_any_element(),
+ None => Empty.into_any_element(),
+ },
+ ToolKind::Terminal => self.workbar.terminal.clone().into_any_element(),
+ };
+ v_flex()
+ .id("workbar-pane")
+ .test_support()
+ .role(Role::Region)
+ .aria_label(copy::WORKBAR.get(cx))
+ .size_full()
+ .min_w_0()
+ .bg(cx.maka().plate)
+ .rounded(RADIUS_MODAL)
+ .text_color(cx.maka().ink)
+ .child(self.render_strip(window, cx))
+ .child(div().flex_1().min_h_0().w_full().child(face))
+ .into_any_element()
+ }
+
+ /// Whether the strip is too narrow for every tab's label at
+ /// `available` wide: then the inactive tabs drop theirs.
+ fn strip_overflows(
+ &self,
+ faces: &[Face],
+ available: Pixels,
+ window: &Window,
+ cx: &App,
+ ) -> bool {
+ if available <= Pixels::ZERO {
+ return false;
+ }
+ let rem = window.rem_size();
+ let font_size = rem * BODY_TEXT_REMS;
+ let font = gpui_kit::font(gpui_kit::component::ActiveTheme::theme(cx).font_family.clone());
+ let mut needed = Pixels::ZERO;
+ for face in faces {
+ let name = face.name(cx);
+ let run = TextRun {
+ len: name.len(),
+ font: font.clone(),
+ color: cx.maka().ink,
+ background_color: None,
+ underline: None,
+ strikethrough: None,
+ };
+ let label = window.text_system().layout_line(name.as_ref(), font_size, &[run], None);
+ let marks = match face {
+ Face::Terminal(tab) => usize::from(tab.bell) + usize::from(tab.exited),
+ Face::Changes | Face::Files | Face::Inspector | Face::SideChat(_) => 0,
+ };
+ needed += label.width.min(rem * TAB_LABEL_MAX_REMS)
+ + rem
+ * (TAB_LEADING_REMS
+ + TAB_ICON_REMS
+ + TAB_GAP_REMS * (2. + marks as f32)
+ + TAB_MARK_REMS * marks as f32
+ + TAB_CLOSE_REMS
+ + TAB_TRAILING_REMS
+ + TABS_GAP_REMS);
+ }
+ // The [+] button after the tabs.
+ needed += rem * (ICON_BUTTON_REMS + TABS_GAP_REMS);
+ needed > available
+ }
+
+ /// The strip: a tab per open face, then [+]; maximize and close at its
+ /// end. Tabs keep their order; when they overflow, the inactive ones
+ /// drop their labels (the name in a tooltip) and the active one keeps
+ /// it. No horizontal scrolling.
+ fn render_strip(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
+ let maka = cx.maka();
+ let faces = self.faces(cx);
+ let shown = self.shown_face(cx);
+ let active_terminal = self.workbar.terminal.read(cx).active_ref(cx);
+ let compact = self.strip_overflows(&faces, self.workbar.tabs_width.get(), window, cx);
+ let maximized = self.workbar_maximized_for_task(cx);
+ let (maximize, glyph) = if maximized {
+ (review_copy::RESTORE_SPLIT.get(cx), AssetIcon::Minimize2)
+ } else {
+ (copy::MAXIMIZE.get(cx), AssetIcon::Maximize2)
+ };
+ let close = review_copy::CLOSE_PANEL.get(cx);
+ let icon = |glyph: Icon| glyph.size_4().text_color(maka.ink_muted);
+ let bar_button =
+ |id: &'static str| Button::new(id).ghost().small().size_7().flex_shrink_0();
+ let tabs: Vec<AnyElement> = faces
+ .iter()
+ .map(|face| {
+ let active = match face {
+ Face::Changes => shown == ToolKind::Changes,
+ Face::Files => shown == ToolKind::Files,
+ Face::Inspector => shown == ToolKind::Inspector,
+ Face::SideChat(tab) => {
+ shown == ToolKind::SideChat
+ && self.shown_side_chat_id(cx).as_ref() == Some(&tab.id)
+ }
+ Face::Terminal(tab) => {
+ shown == ToolKind::Terminal
+ && active_terminal.as_ref() == Some(&tab.resource_ref)
+ }
+ };
+ self.render_tab(face, active, compact && !active, cx)
+ })
+ .collect();
+ let add = self.workbar.add_menu.is_open();
+ let tabs_width = self.workbar.tabs_width.clone();
+ let workbench = cx.entity().downgrade();
+ // The probe measures the room the tabs have each frame and draws the
+ // strip again when it changed.
+ let probe = canvas(
+ move |bounds, _, cx| {
+ if tabs_width.replace(bounds.size.width) != bounds.size.width {
+ let workbench = workbench.clone();
+ cx.defer(move |cx| {
+ workbench.update(cx, |_, cx| cx.notify()).ok();
+ });
+ }
+ },
+ |_, _, _, _| {},
+ )
+ .absolute()
+ .top_0()
+ .left_0()
+ .size_full();
+ // The close button puts its glyph's ink on the plate's 16 px line;
+ // the first tab's fill sits half way, 8 px in, so its icon lands on
+ // the line too.
+ let trailing = ink_padding(PLATE_LINE_REMS, ICON_BUTTON_REMS, ICON_GLYPH_REMS, ink::CLOSE);
+ h_flex()
+ .id("workbar-strip")
+ .test_support()
+ .h(rems(STRIP_HEIGHT_REMS))
+ .flex_shrink_0()
+ .w_full()
+ .pl_2()
+ .pr(rems(trailing))
+ .gap_1()
+ .border_b_1()
+ .border_color(maka.border_soft)
+ .child(
+ h_flex()
+ .id("workbar-tabs")
+ .test_support()
+ .role(Role::TabList)
+ .aria_label(copy::TABS.get(cx))
+ .relative()
+ .flex_1()
+ .min_w_0()
+ .overflow_hidden()
+ .gap(rems(TABS_GAP_REMS))
+ .child(probe)
+ .children(tabs)
+ .child(
+ div()
+ .relative()
+ .flex_shrink_0()
+ .child(
+ bar_button("workbar-add")
+ .icon(icon(Icon::new(MakaIcon::Plus)))
+ .accessibility_label(copy::ADD_PANEL.get(cx))
+ .tooltip(copy::ADD_PANEL.get(cx))
+ .selected(add)
+ .on_click(cx.listener(
+ |this, event: &ClickEvent, window, cx| {
+ let width = window.rem_size() * ADD_MENU_WIDTH_REMS;
+ MenuSlot::toggle(
+ this,
+ |this| &mut this.workbar.add_menu,
+ event,
+ |this, cx| this.add_menu_entries(cx),
+ width,
+ window,
+ cx,
+ );
+ },
+ )),
+ )
+ .children(self.workbar.add_menu.layer()),
+ ),
+ )
+ .child(
+ bar_button("workbar-maximize")
+ .icon(icon(Icon::new(glyph)))
+ .accessibility_label(maximize)
+ .tooltip_with_action(maximize, &ToggleMaximized, None)
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.set_workbar_maximized(!maximized, window, cx);
+ })),
+ )
+ .child(
+ bar_button("workbar-close")
+ .icon(icon(Icon::new(MakaIcon::Close)))
+ .accessibility_label(close)
+ .tooltip(close)
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.set_workbar_open(false, window, cx);
+ })),
+ )
+ .into_any_element()
+ }
+
+ /// The [+] menu: every tool, the open ones checked, with its shortcut
+ /// when it has one.
+ fn add_menu_entries(&self, cx: &mut Context<Self>) -> Vec<MenuEntry> {
+ let workbench = cx.entity().downgrade();
+ TOOLS
+ .iter()
+ .map(|tool| {
+ let open = match tool.kind {
+ ToolKind::Changes => self.changes_face_open(cx),
+ ToolKind::Files => self.files_face_open(cx),
+ ToolKind::Inspector => self.inspector_face_open(cx),
+ ToolKind::SideChat => self.side_chat_face_open(cx),
+ ToolKind::Terminal => self.workbar.terminal.read(cx).has_terminals(cx),
+ };
+ let kind = tool.kind;
+ let workbench = workbench.clone();
+ let key = match kind {
+ ToolKind::Changes => "workbar-tool-changes",
+ ToolKind::Files => "workbar-tool-files",
+ ToolKind::Inspector => "workbar-tool-inspector",
+ ToolKind::SideChat => "workbar-tool-side-chat",
+ ToolKind::Terminal => "workbar-tool-terminal",
+ };
+ let mut item =
+ MenuItem::new(key, tool.label.get(cx)).icon(Icon::new(tool.icon)).checked(open);
+ if let Some(shortcut) = tool.shortcut {
+ item = item.shortcut(shortcut());
+ }
+ item.on_select(move |window, cx| {
+ workbench.update(cx, |this, cx| this.choose_tool(kind, window, cx)).ok();
+ })
+ .into()
+ })
+ .collect()
+ }
+
+ /// A face's tab: its icon and name (a terminal's title, its bell and
+ /// exited marks), the selected fill while it shows; its × while it is
+ /// active or under the pointer, which does what unmarking it in [+]
+ /// does. A terminal being closed shows a spinner there; one whose close
+ /// failed, a way to close it again. `bare` drops the label (the strip
+ /// overflows), the name then in a tooltip.
+ fn render_tab(
+ &self,
+ face: &Face,
+ active: bool,
+ bare: bool,
+ cx: &mut Context<Self>,
+ ) -> AnyElement {
+ let maka = cx.maka();
+ let locale = Locale::current(cx);
+ let key = face.key();
+ let name = face.name(cx);
+ let group: SharedString = format!("workbar-tab-{key}").into();
+ let (bell, exited, close_state) = match face {
+ Face::Terminal(tab) => (tab.bell, tab.exited, tab.close.clone()),
+ Face::Changes | Face::Files | Face::Inspector | Face::SideChat(_) => {
+ (false, false, CloseState::Open)
+ }
+ };
+ let mut spoken = vec![name.to_string()];
+ if bell {
+ spoken.push(terminal_copy::BELL.get(cx).to_owned());
+ }
+ if exited {
+ spoken.push(terminal_copy::EXITED.get(cx).to_owned());
+ }
+ if close_state == CloseState::Closing {
+ spoken.push(terminal_copy::CLOSING.get(cx).to_owned());
+ }
+ let spoken: SharedString =
+ shell_copy::parts(locale, &spoken.iter().map(String::as_str).collect::<Vec<_>>())
+ .into();
+ let transparent = |cx: &App| {
+ ButtonCustomVariant::new(cx)
+ .color(Hsla::transparent_black())
+ .foreground(maka.ink)
+ .hover(Hsla::transparent_black())
+ .active(Hsla::transparent_black())
+ .shadow(false)
+ };
+ let tint = if active { maka.ink } else { maka.ink_muted };
+ let face_for_click = face.clone();
+ let main = Button::new(domain_element_id("workbar-tab-button", &key))
+ .custom(transparent(cx))
+ .small()
+ .h_7()
+ .pl(rems(TAB_LEADING_REMS))
+ .pr_0p5()
+ .gap(rems(TAB_GAP_REMS))
+ .role(Role::Tab)
+ .selected(active)
+ .accessibility_label(spoken.clone())
+ .when(bare, |this| this.tooltip(name.clone()))
+ .child(Icon::new(tool(face.kind()).icon).size_4().flex_none().text_color(tint))
+ .when(!bare, |this| {
+ this.child(
+ div()
+ .id(domain_element_id("workbar-tab-label", &key))
+ .test_support()
+ .text_sm()
+ .when(active, |this| this.font_medium())
+ .text_color(tint)
+ .max_w(rems(TAB_LABEL_MAX_REMS))
+ .truncate()
+ .child(name.clone()),
+ )
+ })
+ .when(bell, |this| {
+ this.child(
+ div()
+ .id(domain_element_id("workbar-tab-bell", &key))
+ .test_support()
+ .flex_none()
+ .child(Icon::new(AssetIcon::Bell).size_3().text_color(maka.ink_muted)),
+ )
+ })
+ .when(exited, |this| {
+ this.child(
+ div()
+ .id(domain_element_id("workbar-tab-exited", &key))
+ .test_support()
+ .flex_none()
+ .child(
+ Icon::new(MakaIcon::StatusStopped).size_3().text_color(maka.ink_muted),
+ ),
+ )
+ })
+ .on_click(cx.listener(move |this, _, window, cx| {
+ this.activate_face(&face_for_click, window, cx);
+ }));
+ let trailing: AnyElement = match &close_state {
+ CloseState::Closing => div()
+ .id(domain_element_id("workbar-tab-closing", &key))
+ .test_support()
+ .size(rems(TAB_CLOSE_REMS))
+ .flex_none()
+ .flex()
+ .items_center()
+ .justify_center()
+ .child(Spinner::new().xsmall().color(maka.ink_muted))
+ .into_any_element(),
+ CloseState::Failed(reason) => {
+ let face = face.clone();
+ let label = shell_copy::sentences(
+ locale,
+ terminal_copy::CLOSE_FAILED.get(cx),
+ terminal_copy::RETRY_CLOSE.get(cx),
+ );
+ let tooltip =
+ shell_copy::failure(locale, terminal_copy::CLOSE_FAILED.get(cx), reason);
+ Button::new(domain_element_id("workbar-tab-retry-close", &key))
+ .custom(transparent(cx))
+ .xsmall()
+ .size(rems(TAB_CLOSE_REMS))
+ .flex_none()
+ .icon(Icon::new(MakaIcon::StatusFailed).size_3p5().text_color(maka.destructive))
+ .accessibility_label(label)
+ .tooltip(tooltip)
+ .on_click(cx.listener(move |this, _, window, cx| {
+ cx.stop_propagation();
+ this.close_face(&face, window, cx);
+ }))
+ .into_any_element()
+ }
+ _ => {
+ let face = face.clone();
+ let label = copy::close_tab(locale, &name);
+ Button::new(domain_element_id("workbar-tab-close", &key))
+ .custom(
+ ButtonCustomVariant::new(cx)
+ .color(Hsla::transparent_black())
+ .foreground(maka.ink_muted)
+ .hover(maka.wash)
+ .active(maka.selected)
+ .shadow(false),
+ )
+ .xsmall()
+ .size(rems(TAB_CLOSE_REMS))
+ .flex_none()
+ .icon(Icon::new(MakaIcon::Close).size_3p5())
+ .accessibility_label(label)
+ .when(!active, |this| {
+ this.invisible().group_hover(group.clone(), |this| this.visible())
+ })
+ .on_click(cx.listener(move |this, _, window, cx| {
+ cx.stop_propagation();
+ this.close_face(&face, window, cx);
+ }))
+ .into_any_element()
+ }
+ };
+ let tab = h_flex()
+ .id(domain_element_id("workbar-tab", &key))
+ .test_support()
+ .aria_label(spoken)
+ .group(group.clone())
+ .flex_shrink_0()
+ .h_7()
+ .pr(rems(TAB_TRAILING_REMS))
+ .rounded(RADIUS_CONTROL)
+ .child(main)
+ .child(trailing);
+ selectable_row(tab, active, cx).into_any_element()
+ }
+
+ /// The panel's own plate.
+ fn render_workbar_plate(&self, window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
+ div().size_full().min_w_0().child(self.render_workbar(window, cx)).into_any_element()
+ }
+
+ /// `main` (the plate) with the panel beside it or below it.
+ pub(super) fn with_workbar(
+ &self,
+ main: AnyElement,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> AnyElement {
+ let gap = rems(PLATE_INSET_REMS);
+ match self.workbar_placement(cx) {
+ WorkbarPlacement::Beside(width) => h_flex()
+ .size_full()
+ .items_stretch()
+ .child(div().flex_1().min_w_0().h_full().child(main))
+ .child(
+ div()
+ .w(gap)
+ .h_full()
+ .flex_shrink_0()
+ .relative()
+ .child(self.render_workbar_handle(window, cx)),
+ )
+ .child(
+ div()
+ .w(rems(width))
+ .h_full()
+ .flex_shrink_0()
+ .child(self.render_workbar_plate(window, cx)),
+ )
+ .into_any_element(),
+ WorkbarPlacement::Below => {
+ let rem = window.rem_size();
+ let height = (window.viewport_size().height / rem * BELOW_HEIGHT_SHARE)
+ .min(BELOW_MAX_HEIGHT_REMS);
+ v_flex()
+ .size_full()
+ .child(div().flex_1().min_h_0().w_full().child(main))
+ .child(div().h(gap).flex_shrink_0())
+ .child(
+ div()
+ .h(rems(height))
+ .w_full()
+ .flex_shrink_0()
+ .child(self.render_workbar_plate(window, cx)),
+ )
+ .into_any_element()
+ }
+ }
+ }
+
+ /// The handle on the panel's edge, in the gap between the plates, as
+ /// the sidebar's: a 6 px hit area below the chrome band with the
+ /// column-resize cursor, Desktop's grip on hover, focus or drag. A drag
+ /// moves the edge from the narrowest width to what leaves the
+ /// conversation its least; a double-click restores the default.
+ /// Focused, Left and Right move the edge by 10 (Shift: 50), Enter
+ /// restores it.
+ fn render_workbar_handle(&self, window: &Window, cx: &mut Context<Self>) -> AnyElement {
+ let maka = cx.maka();
+ let dragging = self.workbar.resizing && cx.has_active_drag();
+ let keyboard =
+ self.workbar.resize_focus.is_focused(window) && window.last_input_was_keyboard();
+ let pill = div()
+ .w(px(3.))
+ .h(rems(2.))
+ .rounded_full()
+ .bg(if dragging { maka.border_strong } else { maka.border })
+ .when(!dragging && !keyboard, |this| {
+ this.invisible().group_hover("workbar-resize", |this| this.visible())
+ });
+ div()
+ .id("workbar-resize")
+ .test_support()
+ .role(Role::Splitter)
+ .aria_label(review_copy::RESIZE_PANEL.get(cx))
+ .track_focus(&self.workbar.resize_focus)
+ .key_context(WORKBAR_RESIZE_CONTEXT)
+ .on_action(cx.listener(|this, _: &WidenWorkbarStep, window, cx| {
+ this.step_workbar_width(RESIZE_STEP, window, cx);
+ }))
+ .on_action(cx.listener(|this, _: &NarrowWorkbarStep, window, cx| {
+ this.step_workbar_width(-RESIZE_STEP, window, cx);
+ }))
+ .on_action(cx.listener(|this, _: &WidenWorkbarLargeStep, window, cx| {
+ this.step_workbar_width(RESIZE_LARGE_STEP, window, cx);
+ }))
+ .on_action(cx.listener(|this, _: &NarrowWorkbarLargeStep, window, cx| {
+ this.step_workbar_width(-RESIZE_LARGE_STEP, window, cx);
+ }))
+ .on_action(cx.listener(|this, _: &ResetWorkbarWidth, window, cx| {
+ this.set_workbar_width(DEFAULT_REVIEW_WIDTH, window, cx);
+ }))
+ .absolute()
+ .top(rems(super::CHROME_HEIGHT_REMS))
+ .bottom_0()
+ .left(window.rem_size() * (PLATE_INSET_REMS / 2.) - px(RESIZE_HANDLE_WIDTH / 2.))
+ .w(px(RESIZE_HANDLE_WIDTH))
+ .flex()
+ .items_center()
+ .justify_center()
+ .group("workbar-resize")
+ .cursor_col_resize()
+ .when(keyboard, |this| this.focus_ring_style(window, cx))
+ .on_drag(WorkbarResize, |drag, _, _, cx| cx.new(|_| *drag))
+ .on_click(cx.listener(|this, event: &ClickEvent, window, cx| {
+ if event.click_count() >= 2 {
+ this.set_workbar_width(DEFAULT_REVIEW_WIDTH, window, cx);
+ }
+ }))
+ .child(pill)
+ .into_any_element()
+ }
+
+ /// A drag of the panel's edge to the pointer, which holds the handle in
+ /// the middle of the gap between the plates.
+ pub(super) fn drag_workbar_edge(
+ &mut self,
+ event: &DragMoveEvent<WorkbarResize>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) {
+ let rem = window.rem_size();
+ let right = window.viewport_size().width - rem * PLATE_INSET_REMS;
+ let edge = event.event.position.x + rem * (PLATE_INSET_REMS / 2.);
+ let width = ((right - edge) / rem * DESIGN_PX_PER_REM).round().max(0.);
+ self.workbar.resizing = true;
+ // Within u16 once clamped.
+ let width = width.min(f32::from(u16::MAX)) as u16;
+ self.set_workbar_width(width, window, cx);
+ cx.notify();
+ }
+
+ /// A drag of the edge ended.
+ pub(super) fn end_workbar_drag(&mut self, cx: &mut Context<Self>) {
+ if std::mem::take(&mut self.workbar.resizing) {
+ cx.notify();
+ }
+ }
+
+ /// Moves the edge by `step` of the preferences' pixels; a positive
+ /// step widens the panel.
+ fn step_workbar_width(&mut self, step: i32, window: &Window, cx: &mut Context<Self>) {
+ let width = (i32::from(self.workbar.width) + step).clamp(0, i32::from(u16::MAX));
+ // Within u16 once clamped.
+ self.set_workbar_width(width as u16, window, cx);
+ }
+
+ /// Sets the panel's width, from its narrowest to what leaves the
+ /// conversation its least width beside it, and saves it once it has
+ /// stayed a moment.
+ pub fn set_workbar_width(&mut self, width: u16, window: &Window, cx: &mut Context<Self>) {
+ let rem = window.rem_size();
+ let column = self.form_rems(self.shown_form, cx);
+ let room =
+ window.viewport_size().width / rem - column - PLATE_LEAST_REMS - PLATE_INSET_REMS;
+ let room = (room * DESIGN_PX_PER_REM).floor().clamp(0., f32::from(u16::MAX));
+ // Within u16 once clamped.
+ let width = clamp_review_width(width.min(room as u16));
+ if width == self.workbar.width {
+ return;
+ }
+ self.workbar.width = width;
+ cx.notify();
+ self.workbar._save_width = Some(cx.spawn(async move |this, cx| {
+ cx.background_executor().timer(WIDTH_SAVE_DELAY).await;
+ this.update(cx, |this, cx| {
+ let width = this.workbar.width;
+ AppPreferences::global(cx)
+ .update(cx, |preferences, cx| preferences.set_review_width(width, cx));
+ })
+ .ok();
+ }));
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// At the default font: the plate with the composer's column takes 49
+ /// rems (784 px), with the least conversation 26 (400 px), the gap
+ /// 0.5; both count the plate's margins.
+ #[test]
+ fn the_panel_goes_below_when_the_plate_would_lose_the_composers_width() {
+ // A 1440 px window beside a 256 px sidebar: the panel takes its
+ // 30 rems, up to the 47.5 that leave a 400 px conversation.
+ assert_eq!(WorkbarPlacement::of(90., 16., 480), WorkbarPlacement::Beside(30.));
+ assert_eq!(WorkbarPlacement::of(90., 16., 1200), WorkbarPlacement::Beside(47.5));
+ assert_eq!(WorkbarPlacement::of(120., 16., 1200), WorkbarPlacement::Beside(75.));
+ // Less room than the narrowest 340 px (21.25 rems) beside the
+ // composer's column: below.
+ assert_eq!(WorkbarPlacement::of(85., 16., 480), WorkbarPlacement::Below);
+ // A collapsed sidebar gives the panel its room back.
+ assert_eq!(WorkbarPlacement::of(85., 0., 480), WorkbarPlacement::Beside(30.));
+ }
+
+ #[test]
+ fn the_registry_lists_changes_files_trace_side_chat_then_terminal() {
+ let kinds: Vec<ToolKind> = TOOLS.iter().map(|tool| tool.kind).collect();
+ assert_eq!(
+ kinds,
+ [
+ ToolKind::Changes,
+ ToolKind::Files,
+ ToolKind::Inspector,
+ ToolKind::SideChat,
+ ToolKind::Terminal
+ ]
+ );
+ let shortcut = |kind| tool(kind).shortcut.map(|shortcut| shortcut().name());
+ assert!(tool(ToolKind::Changes).persisted && tool(ToolKind::Changes).singleton);
+ assert!(tool(ToolKind::Files).persisted && tool(ToolKind::Files).singleton);
+ assert_eq!(tool(ToolKind::Files).icon, MakaIcon::Folder);
+ assert_eq!(shortcut(ToolKind::Files), Some(ToggleFiles.name()));
+ // Desktop's `inspector`: persisted, one face, the activity glyph,
+ // no shortcut.
+ assert!(tool(ToolKind::Inspector).persisted && tool(ToolKind::Inspector).singleton);
+ assert_eq!(tool(ToolKind::Inspector).icon, MakaIcon::Activity);
+ assert_eq!(shortcut(ToolKind::Inspector), None);
+ // Desktop's `side-chat`: not persisted, several faces, ⌥⌘S.
+ assert!(!tool(ToolKind::SideChat).persisted && !tool(ToolKind::SideChat).singleton);
+ assert_eq!(tool(ToolKind::SideChat).icon, MakaIcon::Chat);
+ assert_eq!(shortcut(ToolKind::SideChat), Some(ToggleSideChat.name()));
+ assert!(!tool(ToolKind::Terminal).persisted && !tool(ToolKind::Terminal).singleton);
+ assert_eq!(tool(ToolKind::Terminal).icon, MakaIcon::ToolTerminal);
+ assert_eq!(shortcut(ToolKind::Changes), Some(ToggleReview.name()));
+ }
+}
diff --git a/apps/desktop-gpui/crates/automations/src/review.rs b/apps/desktop-gpui/crates/automations/src/review.rs
index 210f6d923d..ff8166a2c7 100644
--- a/apps/desktop-gpui/crates/automations/src/review.rs
+++ b/apps/desktop-gpui/crates/automations/src/review.rs
@@ -53,6 +53,7 @@ use host_protocol::{
use shared::copy::automations as copy;
use shared::copy::{self as shell_copy, Locale, Text};
use shared::domain_element_id;
+use shared::links::follow_link;
use shared::rows::{EmptyRow, list_row};
use shared::theme::{
ActiveMakaPalette as _, HEADING_LINE_REMS, HEADING_TEXT_REMS, RADIUS_SURFACE, back_link,
@@ -942,6 +943,7 @@ impl DailyReviewView {
// paragraph gap; the review keeps 1rem.
.style(TextViewStyle::default().paragraph_gap(rems(1.)))
.selectable(true)
+ .on_link_click(|href, event, _, cx| follow_link(href, event, cx))
.w_full()
.text_sm()
.line_height(relative(22. / 14.))
diff --git a/apps/desktop-gpui/crates/conversation/Cargo.toml b/apps/desktop-gpui/crates/conversation/Cargo.toml
index e465bd158e..5007ccc1c4 100644
--- a/apps/desktop-gpui/crates/conversation/Cargo.toml
+++ b/apps/desktop-gpui/crates/conversation/Cargo.toml
@@ -26,10 +26,15 @@ publish.workspace = true
[dependencies]
async-channel.workspace = true
+blocking.workspace = true
+futures-lite.workspace = true
gpui-kit.workspace = true
host-protocol.workspace = true
image.workspace = true
log.workspace = true
+markdown.workspace = true
+search.workspace = true
+serde.workspace = true
serde_json.workspace = true
shared.workspace = true
transcript-model.workspace = true
@@ -38,7 +43,6 @@ workspace.workspace = true
[dev-dependencies]
base64.workspace = true
-futures-lite.workspace = true
gpui-kit = { workspace = true, features = ["test-support"] }
host-client.workspace = true
diff --git a/apps/desktop-gpui/crates/conversation/src/composer.rs b/apps/desktop-gpui/crates/conversation/src/composer.rs
index e071e227bf..3c11b0dcc6 100644
--- a/apps/desktop-gpui/crates/conversation/src/composer.rs
+++ b/apps/desktop-gpui/crates/conversation/src/composer.rs
@@ -52,6 +52,7 @@ use workspace::{
use crate::attachments::{self, AttachmentSource, PickRefusal, PickedFile};
use crate::queue::QueuePlate;
+use crate::side_chat::SideChat;
use crate::state::{ConversationState, TurnActivity, new_session_id};
use crate::style::{
BODY_SIZE, COLUMN_GUTTER, LABEL_SIZE, RADIUS_CHAT, RADIUS_CONTROL, RADIUS_SURFACE,
@@ -181,11 +182,20 @@ pub enum ComposerAction {
/// the text and files on screen belong to the task shown, and come back
/// when it shows again.
///
+/// A side chat's composer ([`Self::for_side_chat`]) sends through its
+/// [`SideChat`], which makes the fork on the first send. It has one draft
+/// (the side chat's), the quotes staged for the next message as chips
+/// above it, the model as a read-only chip (the fork runs its task's), the
+/// permission mode picker (before the fork exists, the mode it starts
+/// with), and no project chip.
+///
/// Keyboard: Tab goes from the draft to the model and permission mode
/// pickers (once the settings are read) and then to the round button.
pub struct Composer {
draft: Entity<TextareaState>,
state: Entity<ConversationState>,
+ /// The side chat this composer sends for, when it is one's.
+ side: Option<Entity<SideChat>>,
queue: Entity<QueuePlate>,
/// Files picked, pasted, or dropped for the next message, in that
/// order.
@@ -303,6 +313,7 @@ impl Composer {
let mut this = Self {
draft,
state,
+ side: None,
queue,
attachments: Vec::new(),
draft_key,
@@ -332,6 +343,28 @@ impl Composer {
this
}
+ /// A side chat's composer: it sends through `chat`, whose fork it
+ /// shows once made.
+ pub fn for_side_chat(
+ chat: Entity<SideChat>,
+ connections: Entity<ConnectionCatalog>,
+ projects: Entity<ProjectSelection>,
+ window: &mut Window,
+ cx: &mut Context<Self>,
+ ) -> Self {
+ let state = chat.read(cx).state().clone();
+ let mut this = Self::new(state, connections, projects, window, cx);
+ this.draft_key = None;
+ this._subscriptions.push(cx.observe(&chat, |_, _, cx| cx.notify()));
+ this.side = Some(chat);
+ this
+ }
+
+ /// The side chat it sends for, when it is one's.
+ pub fn side_chat(&self) -> Option<&Entity<SideChat>> {
+ self.side.as_ref()
+ }
+
/// Reads the permission mode the Host starts a new task in
/// (`runtime.policy.query`, `chatDefaults.permissionMode`), which the
/// new task's picker shows until the person picks one. A failed read
@@ -362,6 +395,10 @@ impl Composer {
/// Puts the draft of the task now shown on screen, keeping the one it
/// replaces for when its task shows again (Desktop's per-task drafts).
fn sync_draft_key(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ // A side chat has one draft, the fork's from its first send on.
+ if self.side.is_some() {
+ return;
+ }
let key = self.state.read(cx).session_id().cloned();
if key == self.draft_key {
return;
@@ -634,9 +671,11 @@ impl Composer {
}
}
- /// Nothing to send: no text and no attachment.
+ /// Nothing to send: no text, no attachment, and (in a side chat) no
+ /// staged quote, which a message may carry alone.
fn draft_is_empty(&self, cx: &App) -> bool {
- self.attachments.is_empty() && self.draft.read(cx).value().trim().is_empty()
+ let quoted = self.side.as_ref().is_some_and(|side| !side.read(cx).quotes().is_empty());
+ !quoted && self.attachments.is_empty() && self.draft.read(cx).value().trim().is_empty()
}
fn selected_session(&self, cx: &gpui_kit::App) -> Option<SharedString> {
@@ -654,6 +693,12 @@ impl Composer {
if self.sending || !state.host().read(cx).is_connected() || self.draft_is_empty(cx) {
return false;
}
+ if let Some(side) = &self.side {
+ let side = side.read(cx);
+ if side.is_creating() || side.is_disposed() {
+ return false;
+ }
+ }
match state.session_id() {
Some(_) => !state.is_submitting() && state.turn_activity().is_sendable(),
None => !state.is_starting(),
@@ -685,6 +730,12 @@ impl Composer {
let text = self.draft.read(cx).value().trim_end().to_owned();
let files = self.attachments.clone();
let accepted = match self.selected_session(cx) {
+ _ if self.side.is_some() => {
+ let list = self.connections.read(cx).list().cloned();
+ let (text, files) = (text.clone(), files.clone());
+ let side = self.side.clone().expect("a side chat");
+ side.update(cx, |side, cx| side.send(text, files, placement, list.as_ref(), cx))
+ }
Some(session_id) if files.is_empty() => {
let content = MessageContent::text(text.clone());
self.state
@@ -1020,6 +1071,15 @@ impl Composer {
/// for the session's own mode or while another settings change is in
/// flight. No confirmation: a mode is switched back just as easily.
pub fn select_permission_mode(&mut self, mode: PermissionMode, cx: &mut Context<Self>) {
+ if let Some(side) = self.side.clone()
+ && self.selected_session(cx).is_none()
+ {
+ // The mode the fork starts with, set on it before its first
+ // message runs.
+ side.update(cx, |side, cx| side.stage_permission_mode(mode, cx));
+ cx.notify();
+ return;
+ }
if self.selected_session(cx).is_none() {
// The new task's, sent when it is created.
self.draft_mode = Some(mode);
@@ -1246,6 +1306,9 @@ impl Composer {
/// mode unless one is picked. Offline, Desktop's composer keeps both
/// pickers, disabled.
fn render_settings(&mut self, window: &Window, cx: &mut Context<Self>) -> Vec<AnyElement> {
+ if self.side.is_some() {
+ return self.render_side_settings(window, cx);
+ }
if let Some(settings) = self.state.read(cx).settings().cloned() {
// The connection it runs on, found once rather than per model.
let list = self.connections.read(cx).list();
@@ -1303,6 +1366,86 @@ impl Composer {
controls
}
+ /// A side chat's controls: the model as a read-only chip (the fork
+ /// runs its task's model and does not switch it, as in Desktop), then
+ /// the permission mode picker. Nothing until the settings are read.
+ fn render_side_settings(&mut self, window: &Window, cx: &mut Context<Self>) -> Vec<AnyElement> {
+ let Some(side) = self.side.clone() else { return Vec::new() };
+ let side = side.read(cx);
+ let Some(settings) = side.settings(cx).cloned() else { return Vec::new() };
+ let mode = side.permission_mode(cx).unwrap_or(PermissionMode::Ask);
+ let locale = Locale::current(cx);
+ let catalog = self.connections.read(cx);
+ let list = catalog.list();
+ let on = list.and_then(|list| settings.connection_in(list)).map(|c| c.id.clone());
+ let current =
+ |id: &str, model: &str| on.as_deref() == Some(id) && settings.model.as_ref() == model;
+ let label = ModelMenu::new(¤t, list, catalog.status())
+ .current_label()
+ .unwrap_or_else(|| settings.model.clone());
+ // The model's name gives way first at the panel's width (Desktop
+ // caps the side chat's model chip): it shrinks and ends in an
+ // ellipsis, so the mode and the round button keep their place.
+ let (ink, _) = chip_inks(&cx.maka(), true);
+ let model = Button::new("composer-model")
+ .ghost()
+ .h(dp(28.))
+ .px(dp(8.))
+ .min_w_0()
+ .flex_shrink(1.)
+ .rounded(dp_px(RADIUS_SURFACE, window))
+ .disabled(true)
+ .child(
+ div()
+ .min_w_0()
+ .truncate()
+ .text_size(dp(LABEL_SIZE))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(ink)
+ .child(label.clone()),
+ )
+ .accessibility_label(shell_copy::labeled(locale, copy::MODEL.get(cx), &label))
+ .tooltip(shared::copy::side_chat::MODEL_INHERITED.get(cx));
+ let mode = self.render_permission_mode_picker(mode, window, cx);
+ vec![model.into_any_element(), div().flex_none().child(mode).into_any_element()]
+ }
+
+ /// The quotes staged in a side chat for its next message, as chips
+ /// above the files: each with its remove button.
+ fn render_quotes(&self, window: &Window, cx: &mut Context<Self>) -> Option<AnyElement> {
+ let side = self.side.clone()?;
+ let quotes = side.read(cx).quotes().to_vec();
+ if quotes.is_empty() {
+ return None;
+ }
+ let chips = quotes.into_iter().map(|staged| {
+ let id = staged.id;
+ let chat = side.downgrade();
+ let label = staged.quote.label.clone().map(SharedString::from);
+ let text: SharedString =
+ staged.quote.text.split_whitespace().collect::<Vec<_>>().join(" ").into();
+ crate::quotes::staged_quote_chip(
+ shared::domain_element_id("staged-quote", &id.to_string()),
+ label.as_ref(),
+ &text,
+ move |_, cx| {
+ chat.update(cx, |chat, cx| chat.remove_quote(id, cx)).ok();
+ },
+ window,
+ cx,
+ )
+ });
+ Some(
+ v_flex()
+ .id("composer-quotes")
+ .test_support()
+ .w_full()
+ .gap(dp(6.))
+ .children(chips)
+ .into_any_element(),
+ )
+ }
+
/// The thinking level picker (Desktop's `ThinkingLevelSelector`) right
/// after the model picker: a chip naming the level in use (Model
/// default when none), opening Model default and the model's levels,
@@ -1911,15 +2054,21 @@ impl Render for Composer {
.pr(dp(6.));
let mut controls = self.render_settings(window, cx);
controls.insert(0, self.render_attach_button(window, cx));
- // Last in the row, so nothing moves when it goes with the draft.
- if self.selected_session(cx).is_none() {
+ // Last in the row, so nothing moves when it goes with the draft. A
+ // side chat runs where its task does.
+ if self.selected_session(cx).is_none() && self.side.is_none() {
controls.push(self.render_project_picker(window, cx));
}
// First in the row, the note starts on the input's text edge (the
// field's 8 inside the dock's 12, review round 12); after a control,
// 6 from it.
let note = note.pl(dp(if controls.is_empty() { 8. } else { 6. })).into_any_element();
- let chips = self.render_attachments(window, cx);
+ let chips = match (self.render_quotes(window, cx), self.render_attachments(window, cx)) {
+ (Some(quotes), Some(files)) => {
+ Some(v_flex().w_full().gap(dp(6.)).child(quotes).child(files).into_any_element())
+ }
+ (quotes, files) => quotes.or(files),
+ };
let action = self.render_action_button(window, cx);
// The outer row centres the dock in the reading column, 16 px above
// the plate's bottom edge; queued messages sit right above it.
diff --git a/apps/desktop-gpui/crates/conversation/src/corpus.rs b/apps/desktop-gpui/crates/conversation/src/corpus.rs
new file mode 100644
index 0000000000..59e506051a
--- /dev/null
+++ b/apps/desktop-gpui/crates/conversation/src/corpus.rs
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! The text a find in the conversation searches, read from the transcript
+//! model, not from the views: the virtualized list draws only the rows in
+//! view, and a match must count wherever its row is.
+//!
+//! Each held item contributes the text its row shows or would show open:
+//! a user message as written, a reply's visible Markdown text
+//! ([`markdown`]), a reasoning's text (capped as its row caps it), a Tool
+//! call's name, its one-line summary, and the output (or, before a result,
+//! the input) its card shows, collapsed or not. Prompt cards, the edits
+//! card and diffs are not searched. No GPUI: the main thread hands over
+//! what changed ([`ItemSource`]) and a background task extracts and
+//! searches it.
+
+mod markdown;
+
+use std::ops::Range;
+use std::sync::Arc;
+
+use search::SearchQuery;
+use search::matching::{find_ranges, find_ranges_in_cut};
+use shared::copy::Locale;
+use transcript_model::{ToolItem, TurnItem, TurnView};
+
+use crate::rows::{
+ RowKey, cap_cut, hidden_tool, tool_detail_text, tool_name_text, tool_summary_cut,
+};
+
+pub(crate) use markdown::VisibleText;
+
+/// Which text of a row a match is in.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
+pub(crate) enum Field {
+ /// A user message, a reply or a reasoning: the row's own text.
+ Body,
+ /// A Tool call's name, in its header.
+ ToolName,
+ /// A Tool call's one-line summary, in its header.
+ ToolSummary,
+ /// What a Tool call's card shows open: its output, or its input.
+ ToolDetail,
+}
+
+/// One occurrence of a query in the transcript: the row, the text of the
+/// row, and the range. In a reply ([`Field::Body`] of a text row) the
+/// range is of the Markdown source, which the row maps to what it draws;
+/// elsewhere it is of the text the row shows. Equal matches are the same
+/// text of the same row, however the rows around it changed.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct TranscriptMatch {
+ pub(crate) row: Arc<RowKey>,
+ pub(crate) field: Field,
+ pub(crate) range: Range<usize>,
+}
+
+/// An item's searchable text, extracted once per revision of the item.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) struct ItemText {
+ fields: Vec<FieldText>,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+enum FieldText {
+ /// Text the row shows, and the character it went on with where the row
+ /// cut it (before the cut's mark, which is not searched).
+ Plain(Field, String, Option<char>),
+ /// A reply's visible text, matched there and mapped to its source.
+ Markdown(VisibleText),
+}
+
+impl ItemText {
+ /// Every occurrence of `query` in the item, in the order its row reads,
+ /// appended to `out`.
+ fn find(&self, row: &Arc<RowKey>, query: &SearchQuery, out: &mut Vec<TranscriptMatch>) {
+ for field in &self.fields {
+ match field {
+ FieldText::Plain(field, text, next) => {
+ out.extend(
+ find_ranges_in_cut(text, *next, query).into_iter().map(|range| {
+ TranscriptMatch { row: row.clone(), field: *field, range }
+ }),
+ );
+ }
+ FieldText::Markdown(visible) => {
+ out.extend(find_ranges(visible.text(), query).into_iter().filter_map(
+ |range| {
+ let range = visible.source_range(range)?;
+ Some(TranscriptMatch { row: row.clone(), field: Field::Body, range })
+ },
+ ));
+ }
+ }
+ }
+ }
+}
+
+/// What the main thread hands a background search for an item whose text
+/// it does not hold yet: the item's own data, owned.
+#[derive(Debug)]
+pub(crate) enum ItemSource {
+ User(String),
+ Reply(String),
+ Reasoning(String),
+ Tool(Box<ToolItem>, Locale),
+}
+
+impl ItemSource {
+ /// The source of `item` of `turn`, or `None` for an item a find does
+ /// not search (a prompt) or a row the transcript does not show.
+ pub(crate) fn of(turn: &TurnView, item: &TurnItem, locale: Locale) -> Option<Self> {
+ Some(match item {
+ TurnItem::User(user) => Self::User(user.text().to_owned()),
+ TurnItem::Text(text) => Self::Reply(text.text.clone()),
+ TurnItem::Thinking(thinking) => Self::Reasoning(thinking.text.clone()),
+ TurnItem::Tool(tool) if hidden_tool(tool, turn.status) => return None,
+ TurnItem::Tool(tool) => Self::Tool(Box::new(tool.clone()), locale),
+ _ => return None,
+ })
+ }
+
+ /// The text the item's row shows, ready to search.
+ pub(crate) fn extract(self) -> ItemText {
+ let fields = match self {
+ Self::User(text) => vec![FieldText::Plain(Field::Body, text, None)],
+ Self::Reply(text) => vec![FieldText::Markdown(markdown::visible_text(&text))],
+ Self::Reasoning(text) => {
+ let (kept, next) = cap_cut(&text);
+ vec![FieldText::Plain(Field::Body, kept.to_owned(), next)]
+ }
+ Self::Tool(tool, locale) => {
+ let mut fields =
+ vec![FieldText::Plain(Field::ToolName, tool_name_text(&tool), None)];
+ fields
+ .extend(tool_summary_cut(&tool).map(|(summary, next)| {
+ FieldText::Plain(Field::ToolSummary, summary, next)
+ }));
+ fields.extend(
+ tool_detail_text(&tool, locale)
+ .map(|detail| FieldText::Plain(Field::ToolDetail, detail, None)),
+ );
+ fields
+ }
+ };
+ ItemText { fields }
+ }
+}
+
+/// One held item, in transcript order, as a search reads it.
+#[derive(Debug)]
+pub(crate) enum Entry {
+ /// Text extracted by an earlier search and still current.
+ Ready(Arc<RowKey>, Arc<ItemText>),
+ /// To be extracted by this one.
+ Pending(Arc<RowKey>, ItemSource),
+}
+
+/// What a search found, and the text it extracted on the way, for the
+/// next one to reuse.
+#[derive(Debug, Default)]
+pub(crate) struct Found {
+ pub(crate) matches: Vec<TranscriptMatch>,
+ pub(crate) extracted: Vec<(Arc<RowKey>, Arc<ItemText>)>,
+}
+
+/// Searches `entries` for `query`: every match, in transcript order. Runs
+/// on a background thread.
+pub(crate) fn search(entries: Vec<Entry>, query: &SearchQuery) -> Found {
+ let mut found = Found::default();
+ for entry in entries {
+ let (row, text) = match entry {
+ Entry::Ready(row, text) => (row, text),
+ Entry::Pending(row, source) => {
+ let text = Arc::new(source.extract());
+ found.extracted.push((row.clone(), text.clone()));
+ (row, text)
+ }
+ };
+ text.find(&row, query, &mut found.matches);
+ }
+ found
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use search::SearchOptions;
+ use transcript_model::ItemKey;
+
+ fn row(id: &str) -> Arc<RowKey> {
+ Arc::new(RowKey::Item { turn_id: "t".into(), key: ItemKey::Text(id.into()) })
+ }
+
+ #[test]
+ fn a_search_reads_every_item_in_order_and_hands_back_what_it_extracted() {
+ let query = SearchQuery::new("fish", SearchOptions::new());
+ let cached = Arc::new(ItemSource::User("one fish".into()).extract());
+ let entries = vec![
+ Entry::Ready(row("a"), cached),
+ Entry::Pending(row("b"), ItemSource::Reply("**Fish** and `fish`".into())),
+ Entry::Pending(row("c"), ItemSource::Reasoning("no match".into())),
+ ];
+ let found = search(entries, &query);
+ let summary: Vec<(String, std::ops::Range<usize>)> = found
+ .matches
+ .iter()
+ .map(|found| (found.row.element_id().to_string(), found.range.clone()))
+ .collect();
+ assert_eq!(summary.len(), 3);
+ assert_eq!(summary[0].1, 4..8);
+ assert_eq!(summary[1].1, 2..6, "the reply's match is a range of its source");
+ assert_eq!(summary[2].1, 14..18);
+ assert_eq!(found.extracted.len(), 2, "both pending items, none of the cached");
+ }
+}
diff --git a/apps/desktop-gpui/crates/conversation/src/corpus/markdown.rs b/apps/desktop-gpui/crates/conversation/src/corpus/markdown.rs
new file mode 100644
index 0000000000..c478f76e52
--- /dev/null
+++ b/apps/desktop-gpui/crates/conversation/src/corpus/markdown.rs
@@ -0,0 +1,409 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! The text a person sees of a Markdown reply, with where each character
+//! of it comes from in the source, read with the parser and the parse
+//! options gpui-kit's text view uses (`markdown` 1.0, GFM with math, no
+//! frontmatter, no MDX: what `MarkdownExtensions::default` asks for, and
+//! the transcript gives its replies no other).
+//!
+//! Only text the view draws in a text leaf, and whose source the view can
+//! map back (`RenderedText::range_for_source`), is taken: paragraphs,
+//! headings, list items, block quotes, table cells, code blocks, inline
+//! code, and the visible text of links. Markup characters, link
+//! destinations, images, HTML (whose text the view draws without source
+//! positions) and footnote markers are left out, so a find neither counts
+//! what it could not paint nor matches what the reader cannot see.
+//!
+//! Text is decoded as the view decodes it (`\*` reads `*`, `&` reads
+//! `&`, a soft line break reads as a space), each leaf ends with a line
+//! break of its own (mapped to nothing), so no match spans two leaves.
+
+use std::ops::Range;
+
+use markdown::ParseOptions;
+use markdown::mdast::Node;
+
+/// Where a run of the visible text comes from in the source.
+#[derive(Debug, Clone, PartialEq, Eq)]
+struct Segment {
+ text: Range<usize>,
+ source: Range<usize>,
+ /// The run maps byte for byte (no escape, entity or line ending in it).
+ linear: bool,
+}
+
+/// A reply's visible text and its map back to the Markdown source.
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
+pub(crate) struct VisibleText {
+ text: String,
+ segments: Vec<Segment>,
+}
+
+impl VisibleText {
+ /// The text a person sees, a line per leaf.
+ pub(crate) fn text(&self) -> &str {
+ &self.text
+ }
+
+ /// The source a range of [`Self::text`] was rendered from: from where
+ /// its first character comes to where its last one ends. `None` when
+ /// either end maps to nothing.
+ pub(crate) fn source_range(&self, range: Range<usize>) -> Option<Range<usize>> {
+ let last = self.text[..range.end].char_indices().next_back()?.0;
+ let start = self.source_of(range.start)?.start;
+ let end = self.source_of(last)?.end;
+ (start < end).then_some(start..end)
+ }
+
+ /// The source of the character at byte `at` of the text.
+ fn source_of(&self, at: usize) -> Option<Range<usize>> {
+ let ix = self.segments.partition_point(|segment| segment.text.end <= at);
+ let segment = self.segments.get(ix).filter(|segment| segment.text.start <= at)?;
+ if !segment.linear {
+ return Some(segment.source.clone());
+ }
+ let start = segment.source.start + (at - segment.text.start);
+ let len = self.text[at..].chars().next().map_or(0, char::len_utf8);
+ Some(start..start + len)
+ }
+}
+
+/// The parse options of gpui-kit's text view with its default extensions
+/// (`MarkdownExtensions::parse_options`): GFM, inline and block math on.
+fn parse_options() -> ParseOptions {
+ let mut options = ParseOptions::gfm();
+ options.constructs.frontmatter = false;
+ options.constructs.math_text = true;
+ options.constructs.math_flow = true;
+ options
+}
+
+/// The visible text of `source`, a Markdown reply.
+pub(crate) fn visible_text(source: &str) -> VisibleText {
+ let mut builder = Builder { source, base: 0, out: VisibleText::default() };
+ if let Ok(Node::Root(root)) = markdown::to_mdast(source, &parse_options()) {
+ builder.blocks(&root.children);
+ }
+ builder.out
+}
+
+struct Builder<'a> {
+ source: &'a str,
+ /// Where the positions of the nodes being walked start in `source`:
+ /// 0, or the start of an inline math span parsed again on its own.
+ base: usize,
+ out: VisibleText,
+}
+
+impl Builder<'_> {
+ fn span(&self, node: &Node) -> Option<Range<usize>> {
+ let position = node.position()?;
+ let span = self.base + position.start.offset..self.base + position.end.offset;
+ (span.end <= self.source.len()).then_some(span)
+ }
+
+ fn blocks(&mut self, nodes: &[Node]) {
+ for node in nodes {
+ self.block(node);
+ }
+ }
+
+ fn block(&mut self, node: &Node) {
+ match node {
+ Node::Paragraph(paragraph) => self.leaf(¶graph.children),
+ Node::Heading(heading) => self.leaf(&heading.children),
+ Node::Blockquote(quote) => self.blocks("e.children),
+ Node::List(list) => self.blocks(&list.children),
+ Node::ListItem(item) => self.blocks(&item.children),
+ // The view joins a definition's blocks into one paragraph after
+ // a marker of its own; the blocks' text is the reply's.
+ Node::FootnoteDefinition(definition) => self.blocks(&definition.children),
+ Node::Table(table) => {
+ for row in &table.children {
+ for cell in row.children().into_iter().flatten() {
+ if let Some(children) = cell.children() {
+ self.leaf(children);
+ }
+ }
+ }
+ }
+ Node::Code(code) => {
+ if let Some(span) = self.span(node) {
+ self.align(&code.value, span, false);
+ }
+ self.end_leaf();
+ }
+ Node::Math(math) => {
+ if let Some(span) = self.span(node) {
+ self.align(&math.value, span, false);
+ }
+ self.end_leaf();
+ }
+ // HTML blocks render without source positions; rules,
+ // definitions and breaks render no text.
+ _ => {}
+ }
+ }
+
+ fn leaf(&mut self, children: &[Node]) {
+ self.inlines(children);
+ self.end_leaf();
+ }
+
+ fn end_leaf(&mut self) {
+ if !self.out.text.is_empty() && !self.out.text.ends_with('\n') {
+ self.out.text.push('\n');
+ }
+ }
+
+ fn inlines(&mut self, nodes: &[Node]) {
+ for node in nodes {
+ self.inline(node);
+ }
+ }
+
+ fn inline(&mut self, node: &Node) {
+ match node {
+ Node::Text(text) => {
+ // A soft line break reads as a space, as the view draws it.
+ let decoded = text.value.replace("\r\n", " ").replace(['\n', '\r'], " ");
+ if let Some(span) = self.span(node) {
+ self.align(&decoded, span, true);
+ }
+ }
+ Node::InlineCode(code) => {
+ if let Some(span) = self.span(node) {
+ self.align(&code.value, span, false);
+ }
+ }
+ Node::Emphasis(_)
+ | Node::Strong(_)
+ | Node::Delete(_)
+ | Node::Link(_)
+ | Node::LinkReference(_) => {
+ self.inlines(node.children().map_or(&[][..], Vec::as_slice));
+ }
+ // A hard break is a line of its own: no match crosses it.
+ Node::Break(_) => self.out.text.push('\n'),
+ Node::InlineMath(_) => self.inline_math(node),
+ // Inline HTML tags, images and footnote markers.
+ _ => {}
+ }
+ }
+
+ /// Inline math no plugin claims, as the view draws it: the literal
+ /// source, dollars included, unless that source holds inline markup,
+ /// which is then read as ordinary text (gpui-kit's
+ /// `flatten_unclaimed_math`).
+ fn inline_math(&mut self, node: &Node) {
+ let Some(span) = self.span(node) else { return };
+ let literal = &self.source[span.clone()];
+ if may_hold_inline_markup(literal) {
+ let mut prose = parse_options();
+ prose.constructs.math_text = false;
+ prose.constructs.math_flow = false;
+ if let Ok(Node::Root(root)) = markdown::to_mdast(literal, &prose)
+ && let [Node::Paragraph(paragraph)] = root.children.as_slice()
+ && !paragraph.children.iter().all(|child| matches!(child, Node::Text(_)))
+ {
+ let base = std::mem::replace(&mut self.base, span.start);
+ self.inlines(¶graph.children);
+ self.base = base;
+ return;
+ }
+ }
+ let start = self.out.text.len();
+ self.out.text.push_str(literal);
+ self.push(start..self.out.text.len(), span, true);
+ }
+
+ /// Appends `decoded`, the text a node renders, mapping each character
+ /// to where it stands in `span` of the source: the same character, an
+ /// escape (`\*`), an entity (`&`), a line ending a space stands
+ /// for, or the next place it occurs (text the parser dropped
+ /// indentation or quote markers from). A character found nowhere maps
+ /// to nothing.
+ fn align(&mut self, decoded: &str, span: Range<usize>, decode: bool) {
+ let raw = &self.source[span.clone()];
+ let mut cursor = 0;
+ for c in decoded.chars() {
+ let rest = &raw[cursor..];
+ let found = if rest.starts_with(c) {
+ Some((0, c.len_utf8()))
+ } else if decode
+ && let Some(escaped) = rest.strip_prefix('\\')
+ && escaped.starts_with(c)
+ {
+ Some((0, 1 + c.len_utf8()))
+ } else if decode && let Some(len) = entity_len(rest) {
+ Some((0, len))
+ } else if c == ' '
+ && let Some((at, len)) = line_ending(rest)
+ {
+ Some((at, len))
+ } else {
+ rest.find(c).map(|at| (at, c.len_utf8()))
+ };
+ let start = self.out.text.len();
+ self.out.text.push(c);
+ let Some((at, len)) = found else { continue };
+ let source = span.start + cursor + at..span.start + cursor + at + len;
+ self.push(start..self.out.text.len(), source, len == c.len_utf8());
+ cursor += at + len;
+ }
+ }
+
+ /// Records that `text` came from `source`, merging a run that goes on
+ /// byte for byte from the one before.
+ fn push(&mut self, text: Range<usize>, source: Range<usize>, linear: bool) {
+ if let Some(previous) = self.out.segments.last_mut()
+ && previous.linear
+ && linear
+ && previous.text.end == text.start
+ && previous.source.end == source.start
+ {
+ previous.text.end = text.end;
+ previous.source.end = source.end;
+ return;
+ }
+ self.out.segments.push(Segment { text, source, linear });
+ }
+}
+
+/// The length of the character reference `rest` starts with (`&`,
+/// `&`, `&`), if it starts with one.
+fn entity_len(rest: &str) -> Option<usize> {
+ let name = rest.strip_prefix('&')?;
+ let end = name.bytes().take(32).position(|byte| byte == b';')?;
+ let valid = end > 0
+ && name.as_bytes()[..end].iter().all(|byte| byte.is_ascii_alphanumeric() || *byte == b'#');
+ valid.then_some(end + 2)
+}
+
+/// A line ending after optional spaces at the start of `rest`, where a
+/// soft line break the view draws as a space stands: its offset and length.
+fn line_ending(rest: &str) -> Option<(usize, usize)> {
+ let at = rest.bytes().position(|byte| !matches!(byte, b' ' | b'\t'))?;
+ match &rest[at..] {
+ ending if ending.starts_with("\r\n") => Some((at, 2)),
+ ending if ending.starts_with('\n') || ending.starts_with('\r') => Some((at, 1)),
+ _ => None,
+ }
+}
+
+/// gpui-kit's gate before it parses unclaimed math again: every inline
+/// construct starts with one of these bytes, or is a GFM autolink literal.
+fn may_hold_inline_markup(literal: &str) -> bool {
+ literal
+ .bytes()
+ .any(|byte| matches!(byte, b'<' | b'*' | b'_' | b'[' | b'`' | b'~' | b'\\' | b'!' | b'&'))
+ || literal.contains("://")
+ || literal.contains("www.")
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// Each match of `needle` in the visible text, with the source it maps
+ /// to.
+ fn sources<'a>(source: &'a str, needle: &str) -> Vec<&'a str> {
+ let visible = visible_text(source);
+ visible
+ .text()
+ .match_indices(needle)
+ .filter_map(|(at, found)| visible.source_range(at..at + found.len()))
+ .map(|range| &source[range])
+ .collect()
+ }
+
+ #[test]
+ fn markup_stays_out_of_the_text() {
+ let source = "Use **bold**, `code` and [the docs](https://example.com/path \"Title\").";
+ let visible = visible_text(source);
+ assert_eq!(visible.text(), "Use bold, code and the docs.\n");
+ assert_eq!(sources(source, "bold"), ["bold"]);
+ assert_eq!(sources(source, "code"), ["code"]);
+ assert_eq!(sources(source, "the docs"), ["the docs"]);
+ assert!(!visible.text().contains("example.com"), "no link target");
+ assert!(!visible.text().contains('*'));
+ }
+
+ #[test]
+ fn a_match_across_marked_runs_maps_to_the_source_between_them() {
+ assert_eq!(sources("foo **bar** baz", "foo bar"), ["foo **bar"]);
+ assert_eq!(sources("*a* and _b_", "a and b"), ["a* and _b"]);
+ }
+
+ #[test]
+ fn decoded_text_maps_to_its_escapes_entities_and_line_endings() {
+ assert_eq!(visible_text("a \\* b").text(), "a * b\n");
+ assert_eq!(sources("a \\* b", "* b"), ["\\* b"]);
+ assert_eq!(sources("fish & chips", "& chips"), ["& chips"]);
+ assert_eq!(visible_text("one\ntwo").text(), "one two\n", "a soft break is a space");
+ assert_eq!(sources("one\ntwo", "one two"), ["one\ntwo"]);
+ }
+
+ #[test]
+ fn blocks_are_leaves_of_their_own() {
+ let source = "# Title\n\n- first item\n- second\n\n> quoted\n\n```rust\nlet x = 1;\n```\n";
+ assert_eq!(visible_text(source).text(), "Title\nfirst item\nsecond\nquoted\nlet x = 1;\n");
+ assert_eq!(sources(source, "let x"), ["let x"]);
+ assert!(sources(source, "Title first").is_empty(), "no match spans two leaves");
+ assert!(sources(source, "rust").is_empty(), "a fence's language is not text");
+ }
+
+ #[test]
+ fn table_cells_and_list_text_keep_their_sources() {
+ let source = "| Name | Size |\n| --- | --- |\n| alpha | 10 |\n";
+ assert_eq!(visible_text(source).text(), "Name\nSize\nalpha\n10\n");
+ assert_eq!(sources(source, "alpha"), ["alpha"]);
+ let nested = "1. one\n continued\n2. two";
+ assert_eq!(sources(nested, "one continued"), ["one\n continued"]);
+ }
+
+ #[test]
+ fn html_images_and_footnote_markers_are_left_out() {
+ let source = "<div>block html</div>\n\nSee  and <b>bold</b>[^1].\n\n[^1]: The note.";
+ let text = visible_text(source).text().to_owned();
+ assert!(!text.contains("block html"), "{text:?}");
+ assert!(!text.contains("alt text"), "{text:?}");
+ assert!(text.contains("See and bold."), "{text:?}");
+ assert!(text.contains("The note."), "{text:?}");
+ }
+
+ #[test]
+ fn unclaimed_math_reads_as_its_literal_source() {
+ let source = "It costs $5 and $10 now.";
+ assert_eq!(visible_text(source).text(), "It costs $5 and $10 now.\n");
+ assert_eq!(sources(source, "$5 and $10"), ["$5 and $10"]);
+ // With markup inside, the span is ordinary text again.
+ let marked = "Pay $a **b** c$ now";
+ assert_eq!(visible_text(marked).text(), "Pay $a b c$ now\n");
+ assert_eq!(sources(marked, "b c"), ["b** c"]);
+ }
+
+ #[test]
+ fn chinese_text_maps_byte_for_byte() {
+ let source = "运行**测试**通过";
+ assert_eq!(visible_text(source).text(), "运行测试通过\n");
+ assert_eq!(sources(source, "测试"), ["测试"]);
+ }
+}
diff --git a/apps/desktop-gpui/crates/conversation/src/edits_card.rs b/apps/desktop-gpui/crates/conversation/src/edits_card.rs
new file mode 100644
index 0000000000..8dc01ce765
--- /dev/null
+++ b/apps/desktop-gpui/crates/conversation/src/edits_card.rs
@@ -0,0 +1,339 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! The card under a settled turn that edited files, as Codex shows it
+//! under a turn's last reply, without its undo: an icon tile, "Edited 4
+//! files" over the lines they added and deleted, a "View changes" button,
+//! and under a divider one row per file (its folder muted, then its name,
+//! then its lines, or "New file" or "Deleted" where the counts are not
+//! known), the first three at first and a button that shows the rest in
+//! place and folds them away again. The rows keep a deletions' lane only
+//! while a row the card shows deletes lines, so counts that only add end
+//! where the "View changes" button does.
+//!
+//! The rows come from the window's worked-out turn changes
+//! ([`transcript_model::edits::EditedTurns`]); the buttons ask the view's
+//! owner to open the changes panel on the turn
+//! ([`crate::ConversationViewEvent::ShowTurnChanges`]), at a file for a
+//! file's row.
+
+use gpui_kit::component::button::{Button, ButtonVariants as _};
+use gpui_kit::component::{Icon, Sizable as _, h_flex, v_flex};
+use gpui_kit::{
+ AnyElement, App, FontWeight, InteractiveElement as _, IntoElement, ParentElement as _,
+ SharedString, StatefulInteractiveElement as _, Styled as _, TestSupportExt as _,
+ Transformation, WeakEntity, Window, div, percentage, prelude::FluentBuilder as _,
+};
+use shared::copy::conversation as copy;
+use shared::copy::review as review_copy;
+use shared::copy::{self as shell_copy, Locale};
+use shared::domain_element_id;
+use shared::icons::MakaIcon;
+use shared::theme::{ActiveMakaPalette as _, plate_radius, quiet_button, tabular_nums};
+use transcript_model::edits::{ChangeKind, EditedFile};
+
+use crate::rows::EditsRow;
+use crate::style::{LABEL_SIZE, RADIUS_CONTROL, RADIUS_MODAL, SUPPORTING_SIZE, dp, dp_px};
+use crate::view::ConversationView;
+
+/// The files the card lists before its "Show n more files".
+pub(crate) const FILES_SHOWN: usize = 3;
+/// The icon tile's side: 32 px, as Codex's.
+const TILE: f32 = 32.;
+/// A file row's height: 32 px, the control size.
+const FILE_ROW: f32 = 32.;
+/// A count's lane, so the figures of every row line up: four digits and a
+/// sign at 12 px.
+const COUNT_LANE: f32 = 40.;
+/// The rows' inset from the card's edge, and their own side padding: the
+/// two together put their text on the header's 12 px edge, and a row's
+/// hover fill stays inside the card's rounded corners (12 − 4 ≈ the
+/// control radius).
+const ROWS_INSET: f32 = 4.;
+const ROW_PADDING: f32 = 8.;
+
+/// The card for `row`.
+pub(crate) fn render_edits(
+ row: EditsRow,
+ view: WeakEntity<ConversationView>,
+ window: &Window,
+ cx: &App,
+) -> AnyElement {
+ let maka = cx.maka();
+ let locale = Locale::current(cx);
+ let count = row.files.len();
+ let (added, deleted) =
+ row.files.iter().filter_map(|file| file.counts).fold((0u32, 0u32), |(a, d), (add, del)| {
+ (a.saturating_add(add), d.saturating_add(del))
+ });
+ let known = row.files.iter().any(|file| file.counts.is_some());
+ let title = copy::edited_files(locale, count);
+ // The raised tile of the changes panel's bar and the header's pressed
+ // changes button, the `selected` fill: `sunken` is a hole in dark.
+ let tile = div()
+ .flex_none()
+ .size(dp(TILE))
+ .rounded(plate_radius(dp_px(TILE, window)))
+ .bg(maka.selected)
+ .flex()
+ .items_center()
+ .justify_center()
+ .child(
+ Icon::new(MakaIcon::FileDiff).with_size(dp_px(16., window)).text_color(maka.ink_muted),
+ );
+ let view_changes = {
+ let (view, turn_id) = (view.clone(), row.turn_id.clone());
+ quiet_button(Button::new("turn-edits-view"), cx)
+ .flex_none()
+ .label(copy::VIEW_CHANGES.get(cx))
+ .on_click(move |_, _, cx| {
+ view.update(cx, |view, cx| view.show_turn_changes(&turn_id, None, cx)).ok();
+ })
+ };
+ let header = h_flex()
+ .w_full()
+ .px(dp(12.))
+ .py(dp(10.))
+ .gap(dp(10.))
+ .child(tile)
+ .child(
+ v_flex()
+ .flex_1()
+ .min_w_0()
+ .child(
+ div()
+ .id("turn-edits-title")
+ .test_support()
+ .aria_label(title.clone())
+ .truncate()
+ .text_size(dp(LABEL_SIZE))
+ .font_weight(FontWeight::MEDIUM)
+ .text_color(maka.ink)
+ .child(title),
+ )
+ .when(known, |this| {
+ let label = shell_copy::parts(
+ locale,
+ &[
+ &review_copy::added_lines(locale, added as usize),
+ &review_copy::deleted_lines(locale, deleted as usize),
+ ],
+ );
+ this.child(
+ h_flex()
+ .id("turn-edits-counts")
+ .test_support()
+ .aria_label(label)
+ .gap(dp(6.))
+ .text_size(dp(SUPPORTING_SIZE))
+ .font_features(tabular_nums())
+ .child(div().text_color(maka.success).child(format!("+{added}")))
+ .child(
+ div()
+ .text_color(maka.destructive)
+ .child(format!("\u{2212}{deleted}")),
+ ),
+ )
+ }),
+ )
+ .child(view_changes);
+ let shown = if row.expanded { count } else { count.min(FILES_SHOWN) };
+ let deletions = row
+ .files
+ .iter()
+ .take(shown)
+ .any(|file| matches!(counts_of(file, cx), Counts::Lines(_, deleted) if deleted > 0));
+ let rows = row
+ .files
+ .iter()
+ .take(shown)
+ .map(|file| file_row(file, deletions, &row.turn_id, &view, window, cx));
+ let more = (count > FILES_SHOWN).then(|| {
+ let (view, key) = (view.clone(), row.expansion_key.clone());
+ let label = if row.expanded {
+ copy::SHOW_FEWER_FILES.get(cx).to_owned()
+ } else {
+ copy::show_more_files(locale, count - FILES_SHOWN)
+ };
+ let mut chevron = Icon::new(MakaIcon::ChevronDown)
+ .with_size(dp_px(14., window))
+ .text_color(maka.ink_muted);
+ if row.expanded {
+ chevron = chevron.transform(Transformation::rotate(percentage(0.5)));
+ }
+ Button::new("turn-edits-more")
+ .ghost()
+ .w_full()
+ .h(dp(FILE_ROW))
+ .px(dp(ROW_PADDING))
+ .rounded(dp_px(RADIUS_CONTROL, window))
+ .accessibility_label(label.clone())
+ .on_click(move |_, _, cx| {
+ view.update(cx, |view, cx| view.toggle_edits(&key, cx)).ok();
+ })
+ .child(
+ h_flex()
+ .w_full()
+ .gap(dp(6.))
+ .text_size(dp(SUPPORTING_SIZE))
+ .text_color(maka.ink_muted)
+ .child(label)
+ .child(chevron),
+ )
+ });
+ v_flex()
+ .w_full()
+ .bg(maka.plate)
+ .border_1()
+ .border_color(maka.border)
+ .rounded(dp(RADIUS_MODAL))
+ .child(header)
+ .child(div().w_full().h_px().bg(maka.border_soft))
+ .child(v_flex().w_full().p(dp(ROWS_INSET)).children(rows).children(more))
+ .into_any_element()
+}
+
+/// What a file's row says of its size: its lines, or what the turn did to
+/// it where there are none to count.
+fn counts_of(file: &EditedFile, cx: &App) -> Counts {
+ // A created or deleted file without lines to count says what the turn
+ // did to it instead.
+ match (file.counts, file.kind) {
+ (Some((added, deleted)), _) if added > 0 || deleted > 0 => Counts::Lines(added, deleted),
+ (_, ChangeKind::Created) => Counts::Word(copy::NEW_FILE.get(cx)),
+ (_, ChangeKind::Deleted) => Counts::Word(copy::DELETED_FILE.get(cx)),
+ (Some((added, deleted)), _) => Counts::Lines(added, deleted),
+ (None, _) => Counts::None,
+ }
+}
+
+/// A file's row: its folder muted and its name, then its lines (or what
+/// the turn did to it where they are not known), the deletions' lane only
+/// with `deletions`; a button that opens the changes panel at it.
+fn file_row(
+ file: &EditedFile,
+ deletions: bool,
+ turn_id: &SharedString,
+ view: &WeakEntity<ConversationView>,
+ window: &Window,
+ cx: &App,
+) -> AnyElement {
+ let maka = cx.maka();
+ let locale = Locale::current(cx);
+ let (folder, name) = match file.path.rsplit_once('/') {
+ Some((folder, name)) => (format!("{folder}/"), name.to_owned()),
+ None => (String::new(), file.path.clone()),
+ };
+ let counts = counts_of(file, cx);
+ let counts_label = match counts {
+ Counts::Lines(added, deleted) => shell_copy::parts(
+ locale,
+ &[
+ &review_copy::added_lines(locale, added as usize),
+ &review_copy::deleted_lines(locale, deleted as usize),
+ ],
+ ),
+ Counts::Word(word) => word.to_owned(),
+ Counts::None => String::new(),
+ };
+ let label = shell_copy::parts(locale, &[&file.path, &counts_label]);
+ let lane = |text: Option<String>| {
+ div()
+ .flex_none()
+ .min_w(dp(COUNT_LANE))
+ .text_right()
+ .when_some(text, |this, text| this.child(text))
+ };
+ let (view, turn_id, path) =
+ (view.clone(), turn_id.clone(), SharedString::from(file.path.clone()));
+ Button::new(domain_element_id("turn-edits-file", &file.path))
+ .ghost()
+ .w_full()
+ .h(dp(FILE_ROW))
+ .px(dp(ROW_PADDING))
+ .rounded(dp_px(RADIUS_CONTROL, window))
+ .accessibility_label(label)
+ .on_click(move |_, _, cx| {
+ let path = Some(path.clone());
+ view.update(cx, |view, cx| view.show_turn_changes(&turn_id, path, cx)).ok();
+ })
+ .child(
+ h_flex()
+ .w_full()
+ .min_w_0()
+ .gap(dp(12.))
+ .child(
+ h_flex()
+ .flex_1()
+ .min_w_0()
+ .text_size(dp(SUPPORTING_SIZE))
+ .child(
+ div()
+ .min_w_0()
+ .flex_shrink(1.)
+ .truncate()
+ .text_color(maka.ink_muted)
+ .child(folder),
+ )
+ .child(
+ div()
+ .flex_none()
+ .max_w_full()
+ .truncate()
+ .text_color(maka.ink)
+ .child(name),
+ ),
+ )
+ .child(
+ h_flex()
+ .id(domain_element_id("turn-edits-file-counts", &file.path))
+ .test_support()
+ .flex_none()
+ .gap(dp(4.))
+ .text_size(dp(SUPPORTING_SIZE))
+ .font_features(tabular_nums())
+ .map(|this| match counts {
+ Counts::Lines(added, deleted) => this
+ .child(
+ lane((added > 0).then(|| format!("+{added}")))
+ .text_color(maka.success),
+ )
+ .when(deletions, |this| {
+ this.child(
+ lane((deleted > 0).then(|| format!("\u{2212}{deleted}")))
+ .text_color(maka.destructive),
+ )
+ }),
+ Counts::Word(word) => {
+ this.child(div().text_color(maka.ink_muted).child(word))
+ }
+ Counts::None => this,
+ }),
+ ),
+ )
+ .into_any_element()
+}
+
+/// What a file row says of its size.
+#[derive(Clone, Copy)]
+enum Counts {
+ Lines(u32, u32),
+ Word(&'static str),
+ None,
+}
diff --git a/apps/desktop-gpui/crates/conversation/src/lib.rs b/apps/desktop-gpui/crates/conversation/src/lib.rs
index 09e09f7ef2..6911f4dc52 100644
--- a/apps/desktop-gpui/crates/conversation/src/lib.rs
+++ b/apps/desktop-gpui/crates/conversation/src/lib.rs
@@ -28,19 +28,32 @@
//! - [`ConversationView`] renders the transcript as a virtualized list with
//! inline Tool cards and prompt cards, plus the empty, loading, and failure
//! states of the pane. The transcript is a Tab stop that PageUp, PageDown,
-//! Home, and End scroll; [`init`] binds those keys.
+//! Home, and End scroll; [`init`] binds those keys. It is also the item
+//! of its find bar ([`ConversationView::open_find`], the `search` crate's
+//! `Searchable`), which searches every held row, read from the model.
+//! It also carries the task's terminal output for the `terminal` crate:
+//! [`ConversationState::set_pty_interest`] and [`SessionPtyEvent`].
//! - [`Composer`] edits the draft and sends it, or stops the running turn,
//! through the same state; its [`QueuePlate`] lists the queued messages.
//!
+//! - [`SideChat`] is a side conversation about a task in a fork of it, made
+//! on its first send and removed when it is disposed of; [`SideChatPanel`]
+//! shows it with a view and a composer of its own, and [`SideChatLedger`]
+//! keeps every fork on disk until it is gone.
+//!
//! The shell only places the view and the composer in its window and routes
//! its window-wide Send and Stop commands to the composer.
mod attachments;
mod composer;
+mod corpus;
+mod edits_card;
mod paging;
mod queue;
mod quiet_json;
+mod quotes;
mod rows;
+mod side_chat;
mod state;
mod style;
mod thinking_face;
@@ -53,16 +66,21 @@ pub use composer::{
permission_mode_label, thinking_level_label,
};
pub use queue::{CancelQueueEdit, QueuePlate, queue_entry_element_id};
-pub use rows::{footer_element_id, item_element_id};
+pub use rows::{edits_element_id, footer_element_id, item_element_id};
+pub use side_chat::{
+ ForkEntry, ForkPhase, LEDGER_FILE, LedgerEdit, LedgerFile, LedgerStore, LedgerWrite,
+ OWNER_LOCKS_DIRECTORY, SIDE_CHAT_CONTEXT, SideChat, SideChatLedger, SideChatPanel, StagedQuote,
+};
pub use state::{
- AnswerState, COMMIT_INTERVAL, ConversationEvent, ConversationPhase, ConversationState,
- NewSessionEvent, OLDER_PAGE_BYTES, OlderHistory, SendOutcome, SessionSettings, TurnActivity,
+ AnswerState, BACKGROUND_PAGE_BYTES, COMMIT_INTERVAL, ConversationEvent, ConversationPhase,
+ ConversationState, NewSessionEvent, OLDER_PAGE_BYTES, OlderHistory, SendOutcome,
+ SessionPtyEvent, SessionSettings, TURN_START_PAGE_CAP, TurnActivity,
};
#[doc(hidden)]
pub use view::assistant_text;
pub use view::{
- ConversationView, ScrollPageDown, ScrollPageUp, ScrollToBottom, ScrollToTop,
- TRANSCRIPT_CONTEXT, init,
+ ConversationView, ConversationViewEvent, ScrollPageDown, ScrollPageUp, ScrollToBottom,
+ ScrollToTop, TRANSCRIPT_CONTEXT, init,
};
#[cfg(test)]
diff --git a/apps/desktop-gpui/crates/conversation/src/paging.rs b/apps/desktop-gpui/crates/conversation/src/paging.rs
index b757b10e52..6ed4431dc9 100644
--- a/apps/desktop-gpui/crates/conversation/src/paging.rs
+++ b/apps/desktop-gpui/crates/conversation/src/paging.rs
@@ -43,6 +43,7 @@
use std::cell::{Cell, RefCell};
use std::cmp::Ordering;
+use std::collections::HashSet;
use std::rc::Rc;
use gpui_kit::{
@@ -99,6 +100,9 @@ struct PagingState {
/// Runs once, deferred, when the older-history row is painted inside the
/// viewport: reaching the top loads older messages.
on_history_visible: RefCell<Option<Deferred>>,
+ /// Runs once, deferred, when one of these rows is painted inside the
+ /// viewport: the place of a card that waits for older history.
+ on_rows_visible: RefCell<Option<(HashSet<RowKey>, Deferred)>>,
}
/// Work a paint callback hands to the next effect cycle.
@@ -145,6 +149,17 @@ impl Paging {
})
}
+ /// Whether row `key` was painted inside the viewport in the last frame.
+ pub(crate) fn is_painted(&self, key: &RowKey) -> bool {
+ self.0.rows.borrow().iter().any(|(painted, _)| painted == key)
+ }
+
+ /// The topmost row painted inside the viewport in the last frame.
+ pub(crate) fn top_painted_row(&self) -> Option<RowKey> {
+ let rows = self.0.rows.borrow();
+ rows.iter().min_by(|a, b| by_top(a, b)).map(|(key, _)| key.clone())
+ }
+
/// Runs `action` (deferred, once) the next time the older-history row
/// is painted inside the viewport, replacing an earlier one.
pub(crate) fn when_history_visible(&self, action: impl FnOnce(&mut App) + 'static) {
@@ -156,6 +171,21 @@ impl Paging {
self.0.on_history_visible.replace(None);
}
+ /// Runs `action` (deferred, once) the next time one of `keys` is
+ /// painted inside the viewport, replacing an earlier one.
+ pub(crate) fn when_any_visible(
+ &self,
+ keys: HashSet<RowKey>,
+ action: impl FnOnce(&mut App) + 'static,
+ ) {
+ self.0.on_rows_visible.replace(Some((keys, Box::new(action))));
+ }
+
+ /// Drops the action [`Self::when_any_visible`] set.
+ pub(crate) fn forget_any_visible(&self) {
+ self.0.on_rows_visible.replace(None);
+ }
+
/// An empty element that covers the list's viewport. Place it before the
/// list among its siblings, so it prepaints and paints before any row.
pub(crate) fn viewport_probe(&self) -> impl IntoElement {
@@ -192,6 +222,14 @@ impl Paging {
// this frame.
cx.defer(action);
}
+ let watched = paint
+ .on_rows_visible
+ .borrow()
+ .as_ref()
+ .is_some_and(|(keys, _)| keys.contains(&painted_key));
+ if watched && let Some((_, action)) = paint.on_rows_visible.borrow_mut().take() {
+ cx.defer(action);
+ }
paint.rows.borrow_mut().push((painted_key, bounds));
},
)
diff --git a/apps/desktop-gpui/crates/conversation/src/quotes.rs b/apps/desktop-gpui/crates/conversation/src/quotes.rs
new file mode 100644
index 0000000000..5f3ebbf77a
--- /dev/null
+++ b/apps/desktop-gpui/crates/conversation/src/quotes.rs
@@ -0,0 +1,193 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+//! Quotes on a message (`QuoteRef`): the chips a user row shows for the
+//! quotes it carries, and the side chat's staged ones above its composer.
+//! After Maka Desktop's `QuoteRefChip` (packages/ui/src/quote-ref-chip.tsx):
+//! one line, the label first, the excerpt clipped; a chip on a sent message
+//! opens to the whole excerpt and the note.
+
+use gpui_kit::component::button::{Button, ButtonCustomVariant, ButtonVariants as _};
+use gpui_kit::component::{Icon, Selectable as _, Sizable as _, h_flex, v_flex};
+use gpui_kit::{
+ AnyElement, App, ElementId, FontWeight, InteractiveElement as _, IntoElement,
+ ParentElement as _, SharedString, StatefulInteractiveElement as _, Styled as _,
+ TestSupportExt as _, WeakEntity, Window, div, prelude::FluentBuilder as _,
+};
+use shared::copy::conversation as copy;
+use shared::copy::{self as shell_copy, Locale};
+use shared::icons::MakaIcon;
+use shared::theme::ActiveMakaPalette as _;
+
+use crate::rows::SentQuote;
+use crate::style::{LABEL_SIZE, RADIUS_CONTROL, RADIUS_SURFACE, SUPPORTING_SIZE, dp, dp_px};
+use crate::view::ConversationView;
+
+/// What a quote's chip reads aloud: its label and excerpt, then its note.
+pub(crate) fn spoken(
+ locale: Locale,
+ label: Option<&str>,
+ text: &str,
+ comment: Option<&str>,
+) -> SharedString {
+ let quoted = match label {
+ Some(label) => shell_copy::labeled(locale, label, text),
+ None => text.to_owned(),
+ };
+ let mut parts = vec![copy::QUOTE.in_locale(locale).to_owned(), quoted];
+ if let Some(comment) = comment {
+ parts.push(comment.to_owned());
+ }
+ shell_copy::parts(locale, &parts.iter().map(String::as_str).collect::<Vec<_>>()).into()
+}
+
+/// A chip's words: a rule on its leading edge (a block quote's), the label
+/// in ink at 500, then the excerpt in muted ink; on one line unless
+/// `expanded`, when the excerpt wraps whole and the note follows in ink.
+fn content(
+ label: Option<&SharedString>,
+ text: &SharedString,
+ comment: Option<&SharedString>,
+ expanded: bool,
+ cx: &App,
+) -> impl IntoElement {
+ let maka = cx.maka();
+ let label = label.map(|label| {
+ div().flex_none().font_weight(FontWeight::MEDIUM).text_color(maka.ink).child(label.clone())
+ });
+ let excerpt = div().min_w_0().text_color(maka.ink_muted).child(text.clone());
+ let words = if expanded {
+ v_flex().min_w_0().flex_1().gap(dp(2.)).children(label).child(excerpt).when_some(
+ comment,
+ |this, comment| {
+ this.child(
+ div()
+ .text_size(dp(SUPPORTING_SIZE))
+ .text_color(maka.ink)
+ .child(comment.clone()),
+ )
+ },
+ )
+ } else {
+ v_flex().min_w_0().flex_1().child(
+ h_flex().min_w_0().gap(dp(4.)).children(label).child(excerpt.flex_1().truncate()),
+ )
+ };
+ // The rule spans the first line's 16 px of ink, on its 20 px line.
+ let rule = div().flex_none().w(dp(2.)).h(dp(16.)).mt(dp(2.)).rounded_full();
+ h_flex()
+ .items_start()
+ .min_w_0()
+ .gap(dp(8.))
+ .text_size(dp(LABEL_SIZE))
+ .line_height(dp(20.))
+ .child(rule.bg(maka.border_strong))
+ .child(words)
+}
+
+/// A quote on a sent message: a quiet button on the sunken fill that opens
+/// to the whole excerpt and its note and closes again (Desktop's chip
+/// expands when its text is clipped; here it always may, so the keyboard
+/// reaches the whole text the same way).
+pub(crate) fn sent_quote_chip(
+ quote: &SentQuote,
+ view: WeakEntity<ConversationView>,
+ window: &Window,
+ cx: &App,
+) -> AnyElement {
+ let maka = cx.maka();
+ let locale = Locale::current(cx);
+ let spoken = spoken(locale, quote.label.as_deref(), "e.text, quote.comment.as_deref());
+ let key = quote.key.clone();
+ Button::new(shared::domain_element_id("sent-quote", "e.key))
+ .custom(
+ ButtonCustomVariant::new(cx)
+ .color(maka.sunken)
+ .foreground(maka.ink)
+ .hover(maka.sunken)
+ .active(maka.sunken)
+ .shadow(false),
+ )
+ .h_auto()
+ .min_h(dp(28.))
+ .max_w_full()
+ .min_w_0()
+ .px(dp(10.))
+ .py(dp(5.))
+ .rounded(dp_px(RADIUS_SURFACE, window))
+ .accessibility_label(spoken)
+ .selected(quote.expanded)
+ .child(content(
+ quote.label.as_ref(),
+ "e.text,
+ quote.comment.as_ref(),
+ quote.expanded,
+ cx,
+ ))
+ .on_click(move |_, _, cx| {
+ view.update(cx, |view, cx| view.toggle_quote(&key, cx)).ok();
+ })
+ .into_any_element()
+}
+
+/// A quote staged for the next message, above the composer's draft: the
+/// chip on the sunken fill with a remove button at its end.
+pub(crate) fn staged_quote_chip(
+ id: ElementId,
+ label: Option<&SharedString>,
+ text: &SharedString,
+ remove: impl Fn(&mut Window, &mut App) + 'static,
+ window: &Window,
+ cx: &App,
+) -> AnyElement {
+ let maka = cx.maka();
+ let locale = Locale::current(cx);
+ let spoken = spoken(locale, label.map(|label| label.as_str()), text, None);
+ let remove_label = copy::remove_quote(locale, text);
+ h_flex()
+ .id(id)
+ .test_support()
+ .aria_label(spoken)
+ .max_w_full()
+ .min_w_0()
+ .h(dp(28.))
+ .pl(dp(10.))
+ .pr(dp(4.))
+ .gap(dp(6.))
+ .rounded(dp(RADIUS_SURFACE))
+ .bg(maka.sunken)
+ .child(div().min_w_0().flex_1().child(content(label, text, None, false, cx)))
+ .child(
+ Button::new("quote-remove")
+ .ghost()
+ .size(dp(20.))
+ .p_0()
+ .flex_none()
+ .rounded(dp_px(RADIUS_CONTROL, window))
+ .child(
+ Icon::new(MakaIcon::Close)
+ .with_size(dp_px(12., window))
+ .text_color(maka.ink_muted),
+ )
+ .accessibility_label(remove_label.clone())
+ .tooltip(remove_label)
+ .on_click(move |_, window, cx| remove(window, cx)),
+ )
+ .into_any_element()
+}
diff --git a/apps/desktop-gpui/crates/conversation/src/rows.rs b/apps/desktop-gpui/crates/conversation/src/rows.rs
index cf87a89d3d..e20b258ced 100644
--- a/apps/desktop-gpui/crates/conversation/src/rows.rs
+++ b/apps/desktop-gpui/crates/conversation/src/rows.rs
@@ -29,16 +29,18 @@
use std::collections::{HashMap, HashSet};
use std::ops::Range;
+use std::sync::Arc;
use gpui_kit::{ElementId, SharedString};
use host_protocol::{
AttachmentKind, AttachmentRef, InteractionClosureReason, InteractionRequest,
- PermissionDecision, PermissionPrompt, PermissionReview, SandboxBoundaryRequest,
+ PermissionDecision, PermissionPrompt, PermissionReview, QuoteRef, SandboxBoundaryRequest,
SandboxBoundaryScope, SandboxBoundaryStatus, StorageRef, TurnProviderRetry,
};
use serde_json::Value;
use shared::diff::DiffRows;
use shared::domain_element_id;
+use transcript_model::edits::{EditedFile, EditedTurns};
use transcript_model::{
InteractionItem, InteractionState, ItemKey, Resolution, ThinkingItem, ToolItem, ToolStatus,
Transcript, TurnItem, TurnView, TurnViewStatus,
@@ -70,6 +72,12 @@ pub fn footer_element_id(turn_id: &str) -> ElementId {
domain_element_id("turn-footer", turn_id)
}
+/// The `ElementId` of the card under turn `turn_id` that lists the files
+/// it edited.
+pub fn edits_element_id(turn_id: &str) -> ElementId {
+ domain_element_id("turn-edits", turn_id)
+}
+
/// The `ElementId` of the row above the first message that loads, or
/// marks the end of, older history.
pub fn history_element_id() -> ElementId {
@@ -85,16 +93,35 @@ pub(crate) enum RowKey {
turn_id: String,
key: ItemKey,
},
+ /// The card of the files the turn edited, before its footer.
+ Edits {
+ turn_id: String,
+ },
Footer {
turn_id: String,
},
}
impl RowKey {
+ /// The turn the row belongs to; `None` for the older-history row.
+ pub(crate) fn turn_id(&self) -> Option<&str> {
+ match self {
+ Self::History => None,
+ Self::Item { turn_id, .. } | Self::Edits { turn_id } | Self::Footer { turn_id } => {
+ Some(turn_id)
+ }
+ }
+ }
+
+ pub(crate) fn is_of_turn(&self, turn_id: &str) -> bool {
+ self.turn_id() == Some(turn_id)
+ }
+
pub(crate) fn element_id(&self) -> ElementId {
match self {
Self::History => history_element_id(),
Self::Item { turn_id, key } => item_element_id(turn_id, key),
+ Self::Edits { turn_id } => edits_element_id(turn_id),
Self::Footer { turn_id } => footer_element_id(turn_id),
}
}
@@ -109,14 +136,27 @@ pub(crate) struct Row {
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum RowBody {
History(HistoryRow),
- User { text: SharedString, attachments: Vec<SentAttachment> },
+ User { text: SharedString, attachments: Vec<SentAttachment>, quotes: Vec<SentQuote> },
Thinking(ThinkingRow),
Text { text: SharedString, streaming: bool, interrupted: bool },
Tool(ToolRow),
Prompt(PromptRow),
+ Edits(EditsRow),
... 49450 lines suppressed ...
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org