A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Preserve Flow drafts and history when disk writes fail
Anatoly Lazarevbb7ee21d7329
diff --git a/CLAUDE.md b/CLAUDE.mdindex e0d51a02..825a3bbf 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -18,6 +18,8 @@ cd NotchBuddy && xcodegen && xcodebuild -scheme NotchBuddy -configuration DebugTo run it day to day on the Mac (signed, iPhone link, permissions kept across builds): `./scripts/dev-install.sh` — it installs the only Coucou in /Applications and removes the copies earlier builds left.Windows and Linux: `cd windows && npm install && npm run tauri dev`+Flow dictionary, snippet, style and history mutations report native write failures. Commit in-memory edits only after disk replacement succeeds; retain drafts and destructive-action confirmation on failure so the user can retry. History and statistics erase is sequential and reports partial completion.+## Rules- Swift 6, SwiftUI + AppKit. No third-party dependencies unless truly unavoidable. The character is drawn in code (`Canvas` + `TimelineView`), no Rive/Lottie/images.- Secrets live in the Keychain, never on disk or in git.diff --git a/windows/screenshots/flow-save-error.jpg b/windows/screenshots/flow-save-error.jpgnew file mode 100644index 00000000..6a4ce2c9Binary files /dev/null and b/windows/screenshots/flow-save-error.jpg differdiff --git a/windows/src-tauri/src/flow/mod.rs b/windows/src-tauri/src/flow/mod.rsindex 894a954c..d2ce59e5 100644--- a/windows/src-tauri/src/flow/mod.rs+++ b/windows/src-tauri/src/flow/mod.rs@@ -514,17 +514,17 @@ pub fn flow_history(flow: State<Arc<Flow>>) -> Vec<Entry> {}#[tauri::command]-pub fn flow_delete(flow: State<Arc<Flow>>, id: String) {- flow.store.lock().unwrap().delete(&id);+pub fn flow_delete(flow: State<Arc<Flow>>, id: String) -> Result<(), String> {+ flow.store.lock().unwrap().delete(&id)}#[tauri::command]-pub fn flow_clear(flow: State<Arc<Flow>>, everything: bool) {+pub fn flow_clear(flow: State<Arc<Flow>>, everything: bool) -> Result<(), String> {let mut store = flow.store.lock().unwrap();if everything {- store.clear_everything();+ store.clear_everything()} else {- store.clear_history();+ store.clear_history()}}@@ -588,10 +588,8 @@ pub fn flow_words(flow: State<Arc<Flow>>) -> Words {}#[tauri::command]-pub fn flow_set_words(flow: State<Arc<Flow>>, words: Words) {- let mut store = flow.store.lock().unwrap();- store.words = words;- store.save_words();+pub fn flow_set_words(flow: State<Arc<Flow>>, words: Words) -> Result<(), String> {+ flow.store.lock().unwrap().set_words(words)}#[tauri::command]@@ -600,10 +598,8 @@ pub fn flow_snippets(flow: State<Arc<Flow>>) -> Vec<Snippet> {}#[tauri::command]-pub fn flow_set_snippets(flow: State<Arc<Flow>>, snippets: Vec<Snippet>) {- let mut store = flow.store.lock().unwrap();- store.snippets = snippets;- store.save_snippets();+pub fn flow_set_snippets(flow: State<Arc<Flow>>, snippets: Vec<Snippet>) -> Result<(), String> {+ flow.store.lock().unwrap().set_snippets(snippets)}#[tauri::command]@@ -612,10 +608,8 @@ pub fn flow_styles(flow: State<Arc<Flow>>) -> Vec<AppStyle> {}#[tauri::command]-pub fn flow_set_styles(flow: State<Arc<Flow>>, styles: Vec<AppStyle>) {- let mut store = flow.store.lock().unwrap();- store.app_styles = styles;- store.save_styles();+pub fn flow_set_styles(flow: State<Arc<Flow>>, styles: Vec<AppStyle>) -> Result<(), String> {+ flow.store.lock().unwrap().set_styles(styles)}#[derive(Serialize, Deserialize)]diff --git a/windows/src-tauri/src/flow/store.rs b/windows/src-tauri/src/flow/store.rsindex 99b38f22..749d25bd 100644--- a/windows/src-tauri/src/flow/store.rs+++ b/windows/src-tauri/src/flow/store.rs@@ -128,7 +128,7 @@ impl Default for Prefs {}}-#[derive(Debug, Clone, Default, Serialize, Deserialize)]+#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]pub struct Words {pub words: Vec<String>,pub replacements: Vec<Replacement>,@@ -211,15 +211,16 @@ impl Store {store}+ fn write<T: Serialize>(&self, value: &T, name: &str) -> std::io::Result<()> {+ crate::platform::ensure_private_dir(&self.folder)?;+ let text = serde_json::to_string_pretty(value).map_err(std::io::Error::other)?;+ let tmp = self.folder.join(format!("{name}.tmp"));+ std::fs::write(&tmp, text)?;+ std::fs::rename(&tmp, self.folder.join(name))+ }+fn save<T: Serialize>(&self, value: &T, name: &str) {- let write = || -> std::io::Result<()> {- crate::platform::ensure_private_dir(&self.folder)?;- let text = serde_json::to_string_pretty(value).map_err(std::io::Error::other)?;- let tmp = self.folder.join(format!("{name}.tmp"));- std::fs::write(&tmp, text)?;- std::fs::rename(&tmp, self.folder.join(name))- };- if let Err(err) = write() {+ if let Err(err) = self.write(value, name) {crate::log::line(format!("flow: could not save {name}: {err}"));}}@@ -227,14 +228,20 @@ impl Store {pub fn save_prefs(&self) {self.save(&self.prefs, "prefs.json");}- pub fn save_words(&self) {- self.save(&self.words, "words.json");+ pub fn set_words(&mut self, words: Words) -> Result<(), String> {+ self.write(&words, "words.json").map_err(|e| format!("Could not save dictionary: {e}"))?;+ self.words = words;+ Ok(())}- pub fn save_snippets(&self) {- self.save(&self.snippets, "snippets.json");+ pub fn set_snippets(&mut self, snippets: Vec<Snippet>) -> Result<(), String> {+ self.write(&snippets, "snippets.json").map_err(|e| format!("Could not save snippets: {e}"))?;+ self.snippets = snippets;+ Ok(())}- pub fn save_styles(&self) {- self.save(&self.app_styles, "styles.json");+ pub fn set_styles(&mut self, styles: Vec<AppStyle>) -> Result<(), String> {+ self.write(&styles, "styles.json").map_err(|e| format!("Could not save app styles: {e}"))?;+ self.app_styles = styles;+ Ok(())}fn save_history(&self) {self.save(&self.history, "history.json");@@ -283,23 +290,30 @@ impl Store {Some(entry)}- pub fn delete(&mut self, id: &str) {- self.history.retain(|e| e.id != id);- self.save_history();+ fn set_history(&mut self, history: Vec<Entry>) -> Result<(), String> {+ self.write(&history, "history.json").map_err(|e| format!("Could not update dictation history: {e}"))?;+ self.history = history;+ Ok(())+ }++ pub fn delete(&mut self, id: &str) -> Result<(), String> {+ self.set_history(self.history.iter().filter(|e| e.id != id).cloned().collect())}/// Empties the history; the numbers stay.- pub fn clear_history(&mut self) {- self.history.clear();+ pub fn clear_history(&mut self) -> Result<(), String> {+ self.set_history(Vec::new())?;self.last_unkept = None;- self.save_history();+ Ok(())}/// Empties the history and the numbers.- pub fn clear_everything(&mut self) {- self.clear_history();- self.stats = Stats::default();- self.save_stats();+ pub fn clear_everything(&mut self) -> Result<(), String> {+ self.clear_history()?;+ let stats = Stats::default();+ self.write(&stats, "stats.json").map_err(|e| format!("History erased; could not erase statistics: {e}"))?;+ self.stats = stats;+ Ok(())}pub fn prune(&mut self, now: u64) {@@ -344,6 +358,183 @@ mod tests {(Store::load_from(dir.clone()), dir)}+ #[test]+ fn dictionary_edits_are_durable_and_failed_writes_keep_the_live_and_saved_words() {+ let (mut store, path) = temp_store();+ let words = Words { words: vec!["Coucou".into()], replacements: vec![+ Replacement { id: "one".into(), from: "cloud code".into(), to: "Claude Code".into() },+ ] };+ store.set_words(words.clone()).unwrap();+ assert_eq!(Store::load_from(path.clone()).words, words);+ let before = std::fs::read(path.join("words.json")).unwrap();+ std::fs::create_dir(path.join("words.json.tmp")).unwrap();+ assert!(store.set_words(Words::default()).is_err());+ assert_eq!(store.words, words);+ assert_eq!(std::fs::read(path.join("words.json")).unwrap(), before);+ assert_eq!(store.prepare("coucou cloud code").text, "Coucou Claude Code");+ std::fs::remove_dir(path.join("words.json.tmp")).unwrap();+ store.set_words(Words::default()).unwrap();+ assert_eq!(Store::load_from(path.clone()).words, Words::default());+ std::fs::remove_file(path.join("words.json")).unwrap();+ std::fs::remove_dir(path).unwrap();+ }++ #[test]+ fn snippet_edits_are_durable_and_failed_writes_keep_the_live_and_saved_snippets() {+ let (mut store, path) = temp_store();+ let snippets = vec![Snippet { id: "one".into(), trigger: "signature".into(), text: "Hello world".into() }];+ store.set_snippets(snippets.clone()).unwrap();+ assert_eq!(Store::load_from(path.clone()).snippets, snippets);+ let before = std::fs::read(path.join("snippets.json")).unwrap();+ std::fs::create_dir(path.join("snippets.json.tmp")).unwrap();+ assert!(store.set_snippets(vec![]).is_err());+ assert_eq!(store.snippets, snippets);+ assert_eq!(std::fs::read(path.join("snippets.json")).unwrap(), before);+ assert_eq!(store.prepare("signature").snippets.values().next().unwrap(), "Hello world");+ std::fs::remove_dir(path.join("snippets.json.tmp")).unwrap();+ store.set_snippets(vec![]).unwrap();+ assert!(Store::load_from(path.clone()).snippets.is_empty());+ std::fs::remove_file(path.join("snippets.json")).unwrap();+ std::fs::remove_dir(path).unwrap();+ }++ #[test]+ fn style_edits_are_durable_and_failed_writes_keep_the_live_and_saved_styles() {+ let (mut store, path) = temp_store();+ let styles = vec![AppStyle { id: "mail".into(), name: "Mail".into(), style: Style::Polished }];+ store.set_styles(styles.clone()).unwrap();+ assert_eq!(Store::load_from(path.clone()).app_styles, styles);+ let before = std::fs::read(path.join("styles.json")).unwrap();+ std::fs::create_dir(path.join("styles.json.tmp")).unwrap();+ assert!(store.set_styles(vec![]).is_err());+ assert_eq!(store.app_styles, styles);+ assert_eq!(std::fs::read(path.join("styles.json")).unwrap(), before);+ assert_eq!(store.style_for(Some("mail")), Style::Polished);+ std::fs::remove_dir(path.join("styles.json.tmp")).unwrap();+ store.set_styles(vec![]).unwrap();+ assert!(Store::load_from(path.clone()).app_styles.is_empty());+ std::fs::remove_file(path.join("styles.json")).unwrap();+ std::fs::remove_dir(path).unwrap();+ }++ #[cfg(target_os = "windows")]+ #[test]+ fn locked_editor_files_reject_replacement_without_changing_live_values() {+ use std::os::windows::fs::OpenOptionsExt;+ let (mut store, path) = temp_store();+ store.set_words(Words::default()).unwrap();+ store.set_snippets(vec![]).unwrap();+ store.set_styles(vec![]).unwrap();+ let locks: Vec<_> = ["words", "snippets", "styles"].iter().map(|name|+ std::fs::OpenOptions::new().read(true).share_mode(0).open(path.join(format!("{name}.json"))).unwrap()+ ).collect();+ assert!(store.set_words(Words { words: vec!["unsaved".into()], replacements: vec![] }).is_err());+ assert!(store.set_snippets(vec![Snippet { id: "one".into(), trigger: "unsaved".into(), text: "unsaved".into() }]).is_err());+ assert!(store.set_styles(default_app_styles()).is_err());+ assert!(store.words.words.is_empty());+ assert!(store.snippets.is_empty());+ assert!(store.app_styles.is_empty());+ drop(locks);+ let again = Store::load_from(path.clone());+ assert!(again.words.words.is_empty());+ assert!(again.snippets.is_empty());+ assert!(again.app_styles.is_empty());+ for name in ["words", "snippets", "styles"] {+ std::fs::remove_file(path.join(format!("{name}.json"))).unwrap();+ std::fs::remove_file(path.join(format!("{name}.json.tmp"))).unwrap();+ }+ std::fs::remove_dir(path).unwrap();+ }++ #[test]+ fn failed_history_deletion_keeps_live_and_saved_entries_until_retry() {+ let (mut store, path) = temp_store();+ let entry = store.record("saved dictation", None, 1.0, today(), now_ms()).unwrap();+ let before = std::fs::read(path.join("history.json")).unwrap();+ std::fs::create_dir(path.join("history.json.tmp")).unwrap();+ assert!(store.delete(&entry.id).is_err());+ assert_eq!(store.history.len(), 1);+ assert_eq!(store.history[0].id, entry.id);+ assert_eq!(std::fs::read(path.join("history.json")).unwrap(), before);+ std::fs::remove_dir(path.join("history.json.tmp")).unwrap();+ store.delete(&entry.id).unwrap();+ assert!(store.history.is_empty());+ assert!(Store::load_from(path.clone()).history.is_empty());+ assert_eq!(store.totals(None).0, 2);+ for name in ["history.json", "stats.json"] { std::fs::remove_file(path.join(name)).unwrap(); }+ std::fs::remove_dir(path).unwrap();+ }++ #[test]+ fn failed_history_clear_keeps_the_last_dictation_and_statistics() {+ let (mut store, path) = temp_store();+ store.record("saved dictation", None, 1.0, today(), now_ms()).unwrap();+ store.last_unkept = Some("memory dictation".into());+ std::fs::create_dir(path.join("history.json.tmp")).unwrap();+ assert!(store.clear_everything().is_err());+ assert_eq!(store.history.len(), 1);+ assert_eq!(store.last_unkept.as_deref(), Some("memory dictation"));+ assert_eq!(store.totals(None).0, 2);+ let again = Store::load_from(path.clone());+ assert_eq!(again.history.len(), 1);+ assert_eq!(again.totals(None).0, 2);+ std::fs::remove_dir(path.join("history.json.tmp")).unwrap();+ store.clear_history().unwrap();+ assert!(store.history.is_empty());+ assert!(store.last_unkept.is_none());+ assert_eq!(store.totals(None).0, 2);+ for name in ["history.json", "stats.json"] { std::fs::remove_file(path.join(name)).unwrap(); }+ std::fs::remove_dir(path).unwrap();+ }++ #[test]+ fn a_failed_statistics_erase_keeps_live_and_saved_counts_and_can_be_retried() {+ let (mut store, path) = temp_store();+ store.record("saved dictation", None, 1.0, today(), now_ms()).unwrap();+ std::fs::create_dir(path.join("stats.json.tmp")).unwrap();+ assert!(store.clear_everything().unwrap_err().contains("History erased; could not erase statistics"));+ // History is already durably erased; the statistics remain until their write succeeds.+ assert!(store.history.is_empty());+ assert_eq!(store.totals(None).0, 2);+ let again = Store::load_from(path.clone());+ assert!(again.history.is_empty());+ assert_eq!(again.totals(None).0, 2);+ std::fs::remove_dir(path.join("stats.json.tmp")).unwrap();+ store.clear_everything().unwrap();+ assert_eq!(store.totals(None).0, 0);+ assert_eq!(Store::load_from(path.clone()).totals(None).0, 0);+ for name in ["history.json", "stats.json"] { std::fs::remove_file(path.join(name)).unwrap(); }+ std::fs::remove_dir(path).unwrap();+ }++ #[cfg(target_os = "windows")]+ #[test]+ fn locked_history_and_statistics_files_report_failed_replacements() {+ use std::os::windows::fs::OpenOptionsExt;+ let (mut store, path) = temp_store();+ let entry = store.record("saved dictation", None, 1.0, today(), now_ms()).unwrap();+ let history_lock = std::fs::OpenOptions::new().read(true).share_mode(0).open(path.join("history.json")).unwrap();+ assert!(store.delete(&entry.id).is_err());+ assert!(store.clear_everything().is_err());+ assert_eq!(store.history.len(), 1);+ assert_eq!(store.totals(None).0, 2);+ drop(history_lock);+ assert_eq!(Store::load_from(path.clone()).history.len(), 1);++ let stats_lock = std::fs::OpenOptions::new().read(true).share_mode(0).open(path.join("stats.json")).unwrap();+ assert!(store.clear_everything().unwrap_err().contains("History erased; could not erase statistics"));+ assert!(store.history.is_empty());+ assert_eq!(store.totals(None).0, 2);+ drop(stats_lock);+ assert_eq!(Store::load_from(path.clone()).totals(None).0, 2);+ store.clear_everything().unwrap();+ let again = Store::load_from(path.clone());+ assert!(again.history.is_empty());+ assert_eq!(again.totals(None).0, 0);+ for name in ["history.json", "stats.json"] { std::fs::remove_file(path.join(name)).unwrap(); }+ std::fs::remove_dir(path).unwrap();+ }+#[test]fn a_dictation_counts_and_is_kept_for_the_chosen_days() {let (mut s, dir) = temp_store();diff --git a/windows/src/core/flow.ts b/windows/src/core/flow.tsindex 8464e65a..ae619b50 100644--- a/windows/src/core/flow.ts+++ b/windows/src/core/flow.ts@@ -188,15 +188,15 @@ export const FlowBridge = {hubShown: () => call<boolean>("hub_shown"),setPrefs: (prefs: FlowPrefs) => call<void>("flow_set_prefs", { prefs }),history: () => call<FlowEntry[]>("flow_history"),- deleteEntry: (id: string) => call<void>("flow_delete", { id }),- clear: (everything: boolean) => call<void>("flow_clear", { everything }),+ deleteEntry: (id: string) => callOrThrow<void>("flow_delete", { id }),+ clear: (everything: boolean) => callOrThrow<void>("flow_clear", { everything }),stats: () => call<FlowStats>("flow_stats"),words: () => call<{ words: string[]; replacements: Replacement[] }>("flow_words"),- setWords: (words: { words: string[]; replacements: Replacement[] }) => call<void>("flow_set_words", { words }),+ setWords: (words: { words: string[]; replacements: Replacement[] }) => callOrThrow<void>("flow_set_words", { words }),snippets: () => call<Snippet[]>("flow_snippets"),- setSnippets: (snippets: Snippet[]) => call<void>("flow_set_snippets", { snippets }),+ setSnippets: (snippets: Snippet[]) => callOrThrow<void>("flow_set_snippets", { snippets }),styles: () => call<AppStyle[]>("flow_styles"),- setStyles: (styles: AppStyle[]) => call<void>("flow_set_styles", { styles }),+ setStyles: (styles: AppStyle[]) => callOrThrow<void>("flow_set_styles", { styles }),runningApps: () => call<{ id: string; name: string }[]>("flow_running_apps"),copy: (text: string) => call<boolean>("flow_copy", { text }),pasteAgain: () => call<void>("flow_paste_again"),diff --git a/windows/src/hub/pages/dictation.ts b/windows/src/hub/pages/dictation.tsindex 43932d1b..f94444b9 100644--- a/windows/src/hub/pages/dictation.ts+++ b/windows/src/hub/pages/dictation.ts@@ -10,6 +10,7 @@ import type { HubContext } from "../shell";import { emptyState, glowCard } from "../hero";import { button, card, icon, iconButton, keyLabel, label, number, row, shortCount, toggle } from "../ui";import { modelsControl } from "./flowsettings";+import { pageSave } from "../save";function dayKey(ms: number): string {const d = new Date(ms);@@ -81,9 +82,11 @@ export async function dictationPage(page: HTMLElement, ctx: HubContext) {const tools = h("div", { class: "tools" },iconButton("copy", t("Copy"), () => void FlowBridge.copy(e.text)),iconButton("trash", t("Delete"), () => {- entries = entries.filter((x) => x.id !== e.id);- void FlowBridge.deleteEntry(e.id);- draw();+ void saveHistory(async () => {+ await FlowBridge.deleteEntry(e.id);+ entries = entries.filter((x) => x.id !== e.id);+ draw();+ });}),);group!.append(h("div", { class: "hub-entry" }, when, h("div", { class: "words", text: e.text }), tools));@@ -92,8 +95,9 @@ export async function dictationPage(page: HTMLElement, ctx: HubContext) {const left = h("div", { style: "display:flex;flex-direction:column;gap:10px;min-width:0" },h("div", { class: "hub-history-head" }, label(t("History")), search),- list,);+ const saveHistory = pageSave(left);+ left.append(list);const right = h("div", { style: "display:flex;flex-direction:column;gap:14px" }, numbers(stats), promo(ctx));page.append(h("div", { class: "hub-columns" }, left, right));draw();diff --git a/windows/src/hub/pages/flowsettings.ts b/windows/src/hub/pages/flowsettings.tsindex f195ba55..6f45ac36 100644--- a/windows/src/hub/pages/flowsettings.ts+++ b/windows/src/hub/pages/flowsettings.ts@@ -7,6 +7,7 @@ import { t } from "../../i18n/i18n";import { onEvent } from "../../core/bridge";import { FlowBridge, type Edge, type FlowKey, type ModelsStatus } from "../../core/flow";import type { HubContext } from "../shell";+import { pageSave } from "../save";import { button, card, divider, keyKeycap, keycap, label, number, row, segmented, select, toggle } from "../ui";/** Download / progress / installed, for the voice model. Redraws itself. */@@ -127,17 +128,26 @@ export async function flowSettingsPage(page: HTMLElement, ctx: HubContext) {page.append(label(t("Privacy")));const keep: [string, string][] = [["0", t("Don't keep")], ["7", t("7 days")], ["30", t("30 days")], ["365", t("1 year")], ["-1", t("Forever")]];const confirmRow = h("div", { class: "hub-row" });+ const privacy = card(+ row(t("Keep the history"), null, select(keep, String(prefs.keepDays), (v) => void ctx.setPrefs((p) => (p.keepDays = Number(v))))),+ divider(),+ confirmRow,+ h("div", { class: "hub-note", text: t("The history, the statistics and your notes stay on this computer, in Coucou's folder. Dictations are never saved as audio; a call's audio is deleted as soon as its transcript is written.") }),+ );+ const saveErase = pageSave(privacy);const erase = () => {clear(confirmRow);confirmRow.append(- button(t("Erase the history"), () => void FlowBridge.clear(false), "", true),+ button(t("Erase the history"), () => void saveErase(() => FlowBridge.clear(false)), "", true),button(t("Erase everything"), () => {clear(confirmRow);confirmRow.append(h("span", { class: "hub-note", style: "flex:1", text: t("Erase the history and the statistics?") }),button(t("Erase everything"), () => {- void FlowBridge.clear(true);- erase();+ void saveErase(async () => {+ await FlowBridge.clear(true);+ erase();+ });}, "danger", true),button(t("Cancel"), erase, "", true),);@@ -145,10 +155,5 @@ export async function flowSettingsPage(page: HTMLElement, ctx: HubContext) {);};erase();- page.append(card(- row(t("Keep the history"), null, select(keep, String(prefs.keepDays), (v) => void ctx.setPrefs((p) => (p.keepDays = Number(v))))),- divider(),- confirmRow,- h("div", { class: "hub-note", text: t("The history, the statistics and your notes stay on this computer, in Coucou's folder. Dictations are never saved as audio; a call's audio is deleted as soon as its transcript is written.") }),- ));+ page.append(privacy);}diff --git a/windows/src/hub/pages/styles.ts b/windows/src/hub/pages/styles.tsindex 16996abc..afe8ccbe 100644--- a/windows/src/hub/pages/styles.ts+++ b/windows/src/hub/pages/styles.ts@@ -6,6 +6,7 @@ import { h, clear } from "../../views/dom";import { t } from "../../i18n/i18n";import { FlowBridge, type AppStyle, type Style } from "../../core/flow";import type { HubContext } from "../shell";+import { pageSave } from "../save";import { card, divider, iconButton, label, row, select, toggle } from "../ui";export function styleOptions(): [Style, string][] {@@ -15,8 +16,15 @@ export function styleOptions(): [Style, string][] {export async function stylesPage(page: HTMLElement, ctx: HubContext) {const status = await ctx.refresh();let styles: AppStyle[] = (await FlowBridge.styles()) ?? [];- const save = () => void FlowBridge.setStyles(styles);page.append(ctx.hero("styles", t("Styles"), t("Claude cleans up what you say, in the style of the app you write in.")));+ const write = pageSave(page);+ const save = async (next: AppStyle[]) => {+ const result = await write(() => FlowBridge.setStyles(next));+ if (result === "pending") return;+ if (result === "saved") styles = next;+ // Restore the actual selection as well when the native store rejects it.+ drawApps();+ };const perApp = h("div", {});const drawApps = () => {@@ -26,13 +34,10 @@ export async function stylesPage(page: HTMLElement, ctx: HubContext) {if (i > 0) perApp.append(divider());perApp.append(row(s.name, null,select(styleOptions(), s.style, (style) => {- styles = styles.map((x) => (x.id === s.id ? { ...x, style } : x));- save();+ void save(styles.map((x) => (x.id === s.id ? { ...x, style } : x)));}),iconButton("x", t("Delete"), () => {- styles = styles.filter((x) => x.id !== s.id);- save();- drawApps();+ void save(styles.filter((x) => x.id !== s.id));}),));});@@ -64,12 +69,10 @@ export async function stylesPage(page: HTMLElement, ctx: HubContext) {add.value = "";};add.addEventListener("focus", () => void fillAdd());- add.addEventListener("change", () => {+ add.addEventListener("change", async () => {const [id, name] = add.value.split("\n");if (!id || id === "-") return;- styles = [...styles, { id, name: name ?? id, style: ctx.status.prefs.defaultStyle }];- save();- drawApps();+ await save([...styles, { id, name: name ?? id, style: ctx.status.prefs.defaultStyle }]);void fillAdd();});void fillAdd();diff --git a/windows/src/hub/pages/words.ts b/windows/src/hub/pages/words.tsindex d5515ebd..ab50a316 100644--- a/windows/src/hub/pages/words.ts+++ b/windows/src/hub/pages/words.ts@@ -6,6 +6,7 @@ import { t } from "../../i18n/i18n";import { FlowBridge, type Replacement, type Snippet } from "../../core/flow";import type { HubContext } from "../shell";import { emptyState } from "../hero";+import { pageSave } from "../save";import { button, card, icon, iconButton, label } from "../ui";function newId(): string {@@ -22,19 +23,24 @@ export async function dictionaryPage(page: HTMLElement, ctx: HubContext) {const data = (await FlowBridge.words()) ?? { words: [], replacements: [] };let words = data.words;let replacements: Replacement[] = data.replacements;- const save = () => void FlowBridge.setWords({ words, replacements });page.append(ctx.hero("dictionary", t("Dictionary"), t("Names and words Coucou must always spell right.")));+ const write = pageSave(page);+ const save = async (next: typeof data) => {+ if (await write(() => FlowBridge.setWords(next)) !== "saved") return false;+ words = next.words;+ replacements = next.replacements;+ drawWords();+ drawReplacements();+ return true;+ };// ── Words ──const chips = h("div", { class: "hub-chips" });const wordInput = input(t("Add a word, e.g. Supabase"), () => addWord());- const addWord = () => {+ const addWord = async () => {const w = wordInput.value.trim();if (!w || words.some((x) => x.toLowerCase() === w.toLowerCase())) return;- words = [...words, w];- wordInput.value = "";- save();- drawWords();+ if (await save({ words: [...words, w], replacements })) wordInput.value = "";};const drawWords = () => {clear(chips);@@ -46,9 +52,7 @@ export async function dictionaryPage(page: HTMLElement, ctx: HubContext) {const remove = h("button", { title: t("Delete"), "aria-label": t("Delete") });remove.append(icon("x"));remove.addEventListener("click", () => {- words = words.filter((x) => x !== w);- save();- drawWords();+ void save({ words: words.filter((x) => x !== w), replacements });});chips.append(h("span", { class: "hub-chip" }, h("span", { text: w }), remove));}@@ -62,15 +66,14 @@ export async function dictionaryPage(page: HTMLElement, ctx: HubContext) {const list = h("div", {});const from = input(t("Heard, e.g. cloud code"));const to = input(t("Written, e.g. Claude Code"), () => addReplacement());- const addReplacement = () => {+ const addReplacement = async () => {const f = from.value.trim();const w = to.value.trim();if (!f || !w) return;- replacements = [...replacements.filter((r) => r.from.toLowerCase() !== f.toLowerCase()), { id: newId(), from: f, to: w }];- from.value = "";- to.value = "";- save();- drawReplacements();+ if (await save({ words, replacements: [...replacements.filter((r) => r.from.toLowerCase() !== f.toLowerCase()), { id: newId(), from: f, to: w }] })) {+ from.value = "";+ to.value = "";+ }};const drawReplacements = () => {clear(list);@@ -81,9 +84,7 @@ export async function dictionaryPage(page: HTMLElement, ctx: HubContext) {h("span", { class: "arrow", text: "→" }),h("b", { text: r.to, style: "font-weight:600" }),iconButton("trash", t("Delete"), () => {- replacements = replacements.filter((x) => x.id !== r.id);- save();- drawReplacements();+ void save({ words, replacements: replacements.filter((x) => x.id !== r.id) });}),),));@@ -95,26 +96,28 @@ export async function dictionaryPage(page: HTMLElement, ctx: HubContext) {export async function snippetsPage(page: HTMLElement, ctx: HubContext) {let snippets: Snippet[] = (await FlowBridge.snippets()) ?? [];- const save = () => void FlowBridge.setSnippets(snippets);page.append(ctx.hero("snippets", t("Snippets"), t("Say the trigger while dictating: Coucou pastes the whole text in its place.")));+ const write = pageSave(page);+ const save = async (next: Snippet[]) => {+ if (await write(() => FlowBridge.setSnippets(next)) !== "saved") return false;+ snippets = next;+ draw();+ return true;+ };let editing: Snippet | null = null;const formTitle = h("div", { style: "font:700 14px var(--font)" });const trigger = h("input", { class: "hub-input", placeholder: t("What you say, e.g. my signature") }) as HTMLInputElement;const text = h("textarea", { class: "hub-textarea", placeholder: t("The text Coucou pastes") }) as HTMLTextAreaElement;const cancel = button(t("Cancel"), () => edit(null));- const saveButton = button(t("Save"), () => {+ const saveButton = button(t("Save"), async () => {const tr = trigger.value.trim();const tx = text.value;if (!tr || !tx.trim()) return;- if (editing) {- snippets = snippets.map((s) => (s.id === editing!.id ? { ...s, trigger: tr, text: tx } : s));- } else {- snippets = [...snippets, { id: newId(), trigger: tr, text: tx }];- }- save();- edit(null);- draw();+ const next = editing+ ? snippets.map((s) => (s.id === editing!.id ? { ...s, trigger: tr, text: tx } : s))+ : [...snippets, { id: newId(), trigger: tr, text: tx }];+ if (await save(next)) edit(null);}, "primary");const edit = (s: Snippet | null) => {editing = s;@@ -143,10 +146,8 @@ export async function snippetsPage(page: HTMLElement, ctx: HubContext) {edit(s);trigger.focus();}),- iconButton("trash", t("Delete"), () => {- snippets = snippets.filter((x) => x.id !== s.id);- save();- draw();+ iconButton("trash", t("Delete"), async () => {+ if (await save(snippets.filter((x) => x.id !== s.id)) && editing?.id === s.id) edit(null);}),));}diff --git a/windows/src/hub/save.ts b/windows/src/hub/save.tsnew file mode 100644index 00000000..dd7af2d6--- /dev/null+++ b/windows/src/hub/save.ts@@ -0,0 +1,29 @@+import { h } from "../views/dom";++/** One write at a time; keep the form intact until the native store confirms it. */+export function pageSave(page: HTMLElement) {+ const error = h("div", { class: "hub-warn", role: "alert" });+ error.hidden = true;+ page.append(error);+ let pending = false;+ return async (write: () => Promise<void>): Promise<"saved" | "failed" | "pending"> => {+ if (pending) return "pending";+ pending = true;+ error.textContent = "";+ error.hidden = true;+ const controls = [...page.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | HTMLButtonElement>("input, select, textarea, button")]+ .map(el => ({ el, disabled: el.disabled }));+ for (const { el } of controls) el.disabled = true;+ try {+ await write();+ return "saved";+ } catch (cause) {+ error.textContent = cause instanceof Error ? cause.message : String(cause);+ error.hidden = false;+ return "failed";+ } finally {+ for (const { el, disabled } of controls) el.disabled = disabled;+ pending = false;+ }+ };+}diff --git a/windows/tests/flow-editors.test.mjs b/windows/tests/flow-editors.test.mjsnew file mode 100644index 00000000..536c89ed--- /dev/null+++ b/windows/tests/flow-editors.test.mjs@@ -0,0 +1,231 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { registerHooks } from "node:module";+import ts from "typescript";+import { installFakeDom } from "./fakedom.mjs";+import { calls, internals, sent } from "./tauri.mjs";++const { root } = installFakeDom();+registerHooks({ load(url, context, nextLoad) {+ const loaded = nextLoad(url, context);+ if (!url.endsWith("/src/hub/hero.ts")) return loaded;+ return { ...loaded, format: "module", source: ts.transpileModule(String(loaded.source), {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },+ }).outputText };+} });+document.addEventListener = () => {};+window.addEventListener = () => {};+document.documentElement = { lang: "en" };+document.visibilityState = "hidden";+Object.getPrototypeOf(root()).disabled = false;+Object.getPrototypeOf(root()).querySelectorAll = function (selector) {+ const tags = selector.split(",").map(tag => tag.trim().toUpperCase());+ return [...this.walk()].filter(el => tags.includes(el.tagName));+};+const { dictionaryPage, snippetsPage } = await import("../src/hub/pages/words.ts");+const { stylesPage } = await import("../src/hub/pages/styles.ts");+const flush = () => new Promise(resolve => setTimeout(resolve, 0));+const originalInvoke = internals.invoke;+const button = (page, name) => page.find("button").find(b => b.textContent === name || b.getAttribute("aria-label") === name);+const error = page => page.querySelector(".hub-warn");++async function fixture(t, render, initial = {}) {+ calls.length = 0;+ const data = {+ words: { words: ["Coucou"], replacements: [] },+ snippets: [{ id: "one", trigger: "signature", text: "Original signature" }],+ styles: [{ id: "mail", name: "Mail", style: "polished" }],+ ...initial,+ };+ let write = async () => {};+ t.mock.method(internals, "invoke", async (cmd, args) => {+ const fallback = await originalInvoke(cmd, args);+ if (cmd === "flow_running_apps") return [{ id: "editor", name: "Editor" }];+ for (const kind of ["words", "snippets", "styles"]) {+ if (cmd === `flow_${kind}`) return structuredClone(data[kind]);+ if (cmd === `flow_set_${kind}`) {+ await write(cmd, args);+ data[kind] = structuredClone(args[kind]);+ return;+ }+ }+ return fallback;+ });+ const page = root();+ const status = { prefs: { cleanup: true, defaultStyle: "natural" } };+ await render(page, { hero: root, status, refresh: async () => status, setPrefs: async change => change(status.prefs) });+ await flush();+ return { page, data, write: fn => { write = fn; } };+}++test("dictionary writes wait for disk, prevent duplicate submits and retain input on failure", async t => {+ const f = await fixture(t, dictionaryPage);+ const input = f.page.find("input")[0];+ input.value = "Parakeet";+ let reject;+ f.write(() => new Promise((_, fail) => { reject = fail; }));+ const add = button(f.page, "Add");+ add.fire("click");+ await flush();+ assert.equal(add.disabled, true);+ add.fire("click");+ await flush();+ assert.equal(sent("flow_set_words").length, 1);+ assert.equal(input.value, "Parakeet");+ assert.deepEqual(f.data.words.words, ["Coucou"]);+ reject(new Error("Dictionary destination is read-only"));+ await flush();+ assert.equal(add.disabled, false);+ assert.equal(input.value, "Parakeet");+ assert.equal(error(f.page).hidden, false);+ assert.match(error(f.page).textContent, /read-only/);+ assert.doesNotMatch(f.page.querySelector(".hub-chips").textContent, /Parakeet/);+ f.write(async () => {});+ add.fire("click");+ await flush();+ assert.deepEqual(f.data.words.words, ["Coucou", "Parakeet"]);+ assert.equal(input.value, "");+ assert.equal(error(f.page).hidden, true);+});++test("dictionary deletion and replacement failures keep the saved values and unfinished form", async t => {+ const f = await fixture(t, dictionaryPage);+ f.write(async () => { throw new Error("Disk full"); });+ button(f.page, "Delete").fire("click");+ await flush();+ assert.match(f.page.querySelector(".hub-chips").textContent, /Coucou/);+ const [, from, to] = f.page.find("input");+ from.value = "cloud code";+ to.value = "Claude Code";+ const add = f.page.find("button").filter(b => b.textContent === "Add")[1];+ add.fire("click");+ await flush();+ assert.equal(from.value, "cloud code");+ assert.equal(to.value, "Claude Code");+ assert.deepEqual(f.data.words.replacements, []);+ f.write(async () => {});+ add.fire("click");+ await flush();+ assert.equal(f.data.words.replacements.length, 1);+ assert.equal(f.data.words.replacements[0].to, "Claude Code");+ button(f.page, "Delete").fire("click");+ await flush();+ assert.deepEqual(f.data.words.words, []);+ assert.equal(f.data.words.replacements.length, 1);+});++test("a failed snippet edit retains the draft and original list until a successful retry", async t => {+ const f = await fixture(t, snippetsPage);+ button(f.page, "Edit").fire("click");+ const text = f.page.find("textarea")[0];+ text.value = "Updated signature";+ f.write(async () => { throw new Error("Disk full"); });+ button(f.page, "Save").fire("click");+ await flush();+ assert.equal(text.value, "Updated signature");+ assert.match(f.page.textContent, /Edit the snippet/);+ assert.match(f.page.querySelector(".hub-snippet-text").textContent, /Original signature/);+ assert.equal(error(f.page).hidden, false);+ f.write(async () => {});+ button(f.page, "Save").fire("click");+ await flush();+ assert.equal(f.data.snippets[0].text, "Updated signature");+ assert.equal(text.value, "");+ assert.equal(error(f.page).hidden, true);+});++test("a pending snippet save cannot race a second save or clear its draft", async t => {+ const f = await fixture(t, snippetsPage);+ f.page.find("input")[0].value = "greeting";+ f.page.find("textarea")[0].value = "Hello there";+ let finish;+ f.write(() => new Promise(resolve => { finish = resolve; }));+ const save = button(f.page, "Save");+ save.fire("click");+ await flush();+ save.fire("click");+ await flush();+ assert.equal(sent("flow_set_snippets").length, 1);+ assert.equal(f.page.find("textarea")[0].value, "Hello there");+ assert.equal(save.disabled, true);+ finish();+ await flush();+ assert.equal(f.data.snippets.length, 2);+ assert.equal(save.disabled, false);+});++test("failed snippet deletion keeps the entry and a successful deletion clears its editor", async t => {+ const f = await fixture(t, snippetsPage);+ button(f.page, "Edit").fire("click");+ f.write(async () => { throw new Error("Disk full"); });+ button(f.page, "Delete").fire("click");+ await flush();+ assert.match(f.page.querySelector(".hub-snippet-text").textContent, /Original signature/);+ f.write(async () => {});+ button(f.page, "Delete").fire("click");+ await flush();+ assert.equal(f.data.snippets.length, 0);+ assert.equal(f.page.find("textarea")[0].value, "");+ assert.match(f.page.textContent, /New snippet/);+});++test("a failed app-style change restores the persisted choice and allows retry", async t => {+ const f = await fixture(t, stylesPage);+ const appSelect = () => f.page.find("select").at(-1);+ f.write(async () => { throw new Error("Styles destination is read-only"); });+ appSelect().value = "verbatim";+ appSelect().fire("change");+ await flush();+ assert.equal(appSelect().value, "polished");+ assert.equal(f.data.styles[0].style, "polished");+ assert.equal(error(f.page).hidden, false);+ f.write(async () => {});+ appSelect().value = "verbatim";+ appSelect().fire("change");+ await flush();+ assert.equal(f.data.styles[0].style, "verbatim");+ assert.equal(error(f.page).hidden, true);+});++test("adding and deleting app styles leaves the saved list intact when writing fails", async t => {+ const f = await fixture(t, stylesPage);+ const add = f.page.find("select").find(select => select.find("option").some(option => option.textContent === "+ Add an app"));+ const initialSelects = f.page.find("select").length;+ f.write(async () => { throw new Error("Disk full"); });+ add.value = "editor\nEditor";+ add.fire("change");+ await flush();+ assert.equal(f.data.styles.length, 1);+ assert.equal(f.page.find("select").length, initialSelects);+ f.write(async () => {});+ add.value = "editor\nEditor";+ add.fire("change");+ await flush();+ assert.deepEqual(f.data.styles[1], { id: "editor", name: "Editor", style: "natural" });+ f.write(async () => { throw new Error("Disk full"); });+ button(f.page, "Delete").fire("click");+ await flush();+ assert.equal(f.page.find("select").length, initialSelects + 1);+ f.write(async () => {});+ button(f.page, "Delete").fire("click");+ await flush();+ assert.deepEqual(f.data.styles.map(s => s.id), ["editor"]);+});++test("a repeated style event does not unlock the editor while its first save is pending", async t => {+ const f = await fixture(t, stylesPage);+ let finish;+ f.write(() => new Promise(resolve => { finish = resolve; }));+ const choice = f.page.find("select").at(-1);+ choice.value = "verbatim";+ choice.fire("change");+ await flush();+ choice.fire("change");+ await flush();+ assert.equal(sent("flow_set_styles").length, 1);+ assert.equal(f.page.find("select").at(-1).disabled, true);+ finish();+ await flush();+ assert.equal(f.data.styles[0].style, "verbatim");+ assert.equal(f.page.find("select").at(-1).disabled, false);+});diff --git a/windows/tests/flow-history.test.mjs b/windows/tests/flow-history.test.mjsnew file mode 100644index 00000000..14809798--- /dev/null+++ b/windows/tests/flow-history.test.mjs@@ -0,0 +1,133 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { registerHooks } from "node:module";+import ts from "typescript";+import { installFakeDom } from "./fakedom.mjs";+import { calls, emit, internals, sent } from "./tauri.mjs";++const { root } = installFakeDom();+registerHooks({ load(url, context, nextLoad) {+ const loaded = nextLoad(url, context);+ if (!url.endsWith("/src/hub/hero.ts")) return loaded;+ return { ...loaded, format: "module", source: ts.transpileModule(String(loaded.source), {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.ESNext },+ }).outputText };+} });+document.addEventListener = () => {};+window.addEventListener = () => {};+window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener: () => {} };+document.documentElement = { lang: "en" };+document.visibilityState = "hidden";+const proto = Object.getPrototypeOf(root());+proto.disabled = false;+proto.prepend = function (...nodes) {+ const before = [...this.childNodes];+ this.replaceChildren(...nodes, ...before);+};+proto.querySelectorAll = function (selector) {+ const tags = selector.split(",").map(tag => tag.trim().toUpperCase());+ return [...this.walk()].filter(el => tags.includes(el.tagName));+};+const querySelector = proto.querySelector;+proto.querySelector = function (selector) {+ return selector.startsWith(".") ? querySelector.call(this, selector) : this.find(selector)[0] ?? null;+};+const { dictationPage } = await import("../src/hub/pages/dictation.ts");+const { flowSettingsPage } = await import("../src/hub/pages/flowsettings.ts");+const flush = () => new Promise(resolve => setTimeout(resolve, 0));+const originalInvoke = internals.invoke;+const button = (page, name) => page.find("button").find(b => b.textContent === name || b.getAttribute("aria-label") === name);+const entry = (id, text) => ({ id, text, date: Date.now(), app: null, words: 2, seconds: 1 });++async function fixture(t, render) {+ calls.length = 0;+ let write = async () => {};+ t.mock.method(internals, "invoke", async (cmd, args) => {+ const fallback = await originalInvoke(cmd, args);+ if (cmd === "flow_history") return [entry("first", "Saved dictation")];+ if (cmd === "flow_delete" || cmd === "flow_clear") return write(cmd, args);+ return fallback;+ });+ const page = root();+ const status = {+ prefs: { enabled: true, key: "right_ctrl", keepDays: 30, mic: "" },+ models: { parakeet: { state: "ready" }, downloadMb: 700 },+ mics: [], keys: "ok", platform: "windows",+ };+ const ctx = { hero: root, status, refresh: async () => status, setPrefs: async change => change(status.prefs) };+ await render(page, ctx);+ t.after(() => ctx.onLeave?.());+ await flush();+ return { page, write: fn => { write = fn; } };+}++test("a failed history deletion retains the entry and supports retry", async t => {+ const f = await fixture(t, dictationPage);+ f.write(async () => { throw new Error("History file is locked"); });+ button(f.page, "Delete").fire("click");+ await flush();+ assert.match(f.page.textContent, /Saved dictation/);+ assert.match(f.page.querySelector(".hub-warn").textContent, /locked/);+ f.write(async () => {});+ button(f.page, "Delete").fire("click");+ await flush();+ assert.doesNotMatch(f.page.textContent, /Saved dictation/);+ assert.equal(f.page.querySelector(".hub-warn").hidden, true);+});++test("pending deletion waits for disk, prevents duplicates and preserves incoming dictations", async t => {+ const f = await fixture(t, dictationPage);+ let finish;+ f.write(() => new Promise(resolve => { finish = resolve; }));+ const remove = button(f.page, "Delete");+ remove.fire("click");+ await flush();+ assert.equal(remove.disabled, true);+ assert.match(f.page.textContent, /Saved dictation/);+ remove.fire("click");+ emit("flow-history", entry("second", "New dictation"));+ button(f.page, "Delete").fire("click");+ await flush();+ assert.equal(sent("flow_delete").length, 1);+ finish();+ await flush();+ assert.doesNotMatch(f.page.textContent, /Saved dictation/);+ assert.match(f.page.textContent, /New dictation/);+});++test("erasing history reports disk failures and blocks duplicate requests until retry", async t => {+ const f = await fixture(t, flowSettingsPage);+ let fail;+ f.write(() => new Promise((_, reject) => { fail = reject; }));+ const erase = button(f.page, "Erase the history");+ erase.fire("click");+ await flush();+ assert.equal(erase.disabled, true);+ erase.fire("click");+ assert.equal(sent("flow_clear").length, 1);+ fail(new Error("History file is locked"));+ await flush();+ assert.equal(erase.disabled, false);+ assert.match(f.page.querySelector(".hub-warn").textContent, /locked/);+ f.write(async () => {});+ erase.fire("click");+ await flush();+ assert.equal(f.page.querySelector(".hub-warn").hidden, true);+});++test("Erase everything retains confirmation on failure and resets it only after success", async t => {+ const f = await fixture(t, flowSettingsPage);+ f.write(async () => { throw new Error("Could not erase statistics"); });+ button(f.page, "Erase everything").fire("click");+ assert.equal(sent("flow_clear").length, 0);+ button(f.page, "Erase everything").fire("click");+ await flush();+ assert.match(f.page.textContent, /Erase the history and the statistics\?/);+ assert.match(f.page.querySelector(".hub-warn").textContent, /statistics/);+ f.write(async () => {});+ button(f.page, "Erase everything").fire("click");+ await flush();+ assert.doesNotMatch(f.page.textContent, /Erase the history and the statistics\?/);+ assert.equal(f.page.querySelector(".hub-warn").hidden, true);+ assert.deepEqual(sent("flow_clear"), [{ everything: true }, { everything: true }]);+});