diff options
| author | Christopher Warner <cwarner@kernelcode.com> | 2026-10-10 18:40:56 -0400 |
|---|---|---|
| committer | Christopher Warner <cwarner@kernelcode.com> | 2026-10-10 18:40:56 -0400 |
| commit | 50b9b2b4c0db6a5e1d9dd511d062d99ae2e11dd3 (patch) | |
| tree | 612f1421cb589e957598aee175ac90e1ee106487 /scripts/icloud-note.mjs | |
| parent | ef0165cc6cbe001997e5d05af5de6d4849481d7a (diff) | |
| download | iphone-notes-50b9b2b4c0db6a5e1d9dd511d062d99ae2e11dd3.tar.gz iphone-notes-50b9b2b4c0db6a5e1d9dd511d062d99ae2e11dd3.tar.bz2 iphone-notes-50b9b2b4c0db6a5e1d9dd511d062d99ae2e11dd3.tar.xz iphone-notes-50b9b2b4c0db6a5e1d9dd511d062d99ae2e11dd3.zip | |
fix: run create/status headless without a visible browser
Use a saved storage-state session for note ops so only `login` opens a
window; launchPersistentContext was flashing Chromium on Linux.
Co-authored-by: Cursor <cursoragent@cursor.com>
Diffstat (limited to 'scripts/icloud-note.mjs')
| -rwxr-xr-x | scripts/icloud-note.mjs | 212 |
1 files changed, 144 insertions, 68 deletions
diff --git a/scripts/icloud-note.mjs b/scripts/icloud-note.mjs index 13a6efd..30c3b83 100755 --- a/scripts/icloud-note.mjs +++ b/scripts/icloud-note.mjs @@ -16,6 +16,7 @@ const CONFIG_DIR = process.env.ICLOUD_NOTES_CONFIG || path.join(os.homedir(), ".config", "icloud-notes"); const PROFILE_DIR = path.join(CONFIG_DIR, "browser-profile"); +const STATE_PATH = path.join(CONFIG_DIR, "storage-state.json"); const NOTES_URL = "https://www.icloud.com/notes/"; function die(msg, code = 1) { @@ -39,17 +40,71 @@ function loadPlaywright() { } } -async function withNotesContext({ headed, fn }) { +async function ensureStorageState(chromium) { + if (fs.existsSync(STATE_PATH)) return; + // One-time migration from an older profile-only login (still headless). + if (!fs.existsSync(path.join(PROFILE_DIR, "Default"))) { + throw new Error("No saved session. Run: icloud-note login"); + } + const context = await chromium.launchPersistentContext(PROFILE_DIR, { + headless: true, + args: [ + "--headless=new", + "--ozone-platform=headless", + "--disable-blink-features=AutomationControlled", + ], + }); + try { + await context.storageState({ path: STATE_PATH }); + fs.chmodSync(STATE_PATH, 0o600); + } finally { + await context.close(); + } +} + +/** + * Headless-only path for status/create. Uses saved storage state — never opens + * a visible window (launchPersistentContext can still flash UI on Linux). + */ +async function withHeadlessNotes(fn) { + ensureConfigDir(); + const { chromium } = loadPlaywright(); + await ensureStorageState(chromium); + const browser = await chromium.launch({ + headless: true, + args: [ + "--disable-blink-features=AutomationControlled", + "--headless=new", + "--ozone-platform=headless", + ], + }); + try { + const context = await browser.newContext({ + storageState: STATE_PATH, + viewport: { width: 1280, height: 900 }, + }); + const page = await context.newPage(); + try { + return await fn(page, context); + } finally { + await context.close(); + } + } finally { + await browser.close(); + } +} + +/** Headed login only — saves storage-state.json for later headless runs. */ +async function withLoginBrowser(fn) { ensureConfigDir(); const { chromium } = loadPlaywright(); const context = await chromium.launchPersistentContext(PROFILE_DIR, { - headless: !headed, + headless: false, viewport: { width: 1280, height: 900 }, args: ["--disable-blink-features=AutomationControlled"], }); try { - const page = - context.pages()[0] || (await context.newPage()); + const page = context.pages()[0] || (await context.newPage()); return await fn(page, context); } finally { await context.close(); @@ -88,7 +143,14 @@ async function waitForNotesApp(page, { timeoutMs = 120_000, allowLoginWait = fal const ready = await page.evaluate(() => { const iframe = document.querySelector("iframe"); const w = iframe?.contentWindow; - return Boolean(w?.NotesApp?.dataManager); + const dm = w?.NotesApp?.dataManager; + if (!dm) return false; + // Need at least one loaded note/folder so Note.create* is reachable + const notes = dm.allNotes || dm.__CW__allNotes; + const folders = dm.allFolders || dm.__CW__allFolders || dm.folders; + const n = notes?.length || 0; + const f = folders?.length || 0; + return n > 0 || f > 0; }).catch(() => false); if (ready) return; @@ -121,30 +183,47 @@ async function createViaNotesApp(page, title, body) { const dataManager = app.dataManager; const mv = app.mainViewModel; - let Note = mv?.selectedNote?.constructor; - if (!Note && dataManager.allNotes?.length) { - Note = dataManager.allNotes[0].constructor; - } - if (!Note?.createNoteWithTitleText) { + const noteList = dataManager.allNotes || dataManager.__CW__allNotes; + const sample = + mv?.selectedNote || + (noteList?.objectAt ? noteList.objectAt(0) : noteList?.[0]) || + null; + const Note = sample?.constructor; + if (!Note?.createNoteWithTitleText && !Note?.createEmptyNote) { throw new Error( "Could not find Note.createNoteWithTitleText — UI may have changed", ); } + const folderList = + dataManager.allFolders || + dataManager.__CW__allFolders || + dataManager.folders; const folder = mv?.selectedFolder || dataManager.defaultFolder || dataManager.inboxFolder || - (Array.isArray(dataManager.folders) ? dataManager.folders[0] : null) || - (dataManager.allFolders && dataManager.allFolders[0]) || + (folderList?.objectAt ? folderList.objectAt(0) : folderList?.[0]) || null; if (!folder) { throw new Error("Could not resolve a Notes folder"); } - const note = Note.createNoteWithTitleText(text, folder); - dataManager.userDidCreateNote(note); + let note; + if (typeof Note.createNoteWithTitleText === "function") { + note = Note.createNoteWithTitleText(text, folder); + } else { + note = Note.createEmptyNote(folder); + if (typeof note.userDidChangeTopoText === "function") { + // Prefer structured text update when available + note.userDidChangeTopoText?.(text); + } + if (note.Title !== undefined) note.Title = text.split("\n")[0] || "Note"; + } + if (typeof dataManager.userDidCreateNote === "function") { + dataManager.userDidCreateNote(note); + } await note.save(true); return { title: String(note.Title || text.split("\n")[0] || "(untitled)"), @@ -156,30 +235,26 @@ async function createViaNotesApp(page, title, body) { async function createViaUiFallback(page, title, body) { // Last resort: keyboard into the Notes UI const candidates = [ + '[title="Create a note"]', + 'button[aria-label="Create"]', + 'ui-button[aria-label="Create"]', 'button[aria-label*="New Note" i]', 'button[title*="New Note" i]', 'button[aria-label*="Create" i]', '[data-testid="new-note"]', ]; let clicked = false; - for (const sel of candidates) { - const btn = page.frameLocator("iframe").locator(sel).first(); - if ((await btn.count().catch(() => 0)) > 0) { - await btn.click({ timeout: 5000 }); - clicked = true; - break; - } - } - if (!clicked) { - // try top-level too + const scopes = [page.frameLocator("iframe"), page]; + for (const scope of scopes) { for (const sel of candidates) { - const btn = page.locator(sel).first(); + const btn = scope.locator(sel).first(); if ((await btn.count().catch(() => 0)) > 0) { await btn.click({ timeout: 5000 }); clicked = true; break; } } + if (clicked) break; } if (!clicked) { throw new Error("UI fallback: could not find New Note control"); @@ -198,12 +273,9 @@ async function createViaUiFallback(page, title, body) { async function cmdStatus() { try { - await withNotesContext({ - headed: false, - fn: async (page) => { - await waitForNotesApp(page, { timeoutMs: 20_000 }); - console.log("ok: logged in to icloud.com/notes"); - }, + await withHeadlessNotes(async (page) => { + await waitForNotesApp(page, { timeoutMs: 20_000 }); + console.log("ok: logged in to icloud.com/notes (headless)"); }); } catch (err) { die(`not ready: ${err.message}`); @@ -214,22 +286,22 @@ async function cmdLogin() { if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) { die("login needs a graphical session (DISPLAY or WAYLAND_DISPLAY)."); } - console.error("Opening Chromium for Apple ID sign-in…"); - console.error("Sign in, complete 2FA, wait until Notes loads, then return here."); - await withNotesContext({ - headed: true, - fn: async (page) => { - await page.goto(NOTES_URL, { waitUntil: "domcontentloaded" }); - try { - await waitForNotesApp(page, { - timeoutMs: 10 * 60_000, - allowLoginWait: true, - }); - console.log("ok: session saved — you can close the window next time"); - } catch (err) { - die(`login incomplete: ${err.message}`); - } - }, + console.error("Opening Chromium for Apple ID sign-in (one-time)…"); + console.error("Sign in, complete 2FA, wait until Notes loads."); + await withLoginBrowser(async (page, context) => { + await page.goto(NOTES_URL, { waitUntil: "domcontentloaded" }); + try { + await waitForNotesApp(page, { + timeoutMs: 10 * 60_000, + allowLoginWait: true, + }); + await context.storageState({ path: STATE_PATH }); + fs.chmodSync(STATE_PATH, 0o600); + console.log(`ok: session saved to ${STATE_PATH}`); + console.log("ok: create/status will run headless (no window)"); + } catch (err) { + die(`login incomplete: ${err.message}`); + } }); } @@ -255,24 +327,27 @@ async function cmdCreate(opts) { die("Provide --title and/or --body / --body-file / stdin"); } - const headed = Boolean(opts.values.headed); - await withNotesContext({ - headed, - fn: async (page) => { - await waitForNotesApp(page, { timeoutMs: 90_000 }); - let result; - try { - result = await createViaNotesApp(page, title, body); - } catch (err) { - console.error(`NotesApp path failed (${err.message}); trying UI…`); - result = await createViaUiFallback(page, title, body); - } - // Give CloudKit a moment to flush - await page.waitForTimeout(2000); - console.log( - `created: ${result.title}${result.recordName ? ` (${result.recordName})` : ""}`, - ); - }, + await withHeadlessNotes(async (page) => { + await waitForNotesApp(page, { timeoutMs: 90_000 }); + let result; + try { + result = await createViaNotesApp(page, title, body); + } catch (err) { + console.error(`NotesApp path failed (${err.message}); trying UI…`); + result = await createViaUiFallback(page, title, body); + } + // Give CloudKit a moment to flush + await page.waitForTimeout(2000); + // Refresh saved cookies/session after a successful create + try { + await page.context().storageState({ path: STATE_PATH }); + fs.chmodSync(STATE_PATH, 0o600); + } catch { + /* non-fatal */ + } + console.log( + `created: ${result.title}${result.recordName ? ` (${result.recordName})` : ""}`, + ); }); } @@ -280,10 +355,12 @@ function printHelp() { console.log(`Usage: icloud-note setup icloud-note status - icloud-note login - icloud-note create --title TITLE [--body TEXT | --body-file PATH|-] [--headed] + icloud-note login # only command that opens a visible browser + icloud-note create --title TITLE [--body TEXT | --body-file PATH|-] Config: ${CONFIG_DIR} +Session: ${STATE_PATH} +create/status always run headless (no window). `); } @@ -317,7 +394,6 @@ async function main() { title: { type: "string" }, body: { type: "string" }, "body-file": { type: "string" }, - headed: { type: "boolean", default: false }, }, allowPositionals: true, }); |
