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
19 changes: 17 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,23 @@ runs. Editor automatic correction requires explicit trigger and prose opt-ins,
and a whole segment of recognizable line-comment prose. Terminal automatic
requests still skip because the shell context cannot be proven safe.
Existing permissions survive migration; the new editor prose permission starts
off. Selected results still skip native replacement until caret-end proof is
available, and manual-only rules do not enable continuous typed-input capture.
off. Selected correction requires both UI Automation and the native caret to
prove the selection ends at the caret. Manual-only rules do not enable
continuous typed-input capture.

The manual correction shortcut (default **Ctrl+Alt+Space**) checks security,
app rules, selection ownership and session validity before sending read-only
informative context and editable executable context to the selected engine.
Confidence policy controls whether the result applies, previews or skips.
Successful replacement changes only the proved executable span before the caret,
moves the corrected text into informative context, clears executable context,
records app-level undo and writes metadata without document text.

Selected text must belong to the current typed segment unless **Correct arbitrary
selection** is enabled under **Shortcuts**. Even with that option, backward
selections and selections without reliable caret proof skip correction. Text after
the caret stays untouched. Unchanged or suppressed selections retain their context
and selection; suggestion acceptance remains planned.

## Run App

Expand Down
31 changes: 23 additions & 8 deletions app-core-rust/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,15 @@ An outside or unreadable selection blocks
the shortcut by default. The `shortcuts.correct_arbitrary_selection` setting is
off by default; when enabled, a selected span outside the typed segment becomes
temporary executable context for that request, while text before and after it
stays informative. V1 discards selected results because it cannot prove which
selection end is the live caret.
stays informative. Selected correction requires TextPattern2 and a native caret
in the focused control. The provider caret and a TextPattern range at the native
caret must both equal the selection end; backward selections refuse correction.
Completion recaptures the selected text and its read-only anchors, and the native
replacement owner rechecks exact selection geometry before mutation. Successful
selection replacement establishes a collapsed caret, retires its preceding text
and corrected span into informative context, clears executable context and records
undo. Unselected text after the caret is never changed or promoted to executable
context. Unchanged and suppressed selections retain their original context.
App rules and the hard security gate are checked before routing. Application
policy must be readable: a failed app-rule read blocks capture and correction
for every trigger and engine, even if dictionary reads still work. A matching app
Expand Down Expand Up @@ -301,8 +308,8 @@ Uncertain languages and fragments skip. Editor automatic requests additionally
require their trigger permission and complete `//` or `#` line-comment sentences;
inline/block comments are unsupported. Terminal automatic text requests skip
because the shell dialect and prompt state are unknown. Manual-only rules never
authorize tracking or final-fix triggers. Selected results retain the existing
native replacement refusal until the live caret end can be proven.
authorize tracking or final-fix triggers. Selected results require the same
independently verified caret-end proof as ordinary selected correction.

Admission reads app rules through a fresh, nonblocking read-only connection without
migrations or writer reservations. API sends and native replacement recheck the
Expand Down Expand Up @@ -337,9 +344,10 @@ Before a changed result reaches replacement, completion also requires a stable
focused control identity and a fresh read-only TextPattern capture. The entire
known session region must match exactly at the live caret, including text typed
after a frozen segment. Missing captures or mismatches discard the result; no
fuzzy search or replacement is attempted. Selected-text results are discarded
because their replacement range cannot be proven before the caret, even when
arbitrary selected-text correction is enabled.
fuzzy search or replacement is attempted. Selected-text results require a fresh
exact selection capture with native caret-end proof. Arbitrary-selection opt-in
changes only ownership admission; it never relaxes security, confidence, geometry
or post-caret protection.
Failed, suppressed, or refused frozen results release their slot and restore the
original text and dependent newer segments to active executable context. Their
queued requests are cancelled so a later trigger can check the combined text in
Expand All @@ -363,11 +371,18 @@ manual override, stale and reordered results, queued input,
secure targets, failed replacement, selection boundaries, and commit/undo after
confirmed replacement.

Every successful changed commit writes the same metadata-only correction event
as accepted no-change commits, including trigger, engine, confidence, replacement
method, result reason and latency. Document text and engine response details are
excluded even when full-text debug logging is enabled. Busy or unavailable storage
skips persistence without delaying input processing or losing the committed undo.

The replacement feature lives in `src/background/replacement`. Its strategy
interface tries direct text APIs, UI Automation replacement, clipboard paste,
then SendInput. Direct APIs/TSF and UI Automation mutation currently report
unavailable and can be implemented progressively. UI Automation TextPattern
must first prove a collapsed caret, the exact executable span and any newer
must first prove a collapsed caret (or a selection ending at the native caret),
the exact executable span and any newer
typed text between that span and the caret. Only that span is selected; text
after the original caret remains untouched. Missing or unreliable providers
refuse replacement rather than guessing a keystroke distance.
Expand Down
96 changes: 96 additions & 0 deletions app-core-rust/src/background/context_capture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ fn selected_executable_prefix<'a>(
found
}

#[derive(Debug)]
pub(super) enum SelectionCapture {
NoSelection,
Selected {
Expand All @@ -106,6 +107,100 @@ pub(super) enum SelectionCapture {

const MAX_SELECTED_CHARS: i32 = 4096;

/// A selection is editable only when its active caret is at the range end.
/// TextPattern's sorted endpoints alone cannot establish selection direction.
#[cfg(windows)]
pub(super) unsafe fn selected_caret(
element: &windows::Win32::UI::Accessibility::IUIAutomationElement,
selection: &windows::Win32::UI::Accessibility::IUIAutomationTextRange,
) -> windows::core::Result<windows::Win32::UI::Accessibility::IUIAutomationTextRange> {
use windows::Win32::UI::Accessibility::{
IUIAutomationTextPattern2, TextPatternRangeEndpoint_End as END,
TextPatternRangeEndpoint_Start as START, UIA_TextPattern2Id,
};
let pattern: IUIAutomationTextPattern2 = element.GetCurrentPatternAs(UIA_TextPattern2Id)?;
let mut active = windows::core::BOOL::default();
let caret = pattern.GetCaretRange(&mut active)?;
// Some native Edit providers report the sorted selection end for either
// direction. Independently locate the real system caret in this control.
use windows_sys::Win32::UI::WindowsAndMessaging::{
GetGUIThreadInfo, GetWindowThreadProcessId, GUITHREADINFO,
};
let window = element.CurrentNativeWindowHandle()?.0;
let mut process = 0;
let thread = GetWindowThreadProcessId(window as _, &mut process);
let mut info: GUITHREADINFO = std::mem::zeroed();
info.cbSize = std::mem::size_of::<GUITHREADINFO>() as u32;
let unavailable =
|| windows::core::Error::from_hresult(windows::core::HRESULT(0x80004005u32 as i32));
if window.is_null()
|| thread == 0
|| process != element.CurrentProcessId()? as u32
|| GetGUIThreadInfo(thread, &mut info) == 0
|| !std::ptr::eq(info.hwndFocus, window)
|| !std::ptr::eq(info.hwndCaret, window)
{
return Err(unavailable());
}
let mut point = windows_sys::Win32::Foundation::POINT {
x: info.rcCaret.left,
y: info.rcCaret.top + (info.rcCaret.bottom - info.rcCaret.top) / 2,
};
if windows_sys::Win32::Graphics::Gdi::ClientToScreen(info.hwndCaret, &mut point) == 0 {
return Err(unavailable());
}
let native_caret = pattern.RangeFromPoint(windows::Win32::Foundation::POINT {
x: point.x,
y: point.y,
})?;
if !active.as_bool()
|| caret.CompareEndpoints(START, &caret, END)? != 0
|| caret.CompareEndpoints(END, selection, END)? != 0
|| native_caret.CompareEndpoints(START, &native_caret, END)? != 0
|| native_caret.CompareEndpoints(END, selection, END)? != 0
{
return Err(windows::core::Error::from_hresult(windows::core::HRESULT(
0x80004005u32 as i32,
)));
}
Ok(caret)
}

/// Completion rechecks the exact selected span and both read-only anchors.
pub(super) fn read_correction_context(
target: &FocusedTarget,
request: &super::triggers::CorrectionRequest,
limits: &ContextConfig,
known_chars: usize,
) -> Option<String> {
if !request.selected_text {
return read_before_caret(target, limits, known_chars);
}
let mut capture_limits = limits.clone();
capture_limits.informative_context_max_chars = capture_limits
.informative_context_max_chars
.max(request.following_context.chars().count() as u32);
match read_selection(
target,
&request.informative_context,
&request.executable_context,
&capture_limits,
) {
SelectionCapture::Selected {
text,
preceding,
following,
..
} if text == request.executable_context
&& preceding.ends_with(&request.informative_context)
&& following.starts_with(&request.following_context) =>
{
Some(format!("{preceding}{text}"))
}
_ => None,
}
}

fn capture_char_limit(limits: &ContextConfig, known_typed_chars: usize) -> i32 {
(limits.informative_context_max_chars as usize)
.saturating_add(known_typed_chars)
Expand Down Expand Up @@ -262,6 +357,7 @@ pub(super) fn read_selection(
if selected.is_empty() || selected.chars().count() > MAX_SELECTED_CHARS as usize {
return None;
}
selected_caret(&element, &selection).ok()?;
let selection_at_document_start =
pattern.DocumentRange().ok().is_some_and(|document| {
selection
Expand Down
9 changes: 7 additions & 2 deletions app-core-rust/src/background/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -468,8 +468,13 @@ impl InputProcessor {
SecurityDecision::Allowed { target } if config.correction.enabled => Some(target),
_ => None,
},
|target, known_chars| {
context_capture::read_before_caret(target, &config.context, known_chars)
|target, request, known_chars| {
context_capture::read_correction_context(
target,
request,
&config.context,
known_chars,
)
},
|target, request, output| {
let Some(_policy_guard) = SecurityGate::authorize_correction_replacement(
Expand Down
Loading
Loading