From 22f1b55b0926e981c537cb8d42b314ae364e6ed6 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 13:10:00 +0200 Subject: [PATCH 01/17] docs: plan sidebar view options --- docs/research/sidebar-view-options.md | 327 ++++++++++++++++++++++++++ 1 file changed, 327 insertions(+) create mode 100644 docs/research/sidebar-view-options.md diff --git a/docs/research/sidebar-view-options.md b/docs/research/sidebar-view-options.md new file mode 100644 index 0000000000..b08bab9e4d --- /dev/null +++ b/docs/research/sidebar-view-options.md @@ -0,0 +1,327 @@ +# Sidebar view options and conversation links + +Status: planning +Branch: `wip/sidebar-view-options` +Base: `origin/main` at `3fc7bb0` (`v0.2.20`) +Research date: 2026-08-22 + +## Goal + +Make source-control metadata in the sidebar describe the conversation it belongs +to, add a small set of persistent sidebar view options, and add right-click copy +actions for both Zeron and the conversation's actual harness. + +This plan deliberately keeps the project selector as a scope control. View +options change presentation inside that scope; they do not silently retarget the +new-session canvas or the selected project. + +## Current failure + +The registry shape makes `Chat.branch` look conversation-owned, but its writer is +checkout-owned: + +- `crates/engine/src/diff_sync.rs::sync_entry` captures one checkout snapshot, + then writes that snapshot's branch to every chat registered against the + checkout. +- `crates/ui/src/change_requests.rs::desired_watch_targets` requires a non-empty + `Chat.branch`, but keys the live watch by device and cwd. +- `change_request_for_chat` checks branch equality against that checkout + snapshot, so all chats sharing the main checkout converge on the same branch + and PR. +- The new-chat picker can provisionally stamp a selected/current ref, which is + why the row often gains metadata only after the branch picker or checkout path + has been exercised. + +This is internally consistent as *live checkout state*, but misleading as +*conversation metadata*. A shared checkout changing branch is real; rewriting +the historical identity of every conversation that ever used it is not. + +## Reference findings + +### Codex desktop + +Static inspection of the installed ChatGPT/Codex app +(`com.openai.codex`, v26.818.31338) found: + +- “Organize sidebar” keeps organization (`By project`, conditional + `By connection`, `In one list`) separate from sorting (`Priority`, + `Last updated`, `Manual order`). These preferences are persisted at sidebar + scope, not per task. +- Branch and PR lookup is conversation-scoped. The lookup includes the row's + conversation id, host, cwd, branch, and origin URL. Codex does not need to + print the raw branch on every row; the captured branch primarily powers the + compact PR status. +- Right-click uses `Copy > Copy deeplink` and copies + `codex://threads/`. Public sharing is a separate feature and + should not be conflated with an application deeplink. + +### T3 Code + +At [`pingdotgg/t3code@11f0513`](https://github.com/pingdotgg/t3code/tree/11f051373e79b38fa16f3ec1af825f5164907c1b): + +- Branch and worktree are persisted on each thread shell, not derived from the + repository's current branch. [Thread shell contract](https://github.com/pingdotgg/t3code/blob/11f051373e79b38fa16f3ec1af825f5164907c1b/packages/contracts/src/orchestration.ts#L449-L474) +- Each row queries source-control status through that thread's environment and + cwd/worktree. Live PR state is gated by the thread branch; a mismatch is + represented rather than painted onto every row. [Row lookup and gating](https://github.com/pingdotgg/t3code/blob/11f051373e79b38fa16f3ec1af825f5164907c1b/apps/web/src/components/Sidebar.tsx#L792-L918) +- The current sidebar keeps project scope separate from its lifecycle/inbox + organization. The legacy “Sidebar options” menu offers project/thread sorting + and a visible-row limit. [Legacy sidebar options](https://github.com/pingdotgg/t3code/blob/11f051373e79b38fa16f3ec1af825f5164907c1b/apps/web/src/components/LegacySidebar.tsx#L2602-L2705) +- Sidebar and chat-header menus share one action builder. Its Copy submenu + currently exposes path, branch, and thread ID; it has no provider conversation + link yet. [Shared action builder](https://github.com/pingdotgg/t3code/blob/11f051373e79b38fa16f3ec1af825f5164907c1b/apps/web/src/components/threadActionMenu.logic.ts#L46-L140) + +### Hermes Desktop + +At [`NousResearch/hermes-agent@667c787`](https://github.com/NousResearch/hermes-agent/tree/667c787a1c4b332ea763fb24910268fbd5f7a219): + +- The view menu has an unusually clear taxonomy: Grouping, Ordering, Show, then + Filters. [Option vocabulary](https://github.com/NousResearch/hermes-agent/blob/667c787a1c4b332ea763fb24910268fbd5f7a219/apps/desktop/src/app/chat/sidebar/filter-menu.tsx#L74-L113) +- Branch identity is captured on the individual session when it starts/resumes, + explicitly avoiding attribution of the main checkout's transient branch to + past sessions. [Backend rationale](https://github.com/NousResearch/hermes-agent/blob/667c787a1c4b332ea763fb24910268fbd5f7a219/hermes_state.py#L6505-L6537) +- PR state is keyed by repository root and the session's recorded branch, with + a per-session override for work that moved to another branch/worktree. + [PR store](https://github.com/NousResearch/hermes-agent/blob/667c787a1c4b332ea763fb24910268fbd5f7a219/apps/desktop/src/store/pull-requests.ts#L8-L78) +- PR lookup is lazy and remote-aware: it runs only when PR badges/filtering are + requested and uses the checkout-owning host's `gh` capability. + [Sidebar lookup](https://github.com/NousResearch/hermes-agent/blob/667c787a1c4b332ea763fb24910268fbd5f7a219/apps/desktop/src/app/chat/sidebar/index.tsx#L782-L840) +- Hermes registers `hermes://` and routes `hermes://open/` into a + session, although its sidebar currently copies only the bare ID. + [Deep-link resolver](https://github.com/NousResearch/hermes-agent/blob/667c787a1c4b332ea763fb24910268fbd5f7a219/apps/desktop/src/lib/hermes-open-target.ts#L68-L108) + +## Decisions + +### 1. Separate conversation source context from live checkout state + +Add an optional, explicit conversation-owned source record rather than +continuing to overload the legacy `Chat.branch` field: + +```text +ConversationSourceContext + checkout_id canonical device-scoped checkout identity + repo_root host-resolved repository root + cwd actual run cwd/worktree + branch observed branch, if attached + head_sha observed HEAD, if available + observed_at capture timestamp +``` + +The host captures this after a queued run's worktree directive is materialized +and before the harness starts/resumes. A later turn may refresh *that chat's* +context if the user intentionally continued it after changing the shared +checkout. Filesystem/diff watchers may continue publishing live checkout state, +but must stop rewriting conversation source records. + +The composer-selected ref remains a provisional first-frame label. The host's +observed context is authoritative once the first run starts. + +Migration is conservative: + +- Existing rows start with no trusted conversation source context. +- A uniquely isolated worktree may be backfilled when checkout identity and + branch are unambiguous. +- Shared-main-checkout `Chat.branch` values are not promoted automatically; + the next run/resume captures the truth for that conversation. +- The legacy scalar fields remain readable for older engines during a bounded + compatibility period, but new UI branch/PR rendering prefers the explicit + context. + +### 2. Resolve PRs from conversation context + +Change the PR demand/cache key from “current device + cwd” to a canonical +repository identity plus the conversation's recorded branch, still routed to +the owning device. Conversations recorded on the same repository+branch may +share one lookup; unrelated conversations on the same mutable cwd may not. + +Rules: + +- A conversation override wins when a harness/tool flow explicitly creates or + discovers a PR on another branch. +- Otherwise resolve by recorded repo+branch. +- No source context means no badge, not a guess from the active checkout. +- A live checkout mismatch may appear in tooltip/detail state, but it does not + replace the conversation's association. +- Keep the existing host-local `gh`, sanitized RPC, TTL, and last-success + behavior from PR #116. +- Start/retain PR watches only when `Show pull requests` is on or a PR filter + needs them. + +### 3. Keep scope and view controls separate + +The existing All projects/project selector remains the prominent scope control. +Add one quiet view-options button beside it, persisted in device-local +`ui-settings.json`. + +Focused first version: + +```text +Organize + By project + By device + In one list + +Sort + Last updated + Created + +Show + Branch + Pull request +``` + +Defaults preserve today's presentation (`In one list`, `Last updated`, Branch +on, Pull request on). Organizing deduplicates project/device context into section +headers; it does not change the selected project, open tabs, or new-session +target. Section collapsed state is local to the selected organization mode. + +Follow-ups, not first-slice requirements: + +- Priority sort (needs input/unread first) once its stable-order behavior is + specified. +- Manual order and custom sections. +- Status and PR-state filters. +- Compact/comfortable/detailed density; Hermes correctly treats this as an + appearance preference rather than overloading organization. + +### 4. Use a shared, capability-driven Copy submenu + +Build one session action model and render it from the sidebar right-click menu; +the chat header can adopt the same model later. The menu contains: + +```text +Copy > + Zeron deeplink + conversation link (only when verified/supported) + Session ID +``` + +Use explicit items instead of making one action place surprising multi-line +content on the clipboard. This still gives both links, and makes the distinction +between app navigation and public sharing visible. + +The resolver is bound to the row, never the globally selected harness: + +```text +ConversationLinks + zeron: required internal deeplink + external: optional { label, url } +``` + +Initial provider support: + +- Codex: `codex://threads/` (verified in the installed app). +- Hermes: candidate `hermes://open/`; enable only after the + ACP session id is verified to match the desktop route id end to end. +- Claude Code, Cursor, Grok, Pi, and OpenCode: omit the external item until each + adapter can produce a verified link. Never synthesize a URL from an opaque id. + +The Zeron URI must include an opaque workspace/profile locator in addition to +the durable chat id so local, synced, and development profiles cannot collide. +Proposed shape: + +```text +zeron://open/chat/?workspace= +``` + +“Copy Zeron deeplink” is complete only when the URI round-trips into the correct +chat. That requires URL-scheme registration, cold-start argument/event parsing, +profile-aware chat resolution after bootstrap, and an actionable error when the +link names an unavailable local profile. Do not ship a clipboard action that +copies an unhandled URI. + +## Implementation slices + +### Slice A — conversation source truth + +1. Add the optional source-context wire/doc model in `zeron-proto` and + `zeron-doc`; keep old rows readable. +2. Capture the actual git context in the host command drain after worktree + creation and before dispatch. +3. Remove branch fan-out from `diff_sync::sync_entry`; retain checkout diff and + `checkout_id` upkeep as live checkout responsibilities. +4. Re-key change-request demand and mapping around recorded repo+branch. +5. Render branch/PR from the new context, with a conservative legacy fallback + only for unambiguous worktrees. + +### Slice B — view options + +1. Add typed `SidebarOrganization`, `SidebarSort`, `show_branch`, and `show_pr` + settings with serde defaults and compatibility tests. +2. Add the anchored view menu beside the project scope control. +3. Derive one presentation model before rendering so grouping, ordering, FLIP + keys, archived counts, and keyboard traversal consume the same order. +4. Make PR watch demand follow `show_pr` (and future PR filters), instead of + polling metadata the UI cannot expose. + +### Slice C — links and shared actions + +1. Define a pure session-action/link model with exact clipboard payload tests. +2. Add a workspace-scoped Zeron URI builder/parser and inbound route intent. +3. Register and handle `zeron://` in macOS packaging first; add Linux desktop + entry and Windows registration with their packaging work rather than + claiming unsupported platforms. +4. Add harness conversation-link capability, beginning with verified Codex. +5. Render `Copy` as a submenu in the existing session context menu and provide + brief copied feedback without closing over the currently selected chat. + +These are separate reviewable behaviors. If implemented as OSS contributions, +prefer three focused branches/PRs rather than one broad sidebar rewrite: + +```text +origin/main -> conversation-source-context -> sidebar-view-options +origin/main -----------------------------> conversation-deeplinks +``` + +The source-context slice is the dependency for correct branch/PR display. The +deeplink slice can be developed independently if it reads existing chat and +harness-session identity only. + +## Verification + +Source-context regression fixture: + +1. Create chat A and run it on `main` in the shared checkout. +2. Change that checkout to `feature/a`; create/run chat B. +3. Verify A still reads `main` and B reads `feature/a`. +4. Change the checkout again without running either chat; neither row changes. +5. Resume A; only A adopts the newly observed branch. +6. Resolve different PRs for A and B by recorded branch; verify no badge fans + out by cwd. + +View tests cover settings migration/defaults, scope remaining independent, +stable section/row keys, archived counts, and sort/group derivation. Link tests +cover URI encoding, profile collisions, unavailable profiles, unsupported +harnesses, exact Codex URI output, and menu-open snapshotting so copying from a +background row never uses the selected chat. + +Run the narrow checks first: + +```bash +cargo fmt --all -- --check +cargo test -p zeron-proto +cargo test -p zeron-doc +cargo test -p zeron-engine change_request +cargo test -p zeron-ui change_request +cargo test -p zeron-ui shell +``` + +Broaden to `cargo test -p zeron-engine`, `cargo test -p zeron-ui`, and finally +`cargo test --workspace` in proportion to the implemented slice. + +## Coordination + +PR [#181, pull request dashboard](https://github.com/zeronsh/comet/pull/181) +currently overlaps `crates/ui/src/shell.rs` but is a separate product surface. +Do not fold its dashboard into this contribution. Rebase the implementation +branch on the current `origin/main` immediately before coding and, if #181 has +landed, adapt the sidebar footer/menu without duplicating its route or provider +model. + +## Non-goals + +- Replacing the existing project filter or tab model. +- Building the pull-request dashboard from #181. +- Public/shareable transcript links or access-control changes. +- Inferring external harness URLs from undocumented opaque ids. +- Mobile parity in the first desktop slice. From 054c17e68a4e8e4f2f3b75826b8855912be02895 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 13:45:37 +0200 Subject: [PATCH 02/17] feat: add conversation-aware sidebar views --- apps/zeron/src/main.rs | 4 + crates/doc/src/registry.rs | 29 ++ crates/doc/src/registry/tests.rs | 1 + crates/doc/src/workspace.rs | 52 ++++ crates/engine/src/change_requests.rs | 58 +++- crates/engine/src/diff_sync.rs | 22 +- crates/engine/src/doc_host.rs | 24 +- crates/engine/src/repos.rs | 11 + crates/engine/src/rpc.rs | 5 +- crates/engine/src/workspace_host.rs | 9 + crates/engine/tests/workspace_sync.rs | 1 + crates/proto/src/entities.rs | 22 ++ crates/sync/tests/registry_client.rs | 1 + crates/sync/tests/registry_edge.rs | 1 + crates/ui/src/change_requests.rs | 123 +++++++- crates/ui/src/changes.rs | 1 + crates/ui/src/lib.rs | 22 ++ crates/ui/src/links.rs | 190 ++++++++++++ crates/ui/src/settings.rs | 32 ++ crates/ui/src/settings/archived.rs | 1 + crates/ui/src/shell.rs | 209 ++++++++++++- crates/ui/src/shell/spaces.rs | 405 +++++++++++++++++++++++++- crates/ui/src/state.rs | 74 ++++- dist/macos/Info.plist | 11 + dist/zeron.desktop | 3 +- docs/research/sidebar-view-options.md | 2 +- 26 files changed, 1241 insertions(+), 72 deletions(-) create mode 100644 crates/ui/src/links.rs diff --git a/apps/zeron/src/main.rs b/apps/zeron/src/main.rs index 87bb6f9ba8..75fbb92259 100644 --- a/apps/zeron/src/main.rs +++ b/apps/zeron/src/main.rs @@ -13,6 +13,9 @@ use clap::{Parser, Subcommand}; struct Cli { #[command(subcommand)] command: Option, + /// Open a Zeron conversation URL. + #[arg(value_name = "URL")] + open_url: Option, } #[derive(Subcommand)] @@ -195,6 +198,7 @@ fn main() -> anyhow::Result<()> { edge_token, org_id: std::env::var("ZERON_ORG_ID").ok(), default_harness: zeron_ui::HarnessId::ClaudeCode, + initial_url: cli.open_url, }); Ok(()) } diff --git a/crates/doc/src/registry.rs b/crates/doc/src/registry.rs index 724508b8cb..6269ddefde 100644 --- a/crates/doc/src/registry.rs +++ b/crates/doc/src/registry.rs @@ -872,6 +872,14 @@ impl RegistryDoc { ("cwd", opt_str(chat.cwd.as_deref())), ("branch", opt_str(chat.branch.as_deref())), ("checkoutId", opt_str(chat.checkout_id.as_deref())), + ( + "sourceContext", + chat.source_context + .as_ref() + .map(serde_json::to_value) + .transpose()? + .unwrap_or(Value::Null), + ), ("config", config), ( "lastMessagePreview", @@ -1016,6 +1024,27 @@ impl RegistryDoc { Ok(true) } + pub fn set_chat_source_context( + &mut self, + chat_id: &str, + context: &zeron_proto::ConversationSourceContext, + ) -> Result { + if !self.row_exists(KIND_CHATS, chat_id) { + return Ok(false); + } + self.write( + KIND_CHATS, + chat_id, + OpKind::Update, + fields([ + ("sourceContext", serde_json::to_value(context)?), + ("branch", json!(context.branch)), + ("checkoutId", json!(context.checkout_id)), + ]), + ); + Ok(true) + } + /// Retarget the chat onto another folder — the mid-session "switch to an /// existing worktree" move. Harness resume is cwd-scoped, so the next run /// in the new folder starts a fresh harness conversation by design. diff --git a/crates/doc/src/registry/tests.rs b/crates/doc/src/registry/tests.rs index 6c72cb7bf1..c93f89c207 100644 --- a/crates/doc/src/registry/tests.rs +++ b/crates/doc/src/registry/tests.rs @@ -257,6 +257,7 @@ fn chat(id: &str, device_id: &str) -> Chat { cwd: Some("/tmp/repo".into()), branch: Some("main".into()), checkout_id: None, + source_context: None, config: Some(ChatConfig { harness: HarnessId::Mock, model: Some("mock-1".into()), diff --git a/crates/doc/src/workspace.rs b/crates/doc/src/workspace.rs index e1fe8868ae..f668c8b18c 100644 --- a/crates/doc/src/workspace.rs +++ b/crates/doc/src/workspace.rs @@ -244,6 +244,12 @@ impl WorkspaceDoc { set_opt_str(&row, "cwd", chat.cwd.as_deref())?; set_opt_str(&row, "branch", chat.branch.as_deref())?; set_opt_str(&row, "checkoutId", chat.checkout_id.as_deref())?; + match &chat.source_context { + Some(context) => { + row.insert("sourceContext", LoroValue::from(serde_json::to_value(context)?))? + } + None => row.delete("sourceContext")?, + } match &chat.config { Some(config) => row.insert("config", LoroValue::from(serde_json::to_value(config)?))?, None => row.delete("config")?, @@ -345,6 +351,26 @@ impl WorkspaceDoc { Ok(true) } + /// Capture repository identity for one conversation. Legacy branch and + /// checkout fields are written alongside it for older synced clients. + pub fn set_chat_source_context( + &self, + chat_id: &str, + context: &zeron_proto::ConversationSourceContext, + ) -> Result { + let Some(row) = self.existing_row("chats", chat_id) else { + return Ok(false); + }; + row.insert( + "sourceContext", + LoroValue::from(serde_json::to_value(context)?), + )?; + row.insert("branch", context.branch.as_str())?; + row.insert("checkoutId", context.checkout_id.as_str())?; + self.doc.commit(); + Ok(true) + } + /// Retarget the chat onto another folder — the mid-session "switch to an /// existing worktree" move (t3code `reuseExistingWorktree`). LWW set; /// `false` when no such row. Harness resume is cwd-scoped, so the next @@ -631,6 +657,8 @@ pub(crate) struct RawChat { branch: Option, #[serde(default)] checkout_id: Option, + #[serde(default)] + source_context: Option, /// LENIENT: a config this build can't decode (a harness/reasoning/sandbox /// id from a NEWER peer — field incident: pre-v0.2.10 laptops dropped /// every `"opencode"` chat row wholesale, so new sessions silently never @@ -685,6 +713,7 @@ impl From for Chat { cwd: raw.cwd, branch: raw.branch, checkout_id: raw.checkout_id, + source_context: raw.source_context, config: raw.config, last_message_preview: raw.last_message_preview, last_message_at: raw.last_message_at.map(dt), @@ -751,6 +780,7 @@ mod tests { cwd: Some("/tmp/repo".into()), branch: Some("main".into()), checkout_id: None, + source_context: None, config: Some(ChatConfig { harness: HarnessId::Mock, model: Some("mock-1".into()), @@ -829,6 +859,28 @@ mod tests { assert!(ws.chat("nope").unwrap().is_none()); } + #[test] + fn conversation_source_context_round_trips_with_legacy_fields() { + let ws = WorkspaceDoc::new(); + ws.upsert_chat(&chat("chat-1", "dev-a")).unwrap(); + let context = zeron_proto::ConversationSourceContext { + checkout_id: "checkout-a".into(), + repo_root: "/repo".into(), + cwd: "/repo/worktree".into(), + branch: "feature/sidebar".into(), + head_sha: Some("abc123".into()), + observed_at: ts(8_000), + }; + assert!( + ws.set_chat_source_context("chat-1", &context) + .unwrap() + ); + let row = ws.chat("chat-1").unwrap().expect("row exists"); + assert_eq!(row.source_context, Some(context)); + assert_eq!(row.branch.as_deref(), Some("feature/sidebar")); + assert_eq!(row.checkout_id.as_deref(), Some("checkout-a")); + } + #[test] fn rows_round_trip() { let ws = WorkspaceDoc::new(); diff --git a/crates/engine/src/change_requests.rs b/crates/engine/src/change_requests.rs index da8da75f90..c2012386b1 100644 --- a/crates/engine/src/change_requests.rs +++ b/crates/engine/src/change_requests.rs @@ -16,8 +16,8 @@ use zeron_proto::CheckoutChangeRequestStatus; use crate::repos::{CheckoutIdentity, Repos}; use crate::source_control::{ - ChangeRequestError, ChangeRequestResolver, CheckoutChangeRequestLookup, CheckoutSourceContext, - parse_git_remote, + BranchHeadContext, ChangeRequestError, ChangeRequestResolver, CheckoutChangeRequestLookup, + CheckoutSourceContext, parse_git_remote, }; const WITH_CHANGE_REQUEST_TTL: Duration = Duration::from_secs(2 * 60); @@ -117,6 +117,17 @@ impl CheckoutChangeRequests { pub async fn watch( &self, cwd: &Path, + ) -> Result, ChangeRequestError> { + self.watch_for_branch(cwd, None).await + } + + /// Resolve a PR for the conversation-owned branch while using `cwd` only + /// for repository/remote identity. This keeps a later checkout switch from + /// changing which PR an older conversation displays. + pub async fn watch_for_branch( + &self, + cwd: &Path, + branch: Option<&str>, ) -> Result, ChangeRequestError> { let identity = self .inner @@ -124,18 +135,33 @@ impl CheckoutChangeRequests { .checkout_identity(cwd) .await .map_err(|_| ChangeRequestError::RepositoryUnavailable)?; - Ok(self.watch_checkout(cwd.to_owned(), identity)) + Ok(self.watch_checkout_for_branch( + cwd.to_owned(), + identity, + branch.map(str::to_owned), + )) } + #[cfg(test)] fn watch_checkout( &self, cwd: PathBuf, identity: CheckoutIdentity, + ) -> BoxStream<'static, CheckoutChangeRequestStatus> { + self.watch_checkout_for_branch(cwd, identity, None) + } + + fn watch_checkout_for_branch( + &self, + cwd: PathBuf, + identity: CheckoutIdentity, + requested_branch: Option, ) -> BoxStream<'static, CheckoutChangeRequestStatus> { let state = SubscriptionState { service: self.clone(), cwd, identity, + requested_branch, lease: None, last_emitted: None, }; @@ -144,7 +170,7 @@ impl CheckoutChangeRequests { if state.service.inner.shutdown.is_cancelled() { return None; } - let source = match state + let mut source = match state .service .inner .lookup @@ -163,6 +189,16 @@ impl CheckoutChangeRequests { continue; } }; + if let Some(branch) = state.requested_branch.as_deref() + && source.branch.local_branch != branch + { + source.branch = BranchHeadContext::resolve( + branch, + None, + source.branch.remote_name.as_deref(), + source.branch.remote_url.as_deref(), + ); + } let key = cache_key(&state.identity.id, &source); if state.lease.as_ref().map(|lease| &lease.key) != Some(&key) { state.lease = Some(state.service.acquire(key.clone())); @@ -310,6 +346,7 @@ struct SubscriptionState { service: CheckoutChangeRequests, cwd: PathBuf, identity: CheckoutIdentity, + requested_branch: Option, lease: Option, last_emitted: Option, } @@ -486,6 +523,19 @@ mod tests { } } + #[tokio::test] + async fn requested_conversation_branch_overrides_live_checkout_branch() { + let lookup = FakeLookup::new(source("main"), [Ok(Some(pull_request(90)))]); + let service = service(lookup, Timing::default()); + let mut stream = service.watch_checkout_for_branch( + PathBuf::from("/checkout"), + identity(), + Some("feature/sidebar".into()), + ); + let snapshot = stream.next().await.expect("opening snapshot"); + assert_eq!(snapshot.branch, "feature/sidebar"); + } + #[tokio::test] async fn two_subscribers_share_one_provider_query() { let lookup = FakeLookup::new(source("feature/status"), [Ok(Some(pull_request(90)))]); diff --git a/crates/engine/src/diff_sync.rs b/crates/engine/src/diff_sync.rs index 6f9ebd0994..08fc5ec615 100644 --- a/crates/engine/src/diff_sync.rs +++ b/crates/engine/src/diff_sync.rs @@ -11,17 +11,17 @@ //! - a [`DiffSidecar`] JSON `POST {edge}/diff/{chatId}` for every syncing chat of //! the checkout (bearer = engine edge token), so "review pending changes while //! the host sleeps" works; -//! - `chat.branch` upkeep: the same fs events cover the checkout's git dir (HEAD), -//! so each snapshot reconciles mismatched workspace chat rows' `branch` (and -//! `checkoutId` at reconcile time). +//! Checkout snapshots remain live checkout state. Conversation branch identity +//! is captured by the command host and is never rewritten from this watcher; +//! otherwise one checkout change would relabel every chat sharing that folder. //! //! Fast recursive `notify` watchers (debounced [`WATCH_DEBOUNCE`]) are backed by a //! slow 2-minute repair tick because native watchers may coalesce or drop events. //! Snapshots carry a sha256 checksum; an unchanged checksum publishes nothing. //! //! Reconcile is deliberately damped, because it runs on *every* workspace chat -//! row change — including the `branch`/`checkoutId` writes `sync_entry` itself -//! makes. Checkout identities are memoized per cwd (chat-watch reconciles spawn +//! row change — including the `checkoutId` writes reconcile itself makes. +//! Checkout identities are memoized per cwd (chat-watch reconciles spawn //! no git; the repair tick revalidates), and an entry whose chats vanish is torn //! down only after [`REPAIR_INTERVAL`] of continuous absence rather than on the //! first pass that misses it. See [`resolve_identity`] for the incident this @@ -626,17 +626,6 @@ async fn sync_entry(inner: &Arc, entry: &Arc) { } }; - // chat.branch upkeep — the git-dir watcher covers HEAD, so every snapshot - // reconciles mismatched rows (repair tick covers dropped events). - let chats = lock(&entry.chats).clone(); - for chat in &chats { - if chat.branch.as_deref() != Some(snapshot.branch.as_str()) - && let Err(err) = inner.workspace.set_chat_branch(&chat.id, &snapshot.branch) - { - tracing::debug!(chat = %chat.id, error = %err, "diff-sync: branch write failed"); - } - } - if lock(&entry.checksum).as_deref() == Some(snapshot.checksum.as_str()) { return; // unchanged — publish nothing } @@ -663,6 +652,7 @@ async fn sync_entry(inner: &Arc, entry: &Arc) { publish_watch_with(inner, Some(diff)); // Latest-only sidecar to every syncing chat's session DO slot. + let chats = lock(&entry.chats).clone(); if let Some(edge) = &inner.edge { for chat in &chats { let sidecar = DiffSidecar { diff --git a/crates/engine/src/doc_host.rs b/crates/engine/src/doc_host.rs index 65504b9972..4a29d1f2be 100644 --- a/crates/engine/src/doc_host.rs +++ b/crates/engine/src/doc_host.rs @@ -17,6 +17,7 @@ //! the host's relay receives it and warm-opens the doc, which drains the queue. use std::collections::{HashMap, HashSet}; +use std::path::Path; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, MutexGuard, OnceLock, PoisonError, Weak}; @@ -31,7 +32,7 @@ use zeron_doc::{ SessionCommandStatus, SessionDoc, SessionMessageEntry, evaluate_command, join_continuation_entries, }; -use zeron_proto::{HarnessId, UserInputAnswer, UserInputQuestion}; +use zeron_proto::{ConversationSourceContext, HarnessId, UserInputAnswer, UserInputQuestion}; use zeron_sync::DocsStore; use crate::sessions::{SessionsEngine, SteerOutcome}; @@ -3135,6 +3136,11 @@ impl DocHost { tracing::warn!(chat = %chat_id, error = %err, "worktree branch stamp failed"); } } + if let Some(context) = self.capture_source_context(&request.cwd).await + && let Err(err) = ws.set_chat_source_context(chat_id, &context) + { + tracing::warn!(chat = %chat_id, error = %err, "conversation source stamp failed"); + } } let harness = self.harness_for_request(chat_id, &request); // A row with no config renders no harness glyph (and every @@ -3293,6 +3299,22 @@ impl DocHost { } } + async fn capture_source_context(&self, cwd: &str) -> Option { + let repos = self.inner.repos.get()?; + let path = Path::new(cwd); + let identity = repos.checkout_identity(path).await.ok()?; + let branch = repos.current_branch(path).await.ok()?; + let head_sha = repos.head_sha(path).await.ok().flatten(); + Some(ConversationSourceContext { + checkout_id: identity.id, + repo_root: identity.root.to_string_lossy().into_owned(), + cwd: cwd.to_string(), + branch, + head_sha, + observed_at: chrono::Utc::now(), + }) + } + /// Create (or reuse) the isolated worktree a Run's [`zeron_proto::WorktreeSpec`] /// asks for, returning the resolved cwd plus the fresh worktree when one was /// actually created. Reuse guard: a chat whose row already points inside a diff --git a/crates/engine/src/repos.rs b/crates/engine/src/repos.rs index e5253742a4..a91cc49777 100644 --- a/crates/engine/src/repos.rs +++ b/crates/engine/src/repos.rs @@ -221,6 +221,17 @@ impl Repos { }) } + /// Commit checked out at `path`, or `None` for a repository without an + /// initial commit. + pub async fn head_sha(&self, path: &Path) -> Result, EngineError> { + match self.git(&["rev-parse", "--verify", "HEAD^{commit}"], Some(path)).await { + Ok(sha) if !sha.is_empty() => Ok(Some(sha)), + Ok(_) => Ok(None), + Err(_) if self.is_repo(path).await => Ok(None), + Err(err) => Err(err), + } + } + /// Fetch every configured remote without pruning or integrating anything /// into the active branch. This intentionally updates refs only. pub async fn fetch_all(&self, repo_path: &Path) -> Result<(), EngineError> { diff --git a/crates/engine/src/rpc.rs b/crates/engine/src/rpc.rs index 8a7e36e84f..be45ba1052 100644 --- a/crates/engine/src/rpc.rs +++ b/crates/engine/src/rpc.rs @@ -124,8 +124,11 @@ struct RepoPathParams { } #[derive(Debug, Deserialize)] +#[serde(rename_all = "camelCase")] struct CheckoutChangeRequestParams { cwd: String, + #[serde(default)] + branch: Option, } #[derive(Debug, Deserialize)] @@ -1339,7 +1342,7 @@ impl RpcService for EngineRpc { let cwd = self.change_request_root(&p.cwd).await?; let stream = self .change_requests - .watch(&cwd) + .watch_for_branch(&cwd, p.branch.as_deref()) .await .map_err(|error| RpcError::Failed(error.to_string()))? .filter_map(|status| async move { serde_json::to_value(status).ok() }); diff --git a/crates/engine/src/workspace_host.rs b/crates/engine/src/workspace_host.rs index 2f8ad2fba7..76431d9218 100644 --- a/crates/engine/src/workspace_host.rs +++ b/crates/engine/src/workspace_host.rs @@ -872,6 +872,7 @@ impl WorkspaceHost { })), branch: None, checkout_id: None, + source_context: None, config, last_message_preview: None, last_message_at: None, @@ -1058,6 +1059,14 @@ impl WorkspaceHost { Ok(self.mutate(|doc| doc.set_chat_branch(chat_id, branch))?) } + pub fn set_chat_source_context( + &self, + chat_id: &str, + context: &zeron_proto::ConversationSourceContext, + ) -> Result { + Ok(self.mutate(|doc| doc.set_chat_source_context(chat_id, context))?) + } + /// Retarget a chat onto another folder (mid-session switch to an existing /// worktree). Resume is cwd-scoped — the next run there starts fresh. pub fn set_chat_cwd(&self, chat_id: &str, cwd: &str) -> Result { diff --git a/crates/engine/tests/workspace_sync.rs b/crates/engine/tests/workspace_sync.rs index 632a9e188e..7bb4ef161c 100644 --- a/crates/engine/tests/workspace_sync.rs +++ b/crates/engine/tests/workspace_sync.rs @@ -655,6 +655,7 @@ async fn legacy_workspace_doc_migrates_instantly_on_first_boot() { cwd: Some("/tmp/legacy".into()), branch: Some("main".into()), checkout_id: None, + source_context: None, config: None, last_message_preview: Some("old preview".into()), last_message_at: Some(now), diff --git a/crates/proto/src/entities.rs b/crates/proto/src/entities.rs index e0d1c4289b..c397ef61ee 100644 --- a/crates/proto/src/entities.rs +++ b/crates/proto/src/entities.rs @@ -83,6 +83,23 @@ pub struct ChatConfig { pub sandbox: SandboxLevel, } +/// Immutable-at-run-start repository context owned by one conversation. +/// +/// This is deliberately separate from the live checkout snapshot: another +/// chat may change the branch at the same checkout without changing which +/// branch this conversation belongs to. +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ConversationSourceContext { + pub checkout_id: String, + pub repo_root: String, + pub cwd: String, + pub branch: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub head_sha: Option, + pub observed_at: DateTime, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Chat { @@ -95,6 +112,11 @@ pub struct Chat { pub branch: Option, /// Canonical id of the repo checkout/worktree this chat operates in. pub checkout_id: Option, + /// Repository identity captured for this conversation immediately before + /// its harness run. Unlike `branch`, this is never inferred from another + /// chat sharing the same checkout. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub source_context: Option, pub config: Option, pub last_message_preview: Option, pub last_message_at: Option>, diff --git a/crates/sync/tests/registry_client.rs b/crates/sync/tests/registry_client.rs index 30bb2052e8..d58786b7f0 100644 --- a/crates/sync/tests/registry_client.rs +++ b/crates/sync/tests/registry_client.rs @@ -36,6 +36,7 @@ fn chat(id: &str, device_id: &str) -> Chat { cwd: Some("/tmp".into()), branch: None, checkout_id: None, + source_context: None, config: None, last_message_preview: None, last_message_at: None, diff --git a/crates/sync/tests/registry_edge.rs b/crates/sync/tests/registry_edge.rs index 3f2ac7dc48..44b304a134 100644 --- a/crates/sync/tests/registry_edge.rs +++ b/crates/sync/tests/registry_edge.rs @@ -31,6 +31,7 @@ fn chat(id: &str, device_id: &str) -> Chat { cwd: Some("/tmp".into()), branch: None, checkout_id: None, + source_context: None, config: None, last_message_preview: None, last_message_at: None, diff --git a/crates/ui/src/change_requests.rs b/crates/ui/src/change_requests.rs index 46c778009f..5bf240e11c 100644 --- a/crates/ui/src/change_requests.rs +++ b/crates/ui/src/change_requests.rs @@ -173,6 +173,8 @@ pub(crate) fn pull_request_badge( pub(crate) struct ChangeRequestWatchKey { pub device_id: String, pub cwd: String, + pub branch: String, + pub checkout_id: Option, } #[derive(Debug, Default)] @@ -241,17 +243,25 @@ pub(crate) fn desired_watch_targets( chats .iter() .filter(|chat| !chat.archived) - .filter(|chat| { - chat.branch - .as_deref() - .is_some_and(|branch| !branch.trim().is_empty()) - }) .filter(|chat| !is_unsupported(&chat.device_id)) .filter_map(|chat| { - let cwd = effective_chat_cwd(chat, spaces)?; + let (cwd, branch, checkout_id) = if let Some(source) = &chat.source_context { + ( + source.repo_root.as_str(), + source.branch.as_str(), + Some(source.checkout_id.clone()), + ) + } else { + legacy_conversation_source(chat, spaces)? + }; + if branch.trim().is_empty() { + return None; + } Some(ChangeRequestWatchKey { device_id: chat.device_id.clone(), cwd: cwd.to_owned(), + branch: branch.to_owned(), + checkout_id, }) }) .collect() @@ -261,7 +271,10 @@ pub(crate) fn watch_params( target: &ChangeRequestWatchKey, local_device_id: Option<&str>, ) -> serde_json::Value { - let mut params = serde_json::json!({ "cwd": target.cwd }); + let mut params = serde_json::json!({ + "cwd": target.cwd, + "branch": target.branch, + }); if local_device_id != Some(target.device_id.as_str()) && let Some(object) = params.as_object_mut() { @@ -283,11 +296,20 @@ pub fn change_request_for_chat<'a>( spaces: &[Space], snapshots: impl IntoIterator, ) -> Option<&'a ChangeRequestSummary> { - let branch = chat.branch.as_deref()?.trim(); + let branch = conversation_branch(chat, spaces)?.trim(); if branch.is_empty() { return None; } - let cwd = effective_chat_cwd(chat, spaces)?; + let cwd = if let Some(source) = &chat.source_context { + source.repo_root.as_str() + } else { + legacy_conversation_source(chat, spaces)?.0 + }; + let checkout_id = chat + .source_context + .as_ref() + .map(|source| source.checkout_id.as_str()) + .or(chat.checkout_id.as_deref()); snapshots .into_iter() @@ -295,13 +317,45 @@ pub fn change_request_for_chat<'a>( snapshot.device_id == chat.device_id && snapshot.cwd == cwd && snapshot.branch == branch - && chat.checkout_id.as_deref().is_none_or(|checkout_id| { + && checkout_id.is_none_or(|checkout_id| { !snapshot.checkout_id.is_empty() && snapshot.checkout_id == checkout_id }) }) .and_then(|snapshot| snapshot.change_request.as_ref()) } +/// Branch metadata safe to render for this conversation. Pre-source-context +/// rows that point at their project's shared root are intentionally rejected: +/// old builds copied that checkout's current branch onto every chat. +pub(crate) fn conversation_branch<'a>(chat: &'a Chat, spaces: &'a [Space]) -> Option<&'a str> { + chat.source_context + .as_ref() + .map(|source| source.branch.as_str()) + .or_else(|| legacy_conversation_source(chat, spaces).map(|(_, branch, _)| branch)) + .filter(|branch| !branch.trim().is_empty()) +} + +fn legacy_conversation_source<'a>( + chat: &'a Chat, + spaces: &'a [Space], +) -> Option<(&'a str, &'a str, Option)> { + let cwd = effective_chat_cwd(chat, spaces)?; + let branch = chat.branch.as_deref()?.trim(); + if branch.is_empty() { + return None; + } + let shared_root = chat.space_id.as_deref().and_then(|space_id| { + spaces + .iter() + .find(|space| space.id == space_id && space.device_id == chat.device_id) + .map(|space| space.path.as_str()) + }); + if shared_root.is_some_and(|root| root == cwd) { + return None; + } + Some((cwd, branch, chat.checkout_id.clone())) +} + fn effective_chat_cwd<'a>(chat: &'a Chat, spaces: &'a [Space]) -> Option<&'a str> { chat.cwd .as_deref() @@ -332,6 +386,7 @@ mod tests { cwd: cwd.map(str::to_owned), branch: Some("feature/pr".into()), checkout_id: checkout.map(str::to_owned), + source_context: None, config: None, last_message_preview: None, last_message_at: None, @@ -376,6 +431,36 @@ mod tests { } } + fn with_source(mut chat: Chat, branch: &str) -> Chat { + chat.source_context = Some(zeron_proto::ConversationSourceContext { + checkout_id: "checkout".into(), + repo_root: "/repo".into(), + cwd: "/repo".into(), + branch: branch.into(), + head_sha: Some("abc123".into()), + observed_at: Utc.timestamp_opt(2, 0).unwrap(), + }); + chat + } + + #[test] + fn shared_checkout_keeps_conversation_branches_independent() { + let first = with_source(chat("first", "local", Some("/repo"), None), "feature/one"); + let second = with_source(chat("second", "local", Some("/repo"), None), "feature/two"); + let targets = desired_watch_targets(&[first.clone(), second.clone()], &[], |_| false); + assert_eq!(targets.len(), 2); + assert!(targets.iter().any(|target| target.branch == "feature/one")); + assert!(targets.iter().any(|target| target.branch == "feature/two")); + + let mut first_snapshot = snapshot("local", "/repo", "checkout"); + first_snapshot.branch = "feature/one".into(); + assert_eq!( + change_request_for_chat(&first, &[], [&first_snapshot]).map(|pr| pr.number), + Some(90) + ); + assert!(change_request_for_chat(&second, &[], [&first_snapshot]).is_none()); + } + #[test] fn local_chat_finds_local_snapshot() { let chat = chat("chat", "local", Some("/repo"), Some("checkout")); @@ -411,13 +496,11 @@ mod tests { } #[test] - fn project_root_is_used_only_when_chat_has_no_cwd() { + fn source_less_project_root_hides_legacy_branch_metadata() { let chat = chat("chat", "local", None, None); let status = snapshot("local", "/project", "checkout"); - assert_eq!( - change_request_for_chat(&chat, &[space("local")], [&status]).map(|pr| pr.number), - Some(90) - ); + assert!(change_request_for_chat(&chat, &[space("local")], [&status]).is_none()); + assert!(desired_watch_targets(&[chat], &[space("local")], |_| false).is_empty()); } #[test] @@ -452,6 +535,8 @@ mod tests { ChangeRequestWatchKey { device_id: "old-engine".into(), cwd: "/repo".into(), + branch: "feature/pr".into(), + checkout_id: Some("checkout".into()), }, snapshot("old-engine", "/repo", "checkout"), ); @@ -485,6 +570,8 @@ mod tests { let key = ChangeRequestWatchKey { device_id: "local".into(), cwd: "/repo".into(), + branch: "feature/pr".into(), + checkout_id: Some("checkout".into()), }; let mut state = ChangeRequestClientState::default(); state.store(key.clone(), snapshot("local", "/repo", "checkout")); @@ -501,17 +588,21 @@ mod tests { let target = ChangeRequestWatchKey { device_id: "host".into(), cwd: "/repo".into(), + branch: "feature/pr".into(), + checkout_id: Some("checkout".into()), }; assert_eq!( watch_params(&target, Some("host")), serde_json::json!({ - "cwd": "/repo" + "cwd": "/repo", + "branch": "feature/pr" }) ); assert_eq!( watch_params(&target, Some("viewport")), serde_json::json!({ "cwd": "/repo", + "branch": "feature/pr", "targetDeviceId": "host" }) ); diff --git a/crates/ui/src/changes.rs b/crates/ui/src/changes.rs index af9c4b3f03..2a5b942d23 100644 --- a/crates/ui/src/changes.rs +++ b/crates/ui/src/changes.rs @@ -4895,6 +4895,7 @@ rename to new_name.rs cwd: cwd.map(Into::into), branch: None, checkout_id: checkout.map(Into::into), + source_context: None, config: None, last_message_preview: None, last_message_at: None, diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index babed03f1c..8882f77913 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -25,6 +25,7 @@ pub mod frost; pub mod history; pub mod icons; pub mod loaders; +pub mod links; pub mod markdown; pub mod motion; pub mod notify; @@ -43,6 +44,7 @@ pub mod transcript; use std::borrow::Cow; use std::path::PathBuf; +use futures::StreamExt as _; use gpui::{App, AppContext as _, Bounds, TitlebarOptions, WindowBounds, WindowOptions, px, size}; /// Embedded UI fonts — Geist and Geist Mono (variable), © Vercel Inc., @@ -97,6 +99,8 @@ pub struct UiConfig { pub workos_client_id: Option, /// Harness for doc-command runs until per-chat config lands (M4). pub default_harness: HarnessId, + /// Conversation URL passed by the OS on a cold launch. + pub initial_url: Option, } impl UiConfig { @@ -127,6 +131,16 @@ impl gpui::Global for ReopenState {} /// root view, boot splash overlaid until the engine reports ready. pub fn run_app(config: UiConfig) { let app = gpui_platform::application().with_assets(icons::Assets); + let (url_tx, mut url_rx) = futures::channel::mpsc::unbounded::(); + let callback_tx = url_tx.clone(); + app.on_open_urls(move |urls| { + for url in urls { + let _ = callback_tx.unbounded_send(url); + } + }); + if let Some(url) = config.initial_url.clone() { + let _ = url_tx.unbounded_send(url); + } // Dock-icon click with no window (⌘W closed it): rebuild the main window // around the still-running engine — zed does the same via `on_reopen` // (crates/zed/src/main.rs `app.on_reopen`). @@ -154,8 +168,16 @@ pub fn run_app(config: UiConfig) { composer::init(cx); terminal::panel::init(cx); app_menus::init(cx); + cx.register_url_scheme("zeron").detach(); let state = cx.new(|_| state::AppState::new()); + let url_state = state.clone(); + cx.spawn(async move |cx| { + while let Some(url) = url_rx.next().await { + url_state.update(cx, |state, cx| state.open_deep_link(&url, cx)); + } + }) + .detach(); state::AppState::bootstrap(state.clone(), config.boot(), cx); // Graceful teardown: an in-process engine drains live runs and flushes diff --git a/crates/ui/src/links.rs b/crates/ui/src/links.rs new file mode 100644 index 0000000000..748b9bf6e4 --- /dev/null +++ b/crates/ui/src/links.rs @@ -0,0 +1,190 @@ +//! Stable conversation links shared by sidebar copy actions and inbound URL routing. + +use sha2::{Digest, Sha256}; +use zeron_proto::{AuthState, Chat, HarnessId, WorkspaceScope}; + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ConversationDeepLink { + pub chat_id: String, + pub workspace: String, +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HarnessConversationLink { + pub label: &'static str, + pub url: String, +} + +/// Opaque locator: enough to reject links for a different local/synced +/// workspace without putting device, user, or organization ids in the URL. +pub fn workspace_locator( + scope: Option, + auth: Option<&AuthState>, + local_device_id: Option<&str>, +) -> Option { + let scope = scope?; + let identity = match (scope, auth) { + ( + WorkspaceScope::Synced | WorkspaceScope::Development, + Some(AuthState::SignedIn { user, org_id }), + ) => { + format!( + "user:{}:org:{}", + user.id, + org_id.as_deref().unwrap_or("personal") + ) + } + _ => format!("device:{}", local_device_id?), + }; + let mut hash = Sha256::new(); + hash.update(format!("{scope:?}\0{identity}")); + Some(format!("{:x}", hash.finalize())[..16].to_string()) +} + +pub fn zeron_conversation_link(chat_id: &str, workspace: &str) -> String { + format!( + "zeron://open/chat/{}?workspace={}", + encode_component(chat_id), + encode_component(workspace) + ) +} + +pub fn parse_zeron_conversation_link(url: &str) -> Result { + let rest = url + .strip_prefix("zeron://open/chat/") + .ok_or("not a Zeron conversation link")?; + let (chat_id, query) = rest.split_once('?').ok_or("missing workspace locator")?; + if chat_id.is_empty() || chat_id.contains('/') { + return Err("invalid conversation id"); + } + let workspace = query + .split('&') + .find_map(|part| part.strip_prefix("workspace=")) + .ok_or("missing workspace locator")?; + Ok(ConversationDeepLink { + chat_id: decode_component(chat_id)?, + workspace: decode_component(workspace)?, + }) +} + +/// Only return schemes verified against the harness app. Hermes exposes a +/// candidate scheme, but its contract is not stable enough to put on users' +/// clipboards yet. +pub fn harness_conversation_link(chat: &Chat) -> Option { + let id = chat.harness_session_id.as_deref()?.trim(); + if id.is_empty() || chat.config.as_ref()?.harness != HarnessId::Codex { + return None; + } + Some(HarnessConversationLink { + label: "Codex conversation link", + url: format!("codex://threads/{}", encode_component(id)), + }) +} + +fn encode_component(value: &str) -> String { + let mut out = String::new(); + for byte in value.bytes() { + if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~') { + out.push(byte as char); + } else { + use std::fmt::Write as _; + let _ = write!(out, "%{byte:02X}"); + } + } + out +} + +fn decode_component(value: &str) -> Result { + let bytes = value.as_bytes(); + let mut out = Vec::with_capacity(bytes.len()); + let mut index = 0; + while index < bytes.len() { + if bytes[index] == b'%' { + let encoded = bytes + .get(index + 1..index + 3) + .ok_or("invalid URL escape")?; + let text = std::str::from_utf8(encoded).map_err(|_| "invalid URL escape")?; + out.push(u8::from_str_radix(text, 16).map_err(|_| "invalid URL escape")?); + index += 3; + } else { + out.push(bytes[index]); + index += 1; + } + } + String::from_utf8(out).map_err(|_| "invalid UTF-8 in URL") +} + +#[cfg(test)] +mod tests { + use super::*; + + fn harness_chat(harness: HarnessId) -> Chat { + Chat { + id: "chat".into(), + device_id: "device".into(), + title: None, + archived: false, + cwd: None, + branch: None, + checkout_id: None, + source_context: None, + config: Some(zeron_proto::ChatConfig { + harness, + model: None, + reasoning: None, + model_options: Default::default(), + sandbox: zeron_proto::SandboxLevel::WorkspaceWrite, + }), + last_message_preview: None, + last_message_at: None, + created_at: chrono::DateTime::UNIX_EPOCH, + harness_session_id: Some("thread/one".into()), + harness_session_cwd: None, + space_id: None, + last_seen_at: None, + room_gen: None, + } + } + + #[test] + fn zeron_link_round_trips_reserved_characters() { + let link = zeron_conversation_link("chat/with space", "workspace:one"); + assert_eq!( + parse_zeron_conversation_link(&link).unwrap(), + ConversationDeepLink { + chat_id: "chat/with space".into(), + workspace: "workspace:one".into(), + } + ); + } + + #[test] + fn malformed_or_foreign_links_are_rejected() { + assert!(parse_zeron_conversation_link("https://example.com").is_err()); + assert!(parse_zeron_conversation_link("zeron://open/chat/id").is_err()); + assert!(parse_zeron_conversation_link("zeron://open/chat/%GG?workspace=x").is_err()); + } + + #[test] + fn local_workspace_locator_waits_for_device_identity() { + assert_eq!( + workspace_locator(Some(WorkspaceScope::Local), None, None), + None + ); + let first = workspace_locator(Some(WorkspaceScope::Local), None, Some("device-a")); + let second = workspace_locator(Some(WorkspaceScope::Local), None, Some("device-b")); + assert!(first.is_some()); + assert_ne!(first, second); + } + + #[test] + fn codex_link_is_exact_and_unverified_harnesses_are_omitted() { + assert_eq!( + harness_conversation_link(&harness_chat(HarnessId::Codex)) + .unwrap() + .url, + "codex://threads/thread%2Fone" + ); + assert!(harness_conversation_link(&harness_chat(HarnessId::Hermes)).is_none()); + } +} diff --git a/crates/ui/src/settings.rs b/crates/ui/src/settings.rs index a36daab6ff..4df96cb57e 100644 --- a/crates/ui/src/settings.rs +++ b/crates/ui/src/settings.rs @@ -46,6 +46,23 @@ pub const SAVE_DEBOUNCE_MS: u64 = 400; const FILE_NAME: &str = "ui-settings.json"; +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum SidebarOrganization { + ByProject, + ByDevice, + #[default] + InOneList, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] +#[serde(rename_all = "camelCase")] +pub enum SidebarSort { + #[default] + LastUpdated, + Created, +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(default, rename_all = "camelCase")] pub struct UiSettings { @@ -54,6 +71,13 @@ pub struct UiSettings { /// Legacy: the grouped-by-project toggle predates spaces (which group by /// folder inherently). Kept for file compatibility; no longer read. pub sidebar_grouped: bool, + /// How active sessions are partitioned in the sidebar. + pub sidebar_organization: SidebarOrganization, + /// Timestamp used to order active sessions (newest first). + pub sidebar_sort: SidebarSort, + /// Optional repository metadata shown below each session title. + pub sidebar_show_branch: bool, + pub sidebar_show_pull_request: bool, /// The last selected space — restored on boot when the row still exists; /// also the new-tab default when the sidebar filter is "All". #[serde(skip_serializing_if = "Option::is_none")] @@ -107,6 +131,10 @@ impl Default for UiSettings { sidebar_width: SIDEBAR_DEFAULT, sidebar_collapsed: false, sidebar_grouped: false, + sidebar_organization: SidebarOrganization::InOneList, + sidebar_sort: SidebarSort::LastUpdated, + sidebar_show_branch: true, + sidebar_show_pull_request: true, last_space_id: None, open_tabs: None, space_filter: None, @@ -378,6 +406,10 @@ mod tests { sidebar_width: 300.0, sidebar_collapsed: true, sidebar_grouped: true, + sidebar_organization: SidebarOrganization::ByDevice, + sidebar_sort: SidebarSort::Created, + sidebar_show_branch: false, + sidebar_show_pull_request: false, last_space_id: Some("space-1".into()), open_tabs: Some(vec!["b".to_string(), "a".to_string()]), space_filter: Some("space-1".into()), diff --git a/crates/ui/src/settings/archived.rs b/crates/ui/src/settings/archived.rs index 1d81c2eb43..aa6142883f 100644 --- a/crates/ui/src/settings/archived.rs +++ b/crates/ui/src/settings/archived.rs @@ -325,6 +325,7 @@ mod tests { cwd: None, branch: None, checkout_id: None, + source_context: None, config: None, last_message_preview: None, last_message_at: None, diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index 9a2d6dc1f1..37d98ddbcc 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -16,9 +16,9 @@ use std::time::Duration; use chrono::Utc; use gpui::{ - AnyElement, App, Context, Empty, Entity, Focusable as _, IntoElement, KeyBinding, Keystroke, - MouseButton, MouseDownEvent, MouseUpEvent, Pixels, Point, Render, SharedString, Subscription, - Task, Window, WindowControlArea, actions, div, prelude::*, px, + AnyElement, App, ClipboardItem, Context, Empty, Entity, Focusable as _, IntoElement, KeyBinding, + Keystroke, MouseButton, MouseDownEvent, MouseUpEvent, Pixels, Point, Render, SharedString, + Subscription, Task, Window, WindowControlArea, actions, div, prelude::*, px, }; use gpui_tokio::Tokio; @@ -42,7 +42,8 @@ use crate::settings::notifications::{NotificationsEvent, NotificationsPage}; use crate::settings::shortcuts::{ShortcutsEvent, ShortcutsPage}; use crate::settings::{ CHAT_PANEL_MIN, KeymapConfig, RIGHT_PANE_DEFAULT, RIGHT_PANE_MIN, SAVE_DEBOUNCE_MS, - SIDEBAR_DEFAULT, SIDEBAR_MAX, SIDEBAR_MIN, TERMINAL_DEFAULT_HEIGHT, UiSettings, platform_combo, + SIDEBAR_DEFAULT, SIDEBAR_MAX, SIDEBAR_MIN, SidebarOrganization, SidebarSort, + TERMINAL_DEFAULT_HEIGHT, UiSettings, platform_combo, }; use crate::state::{ AppState, ConnectionStatus, EngineBootConfig, EngineMode, GatePhase, Indicator, OrgRow, @@ -62,6 +63,19 @@ actions!( [ToggleSidebar, ToggleChanges, AddSpacePalette, NewSession] ); +#[derive(Clone, Copy)] +enum ChatMenuPage { + Root, + Copy, +} + +#[derive(Clone)] +struct ChatMenuState { + chat_id: String, + position: Point, + page: ChatMenuPage, +} + /// Vertical pane resize hitboxes yield the global titlebar. Keeping this in /// the shared constructor makes left/right seams mirror each other and avoids /// relying on paint order when chrome crosses an animated pane boundary. @@ -858,6 +872,8 @@ pub struct Shell { /// Unarchive affordance and restores the dimmed harness mark (t3code's /// settled-row hover). pub(super) archived_hover: Option, + /// Ephemeral collapsed project/device sections, keyed by organization + id. + pub(super) sidebar_collapsed_groups: std::collections::HashSet, /// Lazy panes: no entity (and no RPC) until first opened. terminal: Option>, /// Embedded terminal host for right-pane Terminal surfaces — a SEPARATE @@ -897,8 +913,8 @@ pub struct Shell { harnesses_page: Option>, shortcuts_sub: Option, notifications_sub: Option, - /// Session-row context menu: (chat id, window position). - chat_menu: popover::Popup<(String, Point)>, + /// Session-row context menu, including the Copy submenu. + chat_menu: popover::Popup, rename_dialog: Option, /// Chat id awaiting delete confirmation. delete_confirm: Option, @@ -912,6 +928,8 @@ pub struct Shell { add_space: Option, /// The sidebar's space-filter dropdown. spaces_menu: popover::Popup, + /// Persisted organization/sort/metadata controls beside the project filter. + sidebar_view_menu: popover::Popup, /// Chat id whose STATUS CORNER is under the pointer — just that corner /// swaps to the archive button (t3code's settle-on-hover); hovering the /// row body leaves the status readable. @@ -1089,6 +1107,9 @@ impl Shell { }); let data_dir = boot.data_dir.clone(); let settings = UiSettings::load(&data_dir); + state.update(cx, |state, cx| { + state.set_change_requests_visible(settings.sidebar_show_pull_request, cx) + }); // Bind the customizable shortcuts from the persisted keymap. apply_keymap(cx, &settings.keymap); // Dev/testing knob: `ZERON_OPEN_ROUTE=settings[/
]` boots @@ -1143,6 +1164,7 @@ impl Shell { archived_open: true, archived_shown: 0, archived_hover: None, + sidebar_collapsed_groups: std::collections::HashSet::new(), terminal: None, right_terminal: None, right_plus: popover::Popup::default(), @@ -1173,6 +1195,7 @@ impl Shell { delete_space_confirm: None, add_space: None, spaces_menu: popover::Popup::default(), + sidebar_view_menu: popover::Popup::default(), chat_status_hover: None, sidebar_scroll: gpui::ScrollHandle::new(), space_boot_applied: false, @@ -1234,6 +1257,9 @@ impl Shell { // ---- splash ---- fn on_state_changed(&mut self, state: &Entity, cx: &mut Context) { + if let Some(notice) = state.update(cx, |state, _| state.take_deep_link_notice()) { + self.sidebar_notice = Some(notice.into()); + } let next_sync_flow = { let state = state.read(cx); sync_flow_after_auth(self.sync_flow, state.workspace_scope, state.auth.as_ref()) @@ -2126,6 +2152,65 @@ impl Shell { } } + fn open_chat_copy_menu(&mut self, cx: &mut Context) { + if let Some(menu) = self.chat_menu.open_mut() { + menu.page = ChatMenuPage::Copy; + cx.notify(); + } + } + + fn copy_zeron_conversation_link(&mut self, chat_id: &str, cx: &mut Context) { + let link = { + let state = self.state.read(cx); + crate::links::workspace_locator( + state.workspace_scope, + state.auth.as_ref(), + state.local_device_id.as_deref(), + ) + .map(|workspace| crate::links::zeron_conversation_link(chat_id, &workspace)) + }; + if let Some(link) = link { + cx.write_to_clipboard(ClipboardItem::new_string(link)); + self.sidebar_notice = Some("Zeron conversation link copied".into()); + } else { + self.sidebar_notice = Some("Conversation link is not ready yet".into()); + } + self.close_chat_menu(cx); + cx.notify(); + } + + fn copy_harness_conversation_link(&mut self, chat_id: &str, cx: &mut Context) { + let link = self + .state + .read(cx) + .chats + .iter() + .find(|chat| chat.id == chat_id) + .and_then(crate::links::harness_conversation_link); + if let Some(link) = link { + cx.write_to_clipboard(ClipboardItem::new_string(link.url)); + self.sidebar_notice = Some(format!("{} copied", link.label).into()); + } + self.close_chat_menu(cx); + cx.notify(); + } + + fn copy_harness_session_id(&mut self, chat_id: &str, cx: &mut Context) { + let id = self + .state + .read(cx) + .chats + .iter() + .find(|chat| chat.id == chat_id) + .and_then(|chat| chat.harness_session_id.clone()); + if let Some(id) = id.filter(|id| !id.trim().is_empty()) { + cx.write_to_clipboard(ClipboardItem::new_string(id)); + self.sidebar_notice = Some("Harness session ID copied".into()); + } + self.close_chat_menu(cx); + cx.notify(); + } + fn open_settings(&mut self, section: SettingsSection, cx: &mut Context) { // Recreate per visit: the page's ListHarnesses load re-probes which // CLIs are installed, so installing one shows up on the next open. @@ -3766,7 +3851,11 @@ impl Shell { .on_mouse_down( MouseButton::Right, cx.listener(move |this, event: &MouseDownEvent, _, cx| { - this.chat_menu.open((menu_id.clone(), event.position)); + this.chat_menu.open(ChatMenuState { + chat_id: menu_id.clone(), + position: event.position, + page: ChatMenuPage::Root, + }); cx.notify(); }), ) @@ -4851,18 +4940,22 @@ impl Shell { let theme = Theme::of(cx).clone(); let mut overlays: Vec = Vec::new(); - if let Some((chat_id, position)) = self.chat_menu.get().cloned() { + if let Some(menu_state) = self.chat_menu.get().cloned() { + let chat_id = menu_state.chat_id; + let position = menu_state.position; let chat_menu_closing = self.chat_menu.closing_since(); let rename_id = chat_id.clone(); let archive_id = chat_id.clone(); let delete_id = chat_id.clone(); let menu = popover::popover_card(&theme) - .w(px(170.0)) + .w(px(216.0)) .on_mouse_down_out(cx.listener(|this, _, _, cx| { this.close_chat_menu(cx); })) .flex() - .flex_col() + .flex_col(); + let menu = match menu_state.page { + ChatMenuPage::Root => menu .child( popover::menu_row(&theme, false, format!("chat-menu-rename-{chat_id}")) .id("chat-menu-rename") @@ -4885,6 +4978,18 @@ impl Shell { ) .child(SharedString::from("Archive")), ) + .child( + popover::menu_row(&theme, false, format!("chat-menu-copy-{chat_id}")) + .id("chat-menu-copy") + .on_click(cx.listener(|this, _, _, cx| this.open_chat_copy_menu(cx))) + .child(icon(icons::COPY).size(px(16.0)).text_color(theme.text_muted)) + .child(div().flex_1().child(SharedString::from("Copy"))) + .child( + icon(icons::ALT_ARROW_RIGHT) + .size(px(14.0)) + .text_color(theme.text_muted.opacity(0.7)), + ), + ) .child(popover::menu_separator()) .child( popover::menu_row(&theme, false, format!("chat-menu-delete-{chat_id}")) @@ -4901,8 +5006,88 @@ impl Shell { .text_color(theme.danger), ) .child(SharedString::from("Delete…")), - ) - .into_any_element(); + ), + ChatMenuPage::Copy => { + let chat = self + .state + .read(cx) + .chats + .iter() + .find(|chat| chat.id == chat_id) + .cloned(); + let harness_link = chat + .as_ref() + .and_then(crate::links::harness_conversation_link); + let session_id = chat + .as_ref() + .and_then(|chat| chat.harness_session_id.as_deref()) + .is_some_and(|id| !id.trim().is_empty()); + let zeron_id = chat_id.clone(); + let harness_id = chat_id.clone(); + let session_chat_id = chat_id.clone(); + menu.child( + popover::menu_row(&theme, false, format!("chat-copy-back-{chat_id}")) + .id("chat-copy-back") + .on_click(cx.listener(|this, _, _, cx| { + if let Some(menu) = this.chat_menu.open_mut() { + menu.page = ChatMenuPage::Root; + cx.notify(); + } + })) + .child( + icon(icons::ALT_ARROW_LEFT) + .size(px(16.0)) + .text_color(theme.text_muted), + ) + .child(SharedString::from("Back")), + ) + .child(popover::menu_separator()) + .child( + popover::menu_row(&theme, false, format!("chat-copy-zeron-{chat_id}")) + .id("chat-copy-zeron") + .on_click(cx.listener(move |this, _, _, cx| { + this.copy_zeron_conversation_link(&zeron_id, cx) + })) + .child(icon(icons::COPY).size(px(16.0)).text_color(theme.text_muted)) + .child(SharedString::from("Zeron conversation link")), + ) + .when_some(harness_link, |menu, link| { + menu.child( + popover::menu_row( + &theme, + false, + format!("chat-copy-harness-{chat_id}"), + ) + .id("chat-copy-harness") + .on_click(cx.listener(move |this, _, _, cx| { + this.copy_harness_conversation_link(&harness_id, cx) + })) + .child( + icon(icons::COPY).size(px(16.0)).text_color(theme.text_muted), + ) + .child(SharedString::from(link.label)), + ) + }) + .when(session_id, |menu| { + menu.child( + popover::menu_row( + &theme, + false, + format!("chat-copy-session-{chat_id}"), + ) + .id("chat-copy-session") + .on_click(cx.listener(move |this, _, _, cx| { + this.copy_harness_session_id(&session_chat_id, cx) + })) + .child( + icon(icons::COPY).size(px(16.0)).text_color(theme.text_muted), + ) + .child(SharedString::from("Harness session ID")), + ) + }) + } + } + .into_any_element(); overlays.push(popover::menu_at( "chat-context-menu", position, diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 794fc2953f..4f010157f7 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -19,6 +19,7 @@ struct ActiveChatRow { folder: String, branch: Option, change_request: Option, + group: Option<(String, String)>, } /// The space-filter dropdown, `Some` while open. The same searchable-menu @@ -36,6 +37,51 @@ pub(super) struct SpacesMenu { _search_events: Subscription, } +pub(super) struct SidebarViewMenu { + active: usize, + focus: FocusHandle, +} + +struct SidebarViewOptionsTooltip; + +impl Render for SidebarViewOptionsTooltip { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + let theme = Theme::of(cx); + div() + .px(px(8.0)) + .py(px(6.0)) + .rounded(px(6.0)) + .border_1() + .border_color(theme.border_strong) + .bg(theme.surface_raised) + .shadow_md() + .text_size(px(11.0)) + .text_color(theme.text) + .child("Sidebar view options") + } +} + +#[derive(Clone, Copy)] +enum SidebarViewRow { + ByProject, + ByDevice, + InOneList, + LastUpdated, + Created, + ShowBranch, + ShowPullRequest, +} + +const SIDEBAR_VIEW_ROWS: [SidebarViewRow; 7] = [ + SidebarViewRow::ByProject, + SidebarViewRow::ByDevice, + SidebarViewRow::InOneList, + SidebarViewRow::LastUpdated, + SidebarViewRow::Created, + SidebarViewRow::ShowBranch, + SidebarViewRow::ShowPullRequest, +]; + /// One row of the open dropdown, in display order. #[derive(Clone, PartialEq)] pub(super) enum SpacesMenuRow { @@ -205,6 +251,7 @@ impl Shell { } fn open_spaces_menu(&mut self, window: &mut Window, cx: &mut Context) { + self.close_sidebar_view_menu(cx); // "PaletteSearch" context: ↑↓/⏎ stay unbound in the input and bubble // to the card's key handler. let search = @@ -293,6 +340,180 @@ impl Shell { } } + fn close_sidebar_view_menu(&mut self, cx: &mut Context) { + if self.sidebar_view_menu.begin_close() { + popover::reap_popup(cx, |shell: &mut Self| &mut shell.sidebar_view_menu); + cx.notify(); + } + } + + fn open_sidebar_view_menu(&mut self, window: &mut Window, cx: &mut Context) { + self.close_spaces_menu(cx); + let focus = cx.focus_handle(); + self.sidebar_view_menu.open(SidebarViewMenu { + active: 0, + focus: focus.clone(), + }); + window.focus(&focus, cx); + cx.notify(); + } + + fn activate_sidebar_view_row(&mut self, row: SidebarViewRow, cx: &mut Context) { + match row { + SidebarViewRow::ByProject => { + self.settings.sidebar_organization = SidebarOrganization::ByProject + } + SidebarViewRow::ByDevice => { + self.settings.sidebar_organization = SidebarOrganization::ByDevice + } + SidebarViewRow::InOneList => { + self.settings.sidebar_organization = SidebarOrganization::InOneList + } + SidebarViewRow::LastUpdated => { + self.settings.sidebar_sort = SidebarSort::LastUpdated + } + SidebarViewRow::Created => self.settings.sidebar_sort = SidebarSort::Created, + SidebarViewRow::ShowBranch => { + self.settings.sidebar_show_branch = !self.settings.sidebar_show_branch + } + SidebarViewRow::ShowPullRequest => { + self.settings.sidebar_show_pull_request = + !self.settings.sidebar_show_pull_request; + let visible = self.settings.sidebar_show_pull_request; + self.state + .update(cx, |state, cx| state.set_change_requests_visible(visible, cx)); + } + } + self.schedule_save(cx); + cx.notify(); + } + + fn sidebar_view_menu_key(&mut self, event: &gpui::KeyDownEvent, cx: &mut Context) { + if !self.sidebar_view_menu.is_open() { + return; + } + match popover::classify_key( + event.keystroke.key.as_str(), + event.keystroke.modifiers.platform, + event.keystroke.modifiers.control, + ) { + popover::MenuKey::Escape => self.close_sidebar_view_menu(cx), + popover::MenuKey::Up | popover::MenuKey::Down => { + let up = event.keystroke.key.eq_ignore_ascii_case("arrowup"); + if let Some(menu) = self.sidebar_view_menu.open_mut() { + menu.active = popover::menu_step( + Some(menu.active), + SIDEBAR_VIEW_ROWS.len(), + if up { -1 } else { 1 }, + ) + .unwrap_or(0); + cx.notify(); + } + } + popover::MenuKey::Enter | popover::MenuKey::ModEnter => { + let active = self.sidebar_view_menu.get().map(|m| m.active).unwrap_or(0); + if let Some(row) = SIDEBAR_VIEW_ROWS.get(active).copied() { + self.activate_sidebar_view_row(row, cx); + } + } + popover::MenuKey::Backspace | popover::MenuKey::Other => {} + } + } + + fn render_sidebar_view_menu(&mut self, theme: &Theme, cx: &mut Context) -> AnyElement { + let Some(menu_state) = self.sidebar_view_menu.get() else { + return div().into_any_element(); + }; + let active = menu_state.active; + let focus = menu_state.focus.clone(); + let organization = self.settings.sidebar_organization; + let sort = self.settings.sidebar_sort; + let show_branch = self.settings.sidebar_show_branch; + let show_pr = self.settings.sidebar_show_pull_request; + + let heading = |label: &'static str| { + div() + .px(px(8.0)) + .pt(px(7.0)) + .pb(px(3.0)) + .text_size(px(10.0)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(theme.text_muted.opacity(0.65)) + .child(SharedString::from(label)) + .into_any_element() + }; + let labels = [ + "By project", + "By device", + "In one list", + "Last updated", + "Created", + "Branch", + "Pull request", + ]; + let selected = [ + organization == SidebarOrganization::ByProject, + organization == SidebarOrganization::ByDevice, + organization == SidebarOrganization::InOneList, + sort == SidebarSort::LastUpdated, + sort == SidebarSort::Created, + show_branch, + show_pr, + ]; + let mut rows: Vec = SIDEBAR_VIEW_ROWS + .iter() + .copied() + .enumerate() + .map(|(ix, row)| { + popover::menu_row_nav( + theme, + selected[ix], + ix == active, + format!("sidebar-view-row-{ix}"), + ) + .id(("sidebar-view-row", ix)) + .on_click(cx.listener(move |this, _, _, cx| { + this.activate_sidebar_view_row(row, cx) + })) + .child( + div().w(px(16.0)).flex_none().when(selected[ix], |el| { + el.child( + icon(icons::CHECK) + .size(px(14.0)) + .text_color(theme.text_muted), + ) + }), + ) + .child(SharedString::from(labels[ix])) + .into_any_element() + }) + .collect(); + let show_rows = rows.split_off(5); + let sort_rows = rows.split_off(3); + let organization_rows = rows; + + popover::popover_card(theme) + .w(px(202.0)) + .track_focus(&focus) + .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, _, cx| { + this.sidebar_view_menu_key(event, cx) + })) + .on_mouse_down_out(cx.listener(|this, _, _, cx| { + this.close_sidebar_view_menu(cx) + })) + .flex() + .flex_col() + .child(heading("Organize")) + .children(organization_rows) + .child(popover::menu_separator()) + .child(heading("Sort")) + .children(sort_rows) + .child(popover::menu_separator()) + .child(heading("Show")) + .children(show_rows) + .into_any_element() + } + /// The sidebar's space-filter row: current filter ("All projects" or the /// space's name) + chevron, the dropdown floating beneath while open. /// Sits OUTSIDE the sidebar's scroll region so the float never clips. @@ -417,6 +638,49 @@ impl Shell { trigger }; + let view_open = self.sidebar_view_menu.is_open(); + let view_trigger = div() + .id("sidebar-view-options") + .size(px(29.0)) + .flex_none() + .flex() + .items_center() + .justify_center() + .rounded(px(8.0)) + .cursor_pointer() + .text_color(theme.text_muted) + .bg(if view_open { + theme.glass_hover() + } else { + theme.glass_hover().opacity(0.0) + }) + .hover(|el| el.bg(theme.glass_hover())) + .on_mouse_down( + gpui::MouseButton::Left, + cx.listener(|this, _, _, _| this.sidebar_view_menu.note_trigger_press()), + ) + .on_click(cx.listener(|this, _, window, cx| { + if this.sidebar_view_menu.take_press_was_open() { + this.close_sidebar_view_menu(cx); + } else { + this.open_sidebar_view_menu(window, cx); + } + })) + .tooltip(|_, cx| cx.new(|_| SidebarViewOptionsTooltip).into()) + .tooltip_show_delay(std::time::Duration::from_millis(350)) + .child(icon(icons::TUNING).size(px(16.0))); + let view_trigger = if self.sidebar_view_menu.get().is_some() { + let closing = self.sidebar_view_menu.closing_since(); + let menu = self.render_sidebar_view_menu(theme, cx); + view_trigger.relative().child(popover::anchored_menu_below( + "sidebar-view-options-menu", + menu, + closing, + )) + } else { + view_trigger + }; + div() .flex_none() .flex() @@ -427,6 +691,7 @@ impl Shell { .pt(px(8.0)) .pb(px(4.0)) .child(trigger) + .child(view_trigger) .into_any_element() } @@ -580,56 +845,151 @@ impl Shell { ) -> Vec<(String, f32, AnyElement)> { let now = Utc::now(); let filter = self.settings.space_filter.clone(); - let rows: Vec = { + let mut rows: Vec = { let state = self.state.read(cx); - state + let mut chats: Vec<_> = state .overview_chats(now) .into_iter() .filter(|(_, chat)| match &filter { Some(space_id) => chat.space_id.as_deref() == Some(space_id.as_str()), None => true, }) + .map(|(status, chat)| (status, chat.clone())) + .collect(); + match self.settings.sidebar_sort { + SidebarSort::Created => { + chats.sort_by(|a, b| b.1.created_at.cmp(&a.1.created_at)); + } + SidebarSort::LastUpdated => chats.sort_by(|a, b| { + b.1.last_message_at + .unwrap_or(b.1.created_at) + .cmp(&a.1.last_message_at.unwrap_or(a.1.created_at)) + }), + } + chats + .into_iter() .map(|(status, chat)| { // Line 1 is "project @ device" (t3code's project row); // project-less sessions read as their home-dir cwd `~`. - let space = state.space_for_chat(chat); - let mut folder = match (space, chat.space_id.as_deref()) { + let space = state.space_for_chat(&chat); + let project = match (space, chat.space_id.as_deref()) { (Some(space), _) => space.display_name().to_string(), (None, None) => "~".to_string(), (None, Some(_)) => "?".to_string(), }; + let device = state + .device_name(&chat.device_id) + .unwrap_or("Unknown device") + .to_string(); + let mut folder = project.clone(); // Unknown device → no fragment, same as the archived list. - if let Some(device) = state.device_name(&chat.device_id) { + if state.device_name(&chat.device_id).is_some() { folder = format!("{folder} @ {device}"); } // The branch shows whenever the engine has stamped one — // main-checkout sessions included, not just worktrees. - let branch = chat - .branch - .as_deref() + let branch = crate::change_requests::conversation_branch(&chat, &state.spaces) .map(str::trim) .filter(|b| !b.is_empty()) .map(str::to_string); - let change_request = state.change_request_for_chat(chat).cloned(); + let change_request = state.change_request_for_chat(&chat).cloned(); + let group = match self.settings.sidebar_organization { + SidebarOrganization::ByProject if filter.is_none() => Some(( + chat.space_id.clone().unwrap_or_else(|| "~".into()), + project, + )), + SidebarOrganization::ByDevice => { + Some((chat.device_id.clone(), device)) + } + SidebarOrganization::ByProject | SidebarOrganization::InOneList => None, + }; ActiveChatRow { status, chat: chat.clone(), folder, branch, change_request, + group, } }) .collect() }; + if !self.settings.sidebar_show_branch { + for row in &mut rows { + row.branch = None; + } + } + if !self.settings.sidebar_show_pull_request { + for row in &mut rows { + row.change_request = None; + } + } + + let mut groups: Vec<(Option<(String, String)>, Vec)> = Vec::new(); + for row in rows { + if let Some((_, existing)) = groups.iter_mut().find(|(group, _)| group == &row.group) { + existing.push(row); + } else { + groups.push((row.group.clone(), vec![row])); + } + } + let selected = self.state.read(cx).selected_chat.clone(); - rows.into_iter() - .map(|row| { + let mut rendered = Vec::new(); + for (group, rows) in groups { + let mut collapsed = false; + if let Some((key, label)) = group { + let organization = match self.settings.sidebar_organization { + SidebarOrganization::ByProject => "project", + SidebarOrganization::ByDevice => "device", + SidebarOrganization::InOneList => "list", + }; + let collapse_key = format!("{organization}:{key}"); + collapsed = self.sidebar_collapsed_groups.contains(&collapse_key); + let toggle_key = collapse_key.clone(); + let height = 27.0; + let element = div() + .id(collapse_key.clone()) + .h(px(height)) + .flex() + .items_end() + .gap(px(4.0)) + .px(px(Theme::SPACE_SM)) + .pb(px(4.0)) + .cursor_pointer() + .on_click(cx.listener(move |this, _, _, cx| { + if !this.sidebar_collapsed_groups.remove(&toggle_key) { + this.sidebar_collapsed_groups.insert(toggle_key.clone()); + } + cx.notify(); + })) + .text_size(px(10.0)) + .font_weight(gpui::FontWeight::SEMIBOLD) + .text_color(theme.text_muted.opacity(0.65)) + .child( + icon(if collapsed { + icons::ALT_ARROW_RIGHT + } else { + icons::ALT_ARROW_DOWN + }) + .size(px(12.0)) + .text_color(theme.text_muted.opacity(0.6)), + ) + .child(SharedString::from(label)) + .into_any_element(); + rendered.push((format!("g:{collapse_key}"), height, element)); + } + if collapsed { + continue; + } + for row in rows { let ActiveChatRow { status, chat, folder, branch, change_request, + group: _, } = row; let time_ago: SharedString = format_time_ago(chat.last_message_at.unwrap_or(chat.created_at), now).into(); @@ -653,9 +1013,10 @@ impl Shell { theme, cx, ); - (format!("c:{}", chat.id), height, element) - }) - .collect() + rendered.push((format!("c:{}", chat.id), height, element)); + } + } + rendered } /// The sidebar's archived shelf — a direct port of t3code's settled @@ -674,7 +1035,7 @@ impl Shell { const PAGE: usize = 25; let now = Utc::now(); let filter = self.settings.space_filter.clone(); - let rows: Vec = { + let mut rows: Vec = { let state = self.state.read(cx); state .chats @@ -687,6 +1048,14 @@ impl Shell { .cloned() .collect() }; + match self.settings.sidebar_sort { + SidebarSort::Created => rows.sort_by(|a, b| b.created_at.cmp(&a.created_at)), + SidebarSort::LastUpdated => rows.sort_by(|a, b| { + b.last_message_at + .unwrap_or(b.created_at) + .cmp(&a.last_message_at.unwrap_or(a.created_at)) + }), + } if rows.is_empty() { return None; } @@ -832,7 +1201,11 @@ impl Shell { .on_mouse_down( MouseButton::Right, cx.listener(move |this, event: &gpui::MouseDownEvent, _, cx| { - this.chat_menu.open((menu_id.clone(), event.position)); + this.chat_menu.open(ChatMenuState { + chat_id: menu_id.clone(), + position: event.position, + page: ChatMenuPage::Root, + }); cx.notify(); }), ) diff --git a/crates/ui/src/state.rs b/crates/ui/src/state.rs index 36e87fb1be..068d729204 100644 --- a/crates/ui/src/state.rs +++ b/crates/ui/src/state.rs @@ -17,7 +17,7 @@ //! Pure logic (sort order, staleness, gate phase) lives in free functions with //! unit tests; rendering reads them. -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::PathBuf; use std::sync::Arc; @@ -616,6 +616,8 @@ pub struct AppState { /// judge by the empty pre-sync lists. pub chats_synced: bool, pub spaces_synced: bool, + pending_deep_link: Option, + deep_link_notice: Option, /// Joined transcript of the selected chat (continuations folded engine-side). pub transcript: Vec, /// The selected chat's opening `WatchDocMessages` reset has landed. An @@ -649,6 +651,7 @@ pub struct AppState { transcript_task: Option>, change_requests: ChangeRequestClientState, change_request_tasks: HashMap>, + change_requests_visible: bool, /// SUBAGENT transcripts keyed by subagent doc id (the right pane's /// subagent tabs read these). Independent of `selected_chat`: a tab's /// feed must survive chat switches — the tab itself is what scopes it. @@ -696,11 +699,14 @@ impl AppState { transcript_task: None, change_requests: ChangeRequestClientState::default(), change_request_tasks: HashMap::new(), + change_requests_visible: true, sub_transcripts: HashMap::new(), sub_watch_tasks: HashMap::new(), auto_selected: false, chats_synced: false, spaces_synced: false, + pending_deep_link: None, + deep_link_notice: None, } } @@ -1460,9 +1466,13 @@ impl AppState { self.change_request_tasks.clear(); return; }; - let targets = desired_watch_targets(&self.chats, &self.spaces, |device| { - !self.change_requests.is_supported(device) - }); + let targets = if self.change_requests_visible { + desired_watch_targets(&self.chats, &self.spaces, |device| { + !self.change_requests.is_supported(device) + }) + } else { + HashSet::new() + }; self.change_request_tasks .retain(|target, _| targets.contains(target)); @@ -1483,6 +1493,54 @@ impl AppState { } } + pub fn set_change_requests_visible(&mut self, visible: bool, cx: &mut Context) { + if self.change_requests_visible != visible { + self.change_requests_visible = visible; + self.reconcile_change_request_watches(cx); + } + } + + pub fn open_deep_link(&mut self, url: &str, cx: &mut Context) { + match crate::links::parse_zeron_conversation_link(url) { + Ok(link) => { + self.pending_deep_link = Some(link); + self.apply_pending_deep_link(cx); + } + Err(error) => self.deep_link_notice = Some(error.to_string()), + } + cx.notify(); + } + + fn apply_pending_deep_link(&mut self, cx: &mut Context) { + let Some(link) = self.pending_deep_link.clone() else { + return; + }; + let Some(locator) = crate::links::workspace_locator( + self.workspace_scope, + self.auth.as_ref(), + self.local_device_id.as_deref(), + ) else { + return; + }; + if locator != link.workspace { + self.pending_deep_link = None; + self.deep_link_notice = + Some("This conversation link belongs to another workspace".into()); + return; + } + if self.chats.iter().any(|chat| chat.id == link.chat_id) { + self.pending_deep_link = None; + self.select_chat(Some(link.chat_id), cx); + } else if self.chats_synced { + self.pending_deep_link = None; + self.deep_link_notice = Some("The linked conversation was not found".into()); + } + } + + pub fn take_deep_link_notice(&mut self) -> Option { + self.deep_link_notice.take() + } + /// Select a chat (or clear). Swaps the per-chat doc-transcript subscription: /// dropping the old task drops its stream receiver, which cancels the doc /// watch server-side. Selecting a chat also lands in its space and marks it @@ -1650,6 +1708,7 @@ fn spawn_chats_watch(cx: &mut Context, handle: EngineHandle) -> Task<( }; let alive = this.update(cx, |state, cx| { state.apply_chats(parsed); + state.apply_pending_deep_link(cx); state.reconcile_change_request_watches(cx); cx.notify(); }); @@ -1796,6 +1855,7 @@ fn spawn_watch( }; let alive = this.update(cx, |state, cx| { apply(state, parsed); + state.apply_pending_deep_link(cx); if matches!(method, methods::WATCH_SPACES | methods::WATCH_DEVICES) { state.reconcile_change_request_watches(cx); } @@ -1834,6 +1894,11 @@ fn spawn_local_device_probe(cx: &mut Context, handle: EngineHandle) -> if let Some(id) = id { this.update(cx, |state, cx| { state.local_device_id = Some(id); + state.apply_pending_deep_link(cx); + // Watches opened before this probe conservatively route through + // targetDeviceId. Recreate them now that local routing is known. + state.change_request_tasks.clear(); + state.reconcile_change_request_watches(cx); cx.notify(); }) .ok(); @@ -2512,6 +2577,7 @@ mod tests { cwd: None, branch: None, checkout_id: None, + source_context: None, config: None, last_message_preview: None, last_message_at: last_msg_min.map(|m| base + TimeDelta::minutes(m)), diff --git a/dist/macos/Info.plist b/dist/macos/Info.plist index b0d81983b0..859b49bb05 100644 --- a/dist/macos/Info.plist +++ b/dist/macos/Info.plist @@ -24,6 +24,17 @@ __VERSION__ CFBundleVersion __VERSION__ + CFBundleURLTypes + + + CFBundleURLName + sh.zeron.app.conversation + CFBundleURLSchemes + + zeron + + + LSMinimumSystemVersion 12.0 NSHighResolutionCapable diff --git a/dist/zeron.desktop b/dist/zeron.desktop index d79d7f3951..3008ef9c2f 100644 --- a/dist/zeron.desktop +++ b/dist/zeron.desktop @@ -3,10 +3,11 @@ Type=Application Name=Zeron GenericName=Coding Agent Controller Comment=Multi-device controller for coding agents -Exec=zeron +Exec=zeron %u TryExec=zeron Icon=zeron Terminal=false Categories=Development;Utility; Keywords=agent;claude;codex;ai;coding; StartupWMClass=zeron +MimeType=x-scheme-handler/zeron; diff --git a/docs/research/sidebar-view-options.md b/docs/research/sidebar-view-options.md index b08bab9e4d..3ad140f8d9 100644 --- a/docs/research/sidebar-view-options.md +++ b/docs/research/sidebar-view-options.md @@ -1,6 +1,6 @@ # Sidebar view options and conversation links -Status: planning +Status: implemented and verified locally Branch: `wip/sidebar-view-options` Base: `origin/main` at `3fc7bb0` (`v0.2.20`) Research date: 2026-08-22 From d539c71b5cc2cf02fd13a0c0689b652d52f1cfe0 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 14:25:10 +0200 Subject: [PATCH 03/17] fix: polish sidebar view options menu --- crates/ui/assets/icons/calendar.svg | 1 + crates/ui/assets/icons/clock-circle.svg | 1 + crates/ui/src/icons.rs | 2 + crates/ui/src/popover.rs | 32 ++++++ crates/ui/src/settings.rs | 6 +- crates/ui/src/shell/spaces.rs | 145 ++++++++++++++---------- docs/research/sidebar-view-options.md | 10 +- 7 files changed, 132 insertions(+), 65 deletions(-) create mode 100644 crates/ui/assets/icons/calendar.svg create mode 100644 crates/ui/assets/icons/clock-circle.svg diff --git a/crates/ui/assets/icons/calendar.svg b/crates/ui/assets/icons/calendar.svg new file mode 100644 index 0000000000..83e72c7373 --- /dev/null +++ b/crates/ui/assets/icons/calendar.svg @@ -0,0 +1 @@ + diff --git a/crates/ui/assets/icons/clock-circle.svg b/crates/ui/assets/icons/clock-circle.svg new file mode 100644 index 0000000000..f8fbc3bd36 --- /dev/null +++ b/crates/ui/assets/icons/clock-circle.svg @@ -0,0 +1 @@ + diff --git a/crates/ui/src/icons.rs b/crates/ui/src/icons.rs index facd97c955..2298b35145 100644 --- a/crates/ui/src/icons.rs +++ b/crates/ui/src/icons.rs @@ -53,6 +53,8 @@ icon_assets![ (LAPTOP, "laptop"), (PEN_NEW_SQUARE, "pen-new-square"), (SORT_VERTICAL, "sort-vertical"), + (CLOCK_CIRCLE, "clock-circle"), + (CALENDAR, "calendar"), (LIST, "list"), (FOLDER_WITH_FILES, "folder-with-files"), (FOLDER, "folder"), diff --git a/crates/ui/src/popover.rs b/crates/ui/src/popover.rs index b5fc67f625..9e627e99bd 100644 --- a/crates/ui/src/popover.rs +++ b/crates/ui/src/popover.rs @@ -427,6 +427,38 @@ pub fn anchored_menu_below( anchored_menu_below_gap(id, content, closing, 6.0) } +/// [`anchored_menu_below`] right-aligned to the trigger's right edge. This is +/// the dropdown counterpart to [`anchored_menu_above_end`]: trailing sidebar +/// controls can open a full-width card leftward without leaving the sidebar. +pub fn anchored_menu_below_end( + id: impl Into, + content: AnyElement, + closing: Option, +) -> AnyElement { + let exit = closing.map(exit_progress); + let content = frosted_menu(exit, content); + div() + .absolute() + .bottom_0() + .right_0() + .size_0() + .child( + gpui::deferred( + gpui::anchored() + .anchor(Anchor::TopRight) + .snap_to_window_with_margin(px(8.0)) + .child(menu_motion( + id.into(), + exit, + div().occlude().pt(px(6.0)).child(content), + )), + ) + .priority(1) + .into_any_element(), + ) + .into_any_element() +} + /// [`anchored_menu_below`] with a caller-chosen trigger→card gap — the /// changes-header dropdowns hang off a tight titlebar band and need more /// breathing room than the default 6px (user report; t3code sits near 10). diff --git a/crates/ui/src/settings.rs b/crates/ui/src/settings.rs index 4df96cb57e..b12bddcd07 100644 --- a/crates/ui/src/settings.rs +++ b/crates/ui/src/settings.rs @@ -75,7 +75,9 @@ pub struct UiSettings { pub sidebar_organization: SidebarOrganization, /// Timestamp used to order active sessions (newest first). pub sidebar_sort: SidebarSort, - /// Optional repository metadata shown below each session title. + /// Optional harness branding and repository metadata shown below each + /// session title. + pub sidebar_show_harness: bool, pub sidebar_show_branch: bool, pub sidebar_show_pull_request: bool, /// The last selected space — restored on boot when the row still exists; @@ -133,6 +135,7 @@ impl Default for UiSettings { sidebar_grouped: false, sidebar_organization: SidebarOrganization::InOneList, sidebar_sort: SidebarSort::LastUpdated, + sidebar_show_harness: true, sidebar_show_branch: true, sidebar_show_pull_request: true, last_space_id: None, @@ -408,6 +411,7 @@ mod tests { sidebar_grouped: true, sidebar_organization: SidebarOrganization::ByDevice, sidebar_sort: SidebarSort::Created, + sidebar_show_harness: false, sidebar_show_branch: false, sidebar_show_pull_request: false, last_space_id: Some("space-1".into()), diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 4f010157f7..fe2fcb59fa 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -70,9 +70,10 @@ enum SidebarViewRow { Created, ShowBranch, ShowPullRequest, + ShowHarness, } -const SIDEBAR_VIEW_ROWS: [SidebarViewRow; 7] = [ +const SIDEBAR_VIEW_ROWS: [SidebarViewRow; 8] = [ SidebarViewRow::ByProject, SidebarViewRow::ByDevice, SidebarViewRow::InOneList, @@ -80,6 +81,7 @@ const SIDEBAR_VIEW_ROWS: [SidebarViewRow; 7] = [ SidebarViewRow::Created, SidebarViewRow::ShowBranch, SidebarViewRow::ShowPullRequest, + SidebarViewRow::ShowHarness, ]; /// One row of the open dropdown, in display order. @@ -369,19 +371,20 @@ impl Shell { SidebarViewRow::InOneList => { self.settings.sidebar_organization = SidebarOrganization::InOneList } - SidebarViewRow::LastUpdated => { - self.settings.sidebar_sort = SidebarSort::LastUpdated - } + SidebarViewRow::LastUpdated => self.settings.sidebar_sort = SidebarSort::LastUpdated, SidebarViewRow::Created => self.settings.sidebar_sort = SidebarSort::Created, SidebarViewRow::ShowBranch => { self.settings.sidebar_show_branch = !self.settings.sidebar_show_branch } SidebarViewRow::ShowPullRequest => { - self.settings.sidebar_show_pull_request = - !self.settings.sidebar_show_pull_request; + self.settings.sidebar_show_pull_request = !self.settings.sidebar_show_pull_request; let visible = self.settings.sidebar_show_pull_request; - self.state - .update(cx, |state, cx| state.set_change_requests_visible(visible, cx)); + self.state.update(cx, |state, cx| { + state.set_change_requests_visible(visible, cx) + }); + } + SidebarViewRow::ShowHarness => { + self.settings.sidebar_show_harness = !self.settings.sidebar_show_harness } } self.schedule_save(cx); @@ -428,20 +431,10 @@ impl Shell { let focus = menu_state.focus.clone(); let organization = self.settings.sidebar_organization; let sort = self.settings.sidebar_sort; + let show_harness = self.settings.sidebar_show_harness; let show_branch = self.settings.sidebar_show_branch; let show_pr = self.settings.sidebar_show_pull_request; - let heading = |label: &'static str| { - div() - .px(px(8.0)) - .pt(px(7.0)) - .pb(px(3.0)) - .text_size(px(10.0)) - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(theme.text_muted.opacity(0.65)) - .child(SharedString::from(label)) - .into_any_element() - }; let labels = [ "By project", "By device", @@ -450,6 +443,17 @@ impl Shell { "Created", "Branch", "Pull request", + "Harness", + ]; + let icons = [ + icons::FOLDER, + icons::LAPTOP, + icons::LIST, + icons::CLOCK_CIRCLE, + icons::CALENDAR, + icons::GIT_BRANCH, + icons::PULL_REQUEST, + icons::BOT, ]; let selected = [ organization == SidebarOrganization::ByProject, @@ -459,6 +463,7 @@ impl Shell { sort == SidebarSort::Created, show_branch, show_pr, + show_harness, ]; let mut rows: Vec = SIDEBAR_VIEW_ROWS .iter() @@ -472,19 +477,23 @@ impl Shell { format!("sidebar-view-row-{ix}"), ) .id(("sidebar-view-row", ix)) - .on_click(cx.listener(move |this, _, _, cx| { - this.activate_sidebar_view_row(row, cx) - })) + .on_click( + cx.listener(move |this, _, _, cx| this.activate_sidebar_view_row(row, cx)), + ) .child( - div().w(px(16.0)).flex_none().when(selected[ix], |el| { - el.child( - icon(icons::CHECK) - .size(px(14.0)) - .text_color(theme.text_muted), - ) - }), + icon(icons[ix]) + .size(px(15.0)) + .flex_none() + .text_color(theme.text_muted.opacity(0.8)), ) - .child(SharedString::from(labels[ix])) + .child(div().flex_1().child(SharedString::from(labels[ix]))) + .child(div().w(px(14.0)).flex_none().when(selected[ix], |el| { + el.child( + icon(icons::CHECK) + .size(px(14.0)) + .text_color(theme.text_muted), + ) + })) .into_any_element() }) .collect(); @@ -493,24 +502,28 @@ impl Shell { let organization_rows = rows; popover::popover_card(theme) - .w(px(202.0)) + .w(px(self.settings.sidebar_width - 2.0 * Theme::SPACE_SM)) .track_focus(&focus) .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, _, cx| { this.sidebar_view_menu_key(event, cx) })) - .on_mouse_down_out(cx.listener(|this, _, _, cx| { - this.close_sidebar_view_menu(cx) - })) + .on_mouse_down_out(cx.listener(|this, _, _, cx| this.close_sidebar_view_menu(cx))) .flex() .flex_col() - .child(heading("Organize")) - .children(organization_rows) + .child(popover::menu_heading(theme, "Organize")) + .child( + div() + .flex() + .flex_col() + .gap(px(2.0)) + .children(organization_rows), + ) .child(popover::menu_separator()) - .child(heading("Sort")) - .children(sort_rows) + .child(popover::menu_heading(theme, "Sort")) + .child(div().flex().flex_col().gap(px(2.0)).children(sort_rows)) .child(popover::menu_separator()) - .child(heading("Show")) - .children(show_rows) + .child(popover::menu_heading(theme, "Show")) + .child(div().flex().flex_col().gap(px(2.0)).children(show_rows)) .into_any_element() } @@ -672,11 +685,13 @@ impl Shell { let view_trigger = if self.sidebar_view_menu.get().is_some() { let closing = self.sidebar_view_menu.closing_since(); let menu = self.render_sidebar_view_menu(theme, cx); - view_trigger.relative().child(popover::anchored_menu_below( - "sidebar-view-options-menu", - menu, - closing, - )) + view_trigger + .relative() + .child(popover::anchored_menu_below_end( + "sidebar-view-options-menu", + menu, + closing, + )) } else { view_trigger }; @@ -995,7 +1010,11 @@ impl Shell { format_time_ago(chat.last_message_at.unwrap_or(chat.created_at), now).into(); let is_selected = selected.as_deref() == Some(chat.id.as_str()); let height = super::CHAT_ROW_HEIGHT; - let harness = chat.config.as_ref().map(|c| c.harness); + let harness = self + .settings + .sidebar_show_harness + .then(|| chat.config.as_ref().map(|c| c.harness)) + .flatten(); let element = self.render_chat_row( chat.id.clone(), transcript::single_line( @@ -1119,11 +1138,13 @@ impl Shell { .into(); let time_ago: SharedString = format_time_ago(chat.last_message_at.unwrap_or(chat.created_at), now).into(); - let (mark, tint) = chat - .config - .as_ref() - .map(|c| crate::pickers::harness_brand_icon(c.harness)) - .unwrap_or((crate::icons::CHAT_ROUND_LINE, None)); + let brand = if self.settings.sidebar_show_harness { + chat.config + .as_ref() + .map(|c| crate::pickers::harness_brand_icon(c.harness)) + } else { + None + }; // Right slot: time at rest; the Unarchive affordance takes // its place on row hover (t3code: "only the time/jump label // yields to the settle affordance"). @@ -1211,16 +1232,18 @@ impl Shell { ) // Archived history recedes: dimmed mark at rest, // restored on hover (t3code's grayscale favicon). - .child( - crate::icons::icon(mark) - .size(px(14.0)) - .flex_none() - .text_color(if hovered || is_selected { - tint.unwrap_or(theme.text_muted) - } else { - tint.unwrap_or(theme.text_muted).opacity(0.4) - }), - ) + .when_some(brand, |el, (mark, tint)| { + el.child( + crate::icons::icon(mark) + .size(px(14.0)) + .flex_none() + .text_color(if hovered || is_selected { + tint.unwrap_or(theme.text_muted) + } else { + tint.unwrap_or(theme.text_muted).opacity(0.4) + }), + ) + }) .child( div() .flex_1() diff --git a/docs/research/sidebar-view-options.md b/docs/research/sidebar-view-options.md index 3ad140f8d9..fc667ba399 100644 --- a/docs/research/sidebar-view-options.md +++ b/docs/research/sidebar-view-options.md @@ -168,12 +168,16 @@ Sort Show Branch Pull request + Harness ``` Defaults preserve today's presentation (`In one list`, `Last updated`, Branch -on, Pull request on). Organizing deduplicates project/device context into section -headers; it does not change the selected project, open tabs, or new-session -target. Section collapsed state is local to the selected organization mode. +on, Pull request on, Harness on). The view menu mirrors the project selector: +it uses the same sidebar-inner width and spacing conventions, but aligns its +trailing edge to the view-options button. Organizing deduplicates project/device +context into section headers; it does not change the selected project, open +tabs, or new-session target. Section collapsed state is local to the selected +organization mode. Follow-ups, not first-slice requirements: From 12f9fcc3e93b4b0bda85a11592721e771a7b2d8c Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 14:32:08 +0200 Subject: [PATCH 04/17] fix: simplify sidebar view controls --- crates/ui/src/settings.rs | 20 ++++++++++++++++++++ crates/ui/src/shell/spaces.rs | 23 +++++------------------ docs/research/sidebar-view-options.md | 5 +++-- 3 files changed, 28 insertions(+), 20 deletions(-) diff --git a/crates/ui/src/settings.rs b/crates/ui/src/settings.rs index b12bddcd07..485adcaac2 100644 --- a/crates/ui/src/settings.rs +++ b/crates/ui/src/settings.rs @@ -49,6 +49,8 @@ const FILE_NAME: &str = "ui-settings.json"; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)] #[serde(rename_all = "camelCase")] pub enum SidebarOrganization { + /// Legacy persisted value. Project scope now belongs exclusively to the + /// project selector and is normalized to [`Self::InOneList`] on load. ByProject, ByDevice, #[default] @@ -334,6 +336,9 @@ pub fn display_combo(combo: &str) -> String { impl UiSettings { /// Clamp widths into their legal ranges (also heals NaN to defaults). pub fn clamped(mut self) -> Self { + if self.sidebar_organization == SidebarOrganization::ByProject { + self.sidebar_organization = SidebarOrganization::InOneList; + } self.sidebar_width = clamp_or( self.sidebar_width, SIDEBAR_MIN, @@ -440,6 +445,21 @@ mod tests { assert_eq!(UiSettings::load(dir.path()), settings); } + #[test] + fn legacy_project_organization_normalizes_to_one_list() { + let dir = tempfile::tempdir().unwrap(); + std::fs::write( + UiSettings::path(dir.path()), + r#"{"sidebarOrganization":"byProject"}"#, + ) + .unwrap(); + + assert_eq!( + UiSettings::load(dir.path()).sidebar_organization, + SidebarOrganization::InOneList + ); + } + /// A settings file written before light mode existed has no `appearance` /// key; it must load as "follow the OS" rather than failing the whole parse /// and resetting every other preference to defaults. diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index fe2fcb59fa..1151ee6a12 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -63,7 +63,6 @@ impl Render for SidebarViewOptionsTooltip { #[derive(Clone, Copy)] enum SidebarViewRow { - ByProject, ByDevice, InOneList, LastUpdated, @@ -73,8 +72,7 @@ enum SidebarViewRow { ShowHarness, } -const SIDEBAR_VIEW_ROWS: [SidebarViewRow; 8] = [ - SidebarViewRow::ByProject, +const SIDEBAR_VIEW_ROWS: [SidebarViewRow; 7] = [ SidebarViewRow::ByDevice, SidebarViewRow::InOneList, SidebarViewRow::LastUpdated, @@ -362,9 +360,6 @@ impl Shell { fn activate_sidebar_view_row(&mut self, row: SidebarViewRow, cx: &mut Context) { match row { - SidebarViewRow::ByProject => { - self.settings.sidebar_organization = SidebarOrganization::ByProject - } SidebarViewRow::ByDevice => { self.settings.sidebar_organization = SidebarOrganization::ByDevice } @@ -436,7 +431,6 @@ impl Shell { let show_pr = self.settings.sidebar_show_pull_request; let labels = [ - "By project", "By device", "In one list", "Last updated", @@ -446,7 +440,6 @@ impl Shell { "Harness", ]; let icons = [ - icons::FOLDER, icons::LAPTOP, icons::LIST, icons::CLOCK_CIRCLE, @@ -456,7 +449,6 @@ impl Shell { icons::BOT, ]; let selected = [ - organization == SidebarOrganization::ByProject, organization == SidebarOrganization::ByDevice, organization == SidebarOrganization::InOneList, sort == SidebarSort::LastUpdated, @@ -497,8 +489,8 @@ impl Shell { .into_any_element() }) .collect(); - let show_rows = rows.split_off(5); - let sort_rows = rows.split_off(3); + let show_rows = rows.split_off(4); + let sort_rows = rows.split_off(2); let organization_rows = rows; popover::popover_card(theme) @@ -681,7 +673,7 @@ impl Shell { })) .tooltip(|_, cx| cx.new(|_| SidebarViewOptionsTooltip).into()) .tooltip_show_delay(std::time::Duration::from_millis(350)) - .child(icon(icons::TUNING).size(px(16.0))); + .child(icon(icons::SORT_VERTICAL).size(px(16.0))); let view_trigger = if self.sidebar_view_menu.get().is_some() { let closing = self.sidebar_view_menu.closing_since(); let menu = self.render_sidebar_view_menu(theme, cx); @@ -909,10 +901,6 @@ impl Shell { .map(str::to_string); let change_request = state.change_request_for_chat(&chat).cloned(); let group = match self.settings.sidebar_organization { - SidebarOrganization::ByProject if filter.is_none() => Some(( - chat.space_id.clone().unwrap_or_else(|| "~".into()), - project, - )), SidebarOrganization::ByDevice => { Some((chat.device_id.clone(), device)) } @@ -955,9 +943,8 @@ impl Shell { let mut collapsed = false; if let Some((key, label)) = group { let organization = match self.settings.sidebar_organization { - SidebarOrganization::ByProject => "project", SidebarOrganization::ByDevice => "device", - SidebarOrganization::InOneList => "list", + SidebarOrganization::ByProject | SidebarOrganization::InOneList => "list", }; let collapse_key = format!("{organization}:{key}"); collapsed = self.sidebar_collapsed_groups.contains(&collapse_key); diff --git a/docs/research/sidebar-view-options.md b/docs/research/sidebar-view-options.md index fc667ba399..2b5318ffc5 100644 --- a/docs/research/sidebar-view-options.md +++ b/docs/research/sidebar-view-options.md @@ -157,7 +157,6 @@ Focused first version: ```text Organize - By project By device In one list @@ -171,7 +170,9 @@ Show Harness ``` -Defaults preserve today's presentation (`In one list`, `Last updated`, Branch +Project scope belongs exclusively to the project selector; the legacy +`By project` organization value normalizes to `In one list`. Defaults preserve +today's presentation (`In one list`, `Last updated`, Branch on, Pull request on, Harness on). The view menu mirrors the project selector: it uses the same sidebar-inner width and spacing conventions, but aligns its trailing edge to the view-options button. Organizing deduplicates project/device From 6667860319fae2cad285fd94a7f9eb30d5ea6c2a Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 14:41:12 +0200 Subject: [PATCH 05/17] fix: stabilize sidebar view menu state --- crates/ui/src/shell/spaces.rs | 45 +++++++++++++++++++++++++++-------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 1151ee6a12..1fa224b8c0 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -38,7 +38,10 @@ pub(super) struct SpacesMenu { } pub(super) struct SidebarViewMenu { - active: usize, + /// Keyboard cursor. Mouse-opened menus start without one so the persisted + /// radio/check state is the only selection signal until an arrow key is + /// pressed. + active: Option, focus: FocusHandle, } @@ -72,6 +75,17 @@ enum SidebarViewRow { ShowHarness, } +impl SidebarViewRow { + /// Radio-style presentation choices behave like the project selector and + /// dismiss after selection. Show toggles stay open for batch changes. + fn closes_menu(self) -> bool { + matches!( + self, + Self::ByDevice | Self::InOneList | Self::LastUpdated | Self::Created + ) + } +} + const SIDEBAR_VIEW_ROWS: [SidebarViewRow; 7] = [ SidebarViewRow::ByDevice, SidebarViewRow::InOneList, @@ -351,7 +365,7 @@ impl Shell { self.close_spaces_menu(cx); let focus = cx.focus_handle(); self.sidebar_view_menu.open(SidebarViewMenu { - active: 0, + active: None, focus: focus.clone(), }); window.focus(&focus, cx); @@ -383,6 +397,9 @@ impl Shell { } } self.schedule_save(cx); + if row.closes_menu() { + self.close_sidebar_view_menu(cx); + } cx.notify(); } @@ -400,17 +417,16 @@ impl Shell { let up = event.keystroke.key.eq_ignore_ascii_case("arrowup"); if let Some(menu) = self.sidebar_view_menu.open_mut() { menu.active = popover::menu_step( - Some(menu.active), + menu.active, SIDEBAR_VIEW_ROWS.len(), if up { -1 } else { 1 }, - ) - .unwrap_or(0); + ); cx.notify(); } } popover::MenuKey::Enter | popover::MenuKey::ModEnter => { - let active = self.sidebar_view_menu.get().map(|m| m.active).unwrap_or(0); - if let Some(row) = SIDEBAR_VIEW_ROWS.get(active).copied() { + let active = self.sidebar_view_menu.get().and_then(|m| m.active); + if let Some(row) = active.and_then(|ix| SIDEBAR_VIEW_ROWS.get(ix)).copied() { self.activate_sidebar_view_row(row, cx); } } @@ -465,12 +481,17 @@ impl Shell { popover::menu_row_nav( theme, selected[ix], - ix == active, + active == Some(ix), format!("sidebar-view-row-{ix}"), ) .id(("sidebar-view-row", ix)) .on_click( - cx.listener(move |this, _, _, cx| this.activate_sidebar_view_row(row, cx)), + cx.listener(move |this, _, _, cx| { + if let Some(menu) = this.sidebar_view_menu.open_mut() { + menu.active = None; + } + this.activate_sidebar_view_row(row, cx) + }), ) .child( icon(icons[ix]) @@ -673,7 +694,11 @@ impl Shell { })) .tooltip(|_, cx| cx.new(|_| SidebarViewOptionsTooltip).into()) .tooltip_show_delay(std::time::Duration::from_millis(350)) - .child(icon(icons::SORT_VERTICAL).size(px(16.0))); + .child( + icon(icons::SORT_VERTICAL) + .size(px(16.0)) + .text_color(theme.text_muted), + ); let view_trigger = if self.sidebar_view_menu.get().is_some() { let closing = self.sidebar_view_menu.closing_since(); let menu = self.render_sidebar_view_menu(theme, cx); From 6ff38dd77100d1518872ab23870a41f1e421ec62 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 14:50:05 +0200 Subject: [PATCH 06/17] fix: refine sidebar dropdown controls --- crates/ui/src/shell/spaces.rs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 1fa224b8c0..fcfcd0250d 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -96,6 +96,11 @@ const SIDEBAR_VIEW_ROWS: [SidebarViewRow; 7] = [ SidebarViewRow::ShowHarness, ]; +// With the search field and card insets, this lets the project picker grow to +// roughly the same maximum footprint as the sidebar view-options menu while +// retaining an internal scroll region for larger project lists. +const SPACES_MENU_LIST_MAX_HEIGHT: f32 = 336.0; + /// One row of the open dropdown, in display order. #[derive(Clone, PartialEq)] pub(super) enum SpacesMenuRow { @@ -695,7 +700,7 @@ impl Shell { .tooltip(|_, cx| cx.new(|_| SidebarViewOptionsTooltip).into()) .tooltip_show_delay(std::time::Duration::from_millis(350)) .child( - icon(icons::SORT_VERTICAL) + icon(icons::LIST) .size(px(16.0)) .text_color(theme.text_muted), ); @@ -778,7 +783,7 @@ impl Shell { .flex() .flex_col() .gap(px(2.0)) - .max_h(px(224.0)) + .max_h(px(SPACES_MENU_LIST_MAX_HEIGHT)) .overflow_y_scroll() .track_scroll(&list_scroll) .children(details.into_iter().enumerate().map( From 34ac9a540d898064aaa17cbfd893c4417b4beb31 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 14:53:57 +0200 Subject: [PATCH 07/17] fix: use canonical Solar sort icon --- crates/ui/assets/icons/sort.svg | 1 + crates/ui/src/icons.rs | 1 + crates/ui/src/shell/spaces.rs | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) create mode 100644 crates/ui/assets/icons/sort.svg diff --git a/crates/ui/assets/icons/sort.svg b/crates/ui/assets/icons/sort.svg new file mode 100644 index 0000000000..dc5c877694 --- /dev/null +++ b/crates/ui/assets/icons/sort.svg @@ -0,0 +1 @@ + diff --git a/crates/ui/src/icons.rs b/crates/ui/src/icons.rs index 2298b35145..bb899bd94e 100644 --- a/crates/ui/src/icons.rs +++ b/crates/ui/src/icons.rs @@ -52,6 +52,7 @@ icon_assets![ (MONITOR, "monitor"), (LAPTOP, "laptop"), (PEN_NEW_SQUARE, "pen-new-square"), + (SORT, "sort"), (SORT_VERTICAL, "sort-vertical"), (CLOCK_CIRCLE, "clock-circle"), (CALENDAR, "calendar"), diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index fcfcd0250d..7696e9ef0f 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -700,7 +700,7 @@ impl Shell { .tooltip(|_, cx| cx.new(|_| SidebarViewOptionsTooltip).into()) .tooltip_show_delay(std::time::Duration::from_millis(350)) .child( - icon(icons::LIST) + icon(icons::SORT) .size(px(16.0)) .text_color(theme.text_muted), ); From 59b63c831459636eab67ef70f7acdba18e53806b Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 15:02:48 +0200 Subject: [PATCH 08/17] feat: animate sidebar disclosures --- crates/ui/src/shell.rs | 49 ++++++ crates/ui/src/shell/spaces.rs | 284 ++++++++++++++++++++++++---------- 2 files changed, 250 insertions(+), 83 deletions(-) diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index 37d98ddbcc..60f4abf472 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -76,6 +76,43 @@ struct ChatMenuState { page: ChatMenuPage, } +/// Interruptible height tween for the sidebar's device/archive disclosures. +/// The rendered element owns the frame clock; this state preserves the current +/// interpolated height when a second click reverses an in-flight transition. +#[derive(Clone, Copy)] +pub(super) struct SidebarDisclosureMotion { + pub(super) epoch: u64, + pub(super) from: f32, + pub(super) to: f32, + started: std::time::Instant, +} + +impl SidebarDisclosureMotion { + fn new(epoch: u64, from: f32, to: f32) -> Self { + Self { + epoch, + from, + to, + started: std::time::Instant::now(), + } + } + + fn current(self) -> f32 { + let total = motion::COLLAPSE.total().as_secs_f32(); + let raw = if total > 0.0 { + self.started.elapsed().as_secs_f32() / total + } else { + 1.0 + }; + motion::lerp(self.from, self.to, motion::COLLAPSE.progress(raw)) + } + + fn animating(self) -> bool { + self.started.elapsed() + < motion::COLLAPSE.total() + spaces::SIDEBAR_DISCLOSURE_TWEEN_GRACE + } +} + /// Vertical pane resize hitboxes yield the global titlebar. Keeping this in /// the shared constructor makes left/right seams mirror each other and avoids /// relying on paint order when chrome crosses an animated pane boundary. @@ -874,6 +911,9 @@ pub struct Shell { pub(super) archived_hover: Option, /// Ephemeral collapsed project/device sections, keyed by organization + id. pub(super) sidebar_collapsed_groups: std::collections::HashSet, + /// In-flight disclosure tweens, shared by device groups and Archived. + pub(super) sidebar_disclosure_motion: + std::collections::HashMap, /// Lazy panes: no entity (and no RPC) until first opened. terminal: Option>, /// Embedded terminal host for right-pane Terminal surfaces — a SEPARATE @@ -1165,6 +1205,7 @@ impl Shell { archived_shown: 0, archived_hover: None, sidebar_collapsed_groups: std::collections::HashSet::new(), + sidebar_disclosure_motion: std::collections::HashMap::new(), terminal: None, right_terminal: None, right_plus: popover::Popup::default(), @@ -8194,4 +8235,12 @@ mod tests { ); assert_eq!(nav.back(), Some(chat("a"))); } + + #[test] + fn sidebar_disclosure_motion_lands_exactly_on_its_target() { + let mut tween = SidebarDisclosureMotion::new(1, 240.0, 0.0); + tween.started = std::time::Instant::now() - motion::COLLAPSE.total().mul_f32(2.0); + assert_eq!(tween.current(), 0.0); + assert!(!tween.animating()); + } } diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 7696e9ef0f..277331075b 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -100,6 +100,35 @@ const SIDEBAR_VIEW_ROWS: [SidebarViewRow; 7] = [ // roughly the same maximum footprint as the sidebar view-options menu while // retaining an internal scroll region for larger project lists. const SPACES_MENU_LIST_MAX_HEIGHT: f32 = 336.0; +const SIDEBAR_DISCLOSURE_HEADER_HEIGHT: f32 = 32.0; +pub(super) const SIDEBAR_DISCLOSURE_TWEEN_GRACE: std::time::Duration = + std::time::Duration::from_millis(120); + +fn sidebar_disclosure_header( + theme: &Theme, + label: SharedString, + chevron: AnyElement, +) -> gpui::Div { + div() + .flex() + .flex_row() + .items_center() + .gap(px(8.0)) + .mt(px(12.0)) + .mb(px(4.0)) + .px(px(10.0)) + .cursor_pointer() + .child( + div() + .flex_none() + .text_size(px(12.0)) + .font_weight(gpui::FontWeight::MEDIUM) + .text_color(theme.text_muted.opacity(0.5)) + .child(label), + ) + .child(div().h(px(1.0)).flex_1().bg(theme.border.opacity(0.6))) + .child(chevron) +} /// One row of the open dropdown, in display order. #[derive(Clone, PartialEq)] @@ -197,6 +226,90 @@ pub(super) fn status_dot_color(status: ChatIndicator, theme: &Theme) -> gpui::Hs } impl Shell { + fn begin_sidebar_disclosure_motion( + &mut self, + key: &str, + resting_height: f32, + target_height: f32, + ) { + let previous = self.sidebar_disclosure_motion.get(key).copied(); + let from = previous + .filter(|motion| motion.animating()) + .map(SidebarDisclosureMotion::current) + .unwrap_or(resting_height); + let epoch = previous.map_or(1, |motion| motion.epoch + 1); + self.sidebar_disclosure_motion.insert( + key.to_owned(), + SidebarDisclosureMotion::new(epoch, from, target_height), + ); + } + + fn render_sidebar_disclosure_body( + &self, + key: &str, + open: bool, + full_height: f32, + content: AnyElement, + ) -> AnyElement { + let target = if open { full_height } else { 0.0 }; + let frame = div().w_full().flex_none().overflow_hidden().child(content); + let Some(tween) = self + .sidebar_disclosure_motion + .get(key) + .copied() + .filter(|motion| motion.animating()) + else { + return frame.h(px(target)).into_any_element(); + }; + let denominator = full_height.max(1.0); + frame + .with_animation( + SharedString::from(format!("sidebar-disclosure-{key}-{}", tween.epoch)), + motion::COLLAPSE.animation(), + move |el, t| { + let height = motion::lerp(tween.from, tween.to, t); + let reveal = (height / denominator).clamp(0.0, 1.0); + el.h(px(height)) + .opacity(0.35 + 0.65 * reveal) + .relative() + .top(px(-3.0 * (1.0 - reveal))) + }, + ) + .into_any_element() + } + + fn sidebar_disclosure_chevron( + &self, + key: &str, + open: bool, + theme: &Theme, + ) -> AnyElement { + let chevron = div().flex_none().size(px(12.0)).child( + icon(if open { + icons::ALT_ARROW_DOWN + } else { + icons::ALT_ARROW_RIGHT + }) + .size(px(12.0)) + .text_color(theme.text_muted.opacity(0.5)), + ); + if let Some(tween) = self + .sidebar_disclosure_motion + .get(key) + .copied() + .filter(|motion| motion.animating()) + { + chevron + .with_animation( + SharedString::from(format!("sidebar-chevron-{key}-{}", tween.epoch)), + motion::CHEVRON.animation(), + |el, t| el.opacity(0.25 + 0.75 * t), + ) + .into_any_element() + } else { + chevron.into_any_element() + } + } // ---- space filter ---- /// Set the sidebar's session filter (`None` = All spaces). On the @@ -970,50 +1083,7 @@ impl Shell { let selected = self.state.read(cx).selected_chat.clone(); let mut rendered = Vec::new(); for (group, rows) in groups { - let mut collapsed = false; - if let Some((key, label)) = group { - let organization = match self.settings.sidebar_organization { - SidebarOrganization::ByDevice => "device", - SidebarOrganization::ByProject | SidebarOrganization::InOneList => "list", - }; - let collapse_key = format!("{organization}:{key}"); - collapsed = self.sidebar_collapsed_groups.contains(&collapse_key); - let toggle_key = collapse_key.clone(); - let height = 27.0; - let element = div() - .id(collapse_key.clone()) - .h(px(height)) - .flex() - .items_end() - .gap(px(4.0)) - .px(px(Theme::SPACE_SM)) - .pb(px(4.0)) - .cursor_pointer() - .on_click(cx.listener(move |this, _, _, cx| { - if !this.sidebar_collapsed_groups.remove(&toggle_key) { - this.sidebar_collapsed_groups.insert(toggle_key.clone()); - } - cx.notify(); - })) - .text_size(px(10.0)) - .font_weight(gpui::FontWeight::SEMIBOLD) - .text_color(theme.text_muted.opacity(0.65)) - .child( - icon(if collapsed { - icons::ALT_ARROW_RIGHT - } else { - icons::ALT_ARROW_DOWN - }) - .size(px(12.0)) - .text_color(theme.text_muted.opacity(0.6)), - ) - .child(SharedString::from(label)) - .into_any_element(); - rendered.push((format!("g:{collapse_key}"), height, element)); - } - if collapsed { - continue; - } + let mut rendered_rows = Vec::with_capacity(rows.len()); for row in rows { let ActiveChatRow { status, @@ -1049,8 +1119,69 @@ impl Shell { theme, cx, ); - rendered.push((format!("c:{}", chat.id), height, element)); + rendered_rows.push((format!("c:{}", chat.id), height, element)); } + + let Some((key, label)) = group else { + rendered.extend(rendered_rows); + continue; + }; + let organization = match self.settings.sidebar_organization { + SidebarOrganization::ByDevice => "device", + SidebarOrganization::ByProject | SidebarOrganization::InOneList => "list", + }; + let collapse_key = format!("{organization}:{key}"); + let motion_key = format!("group:{collapse_key}"); + let collapsed = self.sidebar_collapsed_groups.contains(&collapse_key); + let row_count = rendered_rows.len(); + let body_height = rendered_rows.iter().map(|(_, height, _)| *height).sum::() + + SIDEBAR_LIST_GAP * row_count.saturating_sub(1) as f32; + let body = div() + .w_full() + .flex() + .flex_col() + .gap(px(SIDEBAR_LIST_GAP)) + .children(rendered_rows.into_iter().map(|(_, _, row)| row)); + let visible_label: SharedString = if collapsed { + format!("{label} ({row_count})").into() + } else { + label.into() + }; + let chevron = self.sidebar_disclosure_chevron(&motion_key, !collapsed, theme); + let toggle_key = collapse_key.clone(); + let toggle_motion_key = motion_key.clone(); + let header = sidebar_disclosure_header(theme, visible_label, chevron) + .id(SharedString::from(format!("sidebar-group-{collapse_key}"))) + .on_click(cx.listener(move |this, _, _, cx| { + let was_open = !this.sidebar_collapsed_groups.contains(&toggle_key); + this.begin_sidebar_disclosure_motion( + &toggle_motion_key, + if was_open { body_height } else { 0.0 }, + if was_open { 0.0 } else { body_height }, + ); + if was_open { + this.sidebar_collapsed_groups.insert(toggle_key.clone()); + } else { + this.sidebar_collapsed_groups.remove(&toggle_key); + } + cx.notify(); + })); + let body = self.render_sidebar_disclosure_body( + &motion_key, + !collapsed, + body_height, + body.into_any_element(), + ); + let height = SIDEBAR_DISCLOSURE_HEADER_HEIGHT + + if collapsed { 0.0 } else { body_height }; + let element = div() + .w_full() + .flex() + .flex_col() + .child(header) + .child(body) + .into_any_element(); + rendered.push((format!("g:{collapse_key}"), height, element)); } rendered } @@ -1098,6 +1229,11 @@ impl Shell { let total = rows.len(); let open = self.archived_open; let shown = self.archived_shown.max(INITIAL); + let visible_count = total.min(shown); + let has_more = total > shown; + let body_height = visible_count as f32 * 36.0 + + visible_count.saturating_sub(1) as f32 * SIDEBAR_LIST_GAP + + if has_more { 36.0 + SIDEBAR_LIST_GAP } else { 0.0 }; // Header (t3code settled-shelf toggle): muted 12px label, a hairline // filling the middle, chevron flipping open/closed. The count only // shows while collapsed — expanded, the rows speak for themselves. @@ -1106,42 +1242,22 @@ impl Shell { } else { format!("Archived ({total})").into() }; - let header = div() + let chevron = self.sidebar_disclosure_chevron("archived", open, theme); + let header = sidebar_disclosure_header(theme, label, chevron) .id("archived-toggle") - .flex() - .flex_row() - .items_center() - .gap(px(8.0)) - .mt(px(12.0)) - .mb(px(4.0)) - .px(px(10.0)) - .cursor_pointer() .on_click(cx.listener(move |this, _, _, cx| { - this.archived_open = !this.archived_open; + let was_open = this.archived_open; + this.begin_sidebar_disclosure_motion( + "archived", + if was_open { body_height } else { 0.0 }, + if was_open { 0.0 } else { body_height }, + ); + this.archived_open = !was_open; this.archived_shown = INITIAL; cx.notify(); - })) - .child( - div() - .flex_none() - .text_size(px(12.0)) - .font_weight(gpui::FontWeight::MEDIUM) - .text_color(theme.text_muted.opacity(0.5)) - .child(label), - ) - .child(div().h(px(1.0)).flex_1().bg(theme.border.opacity(0.6))) - .child( - crate::icons::icon(if open { - crate::icons::ALT_ARROW_DOWN - } else { - crate::icons::ALT_ARROW_RIGHT - }) - .size(px(12.0)) - .flex_none() - .text_color(theme.text_muted.opacity(0.5)), - ); - let mut section = div().flex().flex_col().child(header); - if open { + })); + let section = div().flex().flex_col().child(header); + let body = { let selected = self.state.read(cx).selected_chat.clone(); let selected_wash = crate::theme::glass_selected_bg(); let mut list = div().flex().flex_col().gap(px(2.0)); @@ -1277,12 +1393,10 @@ impl Shell { .child(right), ); } - // Mount fade: the shelf popping in whole read as jank — a quick - // fade on the expanded list softens the accordion. - section = section.child(motion::fade_quick("archived-list", list)); - if total > shown { + let mut body = div().w_full().flex().flex_col().child(list); + if has_more { let remaining = (total - shown).min(PAGE); - section = section.child( + body = body.child( div() .id("archived-more") // Sits outside the rows' gapped column — match the @@ -1311,7 +1425,11 @@ impl Shell { .child(SharedString::from(format!("Show {remaining} more"))), ); } - } + body.into_any_element() + }; + let body = + self.render_sidebar_disclosure_body("archived", open, body_height, body); + let section = section.child(body); Some(section.pb(px(Theme::SPACE_SM)).into_any_element()) } From eab54b531e18c6f4643cf91f2026d5c41ddd753a Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 15:16:52 +0200 Subject: [PATCH 09/17] polish sidebar disclosure rhythm --- crates/ui/src/shell.rs | 1 - crates/ui/src/shell/spaces.rs | 107 +++++++++++++++++++++------------- 2 files changed, 66 insertions(+), 42 deletions(-) diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index 60f4abf472..dd40728b53 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -4193,7 +4193,6 @@ impl Shell { .flex() .flex_col() .gap(px(2.0)) - .pb(px(Theme::SPACE_SM)) .children(list_items) .into_any_element() } else { diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 277331075b..60985dffaf 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -100,23 +100,26 @@ const SIDEBAR_VIEW_ROWS: [SidebarViewRow; 7] = [ // roughly the same maximum footprint as the sidebar view-options menu while // retaining an internal scroll region for larger project lists. const SPACES_MENU_LIST_MAX_HEIGHT: f32 = 336.0; -const SIDEBAR_DISCLOSURE_HEADER_HEIGHT: f32 = 32.0; +// Sidebar rhythm: every first-level surface shares Theme's 8px inline edge; +// list items stay tightly related at 2px, while section boundaries use 12px +// (well over 2x the intra-list gap). Disclosure content gets a small 4px +// handoff from its header without leaving dead space while collapsed. +const SIDEBAR_SECTION_GAP: f32 = 12.0; +const SIDEBAR_DISCLOSURE_HEADER_HEIGHT: f32 = 28.0; +const SIDEBAR_DISCLOSURE_BODY_INSET: f32 = 4.0; +const SIDEBAR_DISCLOSURE_SECTION_HEIGHT: f32 = + SIDEBAR_SECTION_GAP + SIDEBAR_DISCLOSURE_HEADER_HEIGHT; pub(super) const SIDEBAR_DISCLOSURE_TWEEN_GRACE: std::time::Duration = std::time::Duration::from_millis(120); -fn sidebar_disclosure_header( - theme: &Theme, - label: SharedString, - chevron: AnyElement, -) -> gpui::Div { +fn sidebar_disclosure_header(theme: &Theme, label: SharedString, chevron: AnyElement) -> gpui::Div { div() .flex() .flex_row() .items_center() .gap(px(8.0)) - .mt(px(12.0)) - .mb(px(4.0)) - .px(px(10.0)) + .h(px(SIDEBAR_DISCLOSURE_HEADER_HEIGHT)) + .px(px(Theme::SPACE_SM)) .cursor_pointer() .child( div() @@ -278,36 +281,44 @@ impl Shell { .into_any_element() } - fn sidebar_disclosure_chevron( - &self, - key: &str, - open: bool, - theme: &Theme, - ) -> AnyElement { - let chevron = div().flex_none().size(px(12.0)).child( - icon(if open { - icons::ALT_ARROW_DOWN - } else { - icons::ALT_ARROW_RIGHT - }) + fn sidebar_disclosure_chevron(&self, key: &str, open: bool, theme: &Theme) -> AnyElement { + let resting_reveal = if open { 1.0 } else { 0.0 }; + let chevron = icon(icons::ALT_ARROW_RIGHT) .size(px(12.0)) - .text_color(theme.text_muted.opacity(0.5)), - ); + .text_color(theme.text_muted.opacity(0.5)); if let Some(tween) = self .sidebar_disclosure_motion .get(key) .copied() .filter(|motion| motion.animating()) { - chevron - .with_animation( + let denominator = tween.from.max(tween.to).max(1.0); + let from = (tween.from / denominator).clamp(0.0, 1.0); + let to = (tween.to / denominator).clamp(0.0, 1.0); + div() + .flex_none() + .size(px(12.0)) + .child(chevron.with_animation( SharedString::from(format!("sidebar-chevron-{key}-{}", tween.epoch)), - motion::CHEVRON.animation(), - |el, t| el.opacity(0.25 + 0.75 * t), - ) + motion::COLLAPSE.animation(), + move |el, t| { + let reveal = motion::lerp(from, to, t); + el.with_transformation(gpui::Transformation::rotate(gpui::percentage( + reveal * 0.25, + ))) + }, + )) .into_any_element() } else { - chevron.into_any_element() + div() + .flex_none() + .size(px(12.0)) + .child( + chevron.with_transformation(gpui::Transformation::rotate(gpui::percentage( + resting_reveal * 0.25, + ))), + ) + .into_any_element() } } // ---- space filter ---- @@ -1134,12 +1145,17 @@ impl Shell { let motion_key = format!("group:{collapse_key}"); let collapsed = self.sidebar_collapsed_groups.contains(&collapse_key); let row_count = rendered_rows.len(); - let body_height = rendered_rows.iter().map(|(_, height, _)| *height).sum::() + let body_height = SIDEBAR_DISCLOSURE_BODY_INSET + + rendered_rows + .iter() + .map(|(_, height, _)| *height) + .sum::() + SIDEBAR_LIST_GAP * row_count.saturating_sub(1) as f32; let body = div() .w_full() .flex() .flex_col() + .pt(px(SIDEBAR_DISCLOSURE_BODY_INSET)) .gap(px(SIDEBAR_LIST_GAP)) .children(rendered_rows.into_iter().map(|(_, _, row)| row)); let visible_label: SharedString = if collapsed { @@ -1172,12 +1188,13 @@ impl Shell { body_height, body.into_any_element(), ); - let height = SIDEBAR_DISCLOSURE_HEADER_HEIGHT - + if collapsed { 0.0 } else { body_height }; + let height = + SIDEBAR_DISCLOSURE_SECTION_HEIGHT + if collapsed { 0.0 } else { body_height }; let element = div() .w_full() .flex() .flex_col() + .pt(px(SIDEBAR_SECTION_GAP)) .child(header) .child(body) .into_any_element(); @@ -1231,9 +1248,14 @@ impl Shell { let shown = self.archived_shown.max(INITIAL); let visible_count = total.min(shown); let has_more = total > shown; - let body_height = visible_count as f32 * 36.0 + let body_height = SIDEBAR_DISCLOSURE_BODY_INSET + + visible_count as f32 * 36.0 + visible_count.saturating_sub(1) as f32 * SIDEBAR_LIST_GAP - + if has_more { 36.0 + SIDEBAR_LIST_GAP } else { 0.0 }; + + if has_more { + 36.0 + SIDEBAR_LIST_GAP + } else { + 0.0 + }; // Header (t3code settled-shelf toggle): muted 12px label, a hairline // filling the middle, chevron flipping open/closed. The count only // shows while collapsed — expanded, the rows speak for themselves. @@ -1260,7 +1282,11 @@ impl Shell { let body = { let selected = self.state.read(cx).selected_chat.clone(); let selected_wash = crate::theme::glass_selected_bg(); - let mut list = div().flex().flex_col().gap(px(2.0)); + let mut list = div() + .flex() + .flex_col() + .pt(px(SIDEBAR_DISCLOSURE_BODY_INSET)) + .gap(px(SIDEBAR_LIST_GAP)); for chat in rows.into_iter().take(shown) { let id = chat.id.clone(); let hovered = self.archived_hover.as_deref() == Some(id.as_str()); @@ -1333,7 +1359,7 @@ impl Shell { .flex_row() .items_center() .gap(px(10.0)) - .px(px(10.0)) + .px(px(Theme::SPACE_SM)) .rounded(px(6.0)) .cursor_pointer() .when(is_selected, |el| el.bg(selected_wash)) @@ -1407,7 +1433,7 @@ impl Shell { .flex_row() .items_center() .gap(px(10.0)) - .px(px(10.0)) + .px(px(Theme::SPACE_SM)) .rounded(px(6.0)) .text_size(px(13.0)) .text_color(theme.text_muted.opacity(0.55)) @@ -1427,10 +1453,9 @@ impl Shell { } body.into_any_element() }; - let body = - self.render_sidebar_disclosure_body("archived", open, body_height, body); - let section = section.child(body); - Some(section.pb(px(Theme::SPACE_SM)).into_any_element()) + let body = self.render_sidebar_disclosure_body("archived", open, body_height, body); + let section = section.pt(px(SIDEBAR_SECTION_GAP)).child(body); + Some(section.into_any_element()) } // ---- add-space flow (the ⌘K palette) ---- From 270bf09a730b5be7ba1e64278dd8a6c54354d738 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 15:36:08 +0200 Subject: [PATCH 10/17] fix sidebar group height accounting --- crates/ui/src/shell.rs | 41 ++++++++++++++++++++++++++++++----- crates/ui/src/shell/spaces.rs | 13 ++++++++++- 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index dd40728b53..456cb741d7 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -509,12 +509,31 @@ pub fn resort_offsets( offsets } -/// Estimated sidebar row height for the resort diff (title line 17px inside -/// 6px vertical padding + the location subline's 14px line + 2px gap — Active -/// rows always carry the folder · device subline). -/// Session row height (FLIP estimate): space line + title + meta line -/// (harness mark, plus branch for worktrees). -const CHAT_ROW_HEIGHT: f32 = 61.0; +/// Exact active-session row height. The first two lines and the two 2px flex +/// gaps consume 47px including vertical padding; the metadata line then grows +/// to its tallest visible child. Keeping this calculation beside the renderer's +/// metrics prevents disclosure clips when view options alter that third line. +pub(super) fn chat_row_height( + shows_harness: bool, + shows_branch: bool, + shows_pull_request: bool, + shows_working_spinner: bool, +) -> f32 { + let mut metadata_height: f32 = 0.0; + if shows_harness { + metadata_height = metadata_height.max(11.0); + } + if shows_branch { + metadata_height = metadata_height.max(14.0); + } + if shows_pull_request { + metadata_height = metadata_height.max(16.0); + } + if shows_working_spinner { + metadata_height = metadata_height.max(8.0); + } + 47.0 + metadata_height +} /// Flex gap between sidebar list items. const SIDEBAR_LIST_GAP: f32 = 2.0; @@ -8087,6 +8106,16 @@ mod tests { list.iter().map(|(k, h)| (k.to_string(), *h)).collect() } + #[test] + fn sidebar_chat_height_tracks_visible_metadata() { + assert_eq!(chat_row_height(false, false, false, false), 47.0); + assert_eq!(chat_row_height(true, false, false, false), 58.0); + assert_eq!(chat_row_height(false, true, false, false), 61.0); + assert_eq!(chat_row_height(false, false, true, false), 63.0); + assert_eq!(chat_row_height(false, false, false, true), 55.0); + assert_eq!(chat_row_height(true, true, true, true), 63.0); + } + #[test] fn resort_offsets_empty_when_order_unchanged() { let order = keys(&[("a", 29.0), ("b", 29.0), ("c", 45.0)]); diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 60985dffaf..bd3d0e1339 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -1107,12 +1107,23 @@ impl Shell { let time_ago: SharedString = format_time_ago(chat.last_message_at.unwrap_or(chat.created_at), now).into(); let is_selected = selected.as_deref() == Some(chat.id.as_str()); - let height = super::CHAT_ROW_HEIGHT; let harness = self .settings .sidebar_show_harness .then(|| chat.config.as_ref().map(|c| c.harness)) .flatten(); + let shows_working_spinner = if status == ChatIndicator::Working { + let state = self.state.read(cx); + !state.send_queued(&chat.id, now) && !state.send_undelivered(&chat.id, now) + } else { + false + }; + let height = super::chat_row_height( + harness.is_some(), + branch.is_some(), + change_request.is_some(), + shows_working_spinner, + ); let element = self.render_chat_row( chat.id.clone(), transcript::single_line( From 5b9677b0772fa52768fa8457c8d6c36538f29107 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 15:53:05 +0200 Subject: [PATCH 11/17] polish sidebar disclosure and status layout --- crates/ui/src/shell.rs | 142 ++++++++++++++++++++-------------- crates/ui/src/shell/spaces.rs | 13 +--- 2 files changed, 83 insertions(+), 72 deletions(-) diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index 456cb741d7..b1783ebd93 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -509,29 +509,30 @@ pub fn resort_offsets( offsets } -/// Exact active-session row height. The first two lines and the two 2px flex -/// gaps consume 47px including vertical padding; the metadata line then grows -/// to its tallest visible child. Keeping this calculation beside the renderer's -/// metrics prevents disclosure clips when view options alter that third line. -pub(super) fn chat_row_height( - shows_harness: bool, - shows_branch: bool, - shows_pull_request: bool, - shows_working_spinner: bool, -) -> f32 { +/// Height changes do not constitute a list reorder. In particular, sidebar +/// disclosures animate their own height and must not also trigger FLIP offsets +/// on every following keyed section. +fn sidebar_key_order_changed(old: &[(String, f32)], new: &[(String, f32)]) -> bool { + old.len() != new.len() + || old + .iter() + .zip(new) + .any(|((old_key, _), (new_key, _))| old_key != new_key) +} + +/// Exact active-session row height. Harness identity now lives on the title +/// line and the Working glyph lives in the status corner, so neither adds a +/// third line. Only branch / pull-request metadata can grow the 47px base. +/// Keeping this calculation beside the renderer's metrics prevents disclosure +/// clips when view options alter that metadata line. +pub(super) fn chat_row_height(shows_branch: bool, shows_pull_request: bool) -> f32 { let mut metadata_height: f32 = 0.0; - if shows_harness { - metadata_height = metadata_height.max(11.0); - } if shows_branch { metadata_height = metadata_height.max(14.0); } if shows_pull_request { metadata_height = metadata_height.max(16.0); } - if shows_working_spinner { - metadata_height = metadata_height.max(8.0); - } 47.0 + metadata_height } /// Flex gap between sidebar list items. @@ -539,7 +540,7 @@ const SIDEBAR_LIST_GAP: f32 = 2.0; /// Ramp height of the sidebar's scroll-edge fade (the gpui /// [`gpui::EdgeFade`] scope — per-primitive, so text fades per glyph). -const SIDEBAR_GLASS_FADE_BAND: f32 = 32.0; +const SIDEBAR_GLASS_FADE_BAND: f32 = 24.0; /// Drag marker for the sidebar resize handle. struct SidebarResize; @@ -3682,10 +3683,9 @@ impl Shell { .into_any_element() } - /// One session row (zeron session-row.tsx): status rail on the left - /// (a live 2×3 mini spinner while working, a dot otherwise), title + - /// relative time on the first line, "folder · device" underneath aligned - /// to the title. Click selects; right-click opens the context menu. + /// One session row: context + status on line one, harness + title on line + /// two, and source metadata below. Working uses the live thread glyph in + /// the status corner. Click selects; right-click opens the context menu. #[allow(clippy::too_many_arguments)] fn render_chat_row( &self, @@ -3741,7 +3741,6 @@ impl Shell { zeron_proto::ChatIndicator::Idle => None, } }; - let queued = queued && !undelivered; let corner_body: AnyElement = if corner_hovered { div() .flex() @@ -3784,15 +3783,26 @@ impl Shell { } else { match status_label { Some(label) => { - // Glyph slot: Done wears the check; every other status a - // dot in its color (the Working spinner lives at the - // row's bottom-right, not up here). + // Glyph slot: Working carries its active thread glyph + // beside the accent word; Done wears the check; other + // statuses retain a quiet semantic dot. let glyph: AnyElement = if status == zeron_proto::ChatIndicator::Completed { icon(icons::CHECK) .size(px(11.0)) .flex_none() .text_color(status_color) .into_any_element() + } else if status == zeron_proto::ChatIndicator::Working + && !queued + && !undelivered + { + loaders::mini_gradient_spinner( + format!("chat-working-{id}"), + 2.0, + cx.entity_id(), + cx, + ) + .into_any_element() } else { div() .size(px(6.0)) @@ -3939,17 +3949,8 @@ impl Shell { ) .child(div().text_color(subline).child(corner)), ) - // Line 2: the session title, flush left (t3code card line 2). - .child( - div() - .w_full() - .truncate() - .text_size(px(13.0)) - .line_height(px(17.0)) - .child(title), - ) - // Line 3 (always): harness brand mark, branch, optional PR badge, - // and the working spinner. Branch remains the only shrinking item. + // Line 2: harness identity belongs directly with the title, + // instead of floating as unrelated metadata below it. .child( div() .w_full() @@ -3968,6 +3969,24 @@ impl Shell { ) }, ) + .child( + div() + .min_w_0() + .truncate() + .text_size(px(13.0)) + .line_height(px(17.0)) + .child(title), + ), + ) + // Line 3 (always): branch and optional PR badge. Branch remains + // the only shrinking item. + .child( + div() + .w_full() + .flex() + .flex_row() + .items_center() + .gap(px(4.0)) .when_some(branch, |el, branch| { el.child( icon(icons::GIT_BRANCH) @@ -3985,23 +4004,9 @@ impl Shell { .child(branch), ) }) - // Stable invisible spring: keeps the optional spinner and - // PR badge pinned right without changing no-PR paint. + // Stable invisible spring keeps the optional PR badge + // pinned right without changing no-PR paint. .child(div().flex_1().min_w_0()) - // Working rows animate the spinner at the row's - // bottom-right (the status word keeps its dot up top). - // Queued/Failed rows don't: a spinner would fake progress. - .when( - status == zeron_proto::ChatIndicator::Working && !queued && !undelivered, - |el| { - el.child(loaders::mini_gradient_spinner( - format!("chat-working-{id}"), - 2.0, - cx.entity_id(), - cx, - )) - }, - ) .when_some(change_request, |el, summary| { el.child(crate::change_requests::pull_request_badge( format!("chat-pr-{id}").into(), @@ -4092,8 +4097,17 @@ impl Shell { // don't reorder) never animate. let order: Vec<(String, f32)> = keyed.iter().map(|(k, h, _)| (k.clone(), *h)).collect(); if self.sidebar_prev_order != order { + let key_order_changed = sidebar_key_order_changed(&self.sidebar_prev_order, &order); if !self.sidebar_prev_order.is_empty() { - let offsets = resort_offsets(&self.sidebar_prev_order, &order, SIDEBAR_LIST_GAP); + // A disclosure already animates its own body height. Applying + // FLIP offsets when only keyed heights change double-counts + // that movement, leaving gaps and momentary overlaps between + // the first group, following groups, and Archived. + let offsets = if key_order_changed { + resort_offsets(&self.sidebar_prev_order, &order, SIDEBAR_LIST_GAP) + } else { + std::collections::HashMap::new() + }; let prev_keys: std::collections::HashSet<&str> = self .sidebar_prev_order .iter() @@ -4104,7 +4118,7 @@ impl Shell { .filter(|(k, _)| !prev_keys.contains(k.as_str())) .map(|(k, _)| k.clone()) .collect(); - if !offsets.is_empty() || !new_keys.is_empty() { + if key_order_changed && (!offsets.is_empty() || !new_keys.is_empty()) { self.resort_epoch += 1; self.sidebar_resort = offsets; self.sidebar_new_keys = new_keys; @@ -8108,12 +8122,20 @@ mod tests { #[test] fn sidebar_chat_height_tracks_visible_metadata() { - assert_eq!(chat_row_height(false, false, false, false), 47.0); - assert_eq!(chat_row_height(true, false, false, false), 58.0); - assert_eq!(chat_row_height(false, true, false, false), 61.0); - assert_eq!(chat_row_height(false, false, true, false), 63.0); - assert_eq!(chat_row_height(false, false, false, true), 55.0); - assert_eq!(chat_row_height(true, true, true, true), 63.0); + assert_eq!(chat_row_height(false, false), 47.0); + assert_eq!(chat_row_height(true, false), 61.0); + assert_eq!(chat_row_height(false, true), 63.0); + assert_eq!(chat_row_height(true, true), 63.0); + } + + #[test] + fn sidebar_height_change_is_not_a_reorder() { + let open = keys(&[("first-group", 105.0), ("second-group", 240.0)]); + let collapsed = keys(&[("first-group", 40.0), ("second-group", 240.0)]); + assert!(!sidebar_key_order_changed(&open, &collapsed)); + + let reordered = keys(&[("second-group", 240.0), ("first-group", 40.0)]); + assert!(sidebar_key_order_changed(&collapsed, &reordered)); } #[test] diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index bd3d0e1339..138c5b307f 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -1112,18 +1112,7 @@ impl Shell { .sidebar_show_harness .then(|| chat.config.as_ref().map(|c| c.harness)) .flatten(); - let shows_working_spinner = if status == ChatIndicator::Working { - let state = self.state.read(cx); - !state.send_queued(&chat.id, now) && !state.send_undelivered(&chat.id, now) - } else { - false - }; - let height = super::chat_row_height( - harness.is_some(), - branch.is_some(), - change_request.is_some(), - shows_working_spinner, - ); + let height = super::chat_row_height(branch.is_some(), change_request.is_some()); let element = self.render_chat_row( chat.id.clone(), transcript::single_line( From 04d917e12a13c3f064e9363fe6484c47da40863c Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 16:09:08 +0200 Subject: [PATCH 12/17] refine sidebar device and row layout --- crates/ui/src/shell.rs | 105 +++++++++++++++++++--------------- crates/ui/src/shell/spaces.rs | 67 +++++++++++++++++++++- 2 files changed, 124 insertions(+), 48 deletions(-) diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index b1783ebd93..22ebcf7e39 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -520,11 +520,12 @@ fn sidebar_key_order_changed(old: &[(String, f32)], new: &[(String, f32)]) -> bo .any(|((old_key, _), (new_key, _))| old_key != new_key) } -/// Exact active-session row height. Harness identity now lives on the title -/// line and the Working glyph lives in the status corner, so neither adds a -/// third line. Only branch / pull-request metadata can grow the 47px base. +/// Exact active-session row height. Harness identity lives on the title line +/// and the Working glyph lives in the status corner, so neither adds a third +/// line. Compact rows omit the metadata line and its preceding gap entirely; +/// branch / pull-request rows add the exact height of their tallest child. /// Keeping this calculation beside the renderer's metrics prevents disclosure -/// clips when view options alter that metadata line. +/// clips when view options alter the row structure. pub(super) fn chat_row_height(shows_branch: bool, shows_pull_request: bool) -> f32 { let mut metadata_height: f32 = 0.0; if shows_branch { @@ -533,10 +534,18 @@ pub(super) fn chat_row_height(shows_branch: bool, shows_pull_request: bool) -> f if shows_pull_request { metadata_height = metadata_height.max(16.0); } - 47.0 + metadata_height + if metadata_height == 0.0 { + 45.0 + } else { + 47.0 + metadata_height + } } /// Flex gap between sidebar list items. const SIDEBAR_LIST_GAP: f32 = 2.0; +/// Shared harness/title geometry for both active and archived sidebar rows. +/// Identity marks should never shift size or relationship as a chat settles. +const SIDEBAR_HARNESS_ICON_SIZE: f32 = 14.0; +const SIDEBAR_HARNESS_TITLE_GAP: f32 = 10.0; /// Ramp height of the sidebar's scroll-edge fade (the gpui /// [`gpui::EdgeFade`] scope — per-primitive, so text fades per glyph). @@ -3741,6 +3750,7 @@ impl Shell { zeron_proto::ChatIndicator::Idle => None, } }; + let shows_metadata = branch.is_some() || change_request.is_some(); let corner_body: AnyElement = if corner_hovered { div() .flex() @@ -3957,13 +3967,13 @@ impl Shell { .flex() .flex_row() .items_center() - .gap(px(4.0)) + .gap(px(SIDEBAR_HARNESS_TITLE_GAP)) .when_some( harness.map(crate::pickers::harness_brand_icon), |el, (path, tint)| { el.child( icon(path) - .size(px(11.0)) + .size(px(SIDEBAR_HARNESS_ICON_SIZE)) .flex_none() .text_color(tint.unwrap_or(subline).opacity(0.8)), ) @@ -3971,6 +3981,7 @@ impl Shell { ) .child( div() + .flex_1() .min_w_0() .truncate() .text_size(px(13.0)) @@ -3978,44 +3989,46 @@ impl Shell { .child(title), ), ) - // Line 3 (always): branch and optional PR badge. Branch remains - // the only shrinking item. - .child( - div() - .w_full() - .flex() - .flex_row() - .items_center() - .gap(px(4.0)) - .when_some(branch, |el, branch| { - el.child( - icon(icons::GIT_BRANCH) - .size(px(11.0)) - .flex_none() - .text_color(subline), - ) - .child( - div() - .min_w_0() - .truncate() - .text_size(px(11.0)) - .line_height(px(14.0)) - .text_color(subline) - .child(branch), - ) - }) - // Stable invisible spring keeps the optional PR badge - // pinned right without changing no-PR paint. - .child(div().flex_1().min_w_0()) - .when_some(change_request, |el, summary| { - el.child(crate::change_requests::pull_request_badge( - format!("chat-pr-{id}").into(), - summary, - crate::change_requests::ChangeRequestBadgeSurface::Sidebar, - theme, - )) - }), - ) + // Line 3 is structural, not reserved whitespace: compact states + // omit it completely when both Branch and Pull request are hidden. + .when(shows_metadata, |row| { + row.child( + div() + .w_full() + .flex() + .flex_row() + .items_center() + .gap(px(4.0)) + .when_some(branch, |el, branch| { + el.child( + icon(icons::GIT_BRANCH) + .size(px(11.0)) + .flex_none() + .text_color(subline), + ) + .child( + div() + .min_w_0() + .truncate() + .text_size(px(11.0)) + .line_height(px(14.0)) + .text_color(subline) + .child(branch), + ) + }) + // Stable invisible spring keeps the optional PR badge + // pinned right without changing no-PR paint. + .child(div().flex_1().min_w_0()) + .when_some(change_request, |el, summary| { + el.child(crate::change_requests::pull_request_badge( + format!("chat-pr-{id}").into(), + summary, + crate::change_requests::ChangeRequestBadgeSurface::Sidebar, + theme, + )) + }), + ) + }) .into_any_element() } @@ -8122,7 +8135,7 @@ mod tests { #[test] fn sidebar_chat_height_tracks_visible_metadata() { - assert_eq!(chat_row_height(false, false), 47.0); + assert_eq!(chat_row_height(false, false), 45.0); assert_eq!(chat_row_height(true, false), 61.0); assert_eq!(chat_row_height(false, true), 63.0); assert_eq!(chat_row_height(true, true), 63.0); diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 138c5b307f..591848c419 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -112,6 +112,29 @@ const SIDEBAR_DISCLOSURE_SECTION_HEIGHT: f32 = pub(super) const SIDEBAR_DISCLOSURE_TWEEN_GRACE: std::time::Duration = std::time::Duration::from_millis(120); +/// Put this machine's device group first without disturbing the recency-based +/// order of any remote groups. A targeted promotion is more truthful than a +/// full name sort: local context leads, then the user's chosen chat sort wins. +fn promote_local_device_group( + groups: &mut Vec<(Option<(String, String)>, Vec)>, + local_device_id: Option<&str>, +) { + let Some(local_device_id) = local_device_id else { + return; + }; + let Some(index) = groups.iter().position(|(group, _)| { + group + .as_ref() + .is_some_and(|(device_id, _)| device_id == local_device_id) + }) else { + return; + }; + if index > 0 { + let local = groups.remove(index); + groups.insert(0, local); + } +} + fn sidebar_disclosure_header(theme: &Theme, label: SharedString, chevron: AnyElement) -> gpui::Div { div() .flex() @@ -1090,6 +1113,10 @@ impl Shell { groups.push((row.group.clone(), vec![row])); } } + if self.settings.sidebar_organization == SidebarOrganization::ByDevice { + let local_device_id = self.state.read(cx).local_device_id.clone(); + promote_local_device_group(&mut groups, local_device_id.as_deref()); + } let selected = self.state.read(cx).selected_chat.clone(); let mut rendered = Vec::new(); @@ -1358,7 +1385,7 @@ impl Shell { .flex() .flex_row() .items_center() - .gap(px(10.0)) + .gap(px(SIDEBAR_HARNESS_TITLE_GAP)) .px(px(Theme::SPACE_SM)) .rounded(px(6.0)) .cursor_pointer() @@ -1394,7 +1421,7 @@ impl Shell { .when_some(brand, |el, (mark, tint)| { el.child( crate::icons::icon(mark) - .size(px(14.0)) + .size(px(SIDEBAR_HARNESS_ICON_SIZE)) .flex_none() .text_color(if hovered || is_selected { tint.unwrap_or(theme.text_muted) @@ -2965,3 +2992,39 @@ impl Shell { overlays } } + +#[cfg(test)] +mod tests { + use super::promote_local_device_group; + + fn group(device: &str, value: u8) -> (Option<(String, String)>, Vec) { + (Some((device.into(), device.into())), vec![value]) + } + + #[test] + fn current_device_is_promoted_without_resorting_remote_groups() { + let mut groups = vec![ + group("recent-remote", 1), + group("local", 2), + group("older-remote", 3), + ]; + + promote_local_device_group(&mut groups, Some("local")); + + let order: Vec<_> = groups + .iter() + .map(|(group, _)| group.as_ref().unwrap().0.as_str()) + .collect(); + assert_eq!(order, ["local", "recent-remote", "older-remote"]); + } + + #[test] + fn missing_current_device_leaves_group_order_untouched() { + let mut groups = vec![group("first", 1), group("second", 2)]; + let before = groups.clone(); + + promote_local_device_group(&mut groups, Some("not-present")); + + assert_eq!(groups, before); + } +} From b1a811427afe5706dde405a8d134e89ba8dd6c05 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sat, 22 Aug 2026 16:27:49 +0200 Subject: [PATCH 13/17] balance sidebar harness spacing --- crates/ui/src/shell.rs | 24 ++++++++++++++++++------ crates/ui/src/shell/spaces.rs | 4 ++-- 2 files changed, 20 insertions(+), 8 deletions(-) diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index 22ebcf7e39..06ab12b1f9 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -542,10 +542,13 @@ pub(super) fn chat_row_height(shows_branch: bool, shows_pull_request: bool) -> f } /// Flex gap between sidebar list items. const SIDEBAR_LIST_GAP: f32 = 2.0; -/// Shared harness/title geometry for both active and archived sidebar rows. -/// Identity marks should never shift size or relationship as a chat settles. -const SIDEBAR_HARNESS_ICON_SIZE: f32 = 14.0; -const SIDEBAR_HARNESS_TITLE_GAP: f32 = 10.0; +/// Harness/title geometry follows the row hierarchy: active multi-line cards +/// keep identity close on the standard 8px rhythm, while the one-line archived +/// shelf gives its larger mark a little more separation. +const SIDEBAR_ACTIVE_HARNESS_ICON_SIZE: f32 = 13.0; +const SIDEBAR_ACTIVE_HARNESS_TITLE_GAP: f32 = Theme::SPACE_SM; +const SIDEBAR_ARCHIVED_HARNESS_ICON_SIZE: f32 = 14.0; +const SIDEBAR_ARCHIVED_HARNESS_TITLE_GAP: f32 = 10.0; /// Ramp height of the sidebar's scroll-edge fade (the gpui /// [`gpui::EdgeFade`] scope — per-primitive, so text fades per glyph). @@ -3967,13 +3970,13 @@ impl Shell { .flex() .flex_row() .items_center() - .gap(px(SIDEBAR_HARNESS_TITLE_GAP)) + .gap(px(SIDEBAR_ACTIVE_HARNESS_TITLE_GAP)) .when_some( harness.map(crate::pickers::harness_brand_icon), |el, (path, tint)| { el.child( icon(path) - .size(px(SIDEBAR_HARNESS_ICON_SIZE)) + .size(px(SIDEBAR_ACTIVE_HARNESS_ICON_SIZE)) .flex_none() .text_color(tint.unwrap_or(subline).opacity(0.8)), ) @@ -8141,6 +8144,15 @@ mod tests { assert_eq!(chat_row_height(true, true), 63.0); } + #[test] + fn sidebar_harness_geometry_reflects_row_hierarchy() { + assert_eq!(SIDEBAR_ACTIVE_HARNESS_TITLE_GAP, Theme::SPACE_SM); + assert!( + SIDEBAR_ACTIVE_HARNESS_TITLE_GAP < SIDEBAR_ARCHIVED_HARNESS_TITLE_GAP + ); + assert!(SIDEBAR_ACTIVE_HARNESS_ICON_SIZE < SIDEBAR_ARCHIVED_HARNESS_ICON_SIZE); + } + #[test] fn sidebar_height_change_is_not_a_reorder() { let open = keys(&[("first-group", 105.0), ("second-group", 240.0)]); diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 591848c419..3dfdccf6cc 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -1385,7 +1385,7 @@ impl Shell { .flex() .flex_row() .items_center() - .gap(px(SIDEBAR_HARNESS_TITLE_GAP)) + .gap(px(SIDEBAR_ARCHIVED_HARNESS_TITLE_GAP)) .px(px(Theme::SPACE_SM)) .rounded(px(6.0)) .cursor_pointer() @@ -1421,7 +1421,7 @@ impl Shell { .when_some(brand, |el, (mark, tint)| { el.child( crate::icons::icon(mark) - .size(px(SIDEBAR_HARNESS_ICON_SIZE)) + .size(px(SIDEBAR_ARCHIVED_HARNESS_ICON_SIZE)) .flex_none() .text_color(if hovered || is_selected { tint.unwrap_or(theme.text_muted) From 6da4e9f9e7346b3bf20b334a27310793a3b68f86 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sun, 23 Aug 2026 19:34:42 +0200 Subject: [PATCH 14/17] fix: address sidebar view options review --- crates/engine/src/doc_host.rs | 111 +++++++++++++++++++--- crates/engine/src/sessions.rs | 24 ++++- crates/ui/src/change_requests.rs | 130 +++++++++++--------------- crates/ui/src/links.rs | 51 ++++++++-- crates/ui/src/shell.rs | 3 + crates/ui/src/shell/spaces.rs | 97 +++++++++++++++---- docs/research/sidebar-view-options.md | 4 +- 7 files changed, 304 insertions(+), 116 deletions(-) diff --git a/crates/engine/src/doc_host.rs b/crates/engine/src/doc_host.rs index 4a29d1f2be..9df08dce35 100644 --- a/crates/engine/src/doc_host.rs +++ b/crates/engine/src/doc_host.rs @@ -3136,11 +3136,6 @@ impl DocHost { tracing::warn!(chat = %chat_id, error = %err, "worktree branch stamp failed"); } } - if let Some(context) = self.capture_source_context(&request.cwd).await - && let Err(err) = ws.set_chat_source_context(chat_id, &context) - { - tracing::warn!(chat = %chat_id, error = %err, "conversation source stamp failed"); - } } let harness = self.harness_for_request(chat_id, &request); // A row with no config renders no harness glyph (and every @@ -3175,9 +3170,14 @@ impl DocHost { ) { tracing::warn!(chat = %chat_id, error = %err, "canonical user-message write failed"); } - sessions - .dispatch(chat_id, harness, request, Some(message_id.clone())) - .await?; + self.dispatch_with_source_context( + sessions, + chat_id, + harness, + request, + Some(message_id.clone()), + ) + .await?; Ok((SessionCommandStatus::Applied, None)) } SessionCommandPayload::Steer { prompt, message_id } => { @@ -3216,9 +3216,14 @@ impl DocHost { // ride the prompt text. request.attachments = Vec::new(); let harness = self.harness_for_request(chat_id, &request); - sessions - .dispatch(chat_id, harness, request, message_id.clone()) - .await?; + self.dispatch_with_source_context( + sessions, + chat_id, + harness, + request, + message_id.clone(), + ) + .await?; Ok(( SessionCommandStatus::Applied, Some("queued as new turn".into()), @@ -3290,7 +3295,8 @@ impl DocHost { "orphaned input resolve failed"); } let harness = self.harness_for_request(chat_id, &request); - sessions.dispatch(chat_id, harness, request, None).await?; + self.dispatch_with_source_context(sessions, chat_id, harness, request, None) + .await?; Ok(( SessionCommandStatus::Applied, Some("answered as new turn".into()), @@ -3315,6 +3321,30 @@ impl DocHost { }) } + /// Every fresh harness dispatch crosses this boundary, including + /// steer/input fallbacks and crash recovery. Capture immediately before + /// dispatch so the conversation records the checkout the harness will + /// actually observe, rather than whichever checkout state was current on + /// an earlier turn. + pub(crate) async fn dispatch_with_source_context( + &self, + sessions: &SessionsEngine, + chat_id: &str, + harness: HarnessId, + request: zeron_proto::RunRequest, + message_id: Option, + ) -> Result { + if let Some(workspace) = self.workspace() + && let Some(context) = self.capture_source_context(&request.cwd).await + && let Err(err) = workspace.set_chat_source_context(chat_id, &context) + { + tracing::warn!(chat = %chat_id, error = %err, "conversation source stamp failed"); + } + sessions + .dispatch(chat_id, harness, request, message_id) + .await + } + /// Create (or reuse) the isolated worktree a Run's [`zeron_proto::WorktreeSpec`] /// asks for, returning the resolved cwd plus the fresh worktree when one was /// actually created. Reuse guard: a chat whose row already points inside a @@ -3550,6 +3580,63 @@ mod transfer_progress_tests { } } +#[cfg(test)] +mod source_context_tests { + use super::{DocHost, DocHostConfig}; + use std::process::Command; + use std::sync::Arc; + + fn git(repo: &std::path::Path, args: &[&str]) { + let status = Command::new("git") + .args(args) + .current_dir(repo) + .status() + .expect("git runs"); + assert!(status.success(), "git {args:?} failed"); + } + + #[tokio::test] + async fn capture_source_context_reads_the_dispatch_checkout() { + let dir = tempfile::tempdir().expect("tempdir"); + let repo = dir.path().join("repo"); + std::fs::create_dir(&repo).unwrap(); + git(&repo, &["init", "-b", "feature/captured"]); + git(&repo, &["config", "user.name", "Zeron Test"]); + git(&repo, &["config", "user.email", "zeron@example.com"]); + std::fs::write(repo.join("README.md"), "capture\n").unwrap(); + git(&repo, &["add", "README.md"]); + git(&repo, &["commit", "-m", "capture"]); + + let store = + Arc::new(zeron_sync::DocsStore::open(dir.path().join("docs")).expect("store opens")); + let host = DocHost::new( + store, + DocHostConfig { + device_id: "device-a".into(), + default_harness: zeron_proto::HarnessId::Mock, + edge: None, + }, + ); + host.set_repos(crate::repos::Repos::new( + &dir.path().join("data"), + "device-a", + )); + + let context = host + .capture_source_context(repo.to_str().unwrap()) + .await + .expect("source context"); + assert_eq!(context.branch, "feature/captured"); + assert_eq!(context.cwd, repo.to_string_lossy()); + assert_eq!( + context.repo_root, + repo.canonicalize().unwrap().to_string_lossy() + ); + assert!(context.head_sha.is_some()); + assert!(!context.checkout_id.is_empty()); + } +} + #[cfg(test)] mod degrade_grace_tests { use super::{DEGRADE_GRACE, DegradeGrace, GraceKey}; diff --git a/crates/engine/src/sessions.rs b/crates/engine/src/sessions.rs index 027ce14eb8..fd20023287 100644 --- a/crates/engine/src/sessions.rs +++ b/crates/engine/src/sessions.rs @@ -733,8 +733,14 @@ impl SessionsEngine { request.resume = None; // dispatch re-injects the remembered session request.attachments = Vec::new(); let harness_id = host.harness_for_request(&chat_id, &request); - match sessions - .dispatch(&chat_id, harness_id, request, Some(user_id)) + match host + .dispatch_with_source_context( + &sessions, + &chat_id, + harness_id, + request, + Some(user_id), + ) .await { Ok(_) => { @@ -2130,8 +2136,18 @@ async fn drive_run( request.resume = None; request.attachments = Vec::new(); tracing::info!(chat = %chat, "re-dispatching steer orphaned by a dying run"); - if let Err(err) = engine - .dispatch(&chat, harness_id, request, Some(steer.message_id.clone())) + let Some(host) = engine.inner.doc_host() else { + tracing::warn!(chat = %chat, "orphaned steer lost: doc host unavailable"); + break; + }; + if let Err(err) = host + .dispatch_with_source_context( + &engine, + &chat, + harness_id, + request, + Some(steer.message_id.clone()), + ) .await { tracing::warn!(chat = %chat, error = %err, "orphaned steer re-dispatch failed"); diff --git a/crates/ui/src/change_requests.rs b/crates/ui/src/change_requests.rs index 5bf240e11c..9baa119b09 100644 --- a/crates/ui/src/change_requests.rs +++ b/crates/ui/src/change_requests.rs @@ -237,7 +237,7 @@ impl ChangeRequestClientState { /// Active, fully identified checkouts that need host-side PR resolution. pub(crate) fn desired_watch_targets( chats: &[Chat], - spaces: &[Space], + _spaces: &[Space], is_unsupported: impl Fn(&str) -> bool, ) -> HashSet { chats @@ -245,15 +245,12 @@ pub(crate) fn desired_watch_targets( .filter(|chat| !chat.archived) .filter(|chat| !is_unsupported(&chat.device_id)) .filter_map(|chat| { - let (cwd, branch, checkout_id) = if let Some(source) = &chat.source_context { - ( - source.repo_root.as_str(), - source.branch.as_str(), - Some(source.checkout_id.clone()), - ) - } else { - legacy_conversation_source(chat, spaces)? - }; + let source = chat.source_context.as_ref()?; + let (cwd, branch, checkout_id) = ( + source.repo_root.as_str(), + source.branch.as_str(), + Some(source.checkout_id.clone()), + ); if branch.trim().is_empty() { return None; } @@ -288,9 +285,8 @@ pub(crate) fn watch_params( /// Resolve a snapshot for a row without trusting the cache key alone. /// -/// Canonical checkout identity wins when the chat has one. Older rows without -/// it fall back to device + effective cwd. Branch equality is mandatory in -/// both cases so a branch switch hides the stale PR immediately. +/// Only conversation-owned source context is trusted. Legacy scalar metadata +/// cannot prove that a worktree has not switched branches since it was written. pub fn change_request_for_chat<'a>( chat: &Chat, spaces: &[Space], @@ -300,11 +296,8 @@ pub fn change_request_for_chat<'a>( if branch.is_empty() { return None; } - let cwd = if let Some(source) = &chat.source_context { - source.repo_root.as_str() - } else { - legacy_conversation_source(chat, spaces)?.0 - }; + let source = chat.source_context.as_ref()?; + let cwd = source.repo_root.as_str(); let checkout_id = chat .source_context .as_ref() @@ -325,51 +318,15 @@ pub fn change_request_for_chat<'a>( } /// Branch metadata safe to render for this conversation. Pre-source-context -/// rows that point at their project's shared root are intentionally rejected: -/// old builds copied that checkout's current branch onto every chat. -pub(crate) fn conversation_branch<'a>(chat: &'a Chat, spaces: &'a [Space]) -> Option<&'a str> { +/// rows are intentionally rejected: their scalar branch may describe an old +/// state of either a shared checkout or a worktree. +pub(crate) fn conversation_branch<'a>(chat: &'a Chat, _spaces: &'a [Space]) -> Option<&'a str> { chat.source_context .as_ref() .map(|source| source.branch.as_str()) - .or_else(|| legacy_conversation_source(chat, spaces).map(|(_, branch, _)| branch)) .filter(|branch| !branch.trim().is_empty()) } -fn legacy_conversation_source<'a>( - chat: &'a Chat, - spaces: &'a [Space], -) -> Option<(&'a str, &'a str, Option)> { - let cwd = effective_chat_cwd(chat, spaces)?; - let branch = chat.branch.as_deref()?.trim(); - if branch.is_empty() { - return None; - } - let shared_root = chat.space_id.as_deref().and_then(|space_id| { - spaces - .iter() - .find(|space| space.id == space_id && space.device_id == chat.device_id) - .map(|space| space.path.as_str()) - }); - if shared_root.is_some_and(|root| root == cwd) { - return None; - } - Some((cwd, branch, chat.checkout_id.clone())) -} - -fn effective_chat_cwd<'a>(chat: &'a Chat, spaces: &'a [Space]) -> Option<&'a str> { - chat.cwd - .as_deref() - .filter(|cwd| !cwd.trim().is_empty()) - .or_else(|| { - let space_id = chat.space_id.as_deref()?; - spaces - .iter() - .find(|space| space.id == space_id && space.device_id == chat.device_id) - .map(|space| space.path.as_str()) - .filter(|path| !path.trim().is_empty()) - }) -} - #[cfg(test)] mod tests { use chrono::{TimeZone as _, Utc}; @@ -462,8 +419,11 @@ mod tests { } #[test] - fn local_chat_finds_local_snapshot() { - let chat = chat("chat", "local", Some("/repo"), Some("checkout")); + fn source_context_chat_finds_local_snapshot() { + let chat = with_source( + chat("chat", "local", Some("/repo"), Some("checkout")), + "feature/pr", + ); let status = snapshot("local", "/repo", "checkout"); assert_eq!( change_request_for_chat(&chat, &[], [&status]).map(|pr| pr.number), @@ -473,26 +433,32 @@ mod tests { #[test] fn remote_chat_requires_the_same_device() { - let chat = chat("chat", "remote", Some("/repo"), Some("checkout")); + let chat = with_source( + chat("chat", "remote", Some("/repo"), Some("checkout")), + "feature/pr", + ); let status = snapshot("local", "/repo", "checkout"); assert!(change_request_for_chat(&chat, &[], [&status]).is_none()); } #[test] fn mismatched_checkout_rejects_cwd_match() { - let chat = chat("chat", "local", Some("/repo"), Some("new-checkout")); + let mut chat = with_source( + chat("chat", "local", Some("/repo"), Some("new-checkout")), + "feature/pr", + ); + chat.source_context.as_mut().unwrap().checkout_id = "new-checkout".into(); let status = snapshot("local", "/repo", "old-checkout"); assert!(change_request_for_chat(&chat, &[], [&status]).is_none()); } #[test] - fn legacy_row_falls_back_to_cwd() { + fn source_less_worktree_hides_stale_legacy_metadata() { let chat = chat("chat", "local", Some("/repo"), None); let status = snapshot("local", "/repo", "checkout"); - assert_eq!( - change_request_for_chat(&chat, &[], [&status]).map(|pr| pr.number), - Some(90) - ); + assert!(change_request_for_chat(&chat, &[], [&status]).is_none()); + assert!(conversation_branch(&chat, &[]).is_none()); + assert!(desired_watch_targets(&[chat], &[], |_| false).is_empty()); } #[test] @@ -505,16 +471,25 @@ mod tests { #[test] fn different_branch_hides_snapshot() { - let mut chat = chat("chat", "local", Some("/repo"), Some("checkout")); - chat.branch = Some("feature/other".into()); + let mut chat = with_source( + chat("chat", "local", Some("/repo"), Some("checkout")), + "feature/other", + ); + chat.branch = Some("feature/pr".into()); let status = snapshot("local", "/repo", "checkout"); assert!(change_request_for_chat(&chat, &[], [&status]).is_none()); } #[test] fn shared_chats_deduplicate_and_last_archive_removes_target() { - let first = chat("one", "local", Some("/repo"), Some("checkout")); - let mut second = chat("two", "local", Some("/repo"), Some("checkout")); + let first = with_source( + chat("one", "local", Some("/repo"), Some("checkout")), + "feature/pr", + ); + let mut second = with_source( + chat("two", "local", Some("/repo"), Some("checkout")), + "feature/pr", + ); let targets = desired_watch_targets(&[first.clone(), second.clone()], &[], |_| false); assert_eq!(targets.len(), 1); @@ -529,7 +504,10 @@ mod tests { #[test] fn unsupported_device_has_no_targets_or_visible_snapshot() { - let chat = chat("chat", "old-engine", Some("/repo"), Some("checkout")); + let chat = with_source( + chat("chat", "old-engine", Some("/repo"), Some("checkout")), + "feature/pr", + ); let mut state = ChangeRequestClientState::default(); state.store( ChangeRequestWatchKey { @@ -550,7 +528,10 @@ mod tests { #[test] fn host_upgrade_reenables_a_previously_unsupported_device() { - let chat = chat("chat", "host", Some("/repo"), Some("checkout")); + let chat = with_source( + chat("chat", "host", Some("/repo"), Some("checkout")), + "feature/pr", + ); let mut state = ChangeRequestClientState::default(); state.mark_unsupported("host".into(), Some("0.2.2".into())); @@ -566,7 +547,10 @@ mod tests { #[test] fn successful_none_clears_a_previous_pr() { - let chat = chat("chat", "local", Some("/repo"), Some("checkout")); + let chat = with_source( + chat("chat", "local", Some("/repo"), Some("checkout")), + "feature/pr", + ); let key = ChangeRequestWatchKey { device_id: "local".into(), cwd: "/repo".into(), diff --git a/crates/ui/src/links.rs b/crates/ui/src/links.rs index 748b9bf6e4..63d599c3bf 100644 --- a/crates/ui/src/links.rs +++ b/crates/ui/src/links.rs @@ -23,18 +23,18 @@ pub fn workspace_locator( local_device_id: Option<&str>, ) -> Option { let scope = scope?; - let identity = match (scope, auth) { - ( - WorkspaceScope::Synced | WorkspaceScope::Development, - Some(AuthState::SignedIn { user, org_id }), - ) => { + let identity = match scope { + WorkspaceScope::Synced | WorkspaceScope::Development => { + let Some(AuthState::SignedIn { user, org_id }) = auth else { + return None; + }; format!( "user:{}:org:{}", user.id, org_id.as_deref().unwrap_or("personal") ) } - _ => format!("device:{}", local_device_id?), + WorkspaceScope::Local => format!("device:{}", local_device_id?), }; let mut hash = Sha256::new(); hash.update(format!("{scope:?}\0{identity}")); @@ -177,6 +177,45 @@ mod tests { assert_ne!(first, second); } + #[test] + fn synced_workspace_locator_waits_for_signed_in_identity() { + let scope = Some(WorkspaceScope::Synced); + assert_eq!(workspace_locator(scope, None, Some("device-a")), None); + assert_eq!( + workspace_locator(scope, Some(&AuthState::SignedOut), Some("device-a")), + None + ); + assert_eq!( + workspace_locator( + scope, + Some(&AuthState::NeedsOrganization { + user: zeron_proto::UserProfile { + id: "user-a".into(), + email: "user@example.com".into(), + name: None, + }, + }), + Some("device-a"), + ), + None + ); + assert!( + workspace_locator( + scope, + Some(&AuthState::SignedIn { + user: zeron_proto::UserProfile { + id: "user-a".into(), + email: "user@example.com".into(), + name: None, + }, + org_id: Some("org-a".into()), + }), + None, + ) + .is_some() + ); + } + #[test] fn codex_link_is_exact_and_unverified_harnesses_are_omitted() { assert_eq!( diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index 06ab12b1f9..9fb2fd9493 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -1002,6 +1002,8 @@ pub struct Shell { spaces_menu: popover::Popup, /// Persisted organization/sort/metadata controls beside the project filter. sidebar_view_menu: popover::Popup, + /// Natural-tab-order focus target for the icon-only view-options button. + sidebar_view_trigger_focus: gpui::FocusHandle, /// Chat id whose STATUS CORNER is under the pointer — just that corner /// swaps to the archive button (t3code's settle-on-hover); hovering the /// row body leaves the status readable. @@ -1269,6 +1271,7 @@ impl Shell { add_space: None, spaces_menu: popover::Popup::default(), sidebar_view_menu: popover::Popup::default(), + sidebar_view_trigger_focus: cx.focus_handle().tab_stop(true), chat_status_hover: None, sidebar_scroll: gpui::ScrollHandle::new(), space_boot_applied: false, diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index 3dfdccf6cc..f0aed8e142 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -22,6 +22,21 @@ struct ActiveChatRow { group: Option<(String, String)>, } +fn compare_sidebar_chats( + sort: SidebarSort, + left: &zeron_proto::Chat, + right: &zeron_proto::Chat, +) -> std::cmp::Ordering { + let primary = match sort { + SidebarSort::Created => right.created_at.cmp(&left.created_at), + SidebarSort::LastUpdated => right + .last_message_at + .unwrap_or(right.created_at) + .cmp(&left.last_message_at.unwrap_or(left.created_at)), + }; + primary.then_with(|| left.id.cmp(&right.id)) +} + /// The space-filter dropdown, `Some` while open. The same searchable-menu /// recipe as the composer's ref picker: filter input on top /// (`PaletteSearch` context so ↑↓/⏎ bubble to the card), ranked substring @@ -817,14 +832,22 @@ impl Shell { }; let view_open = self.sidebar_view_menu.is_open(); + let view_focus = self.sidebar_view_trigger_focus.clone(); let view_trigger = div() .id("sidebar-view-options") + .role(gpui::Role::Button) + .aria_label("Sidebar view options") + .aria_expanded(view_open) + .track_focus(&view_focus) .size(px(29.0)) .flex_none() .flex() .items_center() .justify_center() .rounded(px(8.0)) + .border_1() + .border_color(theme.border.opacity(0.0)) + .in_focus(|el| el.border_color(theme.border_strong)) .cursor_pointer() .text_color(theme.text_muted) .bg(if view_open { @@ -844,6 +867,21 @@ impl Shell { this.open_sidebar_view_menu(window, cx); } })) + .on_key_down(cx.listener(|this, event: &gpui::KeyDownEvent, window, cx| { + if matches!( + event.keystroke.key.to_ascii_lowercase().as_str(), + "enter" | "space" | "arrowdown" + ) { + cx.stop_propagation(); + if this.sidebar_view_menu.is_open() + && !event.keystroke.key.eq_ignore_ascii_case("arrowdown") + { + this.close_sidebar_view_menu(cx); + } else if !this.sidebar_view_menu.is_open() { + this.open_sidebar_view_menu(window, cx); + } + } + })) .tooltip(|_, cx| cx.new(|_| SidebarViewOptionsTooltip).into()) .tooltip_show_delay(std::time::Duration::from_millis(350)) .child( @@ -1040,16 +1078,9 @@ impl Shell { }) .map(|(status, chat)| (status, chat.clone())) .collect(); - match self.settings.sidebar_sort { - SidebarSort::Created => { - chats.sort_by(|a, b| b.1.created_at.cmp(&a.1.created_at)); - } - SidebarSort::LastUpdated => chats.sort_by(|a, b| { - b.1.last_message_at - .unwrap_or(b.1.created_at) - .cmp(&a.1.last_message_at.unwrap_or(a.1.created_at)) - }), - } + chats.sort_by(|left, right| { + compare_sidebar_chats(self.settings.sidebar_sort, &left.1, &right.1) + }); chats .into_iter() .map(|(status, chat)| { @@ -1259,14 +1290,9 @@ impl Shell { .cloned() .collect() }; - match self.settings.sidebar_sort { - SidebarSort::Created => rows.sort_by(|a, b| b.created_at.cmp(&a.created_at)), - SidebarSort::LastUpdated => rows.sort_by(|a, b| { - b.last_message_at - .unwrap_or(b.created_at) - .cmp(&a.last_message_at.unwrap_or(a.created_at)) - }), - } + rows.sort_by(|left, right| { + compare_sidebar_chats(self.settings.sidebar_sort, left, right) + }); if rows.is_empty() { return None; } @@ -2995,12 +3021,45 @@ impl Shell { #[cfg(test)] mod tests { - use super::promote_local_device_group; + use chrono::{TimeZone as _, Utc}; + + use super::{compare_sidebar_chats, promote_local_device_group}; + use crate::settings::SidebarSort; fn group(device: &str, value: u8) -> (Option<(String, String)>, Vec) { (Some((device.into(), device.into())), vec![value]) } + fn chat(id: &str) -> zeron_proto::Chat { + zeron_proto::Chat { + id: id.into(), + device_id: "device".into(), + title: None, + archived: false, + cwd: None, + branch: None, + checkout_id: None, + source_context: None, + config: None, + last_message_preview: None, + last_message_at: Some(Utc.timestamp_opt(10, 0).unwrap()), + created_at: Utc.timestamp_opt(5, 0).unwrap(), + harness_session_id: None, + harness_session_cwd: None, + space_id: None, + last_seen_at: None, + room_gen: None, + } + } + + #[test] + fn equal_sidebar_timestamps_sort_by_stable_chat_id() { + let alpha = chat("alpha"); + let beta = chat("beta"); + assert!(compare_sidebar_chats(SidebarSort::Created, &alpha, &beta).is_lt()); + assert!(compare_sidebar_chats(SidebarSort::LastUpdated, &alpha, &beta).is_lt()); + } + #[test] fn current_device_is_promoted_without_resorting_remote_groups() { let mut groups = vec![ diff --git a/docs/research/sidebar-view-options.md b/docs/research/sidebar-view-options.md index 2b5318ffc5..a1922f7a59 100644 --- a/docs/research/sidebar-view-options.md +++ b/docs/research/sidebar-view-options.md @@ -1,8 +1,8 @@ # Sidebar view options and conversation links Status: implemented and verified locally -Branch: `wip/sidebar-view-options` -Base: `origin/main` at `3fc7bb0` (`v0.2.20`) +Branch: `wip/sidebar-view-options` +Base: `origin/main` at `92b5732` (`ci: add permanent internal TestFlight workflow (#213)`) Research date: 2026-08-22 ## Goal From da659ff67ffdc82964f9a6dcd80fafeffcb6882c Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sun, 23 Aug 2026 19:47:58 +0200 Subject: [PATCH 15/17] chore: format sidebar contribution --- crates/doc/src/workspace.rs | 12 +-- crates/engine/src/change_requests.rs | 6 +- crates/engine/src/doc_host.rs | 7 +- crates/engine/src/repos.rs | 5 +- crates/engine/src/sessions.rs | 3 +- crates/ui/src/lib.rs | 2 +- crates/ui/src/shell.rs | 136 ++++++++++++++------------- crates/ui/src/shell/spaces.rs | 32 +++---- 8 files changed, 97 insertions(+), 106 deletions(-) diff --git a/crates/doc/src/workspace.rs b/crates/doc/src/workspace.rs index f668c8b18c..97ae7c6743 100644 --- a/crates/doc/src/workspace.rs +++ b/crates/doc/src/workspace.rs @@ -245,9 +245,10 @@ impl WorkspaceDoc { set_opt_str(&row, "branch", chat.branch.as_deref())?; set_opt_str(&row, "checkoutId", chat.checkout_id.as_deref())?; match &chat.source_context { - Some(context) => { - row.insert("sourceContext", LoroValue::from(serde_json::to_value(context)?))? - } + Some(context) => row.insert( + "sourceContext", + LoroValue::from(serde_json::to_value(context)?), + )?, None => row.delete("sourceContext")?, } match &chat.config { @@ -871,10 +872,7 @@ mod tests { head_sha: Some("abc123".into()), observed_at: ts(8_000), }; - assert!( - ws.set_chat_source_context("chat-1", &context) - .unwrap() - ); + assert!(ws.set_chat_source_context("chat-1", &context).unwrap()); let row = ws.chat("chat-1").unwrap().expect("row exists"); assert_eq!(row.source_context, Some(context)); assert_eq!(row.branch.as_deref(), Some("feature/sidebar")); diff --git a/crates/engine/src/change_requests.rs b/crates/engine/src/change_requests.rs index c2012386b1..0079c729a4 100644 --- a/crates/engine/src/change_requests.rs +++ b/crates/engine/src/change_requests.rs @@ -135,11 +135,7 @@ impl CheckoutChangeRequests { .checkout_identity(cwd) .await .map_err(|_| ChangeRequestError::RepositoryUnavailable)?; - Ok(self.watch_checkout_for_branch( - cwd.to_owned(), - identity, - branch.map(str::to_owned), - )) + Ok(self.watch_checkout_for_branch(cwd.to_owned(), identity, branch.map(str::to_owned))) } #[cfg(test)] diff --git a/crates/engine/src/doc_host.rs b/crates/engine/src/doc_host.rs index 9df08dce35..f09fc32854 100644 --- a/crates/engine/src/doc_host.rs +++ b/crates/engine/src/doc_host.rs @@ -2026,11 +2026,8 @@ impl DocHost { .as_ref() .and_then(|w| w.sync_status()) .is_some_and(|s| s.connected); - let path_offline = grace.degraded( - GraceKey::OsPath, - zeron_sync::wake::path_is_offline(), - now, - ); + let path_offline = + grace.degraded(GraceKey::OsPath, zeron_sync::wake::path_is_offline(), now); let registry_down = grace.degraded(GraceKey::Registry, !registry_connected, now); let (state, retry_at_ms, last_failure) = if path_offline { ( diff --git a/crates/engine/src/repos.rs b/crates/engine/src/repos.rs index a91cc49777..1ad1f5bbf3 100644 --- a/crates/engine/src/repos.rs +++ b/crates/engine/src/repos.rs @@ -224,7 +224,10 @@ impl Repos { /// Commit checked out at `path`, or `None` for a repository without an /// initial commit. pub async fn head_sha(&self, path: &Path) -> Result, EngineError> { - match self.git(&["rev-parse", "--verify", "HEAD^{commit}"], Some(path)).await { + match self + .git(&["rev-parse", "--verify", "HEAD^{commit}"], Some(path)) + .await + { Ok(sha) if !sha.is_empty() => Ok(Some(sha)), Ok(_) => Ok(None), Err(_) if self.is_repo(path).await => Ok(None), diff --git a/crates/engine/src/sessions.rs b/crates/engine/src/sessions.rs index fd20023287..4501640837 100644 --- a/crates/engine/src/sessions.rs +++ b/crates/engine/src/sessions.rs @@ -1409,8 +1409,7 @@ async fn drive_run( // the freeze must not mint a new doc entry or wedge the transcript back // into Streaming. Only a steer (UserMessage) legitimately REOPENS a // settled subagent: it announces more work is coming. - let mut settled_subagents: std::collections::HashSet = - std::collections::HashSet::new(); + let mut settled_subagents: std::collections::HashSet = std::collections::HashSet::new(); // Live subagent sinks, parent tool-use id → transcript doc state. let mut subagents: std::collections::HashMap = std::collections::HashMap::new(); diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 8882f77913..aefce3ef41 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -24,8 +24,8 @@ pub mod edge_fade; pub mod frost; pub mod history; pub mod icons; -pub mod loaders; pub mod links; +pub mod loaders; pub mod markdown; pub mod motion; pub mod notify; diff --git a/crates/ui/src/shell.rs b/crates/ui/src/shell.rs index 9fb2fd9493..7336f196f6 100644 --- a/crates/ui/src/shell.rs +++ b/crates/ui/src/shell.rs @@ -16,9 +16,9 @@ use std::time::Duration; use chrono::Utc; use gpui::{ - AnyElement, App, ClipboardItem, Context, Empty, Entity, Focusable as _, IntoElement, KeyBinding, - Keystroke, MouseButton, MouseDownEvent, MouseUpEvent, Pixels, Point, Render, SharedString, - Subscription, Task, Window, WindowControlArea, actions, div, prelude::*, px, + AnyElement, App, ClipboardItem, Context, Empty, Entity, Focusable as _, IntoElement, + KeyBinding, Keystroke, MouseButton, MouseDownEvent, MouseUpEvent, Pixels, Point, Render, + SharedString, Subscription, Task, Window, WindowControlArea, actions, div, prelude::*, px, }; use gpui_tokio::Tokio; @@ -108,8 +108,7 @@ impl SidebarDisclosureMotion { } fn animating(self) -> bool { - self.started.elapsed() - < motion::COLLAPSE.total() + spaces::SIDEBAR_DISCLOSURE_TWEEN_GRACE + self.started.elapsed() < motion::COLLAPSE.total() + spaces::SIDEBAR_DISCLOSURE_TWEEN_GRACE } } @@ -1392,8 +1391,7 @@ impl Shell { self.debug_upload = None; if let Some((pct, img_path)) = spec.split_once(':') && let Ok(pct) = pct.parse::() - && let Ok(att) = - crate::attachments::stage_file(std::path::Path::new(img_path)) + && let Ok(att) = crate::attachments::stage_file(std::path::Path::new(img_path)) { let pending_path = format!("pending/{}/{}", att.id, att.name); let device_ids: Vec = { @@ -5048,57 +5046,61 @@ impl Shell { .flex_col(); let menu = match menu_state.page { ChatMenuPage::Root => menu - .child( - popover::menu_row(&theme, false, format!("chat-menu-rename-{chat_id}")) - .id("chat-menu-rename") - .on_click(cx.listener(move |this, _, _, cx| { - this.open_rename_chat(rename_id.clone(), cx) - })) - .child(icon(icons::PEN).size(px(16.0)).text_color(theme.text_muted)) - .child(SharedString::from("Rename…")), - ) - .child( - popover::menu_row(&theme, false, format!("chat-menu-archive-{chat_id}")) - .id("chat-menu-archive") - .on_click(cx.listener(move |this, _, _, cx| { - this.archive_chat(archive_id.clone(), cx) - })) - .child( - icon(icons::ARCHIVE_MINIMALISTIC) - .size(px(16.0)) - .text_color(theme.text_muted), - ) - .child(SharedString::from("Archive")), - ) - .child( - popover::menu_row(&theme, false, format!("chat-menu-copy-{chat_id}")) - .id("chat-menu-copy") - .on_click(cx.listener(|this, _, _, cx| this.open_chat_copy_menu(cx))) - .child(icon(icons::COPY).size(px(16.0)).text_color(theme.text_muted)) - .child(div().flex_1().child(SharedString::from("Copy"))) - .child( - icon(icons::ALT_ARROW_RIGHT) - .size(px(14.0)) - .text_color(theme.text_muted.opacity(0.7)), - ), - ) - .child(popover::menu_separator()) - .child( - popover::menu_row(&theme, false, format!("chat-menu-delete-{chat_id}")) - .id("chat-menu-delete") - .text_color(theme.danger) - .on_click(cx.listener(move |this, _, _, cx| { - this.close_chat_menu(cx); - this.delete_confirm = Some(delete_id.clone()); - cx.notify(); - })) - .child( - icon(icons::TRASH_BIN_MINIMALISTIC) - .size(px(16.0)) - .text_color(theme.danger), - ) - .child(SharedString::from("Delete…")), - ), + .child( + popover::menu_row(&theme, false, format!("chat-menu-rename-{chat_id}")) + .id("chat-menu-rename") + .on_click(cx.listener(move |this, _, _, cx| { + this.open_rename_chat(rename_id.clone(), cx) + })) + .child(icon(icons::PEN).size(px(16.0)).text_color(theme.text_muted)) + .child(SharedString::from("Rename…")), + ) + .child( + popover::menu_row(&theme, false, format!("chat-menu-archive-{chat_id}")) + .id("chat-menu-archive") + .on_click(cx.listener(move |this, _, _, cx| { + this.archive_chat(archive_id.clone(), cx) + })) + .child( + icon(icons::ARCHIVE_MINIMALISTIC) + .size(px(16.0)) + .text_color(theme.text_muted), + ) + .child(SharedString::from("Archive")), + ) + .child( + popover::menu_row(&theme, false, format!("chat-menu-copy-{chat_id}")) + .id("chat-menu-copy") + .on_click(cx.listener(|this, _, _, cx| this.open_chat_copy_menu(cx))) + .child( + icon(icons::COPY) + .size(px(16.0)) + .text_color(theme.text_muted), + ) + .child(div().flex_1().child(SharedString::from("Copy"))) + .child( + icon(icons::ALT_ARROW_RIGHT) + .size(px(14.0)) + .text_color(theme.text_muted.opacity(0.7)), + ), + ) + .child(popover::menu_separator()) + .child( + popover::menu_row(&theme, false, format!("chat-menu-delete-{chat_id}")) + .id("chat-menu-delete") + .text_color(theme.danger) + .on_click(cx.listener(move |this, _, _, cx| { + this.close_chat_menu(cx); + this.delete_confirm = Some(delete_id.clone()); + cx.notify(); + })) + .child( + icon(icons::TRASH_BIN_MINIMALISTIC) + .size(px(16.0)) + .text_color(theme.danger), + ) + .child(SharedString::from("Delete…")), + ), ChatMenuPage::Copy => { let chat = self .state @@ -5140,7 +5142,11 @@ impl Shell { .on_click(cx.listener(move |this, _, _, cx| { this.copy_zeron_conversation_link(&zeron_id, cx) })) - .child(icon(icons::COPY).size(px(16.0)).text_color(theme.text_muted)) + .child( + icon(icons::COPY) + .size(px(16.0)) + .text_color(theme.text_muted), + ) .child(SharedString::from("Zeron conversation link")), ) .when_some(harness_link, |menu, link| { @@ -5155,7 +5161,9 @@ impl Shell { this.copy_harness_conversation_link(&harness_id, cx) })) .child( - icon(icons::COPY).size(px(16.0)).text_color(theme.text_muted), + icon(icons::COPY) + .size(px(16.0)) + .text_color(theme.text_muted), ) .child(SharedString::from(link.label)), ) @@ -5172,7 +5180,9 @@ impl Shell { this.copy_harness_session_id(&session_chat_id, cx) })) .child( - icon(icons::COPY).size(px(16.0)).text_color(theme.text_muted), + icon(icons::COPY) + .size(px(16.0)) + .text_color(theme.text_muted), ) .child(SharedString::from("Harness session ID")), ) @@ -8150,9 +8160,7 @@ mod tests { #[test] fn sidebar_harness_geometry_reflects_row_hierarchy() { assert_eq!(SIDEBAR_ACTIVE_HARNESS_TITLE_GAP, Theme::SPACE_SM); - assert!( - SIDEBAR_ACTIVE_HARNESS_TITLE_GAP < SIDEBAR_ARCHIVED_HARNESS_TITLE_GAP - ); + assert!(SIDEBAR_ACTIVE_HARNESS_TITLE_GAP < SIDEBAR_ARCHIVED_HARNESS_TITLE_GAP); assert!(SIDEBAR_ACTIVE_HARNESS_ICON_SIZE < SIDEBAR_ARCHIVED_HARNESS_ICON_SIZE); } diff --git a/crates/ui/src/shell/spaces.rs b/crates/ui/src/shell/spaces.rs index f0aed8e142..6a3cc598bd 100644 --- a/crates/ui/src/shell/spaces.rs +++ b/crates/ui/src/shell/spaces.rs @@ -652,14 +652,12 @@ impl Shell { format!("sidebar-view-row-{ix}"), ) .id(("sidebar-view-row", ix)) - .on_click( - cx.listener(move |this, _, _, cx| { - if let Some(menu) = this.sidebar_view_menu.open_mut() { - menu.active = None; - } - this.activate_sidebar_view_row(row, cx) - }), - ) + .on_click(cx.listener(move |this, _, _, cx| { + if let Some(menu) = this.sidebar_view_menu.open_mut() { + menu.active = None; + } + this.activate_sidebar_view_row(row, cx) + })) .child( icon(icons[ix]) .size(px(15.0)) @@ -1109,9 +1107,7 @@ impl Shell { .map(str::to_string); let change_request = state.change_request_for_chat(&chat).cloned(); let group = match self.settings.sidebar_organization { - SidebarOrganization::ByDevice => { - Some((chat.device_id.clone(), device)) - } + SidebarOrganization::ByDevice => Some((chat.device_id.clone(), device)), SidebarOrganization::ByProject | SidebarOrganization::InOneList => None, }; ActiveChatRow { @@ -1290,9 +1286,7 @@ impl Shell { .cloned() .collect() }; - rows.sort_by(|left, right| { - compare_sidebar_chats(self.settings.sidebar_sort, left, right) - }); + rows.sort_by(|left, right| compare_sidebar_chats(self.settings.sidebar_sort, left, right)); if rows.is_empty() { return None; } @@ -1685,8 +1679,7 @@ impl Shell { if rows.is_empty() { let text = flow.search.read(cx).text().to_string(); if text.starts_with('/') || text.starts_with('~') { - if let Some(target) = - crate::pickers::typed_path_target(&text, flow.home.as_deref()) + if let Some(target) = crate::pickers::typed_path_target(&text, flow.home.as_deref()) { self.add_space_descend(target, false, cx); } @@ -2263,12 +2256,9 @@ impl Shell { (SharedString::from(d.name.clone()), mount, at_mount) }); let folded = 1 + match (&drive_crumb, home.as_deref()) { - (Some((_, mount, _)), _) => { - mount.split('/').filter(|s| !s.is_empty()).count() - } + (Some((_, mount, _)), _) => mount.split('/').filter(|s| !s.is_empty()).count(), (None, Some(h)) - if listing.path == h - || listing.path.starts_with(&format!("{h}/")) => + if listing.path == h || listing.path.starts_with(&format!("{h}/")) => { h.split('/').filter(|s| !s.is_empty()).count() } From f442dcc6dac7eb91ec8bdbff8a953282daeb95f0 Mon Sep 17 00:00:00 2001 From: gaelcado Date: Sun, 23 Aug 2026 19:53:48 +0200 Subject: [PATCH 16/17] test: initialize conversation source context --- crates/ui/src/shell/tabs.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/ui/src/shell/tabs.rs b/crates/ui/src/shell/tabs.rs index 85a5568a5d..58f6ad85ec 100644 --- a/crates/ui/src/shell/tabs.rs +++ b/crates/ui/src/shell/tabs.rs @@ -374,6 +374,7 @@ mod cycle_tests { cwd: None, branch: None, checkout_id: None, + source_context: None, config: None, last_message_preview: None, last_message_at: None, From 2119bf0cdda721c8a0500cffabc40e3cb6fafd79 Mon Sep 17 00:00:00 2001 From: wing-anara Date: Mon, 24 Aug 2026 10:35:41 +0000 Subject: [PATCH 17/17] test: diff-sync no longer rewrites chat.branch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit diff_sync_publishes_and_updates_chat_branch asserted the checkout watcher's branch upkeep, which this PR deliberately removes — branch identity is conversation-owned and stamped at dispatch. The test now pins the new contract: snapshots publish, checkoutId is still reconciled, and the chat row's branch stays untouched. Co-Authored-By: Claude Fable 5 --- crates/engine/tests/m5_repos_diffs_terminals.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/crates/engine/tests/m5_repos_diffs_terminals.rs b/crates/engine/tests/m5_repos_diffs_terminals.rs index f81094c6cc..4cfede1f57 100644 --- a/crates/engine/tests/m5_repos_diffs_terminals.rs +++ b/crates/engine/tests/m5_repos_diffs_terminals.rs @@ -768,7 +768,7 @@ async fn delete_space_cascades_chats_and_sessions() { // --------------------------------------------------------------------------- #[tokio::test(flavor = "multi_thread", worker_threads = 2)] -async fn diff_sync_publishes_and_updates_chat_branch() { +async fn diff_sync_publishes_without_rewriting_chat_branch() { let tmp = tempfile::tempdir().expect("tempdir"); let repo_dir = tmp.path().join("repo"); init_repo(&repo_dir).await; @@ -809,13 +809,16 @@ async fn diff_sync_publishes_and_updates_chat_branch() { assert!(!diff.checkout_id.is_empty()); assert!(!diff.checksum.is_empty()); - // Row upkeep: branch + checkoutId stamped on the workspace chat row. + // Branch identity is conversation-owned: the checkout watcher must NOT + // relabel chat rows with the live branch — only a dispatch stamps it. + // Reconcile still stamps checkoutId (row ↔ checkout identity). let chat = core .workspace .chat("chat-diff") .expect("read chat") .expect("row"); - assert_eq!(chat.branch.as_deref(), Some("main")); + assert_eq!(chat.branch, None); + assert_eq!(chat.source_context, None); assert_eq!(chat.checkout_id.as_deref(), Some(diff.checkout_id.as_str())); // File watcher path: another edit re-publishes without a manual kick.