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
31 changes: 30 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1026,7 +1026,36 @@ jobs:
run: |
cargo test --locked -p openless-core --target-dir src-tauri/target --test prompt_contract
cargo test --locked -p openless-core --target-dir src-tauri/target --test dictation_target_capture
cargo test --locked -p openless-core --target-dir src-tauri/target --test selection_contract normal_selection_entry_serializes_full_input_and_rejects_incomplete_streams
(
selection_scratch=
selection_finished=false
cleanup_selection_contract() {
selection_status=$?
trap - EXIT
if [ -n "$selection_scratch" ]; then
if [ "$selection_finished" != true ]; then
printf '::warning::selection_contract termination unconfirmed; keeping scratch: %s\n' "$selection_scratch" >&2
if [ "$selection_status" -eq 0 ]; then selection_status=1; fi
elif ! rm -rf -- "$selection_scratch"; then
printf '::error::Failed to remove selection_contract scratch: %s\n' "$selection_scratch" >&2
if [ "$selection_status" -eq 0 ]; then selection_status=1; fi
fi
fi
exit "$selection_status"
}
trap cleanup_selection_contract EXIT
trap 'selection_finished=false; exit 130' INT
trap 'selection_finished=false; exit 143' TERM
trap 'selection_finished=false; exit 129' HUP
selection_scratch="$(mktemp -d "${RUNNER_TEMP:?}/selection-contract.XXXXXX")"
if TMPDIR="$selection_scratch" cargo test --locked -p openless-core --target-dir src-tauri/target --test selection_contract -- --test-threads=1; then
selection_status=0
else
selection_status=$?
fi
if [ "$selection_status" -lt 128 ]; then selection_finished=true; fi
exit "$selection_status"
)
cargo test --locked -p openless-core --target-dir src-tauri/target --test settings_field_updates
cargo test --locked -p openless-core --target-dir src-tauri/target --lib long_recording
cargo test --locked --manifest-path src-tauri/backend-tests/Cargo.toml --target-dir src-tauri/target --test clipboard_delivery
Expand Down
44 changes: 42 additions & 2 deletions openless-all/app/crates/openless-core/src/cloud_providers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1527,7 +1527,13 @@ async fn run_cloud_polish(
if let Some(error) = stream.take_error() {
return Err(error);
}
let polished = result.map_err(map_polish_error)?;
let polished = result.map_err(|error| {
if context.polish.selection_input {
map_selection_provider_error(error)
} else {
map_polish_error(error)
}
})?;
if cancellation.is_cancelled() {
return Err(cancelled_provider_error());
}
Expand Down Expand Up @@ -1976,6 +1982,34 @@ fn map_polish_error(error: crate::polish::LLMError) -> BackendError {
map_llm_error(error).retryable(transient)
}

/// The full selection is already durable before reaching a provider. A channel
/// capacity failure must stay explicit; never retry with a shortened original.
fn map_selection_provider_error(error: crate::polish::LLMError) -> BackendError {
let input_too_large = match &error {
crate::polish::LLMError::InvalidResponse { status, body }
if matches!(status, 400 | 413 | 422) =>
{
let body = body.to_ascii_lowercase();
*status == 413 || [
"context_length_exceeded",
"maximum context length",
"context window",
"input too long",
"input_too_long",
"input token count exceeds",
"request_too_large",
].iter().any(|marker| body.contains(marker))
}
_ => false,
};
if input_too_large {
let mut error = BackendError::new(BackendErrorCode::Provider, "selectionInputTooLarge");
error.details = Some(serde_json::json!({"original_saved": true}));
return error;
}
map_polish_error(error)
}

pub struct SharedAuxiliaryTextPolisher {
credentials: Arc<dyn CredentialStore>,
traditional: Arc<dyn TextPolisher>,
Expand Down Expand Up @@ -2420,7 +2454,13 @@ pub(crate) async fn polish_with_omni_text(
let polished = provider
.complete(&system_prompt, &user_prompt, None)
.await
.map_err(map_omni_error)?;
.map_err(|error| {
if context.polish.selection_input {
map_selection_provider_error(error)
} else {
map_omni_error(error)
}
})?;
let cleaned = crate::output_cleaning::clean_polish_output(&polished);
let text = if context.polish.translation_active {
crate::split_polish_translate_output(&cleaned)
Expand Down
58 changes: 58 additions & 0 deletions openless-all/app/crates/openless-core/src/domains.rs
Original file line number Diff line number Diff line change
Expand Up @@ -337,12 +337,70 @@ pub struct SelectionCapture {
pub source_app: Option<String>,
}

/// Core-issued authority for one capture request. Revocation survives a delayed
/// host call: an old request owns its own marker, not a bounded tombstone entry
/// or the host's current generation. It carries no native target or user text.
#[derive(Debug, Clone)]
pub struct SelectionCaptureAuthorization {
session_id: SessionId,
revoked: Arc<std::sync::atomic::AtomicBool>,
}

impl SelectionCaptureAuthorization {
pub(crate) fn new(session_id: SessionId) -> Self {
Self {
session_id,
revoked: Arc::new(std::sync::atomic::AtomicBool::new(false)),
}
}

pub fn allows(&self, session_id: SessionId) -> bool {
self.session_id == session_id
&& !self.revoked.load(std::sync::atomic::Ordering::Acquire)
}

/// Only Core revokes this marker, before publishing a terminal state or a
/// successor. No host code, callbacks, I/O or host locks run at this boundary.
pub(crate) fn revoke(&self) {
self.revoked.store(true, std::sync::atomic::Ordering::Release);
}
}

/// Platform seam for capturing and replacing the current selection.
///
/// The core owns the session and preview state. Implementations may retain an
/// opaque platform target internally, keyed by `SessionId`, but must never
/// expose native handles through this Interface.
pub trait SelectionRuntimeAdapter: Send + Sync {
/// Hosts with shared target registration must check this authority *inside*
/// their reservation lock, before invalidating another session or mutating
/// the registry. Do not call back into Core from that critical section.
/// The default preserves supplied-text/legacy hosts; it checks cancellation
/// around capture but does not claim to fence a host's shared registry.
fn capture_authorized(
&self,
session_id: SessionId,
supplied_text: Option<String>,
authorization: SelectionCaptureAuthorization,
) -> BoxFuture<'static, Result<SelectionCapture, BackendError>> {
if !authorization.allows(session_id) {
return Box::pin(async {
Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture revoked"))
});
}
let capture = self.capture(session_id, supplied_text);
Box::pin(async move {
if !authorization.allows(session_id) {
return Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture revoked"));
}
let result = capture.await;
if !authorization.allows(session_id) {
return Err(BackendError::new(BackendErrorCode::Cancelled, "selection capture revoked"));
}
result
})
}

fn capture(
&self,
session_id: SessionId,
Expand Down
29 changes: 29 additions & 0 deletions openless-all/app/crates/openless-core/src/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,35 @@ mod tests {
}
}

#[test]
fn legacy_selection_history_keeps_the_full_original_separate_from_the_result() {
let path = std::env::temp_dir().join(format!(
"openless-legacy-selection-{}.json", uuid::Uuid::new_v4()
));
let original = format!(" \t{} LEGACY_MIDDLE {}\n ", "字".repeat(9000), "尾".repeat(9000));
let mut row = session("legacy-selection", chrono::Utc::now().to_rfc3339());
row.source = HistorySource::SelectionPolish;
row.raw_transcript = original.clone();
row.final_text = "existing result".into();
let mut legacy = serde_json::to_value(&row).unwrap();
for field in ["asrTranscript", "polishSource", "pipelineMode", "hasAudioRecording"] {
legacy.as_object_mut().unwrap().remove(field);
}
let bytes = serde_json::to_vec(&vec![legacy]).unwrap();
std::fs::write(&path, &bytes).unwrap();
let store = HistoryStore::at_path(path.clone());
let mut read = store.list().unwrap().remove(0);
assert_eq!(read.raw_transcript, original);
assert_eq!(read.final_text, "existing result");
assert_eq!(std::fs::read(&path).unwrap(), bytes);
read.final_text = "new result".into();
store.update_entry(read).unwrap();
let read = store.list().unwrap();
assert_eq!(read[0].raw_transcript, original);
assert_eq!(read[0].final_text, "new result");
std::fs::remove_file(path).unwrap();
}

#[test]
fn legacy_quick_note_history_survives_read_and_append() {
let path = std::env::temp_dir().join(format!(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

mod diff;
mod observation;
pub mod target;
mod window;

pub use diff::{
Expand Down
36 changes: 36 additions & 0 deletions openless-all/app/crates/openless-core/src/host_document/target.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
//! Local target evidence shared by host integrations. Never include these tokens
//! in prompts or history: they identify a destination, not document context.

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostTargetIdentity {
pub process_id: u32,
/// Opaque, process-local token; not a native handle or a window title.
pub window_token: String,
/// Opaque token for the actual focused input control, not merely its app.
pub control_token: String,
pub selection: Option<HostSelectionRange>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct HostSelectionRange {
pub start: u64,
pub length: u64,
/// Offsets are native units. Consumers must not slice Rust strings using
/// these values (AX/Win32 use UTF-16; UIA may use provider text units).
pub unit: HostTextUnit,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostTextUnit {
Utf16,
Native,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostTargetValidation {
Current,
Unavailable,
TargetChanged,
PositionChanged,
Cancelled,
}
11 changes: 11 additions & 0 deletions openless-all/app/crates/openless-core/src/ports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@ pub struct CapturedTextTarget {
}

pub trait HostContextAdapter: Send + Sync {
/// Local destination evidence from capture time. This is deliberately kept
/// separate from HostContextCapture, whose text may be sent to a model.
fn target_identity(&self) -> Option<crate::host_document::target::HostTargetIdentity> {
None
}
/// Native checks may block; hosts must run them off the async worker.
fn validate_target(
&self,
) -> BoxFuture<'static, crate::host_document::target::HostTargetValidation> {
Box::pin(async { crate::host_document::target::HostTargetValidation::Unavailable })
}
/// Stable identity, when this adapter is attached to a frozen insertion target.
fn input_app(&self) -> Option<crate::app_style_routing::InputApp> {
None
Expand Down
Loading
Loading