refactor: rebuild desktop app with Tauri

This commit is contained in:
leookun committed 2026-08-24 02:49:00 +08:00
1 parent a3ec2a0dfc
commit 4053a7fb20
808 files changed
+87359 -181491

No files matched your search

+253
View File
@@ -0,0 +1,253 @@
use base64::{engine::general_purpose::STANDARD, Engine};
use serde_json::Value;
use crate::{
model::{
CanonicalMessage, ContentPart, MessageContent, Origin, RecoveredToolRound, Role, ToolCall,
ToolCallContent, ToolResultContent, ToolRoundAssistant, ToolRoundId,
},
store::BlobId,
Error, Result,
};
use super::REPLAY_ENVELOPE_PREFIX;
pub fn decode(data: &[u8], internal_id: String) -> Result<CanonicalMessage> {
let value: Value = serde_json::from_slice(data)?;
let role = match required_string(&value, "role")? {
"system" => Role::System,
"user" => Role::User,
"assistant" => Role::Assistant,
"tool" => Role::Tool,
role => {
return Err(Error::Protocol(format!(
"unknown Cursor message role: {role}"
)))
}
};
let wire_id = value
.get("id")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
let origin = match role {
Role::System => Origin::Prompt,
Role::Assistant => Origin::Assistant,
Role::Tool => Origin::Tool,
Role::User if wire_id.starts_with("runtime:") => Origin::Runtime,
Role::User
if wire_id.starts_with("request-context:")
|| wire_id.starts_with("selected-context:") =>
{
Origin::Prompt
}
Role::User => Origin::User,
};
let runtime_event_id = wire_id.strip_prefix("runtime:").map(str::to_string);
let content = match role {
Role::Assistant => decode_assistant(&value, &internal_id)?,
Role::Tool => MessageContent::ToolResult(decode_tool_result(&value)?),
_ => decode_text(&value)?,
};
let message_id = if runtime_event_id.is_some() {
wire_id
} else {
internal_id
};
Ok(CanonicalMessage {
message_id,
role,
origin,
content,
runtime_event_id,
})
}
pub fn decode_pending(value: &str) -> Result<RecoveredToolRound> {
let wire: Value = serde_json::from_str(value)?;
let started_at_ms = wire
.pointer("/providerOptions/cursor/pendingToolCallStartedAtMs")
.and_then(Value::as_u64)
.ok_or_else(|| {
Error::Protocol("Cursor pending assistant is missing pendingToolCallStartedAtMs".into())
})?;
let internal_id = format!(
"cursor-pending:{}",
BlobId::digest(value.as_bytes()).to_base64()
);
let message = decode(value.as_bytes(), internal_id.clone())?;
let MessageContent::Assistant {
text,
thinking,
tool_round_id: _,
replay_state,
tool_calls,
} = message.content
else {
return Err(Error::Protocol(
"Cursor pending message is not an assistant message".into(),
));
};
if tool_calls.is_empty() {
return Err(Error::Protocol(
"Cursor resume contains a pending assistant without tool calls".into(),
));
}
let model_call_id = wire
.pointer("/providerOptions/cursor/modelProviderMessageId")
.and_then(Value::as_str)
.filter(|value| !value.is_empty())
.unwrap_or(&internal_id)
.to_string();
let calls = tool_calls
.into_iter()
.enumerate()
.map(|(index, call)| {
Ok(ToolCall {
index,
call_id: call.call_id,
model_call_id: model_call_id.clone(),
name: call.name,
arguments_text: serde_json::to_string(&call.arguments)?,
arguments: call.arguments,
})
})
.collect::<Result<Vec<_>>>()?;
Ok(RecoveredToolRound {
assistant: ToolRoundAssistant {
text,
thinking,
model_call_id,
replay_state,
},
calls,
started_at_ms,
})
}
fn decode_text(value: &Value) -> Result<MessageContent> {
let content = value.get("content").unwrap_or(&Value::Null);
if let Some(text) = content.as_str() {
return Ok(MessageContent::Parts {
parts: vec![ContentPart::Text { text: text.into() }],
});
}
let parts = content
.as_array()
.ok_or_else(|| Error::Protocol("Cursor message content is not an array".into()))?
.iter()
.map(|part| match part.get("type").and_then(Value::as_str) {
Some("text") => Ok(ContentPart::Text {
text: required_string(part, "text")?.into(),
}),
Some("image") => {
let mime_type = required_string(part, "mimeType")?;
let encoded = required_string(part, "image")?;
Ok(ContentPart::Image {
mime_type: mime_type.into(),
data: STANDARD.decode(encoded).map_err(|error| {
Error::Protocol(format!("invalid Cursor image base64: {error}"))
})?,
})
}
Some(kind) => Err(Error::Protocol(format!(
"unsupported Cursor message content part: {kind}"
))),
None => Err(Error::Protocol(
"Cursor message content part is missing type".into(),
)),
})
.collect::<Result<Vec<_>>>()?;
Ok(MessageContent::Parts { parts })
}
fn decode_assistant(value: &Value, internal_id: &str) -> Result<MessageContent> {
let mut text = String::new();
let mut thinking = String::new();
let mut calls = Vec::new();
let mut replay_state = None;
for part in value
.get("content")
.and_then(Value::as_array)
.into_iter()
.flatten()
{
match part.get("type").and_then(Value::as_str) {
Some("text") => {
text.push_str(part.get("text").and_then(Value::as_str).unwrap_or_default())
}
Some("reasoning") => {
thinking.push_str(part.get("text").and_then(Value::as_str).unwrap_or_default());
if let Some(signature) = part.get("signature").and_then(Value::as_str) {
if replay_state.is_some() {
return Err(Error::Protocol(
"Cursor assistant has multiple reasoning signatures".into(),
));
}
replay_state = Some(decode_replay_state(signature)?);
}
}
Some("tool-call") => calls.push(ToolCallContent {
index: calls.len(),
call_id: required_string(part, "toolCallId")?.into(),
name: required_string(part, "toolName")?.into(),
arguments: part.get("args").cloned().unwrap_or(Value::Null),
}),
_ => {}
}
}
Ok(MessageContent::Assistant {
text,
thinking,
tool_round_id: (!calls.is_empty())
.then(|| ToolRoundId::new(format!("{internal_id}:tool-round"))),
replay_state,
tool_calls: calls,
})
}
fn decode_replay_state(signature: &str) -> Result<crate::model::ProviderReplayState> {
let Some(encoded) = signature.strip_prefix(REPLAY_ENVELOPE_PREFIX) else {
return Ok(crate::model::ProviderReplayState {
provider_kind: "cursor_opaque".into(),
value: Value::String(signature.into()),
});
};
let bytes = STANDARD.decode(encoded).map_err(|error| {
Error::Protocol(format!(
"invalid Cursor BYOK replay envelope base64: {error}"
))
})?;
serde_json::from_slice(&bytes)
.map_err(|error| Error::Protocol(format!("invalid Cursor BYOK replay envelope: {error}")))
}
fn decode_tool_result(value: &Value) -> Result<ToolResultContent> {
let part = value
.get("content")
.and_then(Value::as_array)
.and_then(|parts| parts.first())
.ok_or_else(|| Error::Protocol("Cursor tool message has no result part".into()))?;
Ok(ToolResultContent {
call_id: required_string(part, "toolCallId")?.into(),
name: required_string(part, "toolName")?.into(),
content: part
.get("result")
.and_then(Value::as_str)
.unwrap_or_default()
.into(),
is_error: part
.get("isError")
.and_then(Value::as_bool)
.unwrap_or(false),
image: None,
provider_parts: Vec::new(),
})
}
fn required_string<'a>(value: &'a Value, name: &str) -> Result<&'a str> {
value
.get(name)
.and_then(Value::as_str)
.ok_or_else(|| Error::Protocol(format!("Cursor message is missing {name}")))
}
+276
View File
@@ -0,0 +1,276 @@
use std::collections::HashSet;
use base64::{engine::general_purpose::STANDARD, Engine};
use serde_json::{json, Map, Value};
use crate::{
model::{
project_messages, CanonicalMessage, ContentPart, ProjectedContent, ProjectedMessage, Role,
ToolCall, ToolCallContent, ToolRoundAssistant,
},
Error, Result,
};
use super::REPLAY_ENVELOPE_PREFIX;
pub fn stable_messages(
instructions: &str,
messages: &[CanonicalMessage],
model: &str,
) -> Result<Vec<Vec<u8>>> {
let mut projected = project_messages(messages)?;
if !instructions.is_empty() {
projected.insert(
0,
ProjectedMessage {
message_id: "system".into(),
role: Role::System,
content: ProjectedContent::Parts(vec![ContentPart::Text {
text: instructions.into(),
}]),
},
);
}
projected
.iter()
.map(|message| serde_json::to_vec(&wire_message(message, model, None)?).map_err(Into::into))
.collect::<std::result::Result<_, _>>()
}
pub fn staged_tool_round(
assistant: &ToolRoundAssistant,
calls: &[ToolCall],
model: &str,
allowed_tools: &[String],
dynamic_tools: &HashSet<String>,
started_at_ms: u64,
) -> Result<String> {
let message = ProjectedMessage {
message_id: assistant.model_call_id.clone(),
role: Role::Assistant,
content: ProjectedContent::Assistant {
text: assistant.text.clone(),
thinking: assistant.thinking.clone(),
replay_state: assistant.replay_state.clone(),
calls: calls
.iter()
.map(|call| ToolCallContent {
index: call.index,
call_id: call.call_id.clone(),
name: call.name.clone(),
arguments: call.arguments.clone(),
})
.collect(),
},
};
Ok(serde_json::to_string(&wire_message(
&message,
model,
Some(PendingContext {
allowed_tools,
dynamic_tools,
started_at_ms,
}),
)?)?)
}
pub fn staged_final(
message: &CanonicalMessage,
model: &str,
allowed_tools: &[String],
dynamic_tools: &HashSet<String>,
started_at_ms: u64,
) -> Result<String> {
let projected = project_messages(std::slice::from_ref(message))?;
let assistant = projected
.first()
.filter(|message| message.role == Role::Assistant)
.ok_or_else(|| {
Error::Protocol("final checkpoint stage is not an assistant message".into())
})?;
Ok(serde_json::to_string(&wire_message(
assistant,
model,
Some(PendingContext {
allowed_tools,
dynamic_tools,
started_at_ms,
}),
)?)?)
}
#[derive(Clone, Copy)]
pub(super) struct PendingContext<'a> {
allowed_tools: &'a [String],
dynamic_tools: &'a HashSet<String>,
started_at_ms: u64,
}
pub(super) fn wire_message(
message: &ProjectedMessage,
model: &str,
pending: Option<PendingContext<'_>>,
) -> Result<Value> {
let mut root = Map::new();
root.insert(
"role".into(),
Value::String(role_name(&message.role).into()),
);
root.insert("content".into(), wire_content(&message.content, model)?);
root.insert("id".into(), Value::String(wire_message_id(message)));
if let ProjectedContent::Assistant { calls, .. } = &message.content {
let mut cursor = Map::new();
if let Some(pending) = pending {
cursor.insert(
"pendingToolCallStartedAtMs".into(),
json!(pending.started_at_ms),
);
cursor.insert(
"pendingToolExecutionContracts".into(),
Value::Object(
calls
.iter()
.map(|call| {
(
call.call_id.clone(),
json!({
"toolCallId": call.call_id,
"outerToolName": call.name,
"toolIdentifier": tool_identifier(&call.name, pending.dynamic_tools),
"isDynamic": pending.dynamic_tools.contains(&call.name),
"allowedToolNames": pending.allowed_tools,
}),
)
})
.collect(),
),
);
}
if !cursor.is_empty() {
root.insert("providerOptions".into(), json!({"cursor": cursor}));
}
}
Ok(Value::Object(root))
}
fn tool_identifier(name: &str, dynamic_tools: &HashSet<String>) -> String {
if dynamic_tools.contains(name) {
return name.into();
}
match name {
"AwaitShell" => "AWAIT".into(),
"CallMcpTool" | "SembleSearch" | "SembleFindRelated" => "MCP".into(),
"CreatePlan" => "CREATE_PLAN_V2".into(),
"UpdateCurrentStep" => "COMMUNICATE_UPDATE".into(),
_ => name
.chars()
.enumerate()
.fold(String::new(), |mut value, (index, character)| {
if index > 0 && character.is_ascii_uppercase() {
value.push('_');
}
value.push(character.to_ascii_uppercase());
value
}),
}
}
fn wire_message_id(message: &ProjectedMessage) -> String {
match &message.content {
ProjectedContent::Assistant { .. } => "1".into(),
ProjectedContent::ToolResult(result) => result.call_id.clone(),
ProjectedContent::Parts(_) => message.message_id.clone(),
}
}
fn wire_content(content: &ProjectedContent, model: &str) -> Result<Value> {
Ok(match content {
ProjectedContent::Parts(parts) => Value::Array(
parts
.iter()
.map(|part| match part {
ContentPart::Text { text } => json!({"type":"text", "text":text}),
ContentPart::Image { mime_type, data } => json!({
"type":"image",
"image": STANDARD.encode(data),
"mimeType": mime_type,
}),
})
.collect(),
),
ProjectedContent::Assistant {
text,
thinking,
replay_state,
calls,
} => {
let mut parts = Vec::new();
if !thinking.is_empty() || replay_state.is_some() {
let mut reasoning = json!({
"type": "reasoning",
"text": thinking,
"providerOptions": {"cursor": {"modelName": model}},
});
if let Some(replay_state) = replay_state {
reasoning["signature"] = Value::String(encode_replay_state(replay_state)?);
}
parts.push(reasoning);
}
if !text.is_empty() {
parts.push(json!({"type":"text", "text":text}));
}
parts.extend(calls.iter().map(|call| {
json!({
"type": "tool-call",
"toolCallId": call.call_id,
"toolName": call.name,
"args": call.arguments,
})
}));
Value::Array(parts)
}
ProjectedContent::ToolResult(result) => json!([{
"type": "tool-result",
"toolCallId": result.call_id,
"toolName": result.name,
"result": result.content,
"experimental_content": [{"type":"text", "text":result.content}],
"isError": result.is_error,
}]),
})
}
fn encode_replay_state(replay_state: &crate::model::ProviderReplayState) -> Result<String> {
if replay_state.provider_kind == "cursor_opaque" {
return replay_state
.value
.as_str()
.map(str::to_string)
.ok_or_else(|| Error::Protocol("Cursor opaque replay state is not a string".into()));
}
Ok(format!(
"{REPLAY_ENVELOPE_PREFIX}{}",
STANDARD.encode(serde_json::to_vec(replay_state)?)
))
}
fn role_name(role: &Role) -> &'static str {
match role {
Role::System => "system",
Role::User => "user",
Role::Assistant => "assistant",
Role::Tool => "tool",
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn direct_semble_tools_use_the_cursor_mcp_execution_contract() {
let dynamic = HashSet::new();
assert_eq!(tool_identifier("SembleSearch", &dynamic), "MCP");
assert_eq!(tool_identifier("SembleFindRelated", &dynamic), "MCP");
}
}
+10
View File
@@ -0,0 +1,10 @@
mod decode;
mod encode;
pub use decode::{decode, decode_pending};
pub use encode::{stable_messages, staged_final, staged_tool_round};
const REPLAY_ENVELOPE_PREFIX: &str = "cursor-byok:v1:";
#[cfg(test)]
mod tests;
+243
View File
@@ -0,0 +1,243 @@
use std::collections::HashSet;
use serde_json::{json, Value};
use crate::model::{
project_messages, CanonicalMessage, ContentPart, MessageContent, ProjectedContent,
ProjectedMessage, ProviderReplayState, Role, ToolCall, ToolResultContent, ToolRoundAssistant,
};
use super::{decode, decode_pending, encode::wire_message, staged_tool_round};
#[test]
fn pending_tool_round_is_one_complete_assistant_message_and_round_trips() {
let replay_state = ProviderReplayState {
provider_kind: "anthropic".into(),
value: json!({"blocks":[{"type":"thinking","thinking":"why","signature":"sig"}]}),
};
let assistant = ToolRoundAssistant {
text: "before tools".into(),
thinking: "why".into(),
model_call_id: "model-call".into(),
replay_state: Some(replay_state.clone()),
};
let calls = vec![
ToolCall {
index: 0,
call_id: "a".into(),
model_call_id: "model-call".into(),
name: "Read".into(),
arguments_text: r#"{"path":"/a"}"#.into(),
arguments: json!({"path":"/a"}),
},
ToolCall {
index: 1,
call_id: "b".into(),
model_call_id: "model-call".into(),
name: "Grep".into(),
arguments_text: r#"{"pattern":"x"}"#.into(),
arguments: json!({"pattern":"x"}),
},
];
let pending = staged_tool_round(
&assistant,
&calls,
"claude",
&["Read".into(), "Grep".into()],
&HashSet::new(),
42,
)
.unwrap();
let wire: Value = serde_json::from_str(&pending).unwrap();
assert_eq!(wire["id"], "1");
assert_eq!(
wire["providerOptions"]["cursor"]["pendingToolExecutionContracts"]["a"]["toolIdentifier"],
"READ"
);
assert_eq!(wire["role"], "assistant");
assert_eq!(
wire["providerOptions"]["cursor"]["pendingToolExecutionContracts"]
.as_object()
.unwrap()
.len(),
2
);
assert_eq!(
wire["content"]
.as_array()
.unwrap()
.iter()
.filter(|part| part["type"] == "tool-call")
.count(),
2
);
let recovered = decode_pending(&pending).unwrap();
assert_eq!(recovered.assistant.replay_state, Some(replay_state));
assert_eq!(recovered.calls.len(), 2);
assert_eq!(recovered.calls[0].call_id, "a");
assert_eq!(recovered.calls[1].call_id, "b");
}
#[test]
fn cursor_wire_ids_are_projection_metadata_not_internal_message_ids() {
let assistant = ProjectedMessage {
message_id: "internal-assistant-id".into(),
role: Role::Assistant,
content: ProjectedContent::Assistant {
text: "done".into(),
thinking: String::new(),
replay_state: None,
calls: Vec::new(),
},
};
let result = ProjectedMessage {
message_id: "internal-result-id".into(),
role: Role::Tool,
content: ProjectedContent::ToolResult(ToolResultContent {
call_id: "call-1".into(),
name: "Read".into(),
content: "ok".into(),
is_error: false,
image: None,
provider_parts: Vec::new(),
}),
};
assert_eq!(wire_message(&assistant, "model", None).unwrap()["id"], "1");
assert_eq!(
wire_message(&result, "model", None).unwrap()["id"],
"call-1"
);
}
#[test]
fn runtime_wire_identity_survives_checkpoint_hydration() {
let wire = json!({
"role": "user",
"id": "runtime:subagent-completed:child-id",
"content": "child completed",
});
let message = decode(
serde_json::to_vec(&wire).unwrap().as_slice(),
"cursor-root:blob-id:19".into(),
)
.unwrap();
assert_eq!(message.message_id, "runtime:subagent-completed:child-id");
assert_eq!(
message.runtime_event_id.as_deref(),
Some("subagent-completed:child-id")
);
}
#[test]
fn cursor_user_image_uses_image_field() {
let wire = json!({
"role": "user",
"id": "user-image",
"content": [
{"type":"text", "text":"look"},
{"type":"image", "image":"AQID", "mimeType":"image/png"},
],
});
let message = decode(
serde_json::to_vec(&wire).unwrap().as_slice(),
"cursor-root:user-image".into(),
)
.unwrap();
assert!(matches!(
&message.content,
MessageContent::Parts { parts }
if parts[1] == ContentPart::Image {
mime_type: "image/png".into(),
data: vec![1, 2, 3],
}
));
let projected = project_messages(&[message]).unwrap();
let encoded = wire_message(&projected[0], "model", None).unwrap();
assert_eq!(encoded["content"][1]["image"], "AQID");
assert!(encoded["content"][1].get("data").is_none());
}
#[test]
fn repeated_cursor_wire_ids_do_not_merge_distinct_tool_rounds() {
fn assistant(call_id: &str, internal_id: &str) -> CanonicalMessage {
let wire = json!({
"role": "assistant",
"id": "1",
"content": [{
"type": "tool-call",
"toolCallId": call_id,
"toolName": "Read",
"args": {"path": format!("/{call_id}")},
}],
});
decode(
serde_json::to_vec(&wire).unwrap().as_slice(),
internal_id.into(),
)
.unwrap()
}
fn result(call_id: &str, internal_id: &str) -> CanonicalMessage {
let wire = json!({
"role": "tool",
"id": call_id,
"content": [{
"type": "tool-result",
"toolCallId": call_id,
"toolName": "Read",
"result": "ok",
}],
});
decode(
serde_json::to_vec(&wire).unwrap().as_slice(),
internal_id.into(),
)
.unwrap()
}
let messages = vec![
assistant("a", "cursor-root:a"),
result("a", "cursor-root:a-result"),
assistant("b", "cursor-root:b"),
result("b", "cursor-root:b-result"),
];
assert_ne!(messages[0].message_id, messages[2].message_id);
let projected = project_messages(&messages).unwrap();
assert_eq!(projected.len(), 4);
assert!(matches!(
&projected[0].content,
ProjectedContent::Assistant { calls, .. } if calls[0].call_id == "a"
));
assert!(matches!(
&projected[2].content,
ProjectedContent::Assistant { calls, .. } if calls[0].call_id == "b"
));
}
#[test]
fn opaque_cursor_reasoning_signature_round_trips_without_decoding() {
let signature = "opaque-url-safe_signature-value";
let wire = json!({
"role": "assistant",
"id": "1",
"content": [{"type":"reasoning", "text":"", "signature":signature}],
});
let message = decode(
serde_json::to_vec(&wire).unwrap().as_slice(),
"cursor-root:opaque".into(),
)
.unwrap();
let MessageContent::Assistant { replay_state, .. } = &message.content else {
panic!("expected assistant");
};
assert_eq!(
replay_state.as_ref().unwrap().provider_kind,
"cursor_opaque"
);
let projected = project_messages(&[message]).unwrap();
let encoded = wire_message(&projected[0], "model", None).unwrap();
assert_eq!(encoded["content"][0]["signature"], signature);
}