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
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.

77 changes: 51 additions & 26 deletions docs/architecture/session-projection.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,32 +46,57 @@ 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 ACP client on the executing host owns admission, cancellation, agent binding
and the conversation transcript. A repeated submission with the same Turn ID
and input returns its existing admission. The host accepts the input before
contacting the agent. If earlier history is missing, it persists the admission
and assigns the Turn's storage index after replay, before sending the prompt.
The host records ordered text, thoughts and tool events in the Session journal.
On completion it writes the terminal Turn to ordinary conversation history.
If that write fails, the view receives the recorded outcome and a storage warning.
The journal retains the Turn for a later save. Closing a view leaves the Turn
running on the host. A restarted host can recover partial output and report an unknown
outcome when the agent's terminal response was never recorded.

Views use the existing Session read fence and the optional
`executionProjection: "acp"` marker to hydrate history and execution state.
Older hosts keep their persisted-history path. Older frontends can still send
their checkpoints. The persistence owner protects the runtime-owned range of
ordinary ACP turns. Legacy turns and other session types keep their existing
checkpoint rules. Peer views observe the executing host's state. CLI Peer hosts
continue to report unsupported ACP client operations explicitly.

Switching views and reloading the WebView read the host's live metadata snapshot
or the saved options. The last confirmed model and conversation are available
with the agent offline. Opening a session that has never saved agent options
attaches it once to obtain them, even if the user never opens the model picker.
Sending or explicitly opening the agent controls can also attach the original
session. Normal reattachment prefers the agent's advertised resume capability.
After an unconfirmed stop the host requires load before sending another prompt.
An agent with neither capability needs a new chat. The old chat keeps its
original binding and local history. If load is available, a known gap takes
priority over resume. The runtime registers its receiver before requesting
load and consumes the history through the response. With complete local
history it extracts only session metadata. With a known gap it matches
stable message IDs and unambiguous legacy history. Consecutive user chunks
without message IDs can represent one prompt or several. The saved prompts
decide where they split, using the text the agent was sent, which the host
keeps when it differs from the visible message. A split counts only when
exactly one placement of the saved prompts explains the replay. Otherwise
only stable IDs repair that replay. A local unsent turn has no position in
the agent's history, so an unanchored remote suffix leaves the gap open.
An unresolvable boundary is remembered together with the local history it
was tried against, so a later attach skips the full replay until that history
changes. An incomplete or still growing replay is not remembered. A load
retires its connection after 60 seconds without an update or 10 minutes
overall. The next attempt uses the saved binding, and the user's input remains
available.

An accepted turn whose prompt is not sent yet follows its own Turn ID. A stop,
a session release or a newer Turn ends it before the prompt reaches the
agent, including while the agent starts or the saved session loads. Releasing
a session waits for a load already in progress, so no replay writes history
after the session is deleted.

## The problem this replaces

Expand Down
185 changes: 132 additions & 53 deletions src/apps/desktop/src/api/acp_client_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use openbitfun_acp::client::{
SetAcpSessionConfigOptionRequest, SetAcpSessionModelRequest,
SubmitAcpPermissionResponseRequest,
};
use openbitfun_core::agentic::image_analysis::ImageContextData;
use openbitfun_core::service::workspace::WorkspaceInfo;
use openbitfun_runtime_ports::SessionStorePort;
use serde::{Deserialize, Serialize};
Expand Down Expand Up @@ -150,6 +151,10 @@ pub struct StartAcpDialogTurnRequest {
pub user_input: String,
#[serde(default)]
pub original_user_input: Option<String>,
#[serde(default)]
pub image_contexts: Option<Vec<ImageContextData>>,
#[serde(default)]
pub user_message_metadata: Option<serde_json::Value>,
pub turn_id: String,
/// Workspace identity; authoritative when present.
#[serde(default)]
Expand Down Expand Up @@ -185,6 +190,8 @@ pub struct CancelAcpDialogTurnRequest {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetAcpSessionOptionsRequest {
#[serde(default)]
pub observe_only: bool,
pub session_id: String,
pub client_id: String,
/// Workspace identity; authoritative when present.
Expand Down Expand Up @@ -463,13 +470,42 @@ 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,
)?
let mut user_metadata = request.user_message_metadata;
if let Some(images) = request.image_contexts.filter(|images| !images.is_empty()) {
let mut fields = super::agentic_api::desktop_user_message_metadata(user_metadata);
fields.entry("images").or_insert_with(|| {
let images = images.into_iter().map(|image| {
let name = image
.metadata
.as_ref()
.and_then(|metadata| metadata.get("name"))
.and_then(serde_json::Value::as_str);
serde_json::json!({
"id": image.id,
"name": name,
"mime_type": image.mime_type,
"image_path": image.image_path,
"data_url": image.data_url,
})
});
serde_json::Value::Array(images.collect())
});
fields
.entry("original_text")
.or_insert_with(|| original_user_input.clone().into());
user_metadata = Some(fields.into());
}
let Some(start) = service
.admit_dialog_turn(
&session_id,
&turn_id,
&request.client_id,
&user_input,
&original_user_input,
user_metadata,
session_storage_path.as_deref(),
)
.await?
else {
return Ok(());
};
Expand All @@ -480,14 +516,16 @@ pub async fn start_acp_dialog_turn(
tokio::spawn(async move {
let mut current_round_id: Option<String> = None;
let mut current_round_has_tool_calls = false;
let mut terminal = None;
let result = service
.prompt_agent_stream(
&request.client_id,
request.user_input,
workspace_path,
remote_connection_id,
request.session_id.clone(),
session_storage_path,
Some(&turn_id),
session_storage_path.clone(),
request.timeout_seconds,
|event| {
match event {
Expand Down Expand Up @@ -667,33 +705,7 @@ pub async fn start_acp_dialog_turn(
)
})?;
}
AcpClientStreamEvent::Completed => {
if let Some(round_id) = current_round_id.take() {
emit_acp_model_round_completed(
&app_handle,
&request.session_id,
&request.turn_id,
round_id,
current_round_has_tool_calls,
)?;
}
app_handle
.emit(
"agentic://dialog-turn-completed",
serde_json::json!({
"sessionId": request.session_id,
"turnId": request.turn_id,
"subagentParentInfo": null,
"partialRecoveryReason": null,
}),
)
.map_err(|e| {
openbitfun_core::util::errors::OpenBitFunError::service(
e.to_string(),
)
})?;
}
AcpClientStreamEvent::Cancelled => {
AcpClientStreamEvent::Completed | AcpClientStreamEvent::Cancelled => {
if let Some(round_id) = current_round_id.take() {
emit_acp_model_round_completed(
&app_handle,
Expand All @@ -703,20 +715,20 @@ pub async fn start_acp_dialog_turn(
current_round_has_tool_calls,
)?;
}
app_handle
.emit(
"agentic://dialog-turn-cancelled",
serde_json::json!({
"sessionId": request.session_id,
"turnId": request.turn_id,
"subagentParentInfo": null,
}),
)
.map_err(|e| {
openbitfun_core::util::errors::OpenBitFunError::service(
e.to_string(),
)
})?;
let name = if matches!(event, AcpClientStreamEvent::Cancelled) {
"agentic://dialog-turn-cancelled"
} else {
"agentic://dialog-turn-completed"
};
terminal = Some((
name,
serde_json::json!({
"sessionId": request.session_id,
"turnId": request.turn_id,
"subagentParentInfo": null,
"partialRecoveryReason": null,
}),
));
}
}
Ok(())
Expand All @@ -725,17 +737,61 @@ pub async fn start_acp_dialog_turn(
.await;

if let Err(error) = result {
let _ = app_handle.emit(
use openbitfun_core::util::errors::OpenBitFunError;
let mut detail = error.error_detail();
let detail = match &error {
OpenBitFunError::OutcomeUnknown(_) => {
detail.recovery_constraint = Some("acp_stop_unconfirmed".into());
detail.retryable = Some(false);
detail.action_hints = vec!["copy_diagnostics".into()];
Some(detail)
}
OpenBitFunError::Session(reason) => {
detail.provider = Some(format!("acp:{}", request.client_id));
detail.provider_message = Some(reason.clone());
Some(detail)
}
OpenBitFunError::AIProvider(_) => Some(detail),
_ => None,
};
terminal = Some((
"agentic://dialog-turn-failed",
serde_json::json!({
"sessionId": request.session_id,
"turnId": request.turn_id,
"error": error.to_string(),
"errorCategory": null,
"errorDetail": null,
"errorCategory": detail.as_ref().map(|detail| &detail.category),
"errorDetail": detail,
"subagentParentInfo": null,
}),
);
));
}
if let Some((name, mut payload)) = terminal {
match service
.finish_dialog_turn(
&session_id,
session_storage_path.as_deref(),
name,
&mut payload,
)
.await
{
Ok(()) => {
let _ = app_handle.publish(name, payload);
}
Err(error) => {
log::error!("Failed to commit ACP turn {turn_id}: {error}");
// A retired turn belongs to a newer execution and is dropped. A
// released session has no execution left, so a view that is still
// mounted (for example after a failed delete) would stay running.
// Settle it with the outcome the agent confirmed, as an uncursored
// event, which live subscribers accept without a snapshot cursor.
// Its history was not written, and that turn is recovered on open.
if service.execution_snapshot(&session_id).is_none() {
let _ = app_handle.publish(name, payload);
}
}
}
}
});

Expand Down Expand Up @@ -795,6 +851,17 @@ pub async fn get_acp_session_options(
),
None => (None, None, None),
};
if request.observe_only {
return service
.observe_session_options(
&request.client_id,
&request.session_id,
workspace_path.as_deref(),
session_storage_path.as_deref(),
)
.await
.map_err(|e| e.to_string());
}
service
.get_session_options(
&request.client_id,
Expand Down Expand Up @@ -832,6 +899,18 @@ pub async fn get_acp_session_commands(
),
None => (None, None, None),
};
if request.observe_only {
return service
.observe_session_options(
&request.client_id,
&request.session_id,
workspace_path.as_deref(),
session_storage_path.as_deref(),
)
.await
.map(|options| options.available_commands.unwrap_or_default())
.map_err(|e| e.to_string());
}
service
.get_session_commands(
&request.client_id,
Expand Down
2 changes: 1 addition & 1 deletion src/apps/desktop/src/api/agentic_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2679,7 +2679,7 @@ fn desktop_dialog_turn_request(
})
}

fn desktop_user_message_metadata(
pub(super) fn desktop_user_message_metadata(
metadata: Option<serde_json::Value>,
) -> serde_json::Map<String, serde_json::Value> {
match metadata {
Expand Down
Loading
Loading