Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions apps/zeron/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ use clap::{Parser, Subcommand};
struct Cli {
#[command(subcommand)]
command: Option<Command>,
/// Open a Zeron conversation URL.
#[arg(value_name = "URL")]
open_url: Option<String>,
}

#[derive(Subcommand)]
Expand Down Expand Up @@ -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(())
}
Expand Down
29 changes: 29 additions & 0 deletions crates/doc/src/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -1016,6 +1024,27 @@ impl RegistryDoc {
Ok(true)
}

pub fn set_chat_source_context(
&mut self,
chat_id: &str,
context: &zeron_proto::ConversationSourceContext,
) -> Result<bool, DocError> {
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.
Expand Down
1 change: 1 addition & 0 deletions crates/doc/src/registry/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down
50 changes: 50 additions & 0 deletions crates/doc/src/workspace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,13 @@ 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")?,
Expand Down Expand Up @@ -345,6 +352,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<bool, DocError> {
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
Expand Down Expand Up @@ -631,6 +658,8 @@ pub(crate) struct RawChat {
branch: Option<String>,
#[serde(default)]
checkout_id: Option<String>,
#[serde(default)]
source_context: Option<zeron_proto::ConversationSourceContext>,
/// 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
Expand Down Expand Up @@ -685,6 +714,7 @@ impl From<RawChat> 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),
Expand Down Expand Up @@ -751,6 +781,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()),
Expand Down Expand Up @@ -829,6 +860,25 @@ 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();
Expand Down
54 changes: 50 additions & 4 deletions crates/engine/src/change_requests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -117,25 +117,47 @@ impl CheckoutChangeRequests {
pub async fn watch(
&self,
cwd: &Path,
) -> Result<BoxStream<'static, CheckoutChangeRequestStatus>, 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<BoxStream<'static, CheckoutChangeRequestStatus>, ChangeRequestError> {
let identity = self
.inner
.repos
.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<String>,
) -> BoxStream<'static, CheckoutChangeRequestStatus> {
let state = SubscriptionState {
service: self.clone(),
cwd,
identity,
requested_branch,
lease: None,
last_emitted: None,
};
Expand All @@ -144,7 +166,7 @@ impl CheckoutChangeRequests {
if state.service.inner.shutdown.is_cancelled() {
return None;
}
let source = match state
let mut source = match state
.service
.inner
.lookup
Expand All @@ -163,6 +185,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()));
Expand Down Expand Up @@ -310,6 +342,7 @@ struct SubscriptionState {
service: CheckoutChangeRequests,
cwd: PathBuf,
identity: CheckoutIdentity,
requested_branch: Option<String>,
lease: Option<DemandLease>,
last_emitted: Option<SemanticStatus>,
}
Expand Down Expand Up @@ -486,6 +519,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)))]);
Expand Down
22 changes: 6 additions & 16 deletions crates/engine/src/diff_sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -626,17 +626,6 @@ async fn sync_entry(inner: &Arc<DiffSyncInner>, entry: &Arc<CheckoutEntry>) {
}
};

// 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
}
Expand All @@ -663,6 +652,7 @@ async fn sync_entry(inner: &Arc<DiffSyncInner>, entry: &Arc<CheckoutEntry>) {
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 {
Expand Down
Loading