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
29 changes: 29 additions & 0 deletions docs/architecture/session-projection.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,35 @@ at delayed delivery time; replacement listeners cannot receive old events.
A Session restore fences only that Session. Events buffered for other Sessions
during the read must be flushed, never cleared with the restored projection.

### ACP execution authority

Desktop ACP prompts record their portable lifecycle, text and tool facts in the
same host journal before delivery to local views and Peer host streams. The ACP
service owns prompt admission and terminal facts independently of its long-held
protocol session mutex. Repeated admission of the same Turn/input is idempotent;
a different Turn cannot replace a running or cancelling prompt.

`restore_session_view` advertises this additive authority with
`executionProjection: "acp"`. Its state comes from the ACP owner, not the native
coordinator's idle shell. Both active and terminal ACP journal snapshots can be
replayed through the existing Session read fence. A terminal replay must clear
the repaired gap and wake the queue after the fence settles. A reloaded ACP queue
waits for history/execution hydration before using an idle frontend machine.
When replay reconstructs an ACP turn, the hydrated history supplies its storage
index so terminal output is saved with the conversation.
Older hosts without this marker keep persisted-history loading; a required ACP
execution repair fails visibly and retains queued input rather than claiming
that the native idle shell repaired it. CLI Peer hosts still explicitly reject
ACP client-host operations; this change does not add that capability.

ACP model/options/command reads use a session-scoped metadata watch snapshot
while the protocol receiver is owned by a running request. The single receiver
publishes command, configuration and context updates before their frontend
notifications. Cold reads wait for initialization/publication; idle reads retain
the existing bounded notification drain. Model/config mutations publish accepted
state before returning. This is an in-memory observation projection, with no wire
or persisted-shape changes; reconnect creates a fresh session snapshot.

## The problem this replaces

Seven independent writers currently produce a Session's on-screen state:
Expand Down
5 changes: 5 additions & 0 deletions src/apps/desktop/AGENTS-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ pnpm run prepare:dsh-profile # 可选:本地 DeepSeek Harness 会话

## 验证

验证 ACP 取消请求兼容性时,运行
`cargo test --locked -p openbitfun-desktop --no-default-features --lib acp_cancel_request`,
覆盖旧请求反序列化与往返,以及可选的 Turn 绑定字段。
ACP 队列恢复的原生验收脚本见 `tests/e2e/AGENTS.md`。

```bash
cargo check -p openbitfun-desktop && cargo test -p openbitfun-desktop
```
Expand Down
5 changes: 5 additions & 0 deletions src/apps/desktop/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,11 @@ The `devtools` Cargo feature exists for debugging UI/UX in the desktop app. When

## Verification

For ACP cancellation request compatibility, run
`cargo test --locked -p openbitfun-desktop --no-default-features --lib acp_cancel_request`.
It covers legacy payload deserialization/round trips and the optional Turn binding.
Native ACP queue recovery uses the focused runner in `tests/e2e/AGENTS.md`.

Application updates use the official `tauri-plugin-updater` for discovery,
download and signature verification. `src/update_maintenance` owns native
authorization, publication/recovery and Windows process handoff; keep those
Expand Down
112 changes: 99 additions & 13 deletions src/apps/desktop/src/api/acp_client_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,8 @@ pub struct StartAcpDialogTurnRequest {
pub struct CancelAcpDialogTurnRequest {
pub session_id: String,
pub client_id: String,
#[serde(default)]
pub turn_id: Option<String>,
/// Workspace identity; authoritative when present.
#[serde(default)]
pub workspace_id: Option<String>,
Expand Down Expand Up @@ -205,8 +207,55 @@ pub struct ProbeAcpClientRequirementsRequest {
pub force_refresh: bool,
}

// One ordered delivery task per admitted prompt; disconnecting a WebView
// never cancels it. Both local views and Peer host streams consume this path.
#[derive(Clone)]
struct AcpEventEmitter {
service: std::sync::Arc<openbitfun_acp::AcpClientService>,
sender: tokio::sync::mpsc::UnboundedSender<openbitfun_events::AgenticFrontendEvent>,
}

impl AcpEventEmitter {
fn new(app: AppHandle, service: std::sync::Arc<openbitfun_acp::AcpClientService>) -> Self {
let (sender, mut receiver) = tokio::sync::mpsc::unbounded_channel();
tokio::spawn(async move {
let transport = openbitfun_transport::TauriTransportAdapter::new(app);
while let Some(event) = receiver.recv().await {
crate::deliver_projected_event(&transport, event).await;
}
});
Self { service, sender }
}

fn emit(
&self,
name: &str,
mut payload: serde_json::Value,
) -> Result<(), openbitfun_core::util::errors::OpenBitFunError> {
use openbitfun_core::util::errors::OpenBitFunError;
self.service
.record_dialog_event(name, &mut payload)
.map_err(OpenBitFunError::service)?;
self.publish(name, payload)
}

fn publish(
&self,
name: &str,
payload: serde_json::Value,
) -> Result<(), openbitfun_core::util::errors::OpenBitFunError> {
use openbitfun_core::util::errors::OpenBitFunError;
self.sender
.send(openbitfun_events::AgenticFrontendEvent {
event_name: name.into(),
payload,
})
.map_err(|_| OpenBitFunError::service("ACP event delivery stopped"))
}
}

fn emit_acp_model_round_completed(
app_handle: &AppHandle,
app_handle: &AcpEventEmitter,
session_id: &str,
turn_id: &str,
round_id: String,
Expand Down Expand Up @@ -414,19 +463,19 @@ pub async fn start_acp_dialog_turn(
None => (None, None, None),
};

let Some(start) = service.admit_dialog_turn(
&session_id,
&turn_id,
&request.client_id,
&user_input,
&original_user_input,
)?
else {
return Ok(());
};
let app_handle = AcpEventEmitter::new(app_handle, service.clone());
app_handle
.emit(
"agentic://dialog-turn-started",
serde_json::json!({
"sessionId": session_id,
"turnId": turn_id,
"turnIndex": null,
"userInput": user_input,
"originalUserInput": original_user_input,
"userMessageMetadata": null,
"subagentParentInfo": null,
}),
)
.publish("agentic://dialog-turn-started", start)
.map_err(|e| e.to_string())?;
tokio::spawn(async move {
let mut current_round_id: Option<String> = None;
Expand Down Expand Up @@ -715,6 +764,7 @@ pub async fn cancel_acp_dialog_turn(
&request.client_id,
scope.map(|scope| scope.workspace_path),
request.session_id,
request.turn_id.as_deref(),
)
.await
.map_err(|e| e.to_string())
Expand Down Expand Up @@ -905,3 +955,39 @@ pub async fn submit_acp_permission_response(
.await
.map_err(|e| e.to_string())
}

#[cfg(test)]
mod tests {
use super::CancelAcpDialogTurnRequest;
use serde_json::json;

#[test]
fn acp_cancel_request_preserves_legacy_payload_round_trip() {
let legacy = json!({
"sessionId": "session-1",
"clientId": "controlled",
"workspacePath": "/workspace",
"remoteConnectionId": "remote-1"
});
let request: CancelAcpDialogTurnRequest = serde_json::from_value(legacy.clone()).unwrap();
assert!(request.turn_id.is_none());
let encoded = serde_json::to_value(&request).unwrap();
for (key, value) in legacy.as_object().unwrap() {
assert_eq!(&encoded[key], value);
}
let decoded: CancelAcpDialogTurnRequest = serde_json::from_value(encoded).unwrap();
assert!(decoded.turn_id.is_none());
assert_eq!(decoded.remote_connection_id.as_deref(), Some("remote-1"));
}

#[test]
fn acp_cancel_request_round_trips_the_optional_turn_binding() {
let request: CancelAcpDialogTurnRequest = serde_json::from_value(json!({
"sessionId": "session-1", "clientId": "controlled", "turnId": "turn-1"
}))
.unwrap();
let decoded: CancelAcpDialogTurnRequest =
serde_json::from_value(serde_json::to_value(request).unwrap()).unwrap();
assert_eq!(decoded.turn_id.as_deref(), Some("turn-1"));
}
}
40 changes: 37 additions & 3 deletions src/apps/desktop/src/api/agentic_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -621,6 +621,9 @@ pub struct RestoreSessionWithTurnsResponse {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RestoreSessionViewResponse {
/// Additive capability/authority marker. Older hosts omit it.
#[serde(skip_serializing_if = "Option::is_none")]
pub execution_projection: Option<&'static str>,
pub session: SessionResponse,
pub turns: Vec<DialogTurnData>,
pub interaction_snapshot: SessionInteractionSnapshot,
Expand Down Expand Up @@ -675,6 +678,16 @@ fn frontend_event_projection_snapshot(
}
}

fn enrich_acp_replay_event(name: &str, payload: &mut serde_json::Value) {
// ACP does not provide an absolute persisted Turn ordinal. Preserve the
// established live-wire absence rather than inventing ordinal zero.
if name == "agentic://dialog-turn-started" {
payload["turnIndex"] = serde_json::Value::Null;
} else if name == "agentic://model-round-started" {
payload["renderHints"] = serde_json::json!({"disableExploreGrouping":true});
}
}

/// Incremental catch-up answer, in the same event shape the snapshot uses so a
/// client applies both through one path.
#[derive(Debug, Serialize)]
Expand Down Expand Up @@ -3822,9 +3835,17 @@ pub async fn restore_session_view(
let session = restored.session;
let mut turns = restored.turns;
let interaction_snapshot = restored.interaction_snapshot;
let runtime_event_snapshot = restored
let execution_projection = restored.execution_projection;
let mut runtime_event_snapshot = restored
.runtime_event_snapshot
.map(frontend_event_projection_snapshot);
if execution_projection == Some("acp") {
if let Some(snapshot) = runtime_event_snapshot.as_mut() {
for event in &mut snapshot.events {
enrich_acp_replay_event(&event.event_name, &mut event.payload);
}
}
}
let current_context_usage = restored.current_context_usage;
let total_turn_count = restored.total_turn_count;
let turn_catalog = restored.turn_catalog;
Expand Down Expand Up @@ -3876,6 +3897,7 @@ pub async fn restore_session_view(
);

Ok(RestoreSessionViewResponse {
execution_projection,
session: session_to_response_with_turn_count(session, total_turn_count),
turns,
interaction_snapshot,
Expand Down Expand Up @@ -3913,7 +3935,7 @@ pub async fn load_session_event_backfill(
runtime: State<'_, DesktopRuntimeContext>,
request: LoadSessionEventBackfillRequest,
) -> Result<serde_json::Value, String> {
Ok(session_event_backfill_to_response(
let mut response = session_event_backfill_to_response(
runtime.session_application().session_events_since(
&request.session_id,
&request.stream_id,
Expand All @@ -3922,7 +3944,19 @@ pub async fn load_session_event_backfill(
runtime
.session_application()
.session_interaction_snapshot(&request.session_id),
))
);
if runtime
.session_application()
.has_acp_execution(&request.session_id)
{
if let Some(events) = response["events"].as_array_mut() {
for event in events {
let name = event["eventName"].as_str().unwrap_or_default().to_owned();
enrich_acp_replay_event(&name, &mut event["payload"]);
}
}
}
Ok(response)
}

#[derive(Debug, Deserialize)]
Expand Down
9 changes: 9 additions & 0 deletions src/apps/desktop/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2464,6 +2464,15 @@ async fn deliver_event_to_webview(
attach_session_event_cursor(&mut projected.payload, cursor);
}

deliver_projected_event(transport, projected).await;
}

/// Final product delivery for native and ACP projections alike. ACP records
/// before enqueueing here; native events record after text coalescing above.
pub(crate) async fn deliver_projected_event(
transport: &TauriTransportAdapter,
projected: openbitfun_events::AgenticFrontendEvent,
) {
for hub in api::remote_connect_api::host_stream_hubs().await {
if let Some(session_id) = projected
.payload
Expand Down
5 changes: 5 additions & 0 deletions src/apps/desktop/src/runtime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@ impl DesktopRuntimeContext {
acp_client_service: Option<Arc<openbitfun_acp::AcpClientService>>,
session_event_journal: Arc<SessionEventJournal>,
) -> Result<Self, String> {
if let Some(service) = acp_client_service.as_ref() {
service.configure_execution_journal(Arc::new(
session_host_effects::AcpJournalAdapter(session_event_journal.clone()),
))?;
}
let host_effects = Arc::new(ProductionDesktopSessionHostEffects::new(acp_client_service));
let session_application = DesktopSessionApplication::build(
coordinator,
Expand Down
Loading
Loading