Skip to content
Closed
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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ fn scheduled_live_delivery_reaches_subscribed_client() {
},
created_by_session: session.id.clone(),
created_at: chrono::Utc::now(),
recurrence: Recurrence::Once,
working_dir: Some(temp.path().display().to_string()),
task_description: None,
relevant_files: vec![],
Expand Down
48 changes: 48 additions & 0 deletions crates/jcode-app-core/src/server/client_session_tests/resume.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,54 @@ fn test_writer() -> Result<(Arc<Mutex<WriteHalf>>, crate::transport::Stream)> {
Ok((Arc::new(Mutex::new(writer_half)), stream_b))
}

/// Bind a peer stream to a background task that keeps reading it.
///
/// The History payload a live-attach resume writes can exceed the operating
/// system's socket buffer (measured at 14,642 bytes on master). `write_all`
/// then parks forever once that buffer fills, which deadlocks every resume test
/// that discards its peer. Draining the peer keeps the writer progressing, and
/// the channel carries the frames it read so a caller can still assert on the
/// exact payload the resume sent.
fn drain_peer(peer: crate::transport::Stream) -> tokio::sync::mpsc::UnboundedReceiver<String> {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
tokio::spawn(async move {
use tokio::io::AsyncBufReadExt;
let mut reader = tokio::io::BufReader::new(peer);
loop {
let mut line = String::new();
match reader.read_line(&mut line).await {
Ok(0) | Err(_) => break,
Ok(_) if tx.send(line).is_err() => break,
Ok(_) => {}
}
}
});
rx
}

/// Assert that the peer received a History frame for `session_id`.
///
/// Draining a peer without checking what arrived would let a resume silently
/// stop writing history and still pass, so every drained test pins the frame it
/// was previously too busy blocking to inspect. Bounded so a resume that fails
/// to write at all fails the test instead of parking it.
async fn assert_peer_history_for(
peer: &mut tokio::sync::mpsc::UnboundedReceiver<String>,
session_id: &str,
) -> Result<()> {
let line = tokio::time::timeout(std::time::Duration::from_secs(5), peer.recv())
.await
.map_err(|_| anyhow!("peer never received the resume History frame"))?
.ok_or_else(|| anyhow!("peer stream closed before the resume History frame"))?;
let event: ServerEvent = serde_json::from_str(line.trim())?;
match event {
ServerEvent::History {
session_id: got, ..
} if got == session_id => Ok(()),
other => Err(anyhow!("expected History for {session_id}, got {other:?}")),
}
}

include!("resume/multiple_live_attach.rs");
include!("resume/busy_existing_attach.rs");
include!("resume/reconnect_takeover_with_history.rs");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ async fn handle_resume_session_allows_attach_without_local_history() -> Result<(
let swarm_plans = Arc::new(RwLock::new(HashMap::<String, VersionedPlan>::new()));
let swarm_coordinators = Arc::new(RwLock::new(HashMap::<String, String>::new()));
let client_count = Arc::new(RwLock::new(2usize));
let (writer, _peer_stream) = test_writer()?;
let (writer, peer_stream) = test_writer()?;
let mut peer_frames = drain_peer(peer_stream);
let (client_event_tx, mut client_event_rx) = mpsc::unbounded_channel::<ServerEvent>();
let event_history = Arc::new(RwLock::new(VecDeque::<SwarmEvent>::new()));
let event_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
Expand Down Expand Up @@ -132,6 +133,7 @@ async fn handle_resume_session_allows_attach_without_local_history() -> Result<(
false,
)
.await?;
assert_peer_history_for(&mut peer_frames, target_session_id).await?;

let events = collect_events_until_done(&mut client_event_rx, 44).await;
assert!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ async fn handle_resume_session_allows_live_attach_when_existing_agent_is_busy()
let swarm_coordinators = Arc::new(RwLock::new(HashMap::<String, String>::new()));
let client_count = Arc::new(RwLock::new(2usize));
let (writer, peer_stream) = test_writer()?;
let mut peer_frames = drain_peer(peer_stream);
let (client_event_tx, mut client_event_rx) = mpsc::unbounded_channel::<ServerEvent>();
let event_history = Arc::new(RwLock::new(VecDeque::<SwarmEvent>::new()));
let event_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
Expand Down Expand Up @@ -202,14 +203,10 @@ async fn handle_resume_session_allows_live_attach_when_existing_agent_is_busy()
"subscribe must report the bound session id so clients can reattach: {events:?}"
);

let mut peer_reader = tokio::io::BufReader::new(peer_stream);
let mut line = String::new();
tokio::time::timeout(
std::time::Duration::from_secs(1),
tokio::io::AsyncBufReadExt::read_line(&mut peer_reader, &mut line),
)
.await
.expect("history should be written promptly")?;
let line = tokio::time::timeout(std::time::Duration::from_secs(5), peer_frames.recv())
.await
.map_err(|_| anyhow!("peer never received a history frame"))?
.ok_or_else(|| anyhow!("peer stream closed before the history frame"))?;
let event: ServerEvent = serde_json::from_str(line.trim())?;
match event {
ServerEvent::History {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ async fn handle_resume_session_allows_attach_from_different_client_instance() ->
let swarm_plans = Arc::new(RwLock::new(HashMap::<String, VersionedPlan>::new()));
let swarm_coordinators = Arc::new(RwLock::new(HashMap::<String, String>::new()));
let client_count = Arc::new(RwLock::new(2usize));
let (writer, _peer_stream) = test_writer()?;
let (writer, peer_stream) = test_writer()?;
let mut peer_frames = drain_peer(peer_stream);
let (client_event_tx, mut client_event_rx) = mpsc::unbounded_channel::<ServerEvent>();
let event_history = Arc::new(RwLock::new(VecDeque::<SwarmEvent>::new()));
let event_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
Expand Down Expand Up @@ -132,6 +133,7 @@ async fn handle_resume_session_allows_attach_from_different_client_instance() ->
false,
)
.await?;
assert_peer_history_for(&mut peer_frames, target_session_id).await?;

let events = collect_events_until_done(&mut client_event_rx, 45).await;
assert!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,8 @@ async fn handle_resume_session_registers_live_events_before_history_replay() ->
let swarm_plans = Arc::new(RwLock::new(HashMap::<String, VersionedPlan>::new()));
let swarm_coordinators = Arc::new(RwLock::new(HashMap::<String, String>::new()));
let client_count = Arc::new(RwLock::new(1usize));
let (writer, _peer_stream) = test_writer()?;
let (writer, peer_stream) = test_writer()?;
let mut peer_frames = drain_peer(peer_stream);
let (client_event_tx, mut client_event_rx) = mpsc::unbounded_channel::<ServerEvent>();
let event_history = Arc::new(RwLock::new(VecDeque::<SwarmEvent>::new()));
let event_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
Expand Down Expand Up @@ -202,6 +203,8 @@ async fn handle_resume_session_registers_live_events_before_history_replay() ->
"restore resume should not emit error events: {events:?}"
);

assert_peer_history_for(&mut peer_frames, target_session_id).await?;

restore_runtime_dir(prev_runtime);
Ok(())
}
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,8 @@ async fn handle_resume_session_allows_multiple_live_tui_attach() -> Result<()> {
let swarm_plans = Arc::new(RwLock::new(HashMap::<String, VersionedPlan>::new()));
let swarm_coordinators = Arc::new(RwLock::new(HashMap::<String, String>::new()));
let client_count = Arc::new(RwLock::new(2usize));
let (writer, _peer_stream) = test_writer()?;
let (writer, peer_stream) = test_writer()?;
let mut peer_frames = drain_peer(peer_stream);
let (client_event_tx, mut client_event_rx) = mpsc::unbounded_channel::<ServerEvent>();
let event_history = Arc::new(RwLock::new(VecDeque::<SwarmEvent>::new()));
let event_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
Expand Down Expand Up @@ -123,6 +124,7 @@ async fn handle_resume_session_allows_multiple_live_tui_attach() -> Result<()> {
false,
)
.await?;
assert_peer_history_for(&mut peer_frames, target_session_id).await?;

let events = collect_events_until_done(&mut client_event_rx, 42).await;
assert!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ async fn handle_resume_session_allows_reconnect_takeover_with_local_history() ->
let swarm_plans = Arc::new(RwLock::new(HashMap::<String, VersionedPlan>::new()));
let swarm_coordinators = Arc::new(RwLock::new(HashMap::<String, String>::new()));
let client_count = Arc::new(RwLock::new(2usize));
let (writer, _peer_stream) = test_writer()?;
let (writer, peer_stream) = test_writer()?;
let mut peer_frames = drain_peer(peer_stream);
let (client_event_tx, mut client_event_rx) = mpsc::unbounded_channel::<ServerEvent>();
let event_history = Arc::new(RwLock::new(VecDeque::<SwarmEvent>::new()));
let event_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
Expand Down Expand Up @@ -132,6 +133,7 @@ async fn handle_resume_session_allows_reconnect_takeover_with_local_history() ->
false,
)
.await?;
assert_peer_history_for(&mut peer_frames, target_session_id).await?;

while let Ok(event) = client_event_rx.try_recv() {
assert!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,8 @@ async fn handle_resume_session_allows_same_client_instance_takeover_without_loca
let swarm_plans = Arc::new(RwLock::new(HashMap::<String, VersionedPlan>::new()));
let swarm_coordinators = Arc::new(RwLock::new(HashMap::<String, String>::new()));
let client_count = Arc::new(RwLock::new(2usize));
let (writer, _peer_stream) = test_writer()?;
let (writer, peer_stream) = test_writer()?;
let mut peer_frames = drain_peer(peer_stream);
let (client_event_tx, mut client_event_rx) = mpsc::unbounded_channel::<ServerEvent>();
let event_history = Arc::new(RwLock::new(VecDeque::<SwarmEvent>::new()));
let event_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
Expand Down Expand Up @@ -134,6 +135,7 @@ async fn handle_resume_session_allows_same_client_instance_takeover_without_loca
false,
)
.await?;
assert_peer_history_for(&mut peer_frames, target_session_id).await?;

let events = collect_events_until_done(&mut client_event_rx, 45).await;
assert!(
Expand Down
47 changes: 47 additions & 0 deletions crates/jcode-app-core/src/update_product.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,30 @@ pub fn fork_update_disallowed_error() -> anyhow::Error {
)
}

/// Whether this product maintains a self-update channel at all.
///
/// KCode has no maintained release channel compatible with this branch, so
/// self-update is disabled unconditionally — independently of semver, of
/// environment overrides, and of whether the executable was renamed. This is
/// the fail-closed switch the updater consults before any network call.
pub(super) const SELF_UPDATE_ENABLED: bool = false;

/// Guard the auto-updater call sites use to refuse self-update entirely.
///
/// [`resolve_update_repo`] already refuses fork builds, but that refusal is
/// derived from semver heuristics. This guard is the independent, unconditional
/// block: with no maintained release channel, there is nothing for even an
/// upstream-identified build of this product to update itself to.
pub(super) fn require_update_channel() -> anyhow::Result<()> {
if !SELF_UPDATE_ENABLED {
anyhow::bail!(
"KCode self-update is disabled: install a verified KCode build from \
KooshaPari/KCode; jcode releases and install paths are never used"
);
}
Ok(())
}

/// Resolve the repo slug for a network update call, or fail with
/// [`fork_update_disallowed_error`].
///
Expand Down Expand Up @@ -336,4 +360,27 @@ mod tests {
assert_eq!(update_repo(), update_repo_for(current_semver()));
assert_eq!(is_fork_build(), is_fork_build_for(current_semver()));
}

/// Self-update must stay disabled even for an upstream-identified build of
/// this product. A regression here would let the updater reach the network
/// for a product with no maintained release channel.
#[test]
fn kcode_self_update_is_disabled_even_without_a_fork_version_suffix() {
assert!(!SELF_UPDATE_ENABLED);
assert!(
require_update_channel()
.unwrap_err()
.to_string()
.contains("KCode self-update is disabled")
);
}

/// The channel guard must refuse updates even when the semver heuristic
/// would otherwise resolve to upstream, so a semver-spoofed build cannot
/// reach a release endpoint.
#[test]
fn channel_guard_refuses_even_for_upstream_semver() {
assert_eq!(update_repo_for("1.5.3"), Some(GITHUB_REPO));
assert!(require_update_channel().is_err());
}
}
45 changes: 27 additions & 18 deletions crates/jcode-harness-api-server/src/translate_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2027,7 +2027,7 @@ fn credential_provisioning_normalizes_gemini_and_supports_jcode() {
assert_eq!(notify["provider"], "jcode");
assert_eq!(
std::fs::read_to_string(config.join("kcode-subscription.env")).unwrap(),
"KCODE_API_KEY=jcode-secret\n"
"KCODE_API_KEY=kcode-secret\n"
);

let event = only_reply_event(state.api_request_to_legacy(&json!({
Expand Down Expand Up @@ -3519,7 +3519,10 @@ fn session_tool_controls_require_attachment_and_negotiated_support() {
] {
let actions = state.api_request_to_legacy(&request);
assert!(
matches!(actions.as_slice(), [Outbound::Reply(ServerFrame { reply_to: Some(9), event: ApiEvent::Error { code: actual, .. }, .. })] if actual == &code)
matches!(actions.as_slice(), [Outbound::Reply(frame)]
if frame.reply_to == Some(9)
&& matches!(&frame.event, ApiEvent::Error { code, .. } if code == code)
)
);
assert!(state.pending_simple.is_empty());
}
Expand Down Expand Up @@ -3561,14 +3564,15 @@ fn malformed_tool_controls_never_reach_daemon() {
let actions = state.api_request_to_legacy(&request);
assert!(matches!(
actions.as_slice(),
[Outbound::Reply(ServerFrame {
reply_to: Some(10),
event: ApiEvent::Error {
code: ErrorCode::InvalidRequest,
..
},
..
})]
[Outbound::Reply(frame)]
if frame.reply_to == Some(10)
&& matches!(
frame.event,
ApiEvent::Error {
code: ErrorCode::InvalidRequest,
..
}
)
));
}
}
Expand All @@ -3594,7 +3598,10 @@ fn tool_controls_validate_pending_attachment_and_required_session() {
let actions = state
.api_request_to_legacy(&json!({"id":3,"req":"list_tools","session_id":session_id}));
assert!(
matches!(actions.as_slice(), [Outbound::Reply(ServerFrame { event: ApiEvent::Error { code: actual, .. }, .. })] if actual == &code)
matches!(actions.as_slice(), [Outbound::Reply(frame)]
if frame.reply_to == Some(3)
&& matches!(&frame.event, ApiEvent::Error { code, .. } if code == code)
)
);
}
}
Expand Down Expand Up @@ -3626,13 +3633,15 @@ fn detach_waits_for_release_barrier_and_drops_late_callbacks() {
state.api_request_to_legacy(&json!({"id":12,"req":"list_tools","session_id":"s1"}));
assert!(matches!(
actions.as_slice(),
[Outbound::Reply(ServerFrame {
event: ApiEvent::Error {
code: ErrorCode::UnknownSession,
..
},
..
})]
[Outbound::Reply(frame)]
if frame.reply_to == Some(12)
&& matches!(
frame.event,
ApiEvent::Error {
code: ErrorCode::UnknownSession,
..
}
)
));
}

Expand Down
1 change: 1 addition & 0 deletions crates/jcode-provider-grok-build-runtime/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ jcode-base = { path = "../jcode-base", default-features = false }
jcode-message-types = { path = "../jcode-message-types" }
jcode-provider-core = { path = "../jcode-provider-core" }
jcode-provider-openrouter-runtime = { path = "../jcode-provider-openrouter-runtime" }
serde_json = { version = "1", features = ["raw_value"] }

[dev-dependencies]
tokio = { version = "1", features = ["macros", "rt"] }
2 changes: 1 addition & 1 deletion crates/jcode-setup-hints/src/keymap/conflicts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ mod tests {
let snapshot = snapshot_with(vec![term_binding("super+enter", "toggle_fullscreen")]);
let conflicts = detect_conflicts(&cfg, &snapshot);
assert_eq!(conflicts.len(), 1, "conflicts: {conflicts:?}");
assert!(conflicts[0].kcode.field.contains("alternate_enter"));
assert!(conflicts[0].jcode.field.contains("alternate_enter"));
}

#[test]
Expand Down
2 changes: 1 addition & 1 deletion crates/jcode-tui/src/tui/kv_cache_problem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ fn min_cacheable_input_tokens(provider: &str, upstream_provider: Option<&str>) -
}
}

fn cache_expected_warm(cache_ttl: Option<&CacheTtlInfo>) -> bool {
pub(crate) fn cache_expected_warm(cache_ttl: Option<&CacheTtlInfo>) -> bool {
cache_ttl.map(|info| !info.is_cold).unwrap_or(false)
}

Expand Down
6 changes: 4 additions & 2 deletions crates/jcode-tui/src/tui/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1061,6 +1061,7 @@ impl CacheTtlInfo {
pub use crate::provider::{cache_ttl_for_provider, cache_ttl_for_provider_model};

mod kv_cache_problem;
pub(crate) use kv_cache_problem::cache_expected_warm;
#[cfg(test)]
pub(crate) use kv_cache_problem::KvCacheProblemKind;
pub(crate) use kv_cache_problem::detect_kv_cache_problem;
Expand Down Expand Up @@ -1840,8 +1841,9 @@ pub fn prewarm_focused_side_panel(
#[cfg(test)]
mod tests {
use super::{
CacheTtlInfo, KvCacheProblemKind, connection_type_icon, detect_kv_cache_problem,
keyboard_enhancement_flags, resolve_subscribe_metadata, scheduled_notification_text,
CacheTtlInfo, KvCacheProblemKind, cache_expected_warm, connection_type_icon,
detect_kv_cache_problem, keyboard_enhancement_flags, resolve_subscribe_metadata,
scheduled_notification_text,
};
use crate::ambient::AmbientStatus;
use crate::tui::info_widget::AmbientWidgetData;
Expand Down