From be0d09e2cb91ef391d7455334fc5ed15d6f5649a Mon Sep 17 00:00:00 2001 From: Christopher Warner Date: Sat, 10 Oct 2026 18:49:01 -0400 Subject: feat: update existing Apple Notes by title instead of duplicating Add `icloud-note update` that finds a note by title and replaces its content in place so revision requests do not create a second note. Co-authored-by: Cursor --- README.md | 4 +- SKILL.md | 56 +++++++++++++------------ src/browser.rs | 122 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- src/helpers.rs | 32 ++++++++++++++ src/main.rs | 55 ++++++++++++++++++++++-- tests/cli.test.sh | 22 ++++++++++ 6 files changed, 257 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index b0e79be..1275b13 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Also packaged as a Cursor/Goose agent skill (`SKILL.md`). ./scripts/setup.sh # cargo build --release + Chromium + ~/.local/bin icloud-note login # Apple ID + 2FA once (visible window) icloud-note create --title "Hello" --body "From Linux" +icloud-note update --title "Hello" --body "Revised from Linux" ``` ## CLI @@ -21,7 +22,8 @@ icloud-note create --title "Hello" --body "From Linux" | `icloud-note setup` | Build/install binary + ensure Chromium | | `icloud-note login` | **Only** command that opens a visible browser | | `icloud-note status` | Headless session check | -| `icloud-note create` | Headless create (`--title`, `--body` / `--body-file`) | +| `icloud-note create` | Headless **new** note (`--title`, `--body` / `--body-file`) | +| `icloud-note update` | Headless **update** existing note by title (never creates) | ## Layout diff --git a/SKILL.md b/SKILL.md index e83bf47..6149b86 100644 --- a/SKILL.md +++ b/SKILL.md @@ -1,24 +1,36 @@ --- name: iphone-icloud-notes description: >- - Create real Apple Notes on the user's iPhone by driving icloud.com/notes from - Linux with the Rust icloud-note CLI (headless Chromium). Use when the user asks - to create a note, send/forward results to their iPhone, push text to Apple - Notes, or mentions icloud.com/notes / iCloud Notes from Linux. + Create or update real Apple Notes on the user's iPhone by driving + icloud.com/notes from Linux with the Rust icloud-note CLI (headless Chromium). + Use when the user asks to create/update a note, send/forward results to their + iPhone, push text to Apple Notes, or mentions icloud.com/notes / iCloud Notes + from Linux. --- # iPhone notes via icloud.com/notes (Rust) ## Goal -When asked to create a note or forward prompt results to the iPhone, **create a -real Apple Note** through the iCloud Notes web app using the **Rust** +Drive real Apple Notes through the iCloud Notes web app using the **Rust** `icloud-note` binary. Do not use LocalSend unless the user wants file transfer. +## Create vs update (important) + +| User intent | Command | +|---|---| +| New note / first send | `icloud-note create …` | +| Change / revise / refresh an existing note | `icloud-note update …` | + +**Never use `create` when the user asks to update** — that would add a duplicate +note. `update` finds the note by title (case-insensitive) and replaces its +content in place. If no matching note exists, report the error; do not fall back +to `create` unless the user explicitly asks to create. + ## Source of truth Repo: `~/Code/iphone-notes` -Binary: `~/.local/bin/icloud-note` (from `cargo build --release`) +Binary: `~/.local/bin/icloud-note` Skill link: `~/.agents/skills/iphone-icloud-notes` → that repo ## Helper @@ -27,28 +39,21 @@ Skill link: `~/.agents/skills/iphone-icloud-notes` → that repo icloud-note status icloud-note login # ONE-TIME only — only command that opens a window icloud-note create --title "Title" --body "Body text" -icloud-note create --title "Title" --body-file /path/to.txt -icloud-note create --title "Title" --body-file - # stdin +icloud-note update --title "Title" --body "Revised body" +icloud-note update --title "Title" --body-file /path/to.txt +# optional: search under a different title than the new first line +icloud-note update --match-title "Old Title" --title "New Title" --body "…" ``` -If missing from PATH: - -```bash -"$HOME/Code/iphone-notes/target/release/icloud-note" … -# or: cargo run --manifest-path "$HOME/Code/iphone-notes/Cargo.toml" -- … -``` - -`create` / `status` are **always headless**. Never run `login` unless the user -must re-authenticate. Do **not** set `ICLOUD_NOTES_DRY_RUN=1` for real sends. - -Config: `~/.config/icloud-notes/` (browser profile; private) +`create` / `update` / `status` are **always headless**. Never run `login` unless +re-auth is required. Do **not** set `ICLOUD_NOTES_DRY_RUN=1` for real sends. ## Agent workflow -1. Prepare title + body. -2. `icloud-note status` — if not logged in, ask the user to run `icloud-note login`. -3. `icloud-note create --title "$TITLE" --body-file "$TMPFILE"` -4. Report the `created:` line. Syncs to iPhone when iCloud Notes is enabled. +1. Decide **create** vs **update** from the user’s wording. +2. `icloud-note status` — if not logged in, ask for `icloud-note login`. +3. Run create or update with `--title` + `--body-file` for long text. +4. Report the `created:` or `updated:` line. ## Setup (human / once) @@ -56,6 +61,3 @@ Config: `~/.config/icloud-notes/` (browser profile; private) "$HOME/Code/iphone-notes/scripts/setup.sh" icloud-note login ``` - -Requires Rust (`cargo`) and a Chromium binary (setup can install Playwright’s -Chromium under `~/.cache/ms-playwright`). diff --git a/src/browser.rs b/src/browser.rs index 187b535..b3b72d8 100644 --- a/src/browser.rs +++ b/src/browser.rs @@ -185,13 +185,50 @@ async fn wait_for_notes_app(page: &Page, timeout: Duration, allow_login_wait: bo bail!("NotesApp did not become ready. Run: icloud-note login"); } +fn note_list_helpers_js() -> &'static str { + r#" + function noteLen(list) { + if (!list) return 0; + if (typeof list.get === "function" && typeof list.get("length") === "number") + return list.get("length"); + return list.length || 0; + } + function noteAt(list, i) { + if (!list) return null; + if (typeof list.objectAt === "function") return list.objectAt(i); + if (typeof list.get === "function") return list.objectAt?.(i) ?? list[i]; + return list[i]; + } + function findByTitle(list, want) { + const norm = (s) => String(s || "").trim().toLowerCase(); + const target = norm(want); + let best = null; + let bestMod = -1; + const n = noteLen(list); + for (let i = 0; i < n; i++) { + const note = noteAt(list, i); + if (!note) continue; + const title = note.Title ?? note.title ?? ""; + if (norm(title) !== target) continue; + const mod = Number(note.ModificationDate || note.modificationDate || 0); + if (!best || mod >= bestMod) { + best = note; + bestMod = mod; + } + } + return best; + } + "# +} + async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result { let full = format_note_text(title, body); - // Pass text via JSON.stringify embedded in JS to avoid injection issues let text_js = serde_json::to_string(&full)?; + let helpers = note_list_helpers_js(); let expr = format!( r#"async () => {{ const text = {text_js}; + {helpers} const iframe = document.querySelector("iframe"); const w = iframe?.contentWindow; const app = w?.NotesApp; @@ -201,7 +238,7 @@ async fn create_via_notes_app(page: &Page, title: &str, body: &str) -> Result Result Result Result { + let full = format_note_text(title, body); + let text_js = serde_json::to_string(&full)?; + let match_js = serde_json::to_string(match_title)?; + let helpers = note_list_helpers_js(); + let expr = format!( + r#"async () => {{ + const text = {text_js}; + const matchTitle = {match_js}; + {helpers} + const iframe = document.querySelector("iframe"); + const w = iframe?.contentWindow; + const app = w?.NotesApp; + if (!app?.dataManager) throw new Error("NotesApp unavailable"); + const dataManager = app.dataManager; + const mv = app.mainViewModel; + const noteList = dataManager.allNotes || dataManager.__CW__allNotes; + const note = findByTitle(noteList, matchTitle); + if (!note) {{ + throw new Error("No note titled " + JSON.stringify(matchTitle)); + }} + const Note = note.constructor; + // Preferred path: replace TopoText via NotesApp helpers + if (typeof Note.createInitialTopoTextString === "function" + && dataManager.topoTextManager + && typeof dataManager.topoTextManager.load === "function") {{ + const replacement = Note.createInitialTopoTextString(text); + dataManager.topoTextManager.load(note.id, replacement); + if (typeof note.userDidChangeTopoText === "function") {{ + note.userDidChangeTopoText(); + }} + }} else if (typeof note.userDidChangeTopoText === "function") {{ + note.userDidChangeTopoText(text); + }} else {{ + throw new Error("No supported update path on Note model"); + }} + if (note.Title !== undefined) {{ + note.Title = text.split("\n")[0] || matchTitle; + }} + await note.save(true); + return {{ + title: String(note.Title || text.split("\n")[0] || matchTitle), + record_name: String(note.recordName || note.id || "") + }}; + }}"# + ); + let note: CreatedNote = page.evaluate(expr).await?.into_value()?; + Ok(note) +} + fn mark_session(paths: &Paths) -> Result<()> { std::fs::write(&paths.marker_path, b"ok\n")?; #[cfg(unix)] @@ -300,3 +388,31 @@ pub async fn cmd_create(paths: &Paths, title: &str, body: &str) -> Result<()> { Ok(()) } +/// Update an existing note matched by title. Never creates a new note. +pub async fn cmd_update( + paths: &Paths, + match_title: &str, + title: &str, + body: &str, +) -> Result<()> { + if !paths.has_session() { + bail!("No saved session. Run: icloud-note login"); + } + let (mut browser, handle) = launch(paths, false).await?; + let page = browser.new_page("about:blank").await?; + wait_for_notes_app(&page, Duration::from_secs(90), false).await?; + let note = update_via_notes_app(&page, match_title, title, body) + .await + .context("update note via NotesApp")?; + sleep(Duration::from_secs(2)).await; + mark_session(paths)?; + if note.record_name.is_empty() { + println!("updated: {}", note.title); + } else { + println!("updated: {} ({})", note.title, note.record_name); + } + browser.close().await?; + let _ = handle.await; + Ok(()) +} + diff --git a/src/helpers.rs b/src/helpers.rs index c6a8163..3ea7e37 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -51,6 +51,23 @@ pub fn require_create_content(title: &str, body: &str) -> Result<(String, String Ok((title, body)) } +/// Update requires a title to locate the existing note. +pub fn require_update_content(title: &str, body: &str) -> Result<(String, String), String> { + let title = title.trim().to_string(); + let body = body.trim_end().to_string(); + if title.is_empty() { + return Err( + "Provide --title (existing note title to update)".to_string(), + ); + } + Ok((title, body)) +} + +/// Case-insensitive title equality for matching Notes.app titles. +pub fn titles_match(a: &str, b: &str) -> bool { + a.trim().eq_ignore_ascii_case(b.trim()) +} + /// Conventional Commits 1.0.0 subject line (no regex crate). pub fn is_conventional_commit_subject(subject: &str) -> bool { let line = subject.trim(); @@ -127,6 +144,21 @@ mod tests { assert_eq!(b, "hi"); } + #[test] + fn update_content_requires_title() { + assert!(require_update_content("", "body").is_err()); + let (t, b) = require_update_content(" Hello ", "body\n").unwrap(); + assert_eq!(t, "Hello"); + assert_eq!(b, "body"); + } + + #[test] + fn titles_match_case_insensitive() { + assert!(titles_match("Hello", "hello")); + assert!(titles_match(" Foo ", "foo")); + assert!(!titles_match("a", "b")); + } + #[test] fn conventional_subjects() { assert!(is_conventional_commit_subject( diff --git a/src/main.rs b/src/main.rs index ccd21e2..ca893b5 100644 --- a/src/main.rs +++ b/src/main.rs @@ -7,7 +7,7 @@ use clap::{Parser, Subcommand}; use icloud_note::browser; use icloud_note::config::{dry_run, Paths}; -use icloud_note::helpers::{format_note_text, require_create_content}; +use icloud_note::helpers::{format_note_text, require_create_content, require_update_content}; #[derive(Parser, Debug)] #[command( @@ -29,7 +29,7 @@ enum Command { Status, /// One-time Apple ID sign-in (visible browser) Login, - /// Headless create a note + /// Headless create a new note Create { /// Note title (or positional) #[arg(long)] @@ -44,6 +44,24 @@ enum Command { #[arg(value_name = "TITLE")] positional_title: Option, }, + /// Headless update an existing note (by title) — never creates + Update { + /// Existing note title to find (required) + #[arg(long)] + title: Option, + /// Optional distinct title to search for (defaults to --title) + #[arg(long = "match-title")] + match_title: Option, + /// Replacement body text + #[arg(long)] + body: Option, + /// Read body from file (`-` = stdin) + #[arg(long = "body-file")] + body_file: Option, + /// Positional title fallback + #[arg(value_name = "TITLE")] + positional_title: Option, + }, } #[tokio::main] @@ -115,6 +133,35 @@ async fn run() -> Result<()> { } browser::cmd_create(&paths, &title, &body).await } + Command::Update { + title, + match_title, + body, + body_file, + positional_title, + } => { + let title = title.or(positional_title).unwrap_or_default(); + let body_raw = read_body(body, body_file)?; + let (title, body) = require_update_content(&title, &body_raw) + .map_err(|e| anyhow::anyhow!(e))?; + let match_title = match_title + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .unwrap_or(title.as_str()) + .to_string(); + if dry_run() { + let text = format_note_text(&title, &body); + println!( + "dry-run: would update note match={} title={} chars={}", + serde_json::to_string(&match_title)?, + serde_json::to_string(&title)?, + text.len() + ); + return Ok(()); + } + browser::cmd_update(&paths, &match_title, &title, &body).await + } } } @@ -151,10 +198,12 @@ fn print_help(paths: &Paths) { icloud-note status icloud-note login # only command that opens a visible browser icloud-note create --title TITLE [--body TEXT | --body-file PATH|-] + icloud-note update --title TITLE [--body TEXT | --body-file PATH|-] + # updates existing note by title; never creates Config: {} Profile: {} -create/status always run headless (no window). +create/update/status always run headless (no window). ", paths.config_dir.display(), paths.profile_dir.display() diff --git a/tests/cli.test.sh b/tests/cli.test.sh index 6aeef87..083f73a 100755 --- a/tests/cli.test.sh +++ b/tests/cli.test.sh @@ -17,6 +17,7 @@ pass() { echo "ok: $*"; } # --- help --- out="$("${CLI[@]}" 2>&1)" || fail "no-args help failed" [[ "$out" == *"icloud-note create"* ]] || fail "help missing create: $out" +[[ "$out" == *"icloud-note update"* ]] || fail "help missing update: $out" [[ "$out" == *"headless"* ]] || fail "help should say create/status are headless" [[ "$out" != *"--headed"* ]] || fail "help must not advertise --headed" [[ "$out" == *"$ICLOUD_NOTES_CONFIG"* ]] || fail "help should show ICLOUD_NOTES_CONFIG path" @@ -66,6 +67,27 @@ out="$("${CLI[@]}" create "Positional" --body "x" 2>&1)" || fail "positional cre [[ "$out" == *'title="Positional"'* ]] || fail "positional title: $out" pass "create positional title" +# --- update validation / dry-run --- +set +e +err="$("${CLI[@]}" update --body "x" 2>&1)" +code=$? +set -e +[[ "$code" -ne 0 ]] || fail "update without title should fail" +[[ "$err" == *"Provide --title"* ]] || fail "update empty title message: $err" +pass "update requires title" + +out="$("${CLI[@]}" update --title "Existing" --body "revised" 2>&1)" \ + || fail "update dry-run failed" +[[ "$out" == *'dry-run: would update note match="Existing"'* ]] || fail "update dry-run: $out" +[[ "$out" == *'title="Existing"'* ]] || fail "update dry-run title: $out" +pass "update dry-run" + +out="$("${CLI[@]}" update --match-title "Old" --title "New" --body "x" 2>&1)" \ + || fail "update match-title dry-run failed" +[[ "$out" == *'match="Old"'* ]] || fail "match-title: $out" +[[ "$out" == *'title="New"'* ]] || fail "new title in update dry-run: $out" +pass "update --match-title dry-run" + # --- status dry-run without session --- set +e err="$("${CLI[@]}" status 2>&1)" -- cgit v1.2.3