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
4 changes: 2 additions & 2 deletions docs/word-prediction.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Word prediction

Word prediction is enabled by default in Scanning settings. Its five-position row appears only on the Letters page. Empty positions are skipped. Select the row and then a word using the existing switches. Acceptance appends the missing suffix and a space without deleting text, selecting text or using the clipboard. Shift and Caps affect completion casing; Ctrl, Alt/Option and Windows/Command suppress suggestions.
Word prediction is enabled by default in Scanning settings. Its five-position row appears only on the Letters page. Empty positions are skipped. Select the row and then a word using the existing switches. Acceptance appends the missing suffix and a space without selecting text or using the clipboard. It deletes nothing, with one bounded exception: when the word has a capital where a lowercase letter was typed, as in “lon” for London or “i” for I’m, it backspaces the typed prefix and types the whole word. Shift and Caps affect completion casing; Ctrl, Alt/Option and Windows/Command suppress suggestions.

Predictions use only a temporary buffer of successful Switchify keyboard input, starting with the first letter. Existing text, pasted text and hardware keyboard typing are never read into it. Switchify does not inspect fields, selections, passwords or caret positions. Suggestions may therefore appear anywhere the keyboard is open, including password fields or applications without a text field. The buffer records successful input injection; it cannot verify what an application actually accepted.

Expand All @@ -14,7 +14,7 @@ One Word prediction setting controls an offline SmolLM2-135M int8 ONNX model. Th

For a first typed prefix, a fixed local context keeps the model from favoring website names at the start of a document; it adds no user text. The model loads in the worker while keyboard input remains available. Suggestions are blank until loading finishes. A passive badge beside the scan prompt distinguishes loading, a ready keyboard awaiting typed context, no matching suggestions, available suggestions, paused activity tracking, and prediction failure. It never shows typed text and is not a scan target. If loading or inference fails, or a call exceeds 1.5 seconds, the keyboard continues accepting input and offers **Retry predictions** in its toolbar. Retry restarts only the prediction worker, clears its private text context, and leaves the keyboard open; type a new prefix afterward. A 400 ms search budget bounds candidate exploration. A clipped buffer with no complete earlier word yields no suggestions.

Candidates contain ASCII letters and apostrophes and must have sufficient model probability. There is no vocabulary filter: any word the model finds likely can be suggested, including swearing, because the person typing chose it. Single-letter candidates are limited to “a” and “I”. The pronoun I and its contractions, such as I’m and I’ll, are completed with a capital I; letters already typed stay as typed. Up to five suggestions are shown: the first, third and fifth are the most likely single words, and the second and fourth are the two most likely two-word phrases that begin with one of the top three words, ranked by the probability of the pair. When fewer phrases are found within an extra 200 ms, single words fill the remaining slots, and the other way round. Accepting a phrase inserts the rest of its first word, a space, the second word and a trailing space. Ordinary words use lowercase. Names keep the model's capital: mixed case anywhere, such as WhatsApp, or an initial capital mid-sentence that the model clearly prefers, such as London or Monday, which it does for proper nouns and occasionally a rare word. At a sentence start the model capitalises every word, so the lowercase form wins there and the sentence rule decides. Casing is applied when the keyboard displays a candidate, and the label shows exactly what will be inserted. A typed prefix of two or more letters, all capitals, is completed in capitals whatever the modifiers now say. Otherwise Caps, or Shift locked, uppercases the whole completion, and together they cancel as they do on typed letters. Before any letter of the word is typed, Shift once changes only the first letter, the way it would change the next typed letter, and a sentence start capitalises it without any modifier. The keyboard alone decides what a sentence start is: a full stop, exclamation or question mark it typed, not yet followed by a letter and not cancelled by pressing Shift. Punctuation the worker merely sees in its buffer, or the bare start of that buffer after a reset, does not capitalise anything, so a suggestion never disagrees with the keyboard's own automatic Shift. Shift once under Caps gives a lowercase first letter there, as it would on a typed letter. After typed letters, a pending Shift once is left for the next letter and does not touch the completion.
Candidates contain ASCII letters and apostrophes and must have sufficient model probability. There is no vocabulary filter: any word the model finds likely can be suggested, including swearing, because the person typing chose it. Single-letter candidates are limited to “a” and “I”. The pronoun I and its contractions, such as I’m and I’ll, are completed with a capital I. Accepting restores a capital the typed prefix lacks by retyping that prefix: the prefix is text Switchify typed itself in the current window with no outside activity since, it is never more than one word, and the executor refuses more than 32 deletions. A capital the person typed is kept, a word typed in capitals is never retyped, and when the case already matches nothing is deleted. The label always reads as the text will after acceptance. Any keyboard or mouse activity not made by Switchify between choosing the suggestion and typing it cancels the acceptance, so nothing else is deleted. Deleting and typing cannot be atomic: if typing fails after the deletion, the prefix is lost and prediction context resets. The deletion assumes one Backspace removes one typed character; an application that auto-pairs or autocorrects what was typed can break that, and Switchify cannot verify what an application accepted. Up to five suggestions are shown: the first, third and fifth are the most likely single words, and the second and fourth are the two most likely two-word phrases that begin with one of the top three words, ranked by the probability of the pair. When fewer phrases are found within an extra 200 ms, single words fill the remaining slots, and the other way round. Accepting a phrase inserts the rest of its first word, a space, the second word and a trailing space. Ordinary words use lowercase. Names keep the model's capital: mixed case anywhere, such as WhatsApp, or an initial capital mid-sentence that the model clearly prefers, such as London or Monday, which it does for proper nouns and occasionally a rare word. At a sentence start the model capitalises every word, so the lowercase form wins there and the sentence rule decides. Casing is applied when the keyboard displays a candidate, and the label shows exactly what will be inserted. A typed prefix of two or more letters, all capitals, is completed in capitals whatever the modifiers now say. Otherwise Caps, or Shift locked, uppercases the whole completion, and together they cancel as they do on typed letters. Before any letter of the word is typed, Shift once changes only the first letter, the way it would change the next typed letter, and a sentence start capitalises it without any modifier. The keyboard alone decides what a sentence start is: a full stop, exclamation or question mark it typed, not yet followed by a letter and not cancelled by pressing Shift. Punctuation the worker merely sees in its buffer, or the bare start of that buffer after a reset, does not capitalise anything, so a suggestion never disagrees with the keyboard's own automatic Shift. Shift once under Caps gives a lowercase first letter there, as it would on a typed letter. After typed letters, a pending Shift once is left for the next letter and does not touch the completion.

The model files are too large to commit. `npm run prediction-model` downloads them from a pinned upstream revision and verifies their SHA-256. The Tauri dev and build commands and CI run it automatically. Run it once before `cargo test` or `cargo clippy` in a fresh checkout.

Expand Down
2 changes: 1 addition & 1 deletion src-tauri/src/prediction/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ impl Predict for FakeModel {
) -> Result<Prediction, ()> {
let words: Vec<String> = ["water", "waffle", "walk", "WhatsApp"]
.into_iter()
.filter(|w| w.starts_with(&prefix.to_lowercase()))
.filter(|w| w.to_lowercase().starts_with(&prefix.to_lowercase()))
.map(str::to_owned)
.collect();
let phrases = words.iter().take(1).map(|w| format!("{w} is")).collect();
Expand Down
32 changes: 31 additions & 1 deletion src-tauri/src/prediction/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,9 @@ struct Service {
acknowledged_revision: u64,
reset: bool,
accept: Option<(u64, usize)>,
/// The activity epoch when the suggestion was chosen. A deletion needs it
/// unchanged and the observer healthy at the moment of injection.
accept_activity: (u64, bool),
accepting: bool,
case: Option<(worker::Shift, bool, bool, bool)>,
tracking: bool,
Expand Down Expand Up @@ -368,9 +371,19 @@ pub fn select(token: u64, index: usize) -> Result<(), String> {
return Err("Prediction is unavailable.".into());
}
s.accept = Some((token, index));
s.accept_activity = activity::snapshot();
Ok(())
})
}
/// Whether an accepted suggestion may delete typed characters. The worker
/// checked for outside input up to its reply; this covers the time since the
/// suggestion was chosen. Any keyboard or mouse activity not made by
/// Switchify, or an observer that cannot vouch for the interval, refuses the
/// deletion. Appending without deleting keeps its existing checks.
fn may_delete(backspaces: usize, chosen: (u64, bool), now: (u64, bool)) -> bool {
backspaces == 0 || (chosen.1 && now == chosen)
}

/// The model's config file; its directory is the model. A file rather than
/// the directory, so a half-copied bundle is not mistaken for a model.
fn resource(app: &AppHandle) -> Result<std::path::PathBuf, ()> {
Expand Down Expand Up @@ -463,6 +476,7 @@ pub fn poll(app: &AppHandle, keyboard: Option<&mut Keyboard>, enabled: bool, ign
}
Response::Insert {
generation,
backspaces,
text,
foreground,
} => {
Expand All @@ -474,12 +488,20 @@ pub fn poll(app: &AppHandle, keyboard: Option<&mut Keyboard>, enabled: bool, ign
if Some(scope.foreground) != foreground || !scope.unchanged() {
return Err(());
}
crate::scan_executor::prediction_text(&text).map_err(|_| ())?;
if !may_delete(backspaces, s.accept_activity, activity::snapshot())
{
return Err(());
}
crate::scan_executor::prediction_replace(backspaces, &text)
.map_err(|_| ())?;
if !scope.unchanged() {
return Err(());
}
let trailing_space = text.ends_with(' ');
let contains_letter = text.chars().any(char::is_alphabetic);
for _ in 0..backspaces {
s.queue_edit(Edit::Backspace, scope);
}
s.queue_edit(Edit::Append(text), scope);
Ok((trailing_space, contains_letter))
})
Expand Down Expand Up @@ -573,6 +595,14 @@ mod tests {
});
}
#[test]
fn deleting_needs_an_unbroken_watch_since_the_suggestion_was_chosen() {
assert!(may_delete(0, (3, false), (9, false)));
assert!(may_delete(2, (3, true), (3, true)));
assert!(!may_delete(2, (3, true), (4, true)));
assert!(!may_delete(2, (3, true), (3, false)));
assert!(!may_delete(2, (3, false), (3, false)));
}
#[test]
fn activity_observer_retries_after_failure_or_lost_hook() {
let state = AtomicU8::new(0);
assert!(claim_keyboard_activity_start(&state, false));
Expand Down
Loading
Loading