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
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,17 @@ budget without editing the document. Failed or unsafe results stay executable.
New typing and text after the caret remain untouched; changed text supports
app-level undo, and logs contain metadata only.

Caret uncertainty waits for typing to resume. Backward movement within known
typing keeps the context. Forward movement of up to
`context.forward_movement_word_limit` words (default **5**) retains that context
and adds skipped text as read-only information. Corrections target each typed
span separately and preserve the skipped text. Longer moves run a final check
on eligible old typing, then continue with a fresh segment at the new caret.
Moving away from pending work cancels its old result and permits one final check
when the old span is still proved before the caret. A different field or an
unproved range re-anchors safely. Final checks use the configured engine, mode,
language, confidence, and app rules; text after the caret is never changed.

Local ML correction, suggestion acceptance, IME composition, and direct text API
or UI Automation mutation remain planned. App-level undo restores only recorded
corrections whose exact span and caret can still be verified.
Expand Down
33 changes: 25 additions & 8 deletions app-core-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -240,14 +240,31 @@ configured character budget, prefers configured sentence boundaries, and
preserves the configured minimum number of recent words when they fit. It never
edits or deletes target-application text. Backward movement within known typed
text keeps the executable context. Forward movement of at most the configured
word limit (five by default) keeps the context, adds skipped text to informative
context, and starts a fresh executable segment at the new caret. The old typed
suffix is discarded because it has not been verified at the new position.
Longer forward movement and
unmatched positions re-anchor at the new caret. A longer forward move requests
the final-fix security gate for the old executable text. Final fix remains
unavailable because the old caret cannot be safely targeted after movement. Pending
corrections are invalidated on movement. Runtime ticks delete sessions when
word limit (`context.forward_movement_word_limit`, five by default) retains the
same unchecked typing context. Read-only gaps stay separate from executable
text in `src/background/session/movement.rs`. A later character, word-count or
manual trigger checks the retained typed spans individually, in document order;
skipped text only informs those checks. Word thresholds exclude skipped words.
Retained span ownership is capped at 16 spans, and running requests obey the
configured pending queue size, including the default single slot. Capacity
refusal re-anchors rather than importing a gap into executable text.

Position uncertainty preserves the old context until nonempty typing resumes.
A longer forward move queues one final check per owned contiguous old span,
then starts a fresh active segment. Moving away before pending work applies
cancels its stale result and takes the same final-check route, even for a short
forward move. The existing pipeline validates policy, session ownership, input
generations, exact old text, skipped gaps and newer typing at the live caret.
Native replacement offsets the old span by that verified following text and
preserves gaps, new typing, the document suffix, clipboard and app-level undo.
Accepted corrected or no-change results retire old typing into informative
context. A failed or blocked final attempt preserves the original read-only
without another attempt or an undo record; failed ordinary retained work waits
for a later trigger. Final checks honor the configured engine, correction mode,
language and confidence policy. A different field, backward move into pending
text, ambiguous anchor or failed capture makes the complete old range ineligible
when it cannot be proved before the current caret; it re-anchors without mutation.
Runtime ticks delete sessions when
their owning process exits. All session state disappears on engine exit or
termination and is never written to disk. Session completion methods do not
themselves change target text; the replacement engine must confirm mutation first.
Expand Down
131 changes: 96 additions & 35 deletions app-core-rust/src/background/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ use self::{
process_group::SiblingDisappearanceMonitor,
replacement::ReplacementEngine,
security::{SecurityDecision, SecurityGate, TriggerKind},
session::{MovementResolution, SessionManager},
session::SessionManager,
shortcuts::{GlobalShortcutListener, ShortcutAction},
triggers::CorrectionRequest,
typing::MovementSignal,
Expand Down Expand Up @@ -516,6 +516,18 @@ impl InputProcessor {
self.session_manager
.deactivate(MovementSignal::UnknownPosition);
}
let stamp = Self::input_stamp();
if stamp.sequence == self.processed_input_sequence {
let requests = self
.session_manager
.active_mut()
.map_or_else(Vec::new, |session| {
session.movement_requests(None, &self.config)
});
for request in requests {
self.dispatch_trigger(request, stamp);
}
}
if let Some((event, manual)) = self.pipeline.take_feedback() {
self.feedback.event(event, manual, &self.config.feedback);
}
Expand Down Expand Up @@ -564,7 +576,13 @@ impl InputProcessor {
let generation = key.position_generation;
if generation != input_listener::current_position_generation() {
gate_result = None;
self.session_manager.deactivate(MovementSignal::FocusChange);
if key.window == 0 || key.window != target::active_window_handle_value() {
self.session_manager.deactivate(MovementSignal::FocusChange);
} else {
self.session_manager.input(typing::TypedInput::Uncertain(
MovementSignal::UnknownPosition,
));
}
continue;
}
last_key_generation = Some(generation);
Expand Down Expand Up @@ -620,6 +638,8 @@ impl InputProcessor {
}
let capture_sequence =
last_key_sequence.unwrap_or_else(input_listener::current_input_sequence);
self.pipeline
.invalidate(&mut self.session_manager, Self::input_stamp());
if self.session_manager.needs_movement_resolution() {
if let SecurityDecision::Allowed { target } =
SecurityGate::check(TriggerKind::Tracking, &self.config, &self.database)
Expand All @@ -636,17 +656,7 @@ impl InputProcessor {
)
},
) {
if let MovementResolution::Reanchor {
final_fix: Some(old),
} = self.session_manager.resolve_movement(preceding.as_deref())
{
if self.final_fix_before_reanchor_allowed(&self.database) {
tracing::info!(
typed_chars = old.chars().count(),
"smart final-fix eligible; old caret replacement unavailable after movement"
);
}
}
self.resolve_caret_movement(preceding.as_deref(), &mut pending_requests);
}
} else {
self.session_manager.deactivate(MovementSignal::FocusChange);
Expand Down Expand Up @@ -703,7 +713,7 @@ impl InputProcessor {
if pending.matches_session(session) {
let request = &mut pending.request;
if request.pending_segment_id.is_none() {
request.informative_context = session.informative_context().to_owned();
request.informative_context = session.correction_informative_context();
} else if let Some(prefix) = &captured_prefix {
request.informative_context.insert_str(0, prefix);
}
Expand Down Expand Up @@ -766,6 +776,7 @@ impl InputProcessor {
self.pipeline.cancel();
if let Some(session) = self.session_manager.active_mut() {
session.restore_pending();
session.retire_final_work(&self.config.context);
}
if let Some(session) = self.session_manager.active() {
let executable = session.editable_context();
Expand All @@ -776,7 +787,7 @@ impl InputProcessor {
|| {
context_capture::read_selection(
&target,
session.informative_context(),
&session.correction_informative_context(),
&executable,
&self.config.context,
)
Expand All @@ -797,13 +808,16 @@ impl InputProcessor {
}
if let Some(request) = triggers::manual(
session.id(),
session.informative_context(),
&session.correction_informative_context(),
&executable,
session.versions(),
&selected,
&self.config,
) {
self.dispatch_trigger(request, stamp);
let requests = self.manual_requests(request);
for request in requests {
self.dispatch_trigger(request, stamp);
}
} else if Self::input_stamp() == stamp {
self.feedback.event(
feedback::Event::Blocked,
Expand Down Expand Up @@ -863,11 +877,7 @@ impl InputProcessor {
}
return;
};
let known = format!(
"{}{}",
session.informative_context(),
session.executable_context()
);
let known = session.known_before_caret();
let Some(live) = context_capture::read_before_caret(
&target,
&self.config.context,
Expand Down Expand Up @@ -952,6 +962,35 @@ impl InputProcessor {
}
}

/// Update the typed session and retain trigger requests with their full scope.
fn resolve_caret_movement(
&mut self,
preceding: Option<&str>,
pending: &mut Vec<PendingTrigger>,
) {
let resumed = self
.session_manager
.active()
.and_then(|session| session.resumed_typing());
self.session_manager.resolve_movement(preceding);
if let Some(session) = self.session_manager.active_mut() {
for request in session.movement_requests(None, &self.config) {
pending.push(PendingTrigger {
editable_snapshot: request.executable_context.clone(),
request,
});
}
}
if let Some(inserted) = resumed {
let after = self
.session_manager
.active()
.map_or_else(String::new, |session| session.trigger_context());
let before = after.strip_suffix(&inserted).unwrap_or("").to_owned();
self.queue_automatic(&before, &inserted, pending);
}
}

/// Update the typed session and retain trigger requests with their full scope.
fn track_input(
&mut self,
Expand All @@ -961,26 +1000,43 @@ impl InputProcessor {
let before = self
.session_manager
.active()
.map(|session| session.editable_context());
.map(|session| session.trigger_context());
let inserted = match &input {
typing::TypedInput::Text(text) => Some(text.clone()),
_ => None,
};
let needs_capture = self.session_manager.input(input);
if let (Some(before), Some(inserted), Some(session)) =
(before, inserted, self.session_manager.active_mut())
{
if let (Some(before), Some(inserted)) = (before, inserted) {
self.queue_automatic(&before, &inserted, pending);
}
needs_capture
}

fn queue_automatic(&mut self, before: &str, inserted: &str, pending: &mut Vec<PendingTrigger>) {
if let Some(session) = self.session_manager.active_mut() {
if !session.position_uncertain() {
let editable_snapshot = session.editable_context();
let editable_snapshot = session.trigger_context();
if let Some(mut request) = triggers::automatic(
session.id(),
&before,
before,
&editable_snapshot,
&inserted,
inserted,
&session.correction_informative_context(),
session.versions(),
&self.config,
) {
if session.has_movement_context() {
session.reserve_movement_tail(Some(request.trigger));
for retained in
session.movement_requests(Some(request.trigger), &self.config)
{
pending.push(PendingTrigger {
editable_snapshot: retained.executable_context.clone(),
request: retained,
});
}
return;
}
// Freeze the entire current context, including earlier
// skipped boundaries. New keys belong to a fresh context.
let (segment, cancelled) = session.freeze_pending(&self.config.context);
Expand All @@ -1001,7 +1057,16 @@ impl InputProcessor {
}
}
}
needs_capture
}

/// Preserve disjoint retained ownership when a manual check spans a forward gap.
fn manual_requests(&mut self, request: CorrectionRequest) -> Vec<CorrectionRequest> {
let session = self.session_manager.active_mut().unwrap();
if request.selected_text || !session.has_movement_context() {
return vec![request];
}
session.reserve_movement_tail(Some(TriggerKind::ManualShortcut));
session.movement_requests(Some(TriggerKind::ManualShortcut), &self.config)
}

/// Recheck the focused target and trigger permission before routing.
Expand All @@ -1023,6 +1088,7 @@ impl InputProcessor {
if !dispatched {
if let (Some(id), Some(session)) = (segment_id, self.session_manager.active_mut()) {
if session.id() == session_id {
session.retire_final_pending(id, &self.config.context);
for cancelled in session.restore_pending_from(id) {
self.pipeline.cancel_segment(cancelled);
}
Expand Down Expand Up @@ -1181,11 +1247,6 @@ impl InputProcessor {
fn character_trigger_allowed(&self, database: &Database) -> bool {
self.security_allows(TriggerKind::Character, database)
}

#[allow(dead_code)]
fn final_fix_before_reanchor_allowed(&self, database: &Database) -> bool {
self.security_allows(TriggerKind::FinalFixBeforeReanchor, database)
}
}

fn initialize_logging() {
Expand Down
8 changes: 3 additions & 5 deletions app-core-rust/src/background/pipeline.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ impl ActiveRequest {
return !self.cancelled.load(Ordering::Acquire)
&& self.request.session_id == session.id()
&& self.stamp.permits(stamp, true)
&& session.pending_submitted(id)
&& session.pending_matches(id, &self.request.executable_context);
}
!self.cancelled.load(Ordering::Acquire)
Expand Down Expand Up @@ -586,11 +587,7 @@ impl CorrectionPipeline {
let known_before_caret = if active.request.selected_text {
format!("{}{}", active.request.informative_context, original)
} else {
format!(
"{}{}",
session.informative_context(),
session.executable_context()
)
session.known_before_caret()
};
let Some(live_before_caret) =
read_before_caret(&target, &active.request, known_before_caret.chars().count())
Expand Down Expand Up @@ -719,6 +716,7 @@ impl CorrectionPipeline {
}
if let (Some(id), Some(session)) = (segment_id, manager.active_mut()) {
if session.id() == active.request.session_id {
session.retire_final_pending(id, limits);
for cancelled in session.restore_pending_from(id) {
self.cancel_segment(cancelled);
}
Expand Down
13 changes: 3 additions & 10 deletions app-core-rust/src/background/pipeline/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ use std::{cell::Cell, sync::mpsc, time::Instant};

mod character;
mod manual;
mod movement;
mod word_count;

/// Build the runtime input owner for automatic-trigger flow tests.
Expand Down Expand Up @@ -742,11 +743,7 @@ fn delayed_frozen_corrections_keep_all_results_and_preserve_newer_typing() {
started_rx.recv_timeout(Duration::from_secs(2)).unwrap();
release_tx.send(()).unwrap();
wait_completion(&pipeline);
let live = format!(
"{}{}",
manager.active().unwrap().informative_context(),
manager.active().unwrap().executable_context()
);
let live = manager.active().unwrap().known_before_caret();
assert!(pipeline.finish(
&mut manager,
&config.context,
Expand Down Expand Up @@ -1226,11 +1223,7 @@ fn finish(
replaced: &Cell<usize>,
success: bool,
) -> bool {
let live = format!(
"{}{}",
manager.active().unwrap().informative_context(),
manager.active().unwrap().executable_context()
);
let live = manager.active().unwrap().known_before_caret();
pipeline.finish(
manager,
&config.context,
Expand Down
Loading
Loading