daylight-mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,1496 @@
1
+ # Changelog
2
+
3
+ All notable changes to Daylight are documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and Daylight adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ Daylight is a fork of [safari-mcp](https://github.com/achiya-automation/safari-mcp). safari-mcp's own history, up to 2.24.2, follows Daylight's under [safari-mcp history](#safari-mcp-history).
9
+
10
+ ## [Unreleased]
11
+
12
+ ## [0.1.0]
13
+
14
+ The first Daylight version: safari-mcp 2.24.2 plus the changes below.
15
+
16
+ ### Added
17
+
18
+ - **The visible agent overlay** (`visual-cursor.mjs`). Before each page action, a blue arrow glides to the target with a short label, and a status pill shows the agent's name, the numbered step and its `why`, then ✓ or ✗, then "Thinking…". A thin blue frame marks the page being driven. See [What you see](README.md#what-you-see) and [How it works](README.md#how-it-works).
19
+ - The overlay sits in a closed shadow root in the top layer, above modal dialogs, popovers and fullscreen elements, and out of the page's text, snapshots and clicks. It works on pages with a strict Content Security Policy or Trusted Types, follows its target through scrolling, reflow, open shadow roots and same-origin iframes, and respects reduced motion.
20
+ - The overlay is hidden while `safari_screenshot`, `safari_screenshot_element` and `safari_save_pdf` capture. `safari_evaluate`, `safari_eval_file`, `safari_paste_image` and `safari_handle_dialog` show a line in the pill.
21
+ - Typed text reaches the page only as a preview of at most 28 characters, once the page has shown that the field is an ordinary one. Secret-looking fields, card- and ID-like values, frames and typing with no target get only the length. See [Private data](SECURITY.md#private-data).
22
+ - **Stop.** A Stop button in the pill, Esc in the page, or **■ Stop agent** in the menu bar holds every later tool call that acts on a page, on any page and in any tab. Reads still run. A held call returns "STOPPED BY USER", which tells the agent not to act and to ask the user. See [Stop and Resume](SECURITY.md#stop-and-resume).
23
+ - The server checks Stop before every page action, and again right before it acts, after the arrow's glide and the risky wait. `safari_run_script` checks before every step that is not a read, and shows its steps as their tools do. `safari_new_tab`, `safari_switch_tab`, `safari_close_tab`, `safari_wait_for_new_tab` and `safari_run_script`'s tab steps take the overlay off the tab the agent leaves, and put it back when the move does not happen.
24
+ - A cue the page could not run, or answered with something that is not an answer, is followed by a bare Stop check that carries no agent text; a page that does not answer in time is not asked again. After a held check it did not answer, the session's held calls of the next 2 s are refused without asking it.
25
+ - The Stop button takes clicks while actions run, except while an action of the agent's aims at a point under it, where it rests (also while the pill slides in). The second click of a double click on Stop, which lands on Resume, never resumes. After 25 idle seconds a small Stop stays at the top of the page.
26
+ - The pill hangs from its right edge near the top centre, so its Stop button keeps its place whatever the pill says; on a narrow page, or with Safari's minimum font size, a long agent name is cut rather than move it, and what still does not fit spills out on the left.
27
+ - A Stop pressed just before the page went away is kept in that tab's session storage, and one pressed while an action runs is read right after it.
28
+ - **The menu bar item**, the helper's new `--stop-button` mode: a process of its own that names the agent (`DAYLIGHT_AGENT_NAME`). The server reads it before and after every page action, whatever page or tab the agent is on, so its Stop is not lost when a page opens another site. It starts again at the next page action if its process went away. See [The menu bar item](SECURITY.md#the-menu-bar-item).
29
+ - **Resume in the menu bar.** While the agent is held, the item reads **■ Agent stopped** and carries a menu whose one entry, **▶ Resume agent**, lets it go on at once, even with no tab left to show a Resume button in. A click on the item then only opens that menu, so a double click on Stop, or a second click made to be safe, never resumes.
30
+ - **Resume on the page** needs the one-time proof that a click on the overlay's Resume button leaves, and then your Resume in a macOS dialog of its own `osascript` process. "Keep stopped" is the default, and no answer within 45 s keeps the Stop. The dialog names the agent and the host of its tab, and comes when the agent next acts, at most once every 5 s. See [Resume on the page](SECURITY.md#resume-on-the-page).
31
+ - A Resume pressed before the server has read the Stop needs the dialog too. The server holds the agent until you answer, which decides that step, but for one rare race. Until then the page answers every Stop check as stopped, so a parallel call is refused whatever order the answers come in. If the page moves within its site before that step, the new page shows Stopped, and a Resume there brings the dialog.
32
+ - A menu bar Resume lets go a page's Stop the server has read, also once the page has moved within its site, and a page Resume of such a Stop, with no dialog. A page Resume of a Stop the server has not read still brings the dialog.
33
+ - A menu bar Stop drops every page Resume not confirmed yet, since the item cannot tell which came first: the next step is refused with no dialog, and a dialog already open keeps the Stop. A menu bar Resume read after that Stop ends this.
34
+ - Once the server has read a Stop, a page that stops answering, flips the overlay back or fakes the Resume click releases nothing. Before that, a faked Resume click brings the dialog too, but such a page can still make the Stop go unseen. The server keeps only finite numbers from a page's answers and waits at most 1 s for a glide it reports. See [What a hostile page can still do](SECURITY.md#what-a-hostile-page-can-still-do).
35
+ - **HTTP daemon mode:** each session has its own Stop, and the one menu bar item holds them all, also a session that starts later (a client that reconnects). Its Resume, offered while every session is held, lets them all go on; the "STOPPED BY USER" answer says so, and how to get there while another session runs. An ended session no longer counts, and its page's Stop goes with it. See [HTTP daemon mode](SECURITY.md#http-daemon-mode).
36
+ - **Risky clicks.** A click on a Send, Pay or Delete style button, or a key press that sends, turns the arrow red, adds "may be irreversible" to the pill and waits `DAYLIGHT_RISK_MS` (500 ms) while Stop still works, then checks Stop again. The built-in words are English. A click on a checkbox, radio, switch or form field is never risky. See [The risky-click wait](SECURITY.md#the-risky-click-wait).
37
+ - **The `why` argument**, an optional string on every tool that shows the arrow and on `safari_fill_form` and `safari_fill_and_submit`. The pill shows it, cut to 80 characters. Page scripts can read it, so its description tells agents never to put passwords, codes, card numbers or other private data in it.
38
+ - **Settings:** `DAYLIGHT_AGENT_NAME`, `DAYLIGHT_RISK_MS`, `DAYLIGHT_RISKY_WORDS`, `DAYLIGHT_SECRET_WORDS`, `DAYLIGHT_VISUAL`, `DAYLIGHT_SHOW_TAB`, `DAYLIGHT_NO_HELPER` and `DAYLIGHT_SILENT_INSTALL`, plus `DAYLIGHT_TEST_RESUME` and `DAYLIGHT_TEST_UI` for tests only. The README describes them.
39
+ - **`safari_new_tab` shows the agent's tab.** The new tab becomes the current tab of the window it opened in, found there by the session's marker (never by a bare index or as the front window), without activating Safari, so the overlay can be watched. `DAYLIGHT_SHOW_TAB=0` or `DAYLIGHT_VISUAL=0` keeps it in the background.
40
+ - **Native typing as key events.** `safari_native_type` into rich editors and cross-origin frames, and the native fallbacks of `safari_fill` and `safari_type_text`, send key events that carry the text (the helper's new `typeText` command). They used the clipboard and Cmd+V, which macOS 26 does not paste while Safari is in the background. The clipboard is no longer touched, and the field is read back, so text that did not arrive is reported.
41
+ - The demo: `media/demo.mp4`, `media/demo.gif`, `media/poster.png`, and `demo/index.html`, the made-up page they were recorded on.
42
+ - **One-click installs.** `daylight.mcpb` for Claude Desktop, attached to each GitHub release and built by `scripts/build-mcpb.mjs` (the npm package's files, its production dependencies, `media/icon.png` and a manifest), and Add to Cursor and Install in VS Code links in the README.
43
+ - `SECURITY.md` and `CHANGELOG.md` in the npm package, since the README links to them.
44
+ - Tests: `test/overlay-page.test.mjs` and `test/overlay-driver.test.mjs` (on `test/overlay-harness.mjs`), `test/overlay-hooks.test.mjs`, `test/bridge-off.test.mjs`, `test/native-keys-fronted.test.mjs`, `test/page-script-escaping.test.mjs`, `test/risky-words.test.mjs`, `test/doc-claims.test.mjs` and `test/postinstall.test.mjs`, plus end-to-end suites in `e2e/` that drive a real Safari, the menu bar item and the Resume dialog.
45
+
46
+ ### Changed
47
+
48
+ - Dependencies: `ws` 8.23.1 and, through the MCP SDK, `cross-spawn` 7.1.2, for the two advisories `npm audit` reported.
49
+ - **New name.** The npm package and its command are `daylight-mcp`, and the MCP server calls itself `daylight-mcp`. The startup banner, log lines, errors and `safari_doctor` say Daylight, the banner has no GitHub star line, the postinstall message is Daylight's (with README's MCP config), and the package metadata carries no upstream links or funding.
50
+ - **The native helper is `daylight-helper`** (was `safari-helper`, a name that read like an Apple component in macOS privacy settings). Its codesign identifier is `daylight-mcp.helper` (was `com.achiya-automation.safari-mcp`).
51
+ - **The Safari extension bridge is off** (`_BRIDGE_OFF` in `index.js`). Every page action takes the AppleScript and native helper path, which the overlay and its Stop check take too. With the bridge on, an action could reach a page the overlay could not reach, and another process holding the proxy token could drive the extension through this server. See [No Safari extension](README.md#no-safari-extension).
52
+ - With the bridge off, nothing listens on its ports (9224 and 9223): there is no pairing and no proxying through another server's bridge, and the server creates and reads no bridge token files. Nothing waits for the extension (`safari_native_click` waited 4 s on every call), and `safari_new_tab` no longer says to wait for it.
53
+ - A tab receipt passed to a tool is refused with an explanation: adopting it cleared the session's tab, and every later call failed. Tool descriptions no longer offer receipts or describe the extension path, `safari_doctor` reports the bridge as off, and `safari_reload_extension` only reports that the extension is not in use. `safari_list_frames` and `safari_evaluate`'s `frame`, which need the extension, say so and are refused.
54
+ - **Daylight's own state directory**, `~/.daylight-mcp` (was safari-mcp's `~/.safari-mcp`), for its record of which pages its agents opened, the HTTP daemon's session id, the banner's state and the focus-restore trace. It no longer shares these files with an installed safari-mcp.
55
+ - **`safari_doctor`, the helper and `postinstall` send the macOS permissions to the app the MCP client runs in**, never to the helper. Under launchd, they send them to node, and to `daylight-helper` too if a check still fails. The advice to enable `daylight-helper` in place of that app is gone, and so are the claim that its codesign identifier keeps the Accessibility grant and the startup warning about that identifier. See [The native helper](SECURITY.md#the-native-helper).
56
+ - `safari_doctor` still reports the helper's identifier, as a sign of a build that skipped `scripts/build-helper.sh`. Its Screen Recording line names the tools that fail without it and no longer points to extension screenshots.
57
+ - **`SAFARI_PROFILE` stops the server at startup** with an explanation. A named profile is driven only through the extension, so every call would have waited for an extension that never connects.
58
+ - **`safari_click` reports instead of escalating.** When a synthetic click has no visible effect within about a second, it says so instead of firing a native click on its own. On macOS 26 that press landed on whatever window was on top at that point, and a slow handler that had already run got a second click.
59
+ - A hidden, disabled or zero-size element gets "Not clicked" (nothing is sent), and a form stopped by an invalid field gets "Not submitted".
60
+ - **Native input is refused rather than misdirected.** Native keys and typing need the agent's window to be Safari's front window (and Safari to be the frontmost app when no window is known), and a click at a screen point (the file dialog) needs that Safari window to be on top at that point.
61
+ - Selector lookups take the first visible match (page, open shadow roots, same-origin iframes), so a tool acts on the element the arrow shows, not on a hidden copy earlier in the page.
62
+ - The helper is replaced after 3 consecutive timeouts (was 5), and a late "timed out" reply no longer counts as a sign of life.
63
+ - safari-mcp's `test-daemon-session-id.mjs` moved into `test/daemon-session-id.test.mjs`, so `npm test` runs it.
64
+
65
+ ### Fixed
66
+
67
+ - Page JavaScript that reaches the page after its caller gave up does nothing. Behind a page's `alert()` or `confirm()`, queued scripts used to run when the dialog closed, among them clicks the caller had already reported as failed. The helper also drops a queued script whose time has run out and runs AppleScript on its main thread with a real run loop. Arming that guard leaves a tool's arguments unchanged.
68
+ - One click event per click. A `.click()` plus a dispatched click ran handlers twice (toggles flipped back, forms submitted more than once), and a `location.href` assignment after a link click loaded links twice. Checkboxes, radios, labels and submit buttons go through a real click.
69
+ - A click on a custom switch or checkbox (a real input at opacity 0) reaches the input, and a click never climbs to a container much larger than its element.
70
+ - A ref whose element is gone is found again only when exactly one visible element fits; otherwise the agent is told to take a new snapshot. Text matches prefer what a person could click (on screen and on top), and the options of a closed `<select>` no longer match.
71
+ - `safari_press_key` sends the legacy `keyCode` and `which`. Enter submits the way Safari does (it clicks the form's first submit button, or submits a form with a single text field), presses a focused button or summary and follows a focused link. Tab moves only to elements that can take focus, and Space presses a focused button, checkbox, radio or summary.
72
+ - `safari_fill` and `safari_fill_form` no longer blur comboboxes and autocomplete fields, which cleared what was typed. `safari_fill_form` values arrive as written (`O'Brien`, line breaks), and a quote or backslash around the 20th character of a value no longer breaks `safari_fill`.
73
+ - `safari_type_text` with a selector fails when the element is missing or cannot take focus, instead of typing into the field that had focus before.
74
+ - `safari_fill_and_submit` without a submit selector clicks the first submit button of the filled form, not the first one on the page.
75
+ - The page helpers are checked before every action. A page that had navigated on its own left the next click or fill without them, and it did nothing.
76
+ - `safari_go_back`, `safari_go_forward` and `safari_reload` claim the URL they land on, so the next call is not refused as "not opened by this MCP session".
77
+ - **Native keys go to the agent's tab.** The native fallbacks of `safari_type_text` and `safari_fill`, `safari_press_key`'s Cmd+V into a cross-origin frame and `safari_replace_editor`'s Monaco fallback measured the front window. With another Safari window in front, the keys went there, and in the agent's window they went to the tab the user had selected. They now run with the agent's tab selected and are refused while another Safari window is in front.
78
+ - `safari_replace_editor`'s Monaco fallback types the text as key events and reads the editor back, falling through to the next way when the text differs. It used the clipboard and Cmd+V, which a background Safari ignores on macOS 26, and reported success unchecked.
79
+ - **Tool arguments stay data.** runJS's comment stripper took U+2028 and U+2029 for line starts, so an argument with one of them followed by `//` lost the rest of its line, closing quote included. `safari_verify_state`, which escaped `expected` only for quotes, backslashes and newlines, then ran it as page code, and Stop does not hold a read tool.
80
+ - **Native input of two HTTP sessions no longer mixes.** The native-input section (the session's tab selected, its window measured) kept its depth and its window in process-wide variables. So while one session's step ran, another session's native keys skipped selecting its own tab and went to the first session's tab. One such section now runs at a time, and what it selected lives in its own async context.
81
+ - `npm test` exits on its own and leaves no process behind. With `--test-force-exit` the runner left test processes running, each holding a helper, and cut its own report short.
82
+
83
+ ### Removed
84
+
85
+ - Upstream's directory listings and manifests: `glama.json`, `server.json`, `smithery.yaml`, `smithery-entry.js`, `mcp.json`, `.mcp.json` and the `Dockerfile`.
86
+ - The `xcode/` container app, `scripts/release-app.sh`, `scripts/embed-bridge-token.sh` and its test, `cli.js` with the `pair` command, and `test/bridge-port-takeover.test.mjs` (replaced by `test/bridge-off.test.mjs`).
87
+ - `extension/` from the npm package. The directory stays in the repository because upstream's unit tests read it; its new `README.md` says so.
88
+ - `.github/FUNDING.yml`, `.github/CODEOWNERS`, and the publish, OpenSSF Scorecard and stale-PR workflows. Publishing is manual for now.
89
+ - Upstream's blog posts and covers, `social-preview.png`, `.launch/` and `assets/`.
90
+
91
+ ---
92
+
93
+ # safari-mcp history
94
+
95
+ Everything below is the changelog of [safari-mcp](https://github.com/achiya-automation/safari-mcp) up to 2.24.2, the version Daylight is based on, kept as its author wrote it. Commands, files, issue numbers and links in it (`npx safari-mcp`, the extension app, pairing) refer to safari-mcp, not to Daylight.
96
+
97
+ ## [2.24.2] - 2026-11-24
98
+
99
+ ### Security
100
+ - **No read tool returns what a password, one-time-code or payment-card field holds.** `safari_snapshot` printed `value="…"` for every filled input, so on a sign-up form it returned the password the user had just typed, and the password reached the agent's transcript. A field is sensitive when it is `type="password"` or its `autocomplete` names `current-password`, `new-password`, `one-time-code` or a `cc-*` token. Its value is now reported as `[redacted N chars]`, so an agent still sees that the field is filled and how long the value is. This covers `safari_snapshot` (also with `selector` and `diff`), `safari_read_page` with a selector, `safari_get_element` (its `value` and its `value` attribute), `safari_query_all`, `safari_get_source`, `safari_accessibility_snapshot`, `safari_detect_forms`, `safari_verify_state`, the result of `safari_fill`, and the label a native click reports. Other fields keep their values. The server also masks every extension reply (`sensitive-fields.js`), so an extension app built before this release is already covered in `safari_get_element`, `safari_get_source` and `safari_read_page` with a selector (there the server asks `get_element` what the field is, and masks the value when it cannot tell), and for password fields in `safari_snapshot` and `safari_query_all`. One-time-code and card fields in that app's snapshots and `safari_query_all` results are masked once the extension app is rebuilt. `test/sensitive-field-values.test.mjs`. Manifest 2.10.35.
101
+
102
+ ## [2.24.1] - 2026-11-15
103
+
104
+ ### Fixed
105
+ - **Native input no longer takes the user's focus.** `safari_native_click`, and `safari_click`'s native fallback, used to activate Safari, raise its window and move the cursor. They now go through WebKit's accessibility tree (the helper's new `axDom` command, by DOM id): `press` fires a trusted `mousedown`/`mouseup`/`click`, and `value` fires a trusted `beforeinput`/`input` without touching the clipboard. Safari is never activated and the cursor does not move. `safari_native_type` sets inputs and textareas the same way; rich editors keep the paste, sent to the Safari window without activating it. Native keystrokes are refused when another Safari window is in front, and the native file-dialog escalation in `safari_upload_file` runs only when Safari is already in front.
106
+ - **`pbcopy`/`pbpaste` run with a UTF-8 locale.** Under launchd they fell back to MacRoman, so non-ASCII text (Hebrew) was pasted, and the user's clipboard restored, as mojibake.
107
+
108
+ ## [2.24.0] - 2026-11-15
109
+
110
+ ### Added
111
+ - **The Safari extension pairs with `npx safari-mcp pair` instead of carrying your bridge token from the build.** A local Xcode build bakes this Mac's bridge token into the extension, so one signed app could not serve everyone. Now `npx safari-mcp pair` prints an 8-character code. It works once, expires after 10 minutes, burns after 5 wrong tries, and is stored only as a SHA-256 in `~/.safari-mcp-pairing`. The user enters it in the extension popup. The bridge's new `POST /pair` endpoint answers only an extension origin and returns the token, which the extension keeps in `browser.storage.local`. The token never appears in a URL or a log. Until the extension is paired, the toolbar badge reads **PAIR** and the popup shows the two steps. The same happens when the bridge stops accepting the token. A local build still embeds the token and connects without pairing; a paired token takes precedence. `test/pairing.test.mjs`. Manifest 2.10.34.
112
+ - **`scripts/release-app.sh` builds the downloadable app.** It archives with no bridge token inside (`SAFARI_MCP_EMBED_BRIDGE_TOKEN=NO`), exports with a Developer ID, notarizes with `notarytool`, staples, checks Gatekeeper, and attaches `Safari-MCP.app.zip` to the GitHub release. The README now installs the extension from `releases/latest/download/Safari-MCP.app.zip`, and building from source is the contributor path. A release cut without a new build gets the newest zip from an older release (`release.yml`), so the link keeps working. Xcode registers each copy it builds with LaunchServices, so the script unregisters them as they appear: a Mac that already runs Safari MCP keeps using its installed extension.
113
+
114
+ ### Fixed
115
+
116
+ - **`safari_click` opens menus when the tab's content bridge does not answer.** The recovery path in `sendContentCommand` sent only a focus and a `click`, and answered `Scheduled mcp-content-click` as if it had worked. Radix dropdowns and anything else that opens on `pointerdown` stayed shut (reproduced with `@radix-ui/react-dropdown-menu` 2.1.6 on Safari 27.2). The recovery path now sends the same pointer and mouse sequence as the bridge. `rel="dialog"` links keep their bare click. The Safari extension has to be rebuilt to get this.
117
+ - **`safari_press_key` sends the key names it documents.** With the extension, `down` or `enter` reached the page as the literal strings `"down"` and `"enter"`, which pages ignore. Only `ArrowDown` and `Enter` worked. The server now translates the short names before sending them.
118
+
119
+ ### Changed
120
+ - **The macOS app's `MARKETING_VERSION` matches the extension manifest again (2.10.34).** It had stayed at 2.10.27 while the manifest moved on, so the app and the extension inside it reported different versions from the bundled manifest.
121
+ - **The npm `bin` is `cli.js`.** It runs `safari-mcp pair` without starting the server, and otherwise loads `index.js` as before.
122
+
123
+ ## [2.23.0] - 2026-10-28
124
+
125
+ ### Added
126
+ - **`safari_snapshot({ diff: true })` returns only what changed since that tab's previous snapshot.** After a click or a fill an agent usually needs the few lines that changed, not the whole page again. Lines compare without their refs, which every snapshot renumbers in page order, so an element inserted near the top changes one line instead of all the lines after it. `+` lines are new and carry fresh refs; `-` lines are gone and are shown without their dead refs, at most 50 of them. The first call for a tab returns the full snapshot. Every snapshot is remembered (the newest 50 tabs per process), so a plain snapshot is a base for the next diff. Idea and tests from PR #201 by @fahadjibransheikh. `test/snapshot-diff.test.mjs`.
127
+ - **`SAFARI_MCP_TOOLS=core` registers only the everyday tools** (tabs, navigation, snapshot, reading, clicks, forms, evaluate, console, network, doctor), or a comma list of tool names, `core` allowed among them. For clients that load every tool definition up front. Unset or `all` registers every tool, as before. Idea from PR #204 by @fahadjibransheikh. `tests/smoke.test.js`.
128
+ - **An HTTP session that ends closes the tabs it opened.** A session's `DELETE` used to leave its tabs open until the daemon restarted, up to `MCP_MAX_TABS` for every finished session. A tab whose close fails stays tracked for the shutdown cleanup. `SAFARI_MCP_SESSION_IDLE_MIN` can also end a session after that many idle minutes; unset or `0`, the default, never ends a session for being quiet, so a client that is only waiting keeps its tabs and receipts. Idea and tests from PR #202 by @fahadjibransheikh. `test/transport-http.test.mjs`.
129
+
130
+ ### Changed
131
+ - **`safari_snapshot` is smaller on table and div layouts.** A `div`, `span`, `table`, `tr`, `td` or `th` with nothing of its own (no ref, role, id, label or title) is now only its content, with a line break after block ones and a space after cells and spans, so neighbouring texts stay apart. A link on the page's own origin is shown as its path. On a table layout these tags and the repeated origin were most of the snapshot. Idea and tests from PR #200 by @fahadjibransheikh. `test/snapshot-compact.test.mjs`. Manifest 2.10.32; the extension path picks it up once the extension app is rebuilt.
132
+
133
+ ### Fixed
134
+
135
+ - **An automation tab keeps rendering while hidden or while the screen is locked.** Safari stops `requestAnimationFrame` in every hidden page, a background tab or every tab while the Mac is locked, so apps that paint a streamed answer on the next frame froze mid-answer: on 2026-10-26, with the screen locked, Perplexity stayed at the first 173 characters of its answer for minutes. The post-load visibility spoof did not help, since the page had already captured the native frame clock and the spoof never reached a page that redirected before it was stamped. `content.js` now wraps `requestAnimationFrame` at `document_start`; a tab the extension owns (`command-content.js` asks the background, which answers a boolean for the sender's own top frame) gets a 50 ms timer fallback for every frame the browser withholds, and reads as visible. The user's own tabs keep the native behaviour and cost nothing while hidden. `test/keep-rendering.test.mjs`. Manifest 2.10.31.
136
+ - **`safari_upload_file` no longer reports a failed upload when the page read the file and emptied the input.** Google Business Profile's composer clears its file input as soon as it takes the file, so the check saw `verified 0 file(s)` and went to the native file dialog, which cannot open on a locked screen, and the answer read as a failure while the image sat in the post. With `verifyPreview`, a preview that appears within 3 s (90 s on a locked screen) now counts as the upload.
137
+ - **A profile no longer loses its extension for good after the Mac sleeps.** On waking, the daemon's stale timer saw a poll older than the timeout, dropped the profile's worker with no successor, and woke the worker's own open `/poll`. That poll's check compared the worker against an empty lease holder and answered `423 Worker superseded`, which tells a worker that a replacement verified, so it went dormant until Safari reloads it. In a profile with open pages the content-script keepalive pings that worker every few seconds, so Safari never recycled it: on 2026-10-26 the automation profile answered every tool call with `Safari profile extension unavailable` from 00:03 until the extension was reloaded, its heartbeat frozen at the last tick before sleep, while `safari_doctor` showed only other profiles' workers. An open poll whose worker was dropped with no successor now answers `409 Worker reconnect required`, as the `/poll` gate already does, and the worker reconnects. `test/poll-wake.test.mjs` checks the order. Manifest 2.10.27 — rebuilding the extension app makes Safari reload the extension, which also releases a worker already stuck this way.
138
+
139
+ ## [2.22.19] - 2026-10-26
140
+
141
+ ### Security
142
+ - **`body-parser` 2.3.0 → 2.4.0 and `zod` 4.4.3 → 4.6.7, both through `@modelcontextprotocol/sdk`**, close two high advisories that failed CI's production audit: a denial of service from trailing bytes after a compressed request body in HTTP mode (GHSA-27r3-jxmh-p828), and memory exhaustion while validating oversized constrained collections (GHSA-mrhx-c7xc-m3w5). The same update takes `fast-uri` 3.1.8 → 3.1.9 (four moderate advisories, via `ajv`), `ip-address` 10.7.2 → 10.7.5 (GHSA-rxp7-6hxx-x8q5, via `express-rate-limit`) and `qs` 6.16.0 → 6.16.1. Lockfile only; the declared ranges are unchanged.
143
+ - **`undici` 7.30.0 → 7.30.1** (dev, through `jsdom`): a denial of service from an unhandled error on excessive content encodings (GHSA-xjj6-f33q-929c). Lockfile only. Together with the entry above this covers Dependabot #192–#196.
144
+
145
+ ### Fixed
146
+ - **`safari_snapshot` no longer comes back empty when the page sits inside a `display: contents` wrapper (#187).** Such an element has no box of its own, so its rect is 0×0, and the extension's snapshot walk stopped at any node it judged invisible, children included. A page whose app root used `display: contents` returned an empty snapshot while `safari_read_page`, `safari_query_all` and clicks all worked. The walk now looks through those wrappers to their children; `display: none` still hides a subtree. Reported, with a minimal reproduction and the exact line, by @fakepooh.
147
+ - **`safari_click` checks a checkbox instead of leaving it unchanged, and no longer follows a link inside its label, on the AppleScript path.** The page helpers called `.click()` and then dispatched a click, and a checkbox, a radio or a label bound to one toggles on each, so the box ended where it started. When the box's label wrapped a link (a consent line with a policy link), the probe points could also land on that link and follow it. A form control now stays the click target, and a toggle gets one click. The extension path already dispatched a single click. Idea and test cases from PR #176 by @kad-xyz. The page helpers move to version 7, so pages that still hold the old ones pick up the fix.
148
+ - **`safari_new_tab` waits briefly for the extension after a short drop-out instead of opening a tab without a receipt.** Safari suspends the extension's worker now and then. A new tab requested in that gap went to AppleScript, came back with no receipt, and the extension refused that tab once it was back. When the extension served the daemon in the last two minutes, `safari_new_tab` now waits up to about 10 seconds for it before falling back, and a tab AppleScript does open says so in its result (`receipt: null`, `via: "applescript"`, with a note). Idea and diagnosis from PR #190 by @kad-xyz.
149
+ - **Safari no longer stays in front after an operation steals focus while the user is typing in another app.** On macOS Tahoe some AppleScript commands implicitly activate Safari, and the focus guard gives the foreground back to the app the user was in. It skipped that restore whenever there was any keyboard or mouse input in the last 2.5 seconds, reading it as "the user switched into Safari". A user typing in another app always has recent input, so Safari kept the foreground and took their keystrokes. Typing cannot switch apps; the guard now skips the restore only when a mouse button or a modifier key (Cmd+Tab, Spotlight) was pressed after the operation began.
150
+ - **A profile's extension finds its own daemon when the bridge it remembered now belongs to another profile.** The extension tries the bridge it connected to last before scanning the ports. When daemons come back on different ports, that bridge can be another profile's daemon, which answers `/connect` with 423 while its own worker holds the lease. The extension stopped at that 423 and retried the same bridge every 3 seconds, so the profile never reconnected until its stored bridge was cleared by hand. A 423 now moves on to the next port, and the short lease retry runs only when no bridge accepts the worker.
151
+
152
+ ### Changed
153
+ - **`zod` is declared as a dependency** (`^3.25 || ^4.0`, the range `@modelcontextprotocol/sdk` uses). `index.js` imports it directly but relied on npm hoisting the SDK's copy, which a strict installer such as pnpm does not do. Idea from PR #177 by @fahadjibransheikh.
154
+ - **`eslint` 10.12.0 → 10.13.0** (#175). Dev dependency only.
155
+
156
+ ## [2.22.18] - 2026-10-19
157
+
158
+ ### Fixed
159
+ - **A client that navigates its tab to another origin keeps working in it, without `SAFARI_PROFILE` (#172).** When the extension served `safari_navigate` or `safari_navigate_and_read`, safari.js kept the URL the tab had left as the session's current page, and the tool then released that URL from the session's ownership. Every later write of the same client (click, fill, evaluate) was refused with "current tab (<the URL it left>) was not opened by this MCP session", whichever receipt it passed. A same-origin navigation hid it, because an owned URL that differs only in its query still matches. Both tools now pin the session's current page to the URL they were asked for, which the navigation has already claimed, as `safari_new_tab` does. Where a redirect took the tab is not claimed: that is the site's choice, not the caller's. Nothing is pinned when a call alongside has made another tab the session's current one. Named-profile mode was not affected. Reported, with a live reproduction, by @jkrygel.
160
+
161
+ ### Docs
162
+ - **The README's extension build step re-signs `safari-helper` with the stable identifier** (`--identifier com.achiya-automation.safari-mcp`), as `scripts/postinstall.cjs` already does. Without it the re-sign replaced the identifier with a hash-based one, and macOS keys the Accessibility grant to the identifier, so native clicks stopped working after the next reinstall (#173, by @jkrygel).
163
+
164
+ ### Changed
165
+ - **`actions/setup-node` 7.0.0 → 7.1.0** (#164), **`@types/node` 26.6.4 → 26.6.5** (#167), **`prettier` 3.9.9 → 3.9.10** (#166). CI and dev dependencies only.
166
+
167
+ ## [2.22.17] - 2026-10-14
168
+
169
+ ### Changed
170
+ - **`@modelcontextprotocol/sdk` 1.31.0 → 1.32.1** (#165). Lockfile only; the declared range is unchanged.
171
+
172
+ ### Fixed
173
+ - **Contexts Safari kept from an older app no longer break receipts, and the daemon retires them (#143).** Replacing the extension app does not stop the contexts Safari had already started. Each keeps its own in-memory receipts, writes its own envelope under an epoch of its own, and becomes the daemon's lease holder again every time it verifies, so a lease moving between an old context and a new one lost the receipts the other had minted. Measured on 13.10.26 after the epoch change above shipped: an old context's envelope replaced the new one's twice in ten minutes, and a receipt minted by the new build was refused one command later when an old context held the lease.
174
+ - **The build stores its state under keys no older build touches** (`mcpOwnedTabReceiptsV4`, `mcpOwnedTabsLocalV2`; earlier builds use `...V3` and `mcpOwnedTabsLocal`), so an old context that is still alive cannot replace what this build stored.
175
+ - **The extension announces its build on `/connect`** (`&build=isolated-envelopes-1`). The daemon remembers it with the connecting worker.
176
+ - **The daemon reloads a lease holder that announced no build**, through the same `reload_extension` command `safari_reload_extension` sends, with the reload handoff that lets the replacement worker take the lease (a reload that fails is logged, not swallowed): asked on every poll of the lease holder until it has been reloaded (a command in flight, or a reload a moment ago, only delays it), at most one reload per 20 s and ten per ten minutes. The reload restarts that context from the app now on disk, and the replacement announces the build. A worker that announces any build is never reloaded, so a newer extension talking to an older daemon is left alone. `SAFARI_MCP_NO_AUTO_UPGRADE=1` turns it off.
177
+ - **Reloading turned out not to remove an old context, so the daemon now decides who leads instead (measured 13.10.26).** Safari keeps the extension context of every app generation it ever loaded: its process had the resources of a dozen builds mapped, the deleted ones included, and each context wakes every minute and verifies. Reloading an old lease holder restarts the same old generation, so 45 reloads in 90 minutes never ran out of old contexts. A worker that announced no build now never takes the lease while a current one has verified in the last 15 minutes (it gets the same `worker_lease_held` answer as any worker refused the lease), and a current worker takes it from an old holder at once, unless a command is in flight to that holder or a reload handoff is pending. Reloading is skipped while a current context is around and remains the fallback when none is. The daemon logs every lease change with the build and a short hash of the extension origin of both holders (`lease: 1a2b3c4d (no build, origin 9f3c1a) -> 5e6f7a8b (isolated-envelopes-1, origin 77b2e0)`). Quitting and reopening Safari still removes the old contexts for good.
178
+ - **Current contexts are told apart by extension origin, and one of them leads (measured 13.10.26).** Safari can keep more than one context of the current build alive as well, and each has tab ids of its own: a receipt resolved only in the context that minted it, and any write from another context rewrote the shared envelope without the records it could not resolve (an empty envelope after one `close_tab`). The extension origin of a request identifies the context, so the first current context to lead becomes the home context, and no instance of another origin takes the lease while the home context has been seen within 100 seconds (as a lease holder's poll, or as an instance verifying). When it goes quiet, another current context may lead and becomes the home context. The log says so: `home context: af194c -> 77b2e0`, and `lease: worker 1a2b3c4d of context 77b2e0 waits, context af194c leads` (at most once per context every five minutes).
179
+ New: `worker-upgrade.js`, `test/worker-upgrade.test.mjs`. Existing harnesses that run the connect handshake or read the envelope keys gained the new constants. The extension part takes effect once the extension app is rebuilt; the daemon part once the daemon restarts.
180
+
181
+ ### Fixed
182
+ - **A receipt from `safari_new_tab` survives the extension worker being replaced (#143).** The extension named the browser session with a value kept in `storage.session`, and Safari gives every worker instance its own `storage.session`. So the epoch rotated with each worker succession, instances alive together held different ones, and the first tab removal afterwards made every instance rewrite the shared receipt envelope under its own epoch and drop what the others had stored. On 13.10.26 a receipt stopped resolving about a minute after it worked while Safari's process kept running, and four envelopes written in the same millisecond carried four different epochs. Three changes:
183
+ - **The daemon names the browser session.** Every authenticated bridge response now carries `X-Safari-MCP-Browser-Epoch`, the identity of the running Safari process (`<pid>:<start time>`, read from the process table at most once a second). The extension derives its epoch from it and keeps the last one in `storage.local`, so every worker instance agrees on the epoch and only a Safari restart changes it. A daemon that sends no hint leaves `storage.session` as the authority, as before.
184
+ - **Only the worker that holds the daemon's lease writes the shared envelopes.** A superseded, retiring, disabled or disconnected instance still receives tab events and still holds the maps from when it last hydrated; it no longer writes them over the live worker's receipts. A command's own durable write is refused only once its worker has been superseded.
185
+ - **A receipt this instance has never seen is looked up in the shared envelope again before it is refused**, in case another instance minted it after this one hydrated. A string that is not shaped like a receipt still causes no storage read.
186
+ New: `safari-session-hint.js`, `test/safari-session-hint.test.mjs`, `test/stable-browser-epoch.test.mjs`. The two existing harnesses that run the changed functions directly (`browser-epoch-rotation`, `envelope-writer`) gained the new dependencies. The extension part takes effect once the extension app is rebuilt; the daemon part once the daemon restarts.
187
+
188
+ ## [2.22.16] - 2026-10-13
189
+
190
+ ### Added
191
+ - **Every ownership envelope the extension writes names the worker that wrote it.** `mcpOwnedTabReceiptsV3` and `mcpOwnedTabsLocal` in `storage.local` now carry `writer`, the first eight hex characters of the worker id that the server log prints (`worker 88d445b4`). On 13.10.26 a receipt from `safari_new_tab` stopped resolving about a minute after it worked, while Safari kept running, and the profile's storage history held four browser-session epochs in five minutes, four envelopes of them written in the same millisecond. That reads as several live worker instances in one profile, each with its own `storage.session`, but an envelope could not say who wrote it. With `writer`, a read-only look at `LocalStorage.db` and its WAL shows it directly and lines up with the server log (#143). Hydration never reads the field. It takes effect once the extension app is rebuilt.
192
+
193
+ ## [2.22.15] - 2026-10-10
194
+
195
+ ### Security
196
+ - **A tool argument can no longer end the JavaScript string it is placed in and run as code in the page.** Sixteen places in `safari.js` that hold a tool argument escaped a single quote but not a backslash in front of it, so a value containing a backslash and then a quote (`\'`) closed the string literal and the rest of the value ran as page JavaScript. Seven of them belong to read-only tools that skip the tab-ownership check: `filter` in `safari_network_details` and `safari_extract_links`, `level` in `safari_console_filter`, `selector` in `safari_snapshot`, `safari_accessibility_snapshot` and `safari_extract_tables`, and `dbName` and `storeName` in `safari_get_indexed_db`. A client that allowed only read-only tools could therefore still run any script, in a tab it does not own. The others are `ref` in `safari_select_option` and the two react-select tools, the key in `safari_press_key`, the file name in `safari_upload_file` and `safari_paste_image`, and the first line of the text in `safari_replace_editor`. All of them now use the shared `escJsSingleQuote`, which escapes the backslash before the quote; the server's own tab-marker check escapes it too, and a test fails if a quote-only escape comes back. Reported privately on 2026-10-09.
197
+
198
+ ## [2.22.14] - 2026-10-09
199
+
200
+ ### Fixed
201
+ - **The screen-lock gate reads `IOConsoleLocked` too, and a failed probe now blocks native input.** The gate in front of every CGEvent path counted only `CGSSessionScreenIsLocked` and treated a probe that failed as unlocked. On macOS 27.0.1 the Root registry entry carries `IOConsoleLocked`, `true` while the console is locked and `false` once it is unlocked (both read on 9.10.26), so the gate now treats either key set to `true` as locked, and an `ioreg` probe that fails or returns an unreadable value keeps native input off instead of letting it through.
202
+ - **`safari_doctor` warns when the server is running on a node binary that no longer exists.** A Homebrew upgrade deletes the node that a long-running LaunchAgent daemon still executes, and System Settings cannot grant anything to a deleted file. On 9.10.26 a daemon started two days before node 26.9.0 was replaced by 26.11.0 went from 6/6 to 3/6 (Apple Events -1743, both helper permissions false) while doctor still said to enable the deleted path. Doctor now names the missing binary and says to restart the server on the current node first.
203
+
204
+ ## [2.22.13] - 2026-10-07
205
+
206
+ ### Fixed
207
+ - **A blank tab from `safari_new_tab()` takes commands by its receipt.** Safari leaves `url` off a blank tab, and the extension read the missing URL as no origin at all instead of the `about:blank` the receipt was minted on. Measured on 7.10.26 in a named profile: a fresh blank tab's receipt was refused on its first command, `safari_navigate` included ("receipt is not valid for this origin"), `getReceipt` could not rotate it ("Cannot issue a receipt for this tab URL"), and the tab could be neither used nor closed. A tab Safari shows no URL for now counts as blank; a receipt minted on a web origin still takes no page command there. Like 2.22.12, the change is in the Safari extension and takes effect once the extension app is rebuilt from this version.
208
+
209
+ ## [2.22.12] - 2026-10-07
210
+
211
+ ### Fixed
212
+ - **`safari_close_tab` closes its receipt's tab after the page moved the tab to another origin.** The extension let only `getReceipt` follow a receipt across origins, so a close of a tab that a redirect or a login bounce had moved was refused with "receipt is not valid for this origin". The rotation that refusal suggests works only when the new page has an http(s) origin: a tab that landed on a page without one, or on a page whose URL Safari does not show the extension, could not be rotated, and nothing could close it (claude.ai/new, 6.10.26: two tabs left open in a named profile). A close runs nothing in the page, so it now locates its tab the way `getReceipt` does; every other command stays bound to the receipt's origin, and a receipt the extension never issued still closes nothing. The change is in the Safari extension, so it takes effect once the extension app is rebuilt from this version ([Installing the Extension](README.md#installing-the-extension)).
213
+
214
+ ## [2.22.11] - 2026-10-06
215
+
216
+ ### Fixed
217
+ - **A page that mentions CSP is read like any other page; it is no longer taken for a blocked command.** The server read any result containing "Content Security Policy", "unsafe-eval", "trusted-types" or "Trusted Type" as the extension saying CSP had blocked it, so reading a CSP guide, a security blog or a GitHub issue about Trusted Types failed in a named profile with `Safari profile extension unavailable for "read_page"; refusing AppleScript fallback`, and without one ran the command a second time through AppleScript: a click on a link titled "Content Security Policy" clicked it twice, since the click's result quotes the link text. The extension never reports a CSP block in a result: every other command's failure arrives as an error. Only `safari_evaluate`'s own marker counts now, matched as the whole reply rather than anywhere in it, and the screenshot permission marker likewise.
218
+ - **In a named profile, an evaluate on a page whose CSP refuses every way to run a script string says so.** It failed with `Safari profile extension unavailable for "evaluate"`, which sent callers after an extension that was working: copilot.microsoft.com allows no eval, and its Trusted Types list leaves out the policies the extension creates, so the script cannot start there. The error now names the page's Content-Security-Policy and the tools that run no script string, such as `safari_read_page` and `safari_snapshot`, which still work on that page.
219
+
220
+ ## [2.22.10] - 2026-10-04
221
+
222
+ ### Fixed
223
+ - **On Node 24, a secondary instance no longer exits when its primary goes away; it takes the bridge port over as intended.** Node 24's bundled undici calls `socket.setTypeOfService()` on every HTTP/1.1 write, outside any catch. On macOS, a socket whose peer has just reset makes that call throw `EINVAL` from inside an I/O callback, where no try/catch around `fetch()` can reach it, so the process ended: a secondary's `/proxy-check` to a primary that had just exited killed the secondary instead of letting it take the port over (#140; the takeover test hit it twice on CI, Node 24 on the macOS runner). undici 8.8.0 ignores these errors (nodejs/undici#5547) and Node 24 never got that fix: measured on 2026-10-04, one `fetch()` calls `setTypeOfService` once on Node 24.21.0 and not at all on Node 26.10.0. The server now wraps `Socket.prototype.setTypeOfService` so that `EINVAL` alone is ignored, and a request to a peer that is gone fails the ordinary way, as a rejected `fetch()`. Type of service is a QoS hint, so skipping it changes nothing else.
224
+
225
+ ## [2.22.9] - 2026-10-03
226
+
227
+ ### Fixed
228
+ - **`safari_upload_file` and `safari_paste_image` reach the session's tab when it sits in another window of a named profile, and take a `receipt`.** Both carry the file through AppleScript, which proves the session's tab by its marker and looked for it only in the first window of the profile, while a profile can hold several and the Safari extension opens or picks the tab in any of them. In Google Business Profile the upload failed with "Tab tracking lost during runJSLarge" right after `safari_new_tab`, and again after `safari_switch_tab` with the receipt. Once the first window has no tab carrying the marker, the upload now asks the extension which window holds the tab (`get_tab_locus`, as `safari_native_click` does) and looks there; the marker still has to be found, and it is checked again inside the script. Both tools also accept the `receipt` every other tool takes, so a caller whose MCP session was re-initialised can name its tab.
229
+ - **`safari_upload_file`'s `verifyPreview` counts an SVG `<image>` preview.** Google Business Profile draws its preview as `<svg role=img><image href="blob:…">`, which the count skipped, so a real upload read as a ghost pickup and was escalated to a native file dialog, which added a second copy of the image. The upload script and the recount after it now share one counter.
230
+
231
+ ## [2.22.8] - 2026-10-02
232
+
233
+ ### Fixed
234
+ - **`safari_navigate_and_read` hands back the tab's new receipt when the page lands on another origin, as `safari_navigate` does, and so do run_script's `navigate` and `navigateAndRead` steps in a named profile.** The extension binds a receipt to the origin it was minted on, and only `get_tab_receipt` may move it to another one. `safari_navigate` rotates the receipt after a cross-origin load the caller asked for and returns the new one; the other three navigations did not, so the tab's next call, with the receipt the tab was opened with or with none, was refused ("receipt is not valid for this origin") until the caller ran `getReceipt` itself. All four now go through one rotation: the receipt the navigation carried is read before it waits, aliased to its replacement so callers that keep the old one still reach the tab, and returned in the result.
235
+
236
+ ## [2.22.7] - 2026-10-01
237
+
238
+ ### Fixed
239
+ - **A call that names no receipt keeps working after another client of the same HTTP daemon rotates the tab's receipt.** In HTTP-daemon mode (`SAFARI_MCP_HTTP`) each MCP client has its own current receipt, while the table that keeps a rotated receipt resolving to the one that replaced it is shared by the whole process. The current receipt went through that table only when it was stored, and was read back as stored. Once one client rotated a tab's receipt (`safari_navigate` to another origin, run_script `getReceipt`), the extension retired the old one, and a second client holding it as its current receipt had every call without a `receipt` refused ("this extension has no record of that receipt"): the page tools, `safari_close_tab`, and the marker the AppleScript fallback has the extension write into the tab. The same calls passing the old receipt worked. The current receipt is now resolved through the table whenever it is read. Separate stdio processes each keep a table of their own, so this does not reach a receipt another process rotated. `test/receipt-alias-shared-daemon.test.mjs` runs two clients of one daemon through the real tool handlers and the extension's receipt code over a fake Safari window.
240
+ - **A receipt rotation no longer takes another tab's receipt, and `safari_navigate` hands back the receipt of the tab it navigated.** Without a `receipt` argument, `safari_navigate` took the receipt it rotates from the session only once the page had loaded, and both it and run_script `getReceipt` left the receipt the extension rotates to be read again after their own waits (for the profile's extension worker, among others). A call running alongside that names another tab of the session makes that tab the current one, so the rotation re-minted that tab's receipt instead: `safari_navigate` handed it back as its own tab's, and when the other call came during the rotation's own wait, the first tab's receipt was also aliased to it, so every later call that passed the first tab's receipt acted on the other tab, and with the entry above so would every client holding it as its current receipt. Both now read the receipt once, when the call starts, and name it in every command they send. Covered in `test/receipt-alias-shared-daemon.test.mjs`.
241
+ - **A receipt keeps resolving however often its tab has been rotated since.** Every rotation added a link to a chain the server follows for at most eight links, so after a handful of cross-origin navigations in one tab (`safari_navigate` rotates the receipt at every origin it leaves) the receipt the tab was opened with, which callers keep passing, was refused ("this extension has no record of that receipt"), and so was every call without a receipt from another client that held it. Every rotation now points all of the tab's older receipts straight at its newest one. Covered in `test/receipt-alias-shared-daemon.test.mjs`.
242
+ - **A call keeps its tab when another client rotates the tab's receipt while the call waits for the Safari extension.** A call reads the receipt it names, or the session's current one, when it starts, and may then wait: in a named profile, until Safari's suspended extension worker is back. A rotation by another client of the same HTTP daemon in that time retired the receipt, and the call was refused ("this extension has no record of that receipt"). The receipt is now looked up again when the command is sent, `safari_navigate` judges whether the tab left its receipt's origin by that receipt, and a rotation records the receipt it actually replaced, so the client that rotated first keeps its new receipt. Covered in `test/receipt-alias-shared-daemon.test.mjs`.
243
+
244
+ ## [2.22.6] - 2026-10-01
245
+
246
+ ### Fixed
247
+ - **A tab opened, closed or moved before the session's tab while a page loads no longer takes that page's probes, its marker or navigate's `set URL`.** Without `SAFARI_PROFILE` (and for `safari_click_and_wait` and `safari_fill_and_submit` in any mode), the steps that pin their scripts to `window id N` still addressed the session's tab by its index in that window, and AppleScript has no tab id. `newTab()` polled its new tab, stamped the session's identity marker on it and read its URL by the index its creation script reported. `navigate()`, `reload()`, `goBack()`, `goForward()`, `navigateAndRead()`, `clickAndWait()`, `fillAndSubmit()` and `scrollToElement()` proved the tab once by its marker, then ran `set URL`, the click or history move, the load polls and the re-stamp by that index. A tab the user opened before it meanwhile (a link opened in a new tab lands right after the tab it came from), a tab closed to its left and another opened, or another session's tab cap closing its oldest tab shifted the session's tab, and those scripts reached the tab now at its old index: `set URL` navigated the user's tab away, and the marker made it the session's, so every later write went there and every close path could close it. Now every script of those steps proves the tab again inside itself before it touches it, in one of three ways. First, by the session's marker on the tab, checked in the same `do JavaScript` that acts. Second, by the marker on another tab of the window; the script then acts there and the step follows the tab, so a tab opened or closed before it no longer fails a step whose page still carries the marker. Third, only when no tab of the window carries the marker: by the page being a document the step's own load brought (newer than the moment the step started its load), in a window that still looks the way the last script that proved the tab saw it. That means the same window, the same tab count, the tab selected or not as before, and the same URLs, compared considering case, in the three tabs before it. The third proof never takes a page carrying another session's marker. It is not used while a tab to the right of the session's does not answer, since that tab may be the session's, moved; the poll retries instead. It never serves the scripts that run before the step's load, which need the marker: `set URL` and navigate's two retried `set URL`s, the click, `history.back()`/`forward()`, `location.reload()` and a scroll step. Those scripts also stamp the page they are about to leave, so a page the back/forward cache brings back still carries the marker, and `goBack()`/`goForward()` stamp the page they land on in full. A page where no script runs, such as the Start Page, proves nothing. A page script that throws in a proven tab no longer reads as a lost tab or runs a second time. The load polls stamp a page that lost the marker, the script that makes a tab stamps it while it is still the blank page it made, and a blank `newTab()` opens `about:blank` rather than Safari's new-tab page, where no marker can go. The search for the marker gives each tab a second, and the first check ends the script when its tab does not answer within the call's own budget. So a tab that does not answer (an open dialog, a hung page) can no longer hold up the helper that every session shares, or let an abandoned script act minutes later. When nothing proves the tab, the step touches no tab after that and fails with "Tab tracking lost", and the error says that a URL the step had already loaded, or a click, submit or history move it had already made, happened in the session's tab. A `newTab()` that fails this way leaves the session's state on the new tab, as before, and stamps no other tab. `goBack()`, `goForward()`, `navigateAndRead()`, `clickAndWait()` and `fillAndSubmit()` now stamp the page a cross-site load brings when it arrives before their wait ends; they used to leave it unmarked, and the next call failed with "Tab tracking lost". Their wait still ends at the first complete page, which can be the page being left, so a slower load stays unmarked as before. `fillAndSubmit()` clicks its submit button in the tab its polls watch, and a step keeps the marker its own scan proved even when a parallel call of the same session changes the session's. The trade-off is this. Each of the following fails the step closed, and the session loses that tab, which stays open: a tab opened, closed or selected in that window, or a URL change in one of the three tabs before the session's, between a load that cleared the marker and the next poll; a cross-origin load that started more than a second before the step's write (a previous call's click, the page's own redirect) and commits while `clickAndWait()` or `fillAndSubmit()` waits; a page the back/forward cache restores that the session never stamped (one from before it took the tab). A Cmd+T or another session's new tab at any other time does not, since the marker proves the tab. Not caught: in that gap, while the window's fingerprint matches, any page at the session's index whose document started loading after the step's write less a second passes. That covers a tab created in the session's place and a tab shifted into it (the session's tab closed, or dragged right), including one that reloaded. The age test compares Node's wall clock with WebKit's time origin, so a wall-clock step back of more than a second during a step refuses the session's page, and a sleep during it widens what passes. The proof and the action are still two Apple events of one script, so a tab moved in the milliseconds between them still shifts it. `test/newtab-window-proof.test.mjs` opens, closes, selects and moves tabs before the session's tab at each step, over a fake Safari whose Start Page runs no page script, whose documents have an age and whose back/forward cache restores documents, and `test/fake-safari-scripts.mjs` answers the new scripts only in the exact form safari.js writes them.
248
+ - **A marker scan whose answer does not name the window it scanned proves no tab.** Without `SAFARI_PROFILE`, `_scanForMarker()` took such an answer as a tab index in whichever window was in front when the next script ran, so a navigation's `set URL`, its load polls and its re-stamp could follow it into a tab of the user's. It now reads as a scan that could not complete: the session keeps its marker, and the step refuses with "Tab tracking lost". The test fakes now run the marker scan and the one-script close in the exact form safari.js writes them, with the embedded marker check run against each tab's page (`test/fake-safari-scripts.mjs`).
249
+ - **After `safari_switch_tab` picks a tab whose page took it somewhere else, the session keeps working in that tab.** When the Safari extension served the switch, the server recorded the URL the extension reported for the tab as the session's current page. A page moves its tab by itself (a redirect, a login bounce, a clicked link), so that URL can be one the session never registered, and for a tab on another origin the extension hands back no receipt, since a receipt stays on the origin it was minted on. The ownership guard judges a write by that URL: without `SAFARI_PROFILE` always, and in a named profile when the session holds no receipt, as after a switch to a tab on another origin. Those writes (`safari_click`, `safari_fill`, `safari_evaluate`, `safari_navigate` and the rest) were refused ("current tab (…) was not opened by this MCP session"), and in a named profile so was the argument-free run_script `getReceipt`, the documented recovery after a redirect, although the extension had just proven by the tab's id that the session owns the tab. After a switch the extension served, the URL is now left unknown, as run_script `switchTab` already leaves it. A switch the AppleScript fallback served still records the page AppleScript read, so the guard judges writes there as before, and adoption with `SAFARI_MCP_ALLOW_USER_TABS` (#92) is unchanged. `test/switch-tab-redirected-tab.test.mjs` runs the extension's own switch and receipt code over a fake Safari window under the real tool handlers, in both modes. No extension change.
250
+ - **`safari_navigate` hands back a fresh receipt only when the tab lands off the origin its receipt is valid on.** It compared the landed page with the URL the server held for the session's current tab, and that URL can belong to another tab (when the call names its tab by `receipt`, as `safari_new_tab` advises for every call), be stale (a navigation the Safari extension served leaves it on the page the tab left) or, since the entry above, be unknown (after a switch the extension served). So a navigation that stayed on the receipt's origin could still count as leaving it, and rotated the receipt anyway. The receipt the caller kept then stopped working for any other MCP process and after a daemon restart, and after nine such rotations for this process too ("this extension has no record of that receipt"). The server now remembers the origin each receipt is valid on, from the extension's replies that carry one, and compares the landed page with that. The URL it held is only the fallback for a receipt it has not seen. Covered in `test/switch-tab-redirected-tab.test.mjs`. No extension change.
251
+ - **A session with no tab of its own no longer writes to the tab you are looking at.** The ownership guard in front of the AppleScript fallback asked whether a tab had been opened yet of two sets that hold every session's tabs, and through `~/.safari-mcp/owned-tabs.json` every process's. Once any session on the machine had opened a tab (another client of the HTTP daemon, another stdio process, the same agent before an MCP reconnect or restart), a session that had opened or claimed none passed it. With the extension absent or failing, its `safari_click`, `safari_fill`, `safari_evaluate`, run_script steps and native input then ran in the front document, which is your tab. `safari_navigate` and `safari_navigate_and_read` did it even on a clean machine: they registered their destination as owned before the guard ran, and a refused call still left it in `owned-tabs.json`. The guard now decides from the session's own state (a tab it opened, claimed or adopted, or a receipt passed with the call), the rule the extension already applied on its own path, and a navigation claims its destination only once the guard has passed. Reading the page in front stays allowed. After a reconnect or restart, pass the tab's `receipt` with the call or to `safari_switch_tab`; the error says so. `safari_navigate_and_read` now honours the `receipt` it already declared.
252
+ - **A run_script `newTab` step with a URL no longer locks the rest of the batch out of the tab it opened.** Without `SAFARI_PROFILE`, the step opened its tab through AppleScript and claimed nothing for it, where `safari_new_tab` claims the URL it opens. The page it opened became the session's current URL, so the next step that writes (`navigate`, `click`, `fill`, `evaluate`, …) was refused on the session's own tab with "current tab (…) was not opened by this MCP session"; only a blank `newTab` got through, having no URL to check. Once it has opened the tab, the step now does what `safari_new_tab` does: it claims the URL it asked for (and that URL's `https://` form when it has no scheme, as a `navigate` step does) and keeps it as the session's current URL, so the batch goes on in its tab after a redirect too. It claims nothing the page redirected to, since the site chose that URL, not the caller. A `newTab` step that fails claims nothing; it used to mark a blank tab as opened before it ran. `test/fresh-session-tab-guard.test.mjs` runs such batches through the real handler and `safari.runScript()` over a fake Safari window.
253
+ - **The tabs a run_script `newTab` step opens now count toward the tab cap and close when the MCP server exits.** Without `SAFARI_PROFILE`, the step opened its tab through AppleScript and recorded nothing, unlike `safari_new_tab`. The per-session tab cap counted none of a batch's tabs, so seven `newTab` steps and one `safari_new_tab` left eight tabs open, where seven `safari_new_tab` calls leave six. Shutdown cleanup and the memory-pressure sweep close only the tabs the server has recorded, so a batch's tabs stayed open after the MCP process ended. A `closeTab` step released nothing either, so the URL the tab was opened on stayed claimed in `~/.safari-mcp/owned-tabs.json` for 30 minutes after it closed. A `newTab` step now opens its tab the way `safari_new_tab` does. When the session already has its full cap of tabs (`MCP_MAX_TABS`, default 6), the step first closes the session's oldest tab and names it in its result (`evictedTab`, `note`). It records the new tab by the identity marker AppleScript stamps on it, so the cap, cleanup and the sweep can count and close it. A `closeTab` step now forgets a tab AppleScript opened and releases its URL, as `safari_close_tab` does. Covered in `test/fresh-session-tab-guard.test.mjs`.
254
+ - **A tab the session switches back to by index still counts toward the tab cap, closes when the server exits, and is forgotten when it closes.** Without `SAFARI_PROFILE`, a run_script `switchTab {index}` step runs through safari.js `switchTab()`, and so does `safari_switch_tab {index}` once the extension fails. `switchTab()` stamped a fresh identity marker on the tab even when the tab already carried one of the session's own. The server records each tab AppleScript opens by the marker stamped on it then, and finds the tab by that marker to close it, so after a switch back to one of the session's tabs nothing found that tab any more. Shutdown cleanup left it open. The tab cap and the memory-pressure sweep dropped it from the count as gone and left it open, so it no longer counted toward `MCP_MAX_TABS`. `safari_close_tab` and a run_script `closeTab` step closed it but forgot nothing, so its record stayed and the URL it was opened on stayed claimed in `~/.safari-mcp/owned-tabs.json`. A switch now keeps the marker a tab already carries when it is one of the session's own. A tab that carries none gets a fresh marker, as before, when `safari_wait_for_new_tab` claims it or `safari_switch_tab` adopts it, and a tab adopted from the user still gets a fresh adoption marker at every switch, so a switch never puts one marker on two tabs. The page reads the marker the tab keeps, and a page can write anything after the session's prefix, so only a whole marker counts, letters, digits and `_` as the session mints them, and the server checks the page's answer again: a quote in a marker would end the AppleScript string that every later marker scan puts it in. A tab whose marker is not whole gets a fresh one, as before, and a switch whose page answers with such a marker is refused. A tab recorded again under the same marker, as when `safari_wait_for_new_tab` takes one of the session's tabs that navigated while it waited for the new one, now keeps one record, and the URL it left is released. `test/fresh-session-tab-guard.test.mjs` switches between the session's tabs through the real `safari_switch_tab` and run_script handlers and safari.js over a fake Safari window, then runs shutdown cleanup, the tab cap, the sweep and both closes; `test/ownership-state.test.mjs` records a tab again.
255
+ - **`safari_wait_for_new_tab` no longer takes a tab another MCP session marked.** Without `SAFARI_PROFILE`, its AppleScript claim (`switchTab()` with `claim`) took any tab and stamped the claiming session's own marker on it, over a marker another session had put there: another client of the HTTP daemon, or the server before a restart. That session lost its tab to the claiming one. A tab it had adopted from the user with `SAFARI_MCP_ALLOW_USER_TABS` lost the adoption marker that keeps it from being closed, so the claiming session's tab cap, memory-pressure sweep, shutdown cleanup or `safari_close_tab` could close the user's tab. A claim now refuses a tab that carries another session's marker, whether the session opened or adopted it ("Tab safety: refusing to claim tab N"). A claim given the URL its listing saw (`expectUrl`) also checks, in the page and before it stamps anything, that the tab still shows that page: a tab that closed to its left in between had slid another tab, the user's included, under the index. Covered in `test/fresh-session-tab-guard.test.mjs`.
256
+ - **A tab that opened before `safari_new_tab` or a run_script `newTab` step failed is now the session's own.** Without `SAFARI_PROFILE`, AppleScript's `newTab()` makes the new tab the session's current tab as soon as the tab exists, and it can still throw after that, for example when its last read of the page times out. Neither `safari_new_tab` nor the step then claimed or recorded the tab. The session's next write was refused in its own tab with "current tab (…) was not opened by this MCP session", run_script replaced the `newTab` step's real error with that refusal, and the tab escaped the tab cap and shutdown cleanup. Both now claim and record the tab once `newTab()` reports the marker it minted for it, which it does only when the tab exists, and still report the error. A `newTab` that failed before its tab existed claims nothing.
257
+ - **A tab you let the session adopt is no longer closed because a new tab opened at the same moment.** With `SAFARI_MCP_ALLOW_USER_TABS` and without `SAFARI_PROFILE`, `safari_new_tab` took the session's marker after `newTab()` returned for the marker of the tab it had opened. When a `safari_switch_tab` of the same session adopted one of your tabs while the new tab was still loading, your tab was recorded among the tabs the session opened, and the tab cap, the memory-pressure sweep or shutdown cleanup then closed it. The tab is now recorded by the marker `newTab()` reports for the tab it made, not by the session's marker after the call, and those three never close a tab that carries an adoption marker.
258
+ - **Tab closes within one server process now take turns.** Without `SAFARI_PROFILE`, `closeTabByMarker()` checks a tab's marker and closes the tab in one AppleScript, but as two AppleEvents, and a close sent between them renumbered the window, so the close could land on the tab behind the one it checked, which could be yours. Two tab-cap evictions at once could do it, and so could an eviction next to `safari_close_tab`; with run_script `newTab` steps now enforcing the cap, a batch could too. Tab-cap evictions, the memory-pressure sweep, shutdown cleanup, `safari_close_tab` and run_script `closeTab` now run one at a time within a server process, which covers every client of one HTTP daemon (`SAFARI_MCP_HTTP`).
259
+ - **Closing a tab no longer takes the claim away from another open tab on the same URL.** A close released the URL the tab was opened on even when another tab the server had recorded, of the same session or of another client of the HTTP daemon, was open on it, and that tab's next write was refused with "not opened by this MCP session". A close now keeps the URL while another recorded tab was opened on it; a URL a tab only navigated to is still released, as before. For a URL with no scheme the close also releases the `https://` form that was claimed with it.
260
+ - **`safari_wait_for_new_tab` claims the tab that opened, not a tab of the user's that navigated or moved while it waited.** When AppleScript served the tool (the extension absent or failing), it took the first `index:url` pair it had not seen before once a poll had more tabs. A tab of the user's in the same window that had navigated during the wait came before the new one: the session stamped its own marker on it, later writes went there, and `safari_close_tab`, the tab cap and the shutdown cleanup would close it. A new tab still on about:blank was found again by its index, which by then could name a tab of the user's that had slid into its place. Now a new tab is one on a URL no listing of the wait showed, in a listing where every earlier tab is still there on its URL, in order. A new tab not claimed yet (still on about:blank, not matching `urlContains` yet, or refused) stays new while the window's other tabs only navigate in place, or only close and none next to it, as long as no other tab joins it on its URL; it is claimed once it can be. Any other change makes the listing the new baseline: when a tab changed as a tab opened, or a new tab shows another tab's URL, either could be the new one by URL, so the tool claims nothing rather than guess, and its TIMEOUT reply says a tab opened that it did not claim. A tab that left the window and came back is not new. A tab AppleScript listed is claimed through AppleScript at once, not after the extension's `switch_tab`, which numbers its own window and could hold the claim for 30 s while another tab slid under the index. The AppleScript claim names the URL its listing saw (`switchTab`'s `expectUrl`), and a switch the extension serves must land on the tab it listed. A claim refused with `otherSession` (a tab another session opened) or `moved` (another tab under the index) skips that tab, and the wait goes on. AppleScript gives tabs no id, so the comparison is by URL. A listing the extension answers is compared by its `safeUrl` (origin and path): the tool read a `url` field those listings do not have, so it told their tabs apart by index alone, and `urlContains` failed with a TypeError once a tab opened.
261
+ - **Without the Safari extension, `safari_wait_for_new_tab` watches the window the session's own tab is in.** Its first AppleScript listing pinned whichever window was in front. When the user's window was in front as the wait began, or came to the front before the extension stopped answering mid-wait, the wait watched the user's window: the popup the session's page opened was never seen, and a tab the user opened there was claimed as the session's. It now proves the session's tab by its marker in the window in front, as every other step does, and watches that window by id. A session whose tab is not there, or that has no marker to find it by, gets "Tab safety" and nothing is claimed, with the cause (no marker, a scan Safari did not finish, or the tab in another window) and what to do; a wait that saw a tab open before its listing failed says so. A session with no tab of its own yet still watches the window in front.
262
+ - **A tab that its page took to another origin gets a working receipt back through the step the refusal advises, with or without `SAFARI_PROFILE`.** The extension binds a receipt to the origin it was minted on, and only `get_tab_receipt` may follow its tab to another one. When the page moves the tab by itself — a clicked link, a JS or server redirect, a login bounce — the next call carrying the receipt is refused ("receipt is not valid for this origin"), and the server advises rotating it with a run_script `getReceipt` step. Without a profile, `safari_run_script` runs safari.js's legacy action table, which had no `getReceipt`: the step came back "Unknown action: getReceipt" and the batch carried on. `safari_navigate` and `safari_switch_tab` refuse the same receipt before they run, so a session that passes receipts had no way to get a receipt valid on the tab's new origin, short of `safari_new_tab`, which leaves the page behind. The step now goes to the extension's `get_tab_receipt`, as it does in a profile. It never falls back to AppleScript, and one that fails stops the batch, as a failed `switchTab` does. Without a profile it has to name its tab's receipt, since the batch's own AppleScript `newTab` and `switchTab` leave the session's receipt naming a tab the batch has left. The server's ownership check now leaves a `get_tab_receipt` that names its receipt to the extension, as a profile already does: without a profile it judged the rotation by the URL safari.js held for the tab, which after a redirect during an AppleScript load is one the session never registered. The same change lets `safari_navigate` without a profile return the fresh `receipt` its description promises when it takes a tab, named by its receipt, to another origin; the check had judged that rotation by the URL the tab left, which the navigation had just released. The advice itself put the receipt beside `"action"`, where the tool's schema drops it, so in a profile the step rotated whichever tab the session had used last, and after a reconnect it was refused; it now reads `{"action":"getReceipt","args":{"receipt":"<old receipt>"}}`. A step whose receipt is not one — the advice's `<old receipt>` left in, a token cut short — is now refused; in a profile it rotated the session's current tab instead. The rotation sends the extension the receipt it then aliases, resolved through earlier rotations: a call running alongside can no longer make the step rotate another tab, and in a profile a step that names no receipt now follows a rotation another session made of the session's current receipt, instead of being refused. The extension's origin binding is unchanged, and `getReceipt` still issues a receipt only to the holder of an earlier one for that tab or to the session that owns it. `test/receipt-rotation-default-mode.test.mjs` runs the extension's own receipt checks, `get_tab_receipt` handler and index switch under the real tool handlers and safari.js's `runScript()`, and follows the refusal's advice through the tool's schema in both modes. No extension change.
263
+
264
+ ## [2.22.5] - 2026-09-30
265
+
266
+ ### Fixed
267
+ - **A tab the session opens or navigates stays its own when the user brings another Safari window to the front while the page loads.** Without `SAFARI_PROFILE`, safari.js addressed every AppleScript to `front window`, which Safari resolves again for each script. `newTab()` made the tab in one script and read `count of tabs` in a second. Then, while the page loaded (up to 10 s), it polled the tab, stamped the session's identity marker on it and read its URL in more scripts. All of them used that index and skipped the marker check, since the page carried no marker yet. Once the user brought another window forward, those probes, the marker and the URL read went to the tab at that index in the user's window. A tab the user opened between the first two scripts took them in the same window. The marker then made the user's tab the session's own: `resolveActiveTab()` found it there, and later clicks, fills, evaluates and navigations ran in it. `safari_new_tab`'s AppleScript fallback and run_script `newTab` both went through this. `navigate()`, `reload()`, `goBack()`, `goForward()`, `navigateAndRead()`, `clickAndWait()`, `fillAndSubmit()` and `scrollToElement()` had the same gap. They prove the session's tab once by its marker, then act on its index across several scripts, `set URL`, the load polls and the re-stamp among them. A window brought forward mid-load took those steps into the user's window, where `set URL` navigated the user's tab away. Now the script that makes a tab also reports its window's id and the tab's index there, read off the tab it made, and every later script of `newTab()` addresses `tab N of window id W`. The marker scan reports the window it scanned. The steps above, `runJS`, `runJSLarge` and the helper injection address that window, and `navigateAndRead()` proves its tab once, as `navigate()` does. A stamp with no proven window marks nothing. A new tab that cannot be proven gets no marker, and `safari_new_tab` fails with "Tab tracking lost". That happens when Safari reports no window and index for the tab, or when the tab closes, its window closes or its page stops answering before the marker is on it; in the last three cases the error keeps what Safari said. The user's current tab stays current and nothing is activated, as before. A later call still looks for the session's tab in the front window, as before. If the tab is in another window, that call refuses and drops the tab's marker, so later calls also refuse until `safari_new_tab` or `safari_switch_tab` re-anchors. `test/newtab-window-proof.test.mjs` runs safari.js's `newTab()`, `navigate()`, `reload()`, `goBack()`, `goForward()`, `navigateAndRead()`, `clickAndWait()` and `runJS` over a fake Safari with two windows, and brings the user's window forward at each step.
268
+ - **`safari_wait_for_new_tab` no longer takes a tab of the user's other window for the one that opened.** Without `SAFARI_PROFILE`, when the extension did not serve it, the tool listed `every tab of front window` before the wait and again at every poll. Once a poll had more tabs, it took the first tab it had not seen and claimed it with `switchTab(i, { claim: true })`, which stamps the session's own marker on `tab i of front window`. When the user brought a window with more tabs to the front during the wait, one of their tabs looked new and became the session's tab. Later writes went there, and `safari_close_tab`, the tab cap and the shutdown cleanup would close it. Comparing a listing the extension answered with one AppleScript answered caused the same thing, because the two number tabs differently. Now AppleScript lists the window its first listing read, by id (`listWindowTabs`), and claims the new tab in that window. A listing from the other source starts the comparison over. AppleScript never claims a tab that only the extension's listing saw; that call fails with "Tab safety". `test/wait-new-tab-window.test.mjs` runs the tool's handler and safari.js's listing and claim over a fake Safari with two windows.
269
+ - **A close proves the tab it closes in the same script that closes it.** Without `SAFARI_PROFILE`, `closeTab()` found the session's tab with one AppleScript (the marker scan), counted the window's tabs with a second, and closed `tab N of front window` with a third. `safari_close_tab`'s fallback and run_script `closeTab` go through it. The per-session tab cap, the memory-pressure sweep and the shutdown cleanup ran `findTabByMarker()` and then, several awaits later, `closeTab(N)`. A close in between renumbered the window: another eviction, the extension closing a tab, the user, or a popup. Another front window renamed it. Either way, by the time the close ran, the index could name the user's tab. That tab was then closed, or blanked when it was its window's only tab. The new `closeTabByMarker()` finds the tab carrying the marker and closes it, or blanks a window's last tab, in one script. That script still sends the marker check and the close as two Apple events, so a close another process lands between them can still shift the index (two instances cleaning up at the same moment); the gap is one event wide instead of several scripts. A tab it could only blank no longer counts as closed. When an AppleScript close fails, for example on a page that never answers, the tab cap stops there instead of spending a timeout on every tracked tab. `closeTab()` with no index, the tab cap, the memory sweep and the shutdown cleanup all close through it, and it never closes a tab adopted from the user. `test/close-by-marker.test.mjs` runs the close paths of safari.js and index.js over a fake Safari with two windows, while the user's tabs renumber and their window comes to the front.
270
+ - **`navigate()` keeps its tab after reloading a page over http.** `navigate()` started the background click-helper injection before it re-stamped the page it loaded. The injection found the session's tab with a marker scan of its own. On the path that loads a blocked https page again over http, it ran while that load had cleared `window.name` (the page is on another site). It found no marker, dropped the session's marker, and the re-stamp that followed stamped nothing, so the next call failed with "Tab tracking lost". A late pgrep answer could reorder the two on any cross-site navigation, and a window the user brought forward during the load failed the scan too. The injection now starts only after the re-stamp, and goes into the tab the navigation proved, behind the marker check, without a scan. Covered in `test/newtab-window-proof.test.mjs`.
271
+ - **The AppleScript fallback acts on the tab the Safari extension opened or picked, not on the last tab AppleScript opened.** Without `SAFARI_PROFILE`, safari.js finds the session's tab by an identity marker before its index or URL, and only its own AppleScript `newTab`/`switchTab` set one. When the extension served `safari_new_tab`, `safari_switch_tab`, `safari_wait_for_new_tab` or run_script `newTab`/`switchTab`/`getReceipt`, the server moved safari.js to the new tab's index but left the marker naming the tab AppleScript had opened before. The next call without a receipt whose extension attempt failed ran its AppleScript fallback on that older tab, and `safari_close_tab` closed it — even a tab adopted from the user with `SAFARI_MCP_ALLOW_USER_TABS`, which is never closable. A tab the extension opens or picks now replaces the marker, index and URL together, and a URL the server does not track is left unknown instead of naming the previous tab. `safari_close_tab`'s fallback also forgets the tab it actually closed. `test/extension-tab-marker.test.mjs` runs the real server paths and safari.js's tab resolution over a fake Safari window.
272
+ - **A session whose tabs the Safari extension opened no longer falls back to the user's tab once it loses track of its own.** Without `SAFARI_PROFILE`, safari.js stops falling back to the front document — the tab the user is looking at — once a session has owned a tab, but it counted only tabs its own AppleScript `newTab`/`switchTab` had opened. A session whose tabs the extension opened still fell back, and closing its current tab through the extension got it there two ways: `safari_close_tab` left safari.js tracking the closed tab by index and URL, so the index named whichever tab had shifted into its place, and run_script `closeTab` cleared both, which sent the fallback to the front document. The next call without a receipt whose extension attempt failed — a timeout, a CSP-blocked evaluate — read that tab or ran its script there. A tab the extension opens or picks now counts as the session's own, `safari_close_tab` forgets the tab the extension closed, and the fallback fails with "Tab tracking lost" instead. A session that never opened a tab still reads the page in front of the user. `test/extension-tab-fail-closed.test.mjs` runs the real server paths and safari.js's `runJS` over a fake Safari window.
273
+ - **The AppleScript fallback no longer closes or claims a tab it cannot prove is the one the call named.** Without `SAFARI_PROFILE`, AppleScript can prove a tab only by the identity marker stamped on it, the rule the tab cap and shutdown cleanup already follow (#112). The close and switch paths guessed instead. `safari_close_tab`'s fallback and run_script `closeTab` found their tab through `resolveActiveTab()`, which, with no marker (a tab the extension opened never carries one), answered with a URL-prefix match, a domain match or the bare index: a user's tab on the URL or domain the session's tab had left, or whichever tab had shifted into its place. `safari_close_tab` with another tab's receipt closed the session's current tab instead; run_script `closeTab` with an `index` closed whatever tab sat there, while the ownership guard checked the current tab; and a switch by receipt alone (`safari_switch_tab`, run_script `switchTab`) claimed tab `NaN` under a marker stamped on no tab. A close now proves its tab by the marker alone, an `index` has to name that marked tab, and a close or switch that names its tab by receipt never runs through AppleScript, because only the extension can tell which tab a receipt names. These calls now fail instead ("Tab safety", or "Tab tracking lost" when no tab carries the session's marker), and a tab the extension opened closes only through the extension, not through the AppleScript close in the first entry above. A run_script `switchTab` step without a usable index stops the batch, so the steps meant for the other tab do not run in the current one. An unmarked front document stays readable for a session that owns no tab. `test/fallback-tab-proof.test.mjs` runs the real server paths and safari.js over a fake Safari window.
274
+ - **run_script `closeTab` no longer closes a tab adopted from the user.** A tab adopted with `SAFARI_MCP_ALLOW_USER_TABS` is never closable, but only `safari_close_tab` was refused on one: the ownership guard knew a run_script `closeTab` step as `run_script:closeTab`, not as a close, and let it close the adopted tab. The step is now checked as a close. Covered in `test/fallback-tab-proof.test.mjs`.
275
+ - **A close that names a receipt the server cannot parse is refused instead of closing the session's current tab.** `safari_close_tab` (with or without `SAFARI_PROFILE`) and run_script `closeTab` (in a named profile) fell back to the current tab's receipt whenever the receipt they were given did not parse: the `<old receipt>` placeholder of the getReceipt advice pasted as it is, a token cut to fewer than 24 characters, one with whitespace or quotes around it, or a page URL in the deprecated `url` parameter. The extension then closed the tab the caller was still working in, not the one it named. The refusal meant for such a receipt ("Tab safety: invalid tab receipt") fired only when the current tab had no receipt. Only the session's own current tab could close this way; a tab adopted from the user was refused. Both paths now refuse and close nothing, as `safari_switch_tab` and run_script `switchTab` already did, and a refused `closeTab` step stops the batch ("Tab safety: closeTab requires an extension-issued receipt"). A close that names no receipt, or an empty one, still closes the current tab. `test/close-tab-unparseable-receipt.test.mjs` runs the real tool handlers with the extension's receipt resolver and close over a fake Safari window, in both modes.
276
+ - **In a named profile, a run_script `closeTab` step whose `index` is not a tab number is refused instead of closing the current tab.** The step dropped an index of 0 or one that is not a number (`"abc"`), and sent -1 or 1.5 on to the extension, which ignores an index that is not a positive integer. Either way the close carried only the current tab's receipt, and that tab closed. Such an index is now refused ("Tab safety: closeTab index must be a positive integer when provided") and stops the batch. run_script `switchTab` already refused one, and so does `closeTab` without `SAFARI_PROFILE`. A `null` index still means none. Covered in `test/close-tab-unparseable-receipt.test.mjs`.
277
+ - **The AppleScript fallback acts on a tab the Safari extension opened or picked only once it has proven the tab is the session's, and closes none without that proof.** Without `SAFARI_PROFILE`, safari.js tracked such a tab by the index and URL the extension reported, with no identity marker, and finding it again was a guess. With no URL (a blank `safari_new_tab`), `resolveActiveTab()` returned the index unchecked, and `runJS`, `runJSLarge`, `navigate` and `closeTab` acted on whatever tab sat there, as did the paths that read the index directly (`goBack`, `goForward`, `reload`, `clickAndWait`, and the tab fronting that native input and screenshots use). That was one of the user's tabs once they closed a tab to its left, or the front window's when the extension had opened the tab in another window, so `safari_close_tab`'s fallback after a failed extension close could close the user's tab. With a URL, the lookup took any tab whose URL starts with it (every page under a site root), then any tab whose URL merely contains its domain, and a session without a marker had only the guard that refuses tabs another MCP session marked, so nothing checked the tab when the script ran. Now the extension, which knows the tab by its id, writes a fresh session marker into it (the new `mark_tab` command) when AppleScript first needs the tab, and again after a cross-site load has cleared `window.name`; safari.js acts only on the tab a scan finds carrying that marker, and without one every path refuses with "Tab tracking lost" instead of guessing. A `receipt` passed to a tool that names another tab now moves the fallback to that tab: before, it ran in the session's previous tab, or, for a session re-initialised after a reconnect, in the front document, the tab the user is looking at. A session that never opened a tab still reads the page in front of the user. `test/extension-tab-proof.test.mjs` runs the real tool handlers, `extensionOrFallback` and safari.js's `runJS`, `runJSLarge`, `navigate`, `closeTab` and tab fronting over fake Safari windows. Manifest 2.10.26 — rebuild the extension app to pick it up. An older build writes the marker through `evaluate`, which a strict CSP (github.com's) refuses, and on such a page the AppleScript fallback now refuses too.
278
+ - **A switch by index no longer claims a tab the session cannot show it opened.** Without `SAFARI_PROFILE`, run_script `switchTab {index}` runs through safari.js `switchTab()`, and so does `safari_switch_tab` once the extension fails. It stamped the session's identity marker on whatever tab sat at that index, the user's included, and from then on the marker made the tab the session's own: later writes went there, and `closeTab()`, which proves a tab by that marker, could close it. run_script checked nothing first (`switchTab` is exempt from the ownership guard), and `safari_switch_tab` checked only the target's URL, which the user's tab passes when it shows a page the session also opened. `switchTab()` now claims only a tab that already carries a marker of this session. Every marker a session stamps starts with the session's own marker id, whether on a tab it opened, one it switched to or adopted, or one the extension marked for it, so a session still moves between its own tabs by index wherever the user has dragged them. One script in the page checks the marker, reads the tab's title and URL, and only then stamps it, so a tab closed or dragged in between is not claimed in place of the proven one, and a switch that fails leaves the tab and the session as they were. A tab the extension opened carries a marker only once AppleScript has needed it as the current tab, so when the extension is connected, run_script hands it a `switchTab` that AppleScript cannot prove: the extension knows its tabs by their id. Any other tab is refused ("Tab safety"), and a refused run_script `switchTab` stops the batch, so the steps meant for that tab do not run in the current one. A session re-initialised after a reconnect or a restart has a new marker id, so AppleScript cannot prove the tabs it opened before either: open a new tab, or pass the receipt of a tab the extension opened to `safari_switch_tab`. With `SAFARI_MCP_ALLOW_USER_TABS`, `safari_switch_tab` still adopts the tab (#92), and now records as adopted the tab it actually claimed, even when the URL check passed, so `safari_close_tab` also refuses the user's tab on a URL the session owns; run_script `switchTab` never adopts. `safari_wait_for_new_tab` still claims the tab it saw open. `test/fallback-tab-proof.test.mjs` runs the real tool handlers and safari.js's `switchTab()` and `runScript()` over a fake Safari window that runs their page JavaScript for real. No extension change.
279
+ - **A tab adopted from the user can no longer be closed once it navigates to a URL the session owns.** With `SAFARI_MCP_ALLOW_USER_TABS`, an adoption (#92) was recorded by the tab's URL, while `safari_switch_tab` stamped the adopted tab with the same identity marker the session's own tabs carry. `safari_close_tab` and run_script `closeTab` refused only when the current URL was an adopted one, and without `SAFARI_PROFILE` the AppleScript close proves a tab by that marker alone. So once `safari_navigate` had taken the adopted tab anywhere, since every destination is registered as owned, the refusal let the close through and AppleScript closed the user's tab. The URL record also misfired the other way: adopting a page made every tab on it unclosable, the session's own included, and counted the URL as owned, for every session of an HTTP daemon. An adopted tab now carries a marker family of its own (`MCP_A<markerId>_`), kept in the session's state and never by URL. `safari_close_tab`, run_script `closeTab` and safari.js `closeTab()`/`closeOwnTab()` refuse a tab carrying it wherever it has navigated; every later switch to the tab keeps the family, so switching away and back does not make it closable; and `safari_wait_for_new_tab` no longer records such a tab among the tabs the session opened, which the tab cap and the shutdown cleanup close. Another tab on the adopted URL, this session's or another's, closes as before. `test/fallback-tab-proof.test.mjs` adopts a user's tab, navigates it through the real `safari_navigate` and safari.js `navigate()`, and checks every close path. No extension change.
280
+
281
+ ### Security
282
+ - **A run_script `closeTab` step can no longer run AppleScript of its own.** Without `SAFARI_PROFILE`, the step's `index` went into the AppleScript that closes the tab exactly as written, so a string index could carry further statements, `do shell script` among them, which ran as the user. The index is now only compared with the tab the session proved, and `closeTab()` refuses any index that is not a positive integer.
283
+
284
+ ## [2.22.4] - 2026-09-28
285
+
286
+ ### Changed
287
+ - **A comment in `safari-helper.swift` uses a neutral example window name.** The example `axpressWindow` request named a real window; it now says `Example Window`. Comment only: the shipped `safari-helper` binary is unchanged, so its Accessibility grant is untouched.
288
+
289
+ ## [2.22.3] - 2026-09-28
290
+
291
+ ### Fixed
292
+ - **The per-session tab cap closes the session's oldest tab by its identity, not by the position it had when it opened.** `safari_new_tab` closed the index recorded at opening and sent the session's *current* receipt with it. In a named profile the extension then refused the close ("receipt and requested index identify different tabs") while `safari_new_tab` still reported the oldest tab as closed; with no current receipt — after a `safari_close_tab` — it closed whichever of the session's tabs sat at that position by then, and a tab the user had closed or moved in between guaranteed it. The geo-audit morning run hit this on 24.9: its receipt→tab mapping broke, and a read came back from another query's tab. The cap now closes the oldest tab through its own receipt (or, for a tab AppleScript opened, its marker) with no position in the command. A tab that has left its receipt's origin is closed after the receipt is rotated; a tab that is already gone, or can no longer be proven ours, only drops out of the count, and nothing is closed in its place. `test/tab-cap-eviction.test.mjs` runs the extension's own receipt resolver and close over a profile window whose tabs the user closes and moves.
293
+ - **`evictedTab` names the tab that was actually closed.** It is now `{ receipt, safeUrl }` — the closed tab's receipt and the origin+path it was opened on — instead of a window position that was stale by then, and it appears only when a tab really closed. The note says the same in words.
294
+ - **The tabs a session opened are tracked by identity.** The record was keyed by window position, so a new tab that landed on a shifted position overwrote a live tab's entry — that tab was never counted or evicted again — and `safari_close_tab` forgot whichever entry matched the current index rather than the tab it closed. Entries are now keyed by receipt or marker, `safari_close_tab` and run_script `closeTab` forget exactly the tab they closed, and a tab the extension opened no longer inherits the marker of an earlier AppleScript tab. The memory-pressure sweep closes the oldest tab the same way; it used to drop an extension-opened tab from the count without closing it.
295
+ - **A switch without a receipt makes that tab current.** run_script `switchTab` by index and `safari_wait_for_new_tab` left the previous tab's receipt in place, so the next receipt-less step went back to the previous tab. A receipt rotated by run_script `getReceipt` keeps resolving under its old name, as it already did after `safari_navigate`.
296
+
297
+ ### Changed
298
+ - **In a named profile, a call that names no tab is refused when the session's current tab has closed and two or more of its tabs are still open.** Such a call went to the extension's guess — its cached tab, else the session's newest — which is how a caller that forgot its receipt read another tab's page. The error names the fix: pass the tab's `receipt`, or pick one with `safari_switch_tab`. Requiring a receipt on every call would break every single-tab flow, so only this ambiguous case is refused: a call without a receipt still goes to the session's current tab (the one it last opened, switched to or named), one remaining tab is not ambiguous, and the default mode without `SAFARI_PROFILE` is unchanged. Closing a tab other than the current one by its receipt now leaves the current tab current instead of clearing it.
299
+
300
+ ## [2.22.2] - 2026-09-28
301
+
302
+ ### Fixed
303
+ - **Native input refuses to run on a locked screen instead of reporting success.** On a locked Mac — the lid shut while the machine is kept awake, or the lock screen up — every CGEvent lands on loginwindow: `safari_native_click`, `safari_native_type`, `safari_native_keyboard` and `safari_native_hover` said "clicked" / "typed" while nothing reached Safari, and injected keystrokes could reach the lock screen's password field. Every raw CGEvent sender now checks the session first and fails with one `SCREEN_LOCKED` error that names the in-page tools (`safari_click`, `safari_fill`, `safari_type_text`, `safari_press_key`), which keep working while the screen is locked. `test/screen-lock-gate.test.mjs` pins the gate on every native path.
304
+ - **`safari_upload_file` no longer reports a file dialog that never opened as an upload.** The native file-dialog path returned "Uploaded via native file dialog" with `sheet=false, input.files=0`; that is now an error. The path is gated on the lock too, and the page's file input — restyled into an invisible full-size overlay so the dialog can be opened — is restored even when the click or the dialog fails, instead of being left behind to swallow clicks.
305
+ - **`verifyPreview` waits out a locked screen instead of escalating.** A locked screen occludes every window, Safari throttles the page, and a site can take 30–90 s to render the preview. With the screen locked the upload now polls for the preview for up to 90 s rather than judging after 1.4 s and escalating to a dialog that cannot open there; a result that still has no preview starts with `NO PREVIEW`.
306
+
307
+ ## [2.22.1] - 2026-09-28
308
+
309
+ ### Security
310
+ - **The HTTP transport refuses DNS-rebinding requests.** With `SAFARI_MCP_HTTP=1` the server bound to 127.0.0.1 and checked nothing else, and a loopback bind does not stop a web page: a page whose hostname re-resolves to 127.0.0.1 reaches the port as its own origin, can read the replies, and every tool here runs in the user's logged-in Safari. The MCP specification requires a local HTTP server to validate `Origin` for exactly this reason. Every request is now refused with 403, before it is parsed and before any session exists, unless its `Host` names loopback (`127.0.0.1`, `localhost` or `[::1]`) on the port the server is bound to; an `Origin`, which browsers send and MCP clients do not, must name the same. Clients configured as the README shows (`http://127.0.0.1:9225/mcp`) are unaffected. A client that reaches the daemon under another hostname, or through a port forward to a different port, now gets 403. Every version with the HTTP transport (2.15.0 onward) is affected when it runs in HTTP mode; stdio, the default, opens no socket and never had this exposure. `test/transport-http.test.mjs` covers the check and a rebinding `initialize` refused end to end. Reported by [@GodModeAI2025](https://github.com/GodModeAI2025) in [#114](https://github.com/achiya-automation/safari-mcp/pull/114).
311
+
312
+ ## [2.22.0] - 2026-09-28
313
+
314
+ ### Added
315
+ - **Opt-in thermal backpressure.** Set `SAFARI_MCP_THERMAL_FILE` to a JSON file whose `_t` is the chip temperature and `_ts` its epoch seconds (for example a thermal monitor's latest sample), and page-work commands wait while the chip is at or above `SAFARI_MCP_THERMAL_MAX` (default 80) — until it is 2° cooler, at most `SAFARI_MCP_THERMAL_WAIT_MS` (default 20000). Many agents working in many tabs then slow down instead of heating the Mac. Closing and listing tabs never wait, and a stale or missing reading holds nothing.
316
+
317
+ ### Fixed
318
+ - **An idle daemon no longer wakes up 200 times a second.** The extension's `/poll` long-poll re-checked the command queue on a 5 ms `setInterval` for as long as it was open — which is always, since the extension re-polls at once. It now waits for an event (a command queued, the active worker switched or dropped) and answers immediately; delivery is as fast as before. The profile-window self-heal poll runs every 15 s instead of 3 s (each tick was a `pgrep` plus an Apple Event to Safari, and every AppleScript caller re-validates the window itself), and `isSafariRunning()` reuses a positive answer for 1 s instead of spawning `pgrep` on every AppleScript call.
319
+ - **Under a Safari profile, `safari_navigate` refuses non-http(s) URLs.** The extension cannot issue a receipt for `about:blank` or `file://`, so after such a navigation no tool could reach the tab again — not even `safari_close_tab` — and it stayed open for good.
320
+ - **The WebKit memory monitor is no longer started under a profile.** There it could only log: it may not close profile tabs, and its RSS reading hides compressed and swapped pages (433 MB of RSS against 6.8 GB of real footprint on a 16 GB Mac).
321
+ - **One `safari_evaluate` / `safari_eval_file` call no longer runs its script up to four times.** The extension bounded each `scripting.executeScript` at 3 seconds — a bound on the whole run, not on the injection starting — and on expiry started the *same* script again: in the ISOLATED world, then through the content bridge, whose own 4-second fallback started it once more. A script that merely took longer than 3 seconds ran up to four times, and every side effect in it repeated: on 2026-09-22 a Times of Israel blog flow produced four drafts and two live duplicate posts, and on 2026-09-27 a single `safari_eval_file` call created four identical drafts and uploaded its image twice (daemon log: `evaluate via extension (15835ms)` — 3 + 3 + ~10). The slow script also got its origin filed as injection-blocked, so later calls went bridge-first, hit the bridge's 10-second limit and re-probed the whole ladder: more runs. Now every evaluate carries a run id, and each path that can start the script — the injected runner, the MAIN-world bridge in `content.js`, and `command-content.js`'s ISOLATED fallback — first claims that id through a DOM event, which crosses the MAIN/ISOLATED boundary synchronously where window properties do not. The script starts once, in MAIN; three seconds without an answer only bring in the content bridge, which *joins* the run the injection started (on business.facebook.com the injected evaluate runs but its answer never arrives) or starts it when the injection never began. A slow page is no longer filed as injection-blocked, and an evaluate with no result after 25 seconds says it was started at most once and was not re-run, instead of trying again. A refused `eval` is now told apart from a script that throws by itself by probing `eval("0")` first, so a script whose own error mentions `unsafe-eval` is no longer re-run through the `<script>` strategy (the same probe in frame-targeted evaluate). The bridge's message types are new, so a listener left in an open tab by an older build cannot take these requests and start a script unclaimed. `test/evaluate-at-most-once.test.mjs` runs the real extension code with the real content scripts against a fake page whose MAIN and ISOLATED worlds have separate globals and one DOM: on the previous code a 5-second script recorded its side effect four times on an ordinary page and on a page whose injection runs without answering, three times without `content.js`, and twice where the injection never starts. Extension 2.10.25.
322
+ - **`safari_evaluate` runs on facebook.com again.** Its `script-src` no longer allows `'unsafe-eval'` — it did on 2026-08-23; on 2026-09-27 it is nonce-based with only `'wasm-unsafe-eval'` — so `eval` and the inline-`<script>` fallback were both refused, on the injected path and in the content bridge alike, and no path could run a script there. The inline script now carries the page's own nonce. It also goes in as an expression first, so `document.title` answers with its value as it would through `eval`; a statement list is a SyntaxError in that form, which runs nothing, and then goes in as a function body as before. Verified live on business.facebook.com: a 5-second script ran once and returned its value. On that page the injection now answers (in 90 ms on 2026-09-27); the content bridge stays for pages where it does not.
323
+ - **The AppleScript engine no longer runs a script twice either.** A sync script whose value turned out to be a thenable came back as `"[object Promise]"` and was evaluated again through the async poller; it is now awaited in place. A multi-statement script that threw was re-run as a plain body — a fallback meant only for a CSP that refuses `eval`, which is now probed first.
324
+ - **Without a named profile, an evaluate the extension may have started is not re-run through AppleScript.** Neither after a failed or timed-out command, nor because the script's own error mentions CSP (`unsafe-eval`, `Content Security Policy`, …) — such a script ran. The fallback still runs when the command never reached the extension (not connected, or still queued when it timed out), or when the extension reports that nothing ran (`CSP blocked all strategies`, now also sent when a Worker cannot start or its `eval` is refused).
325
+ - `safari_eval_file` accepts `receipt`, like `safari_evaluate`; it was silently dropped before.
326
+
327
+ ## [2.21.14] - 2026-09-24
328
+
329
+ ### Fixed
330
+ - **Shutdown cleanup no longer closes a tab of the user's that happens to sit on the URL our tab started from ([#112](https://github.com/achiya-automation/safari-mcp/issues/112)).** `_cleanupTabs()` closed the tabs this process had opened by looking their *recorded URL* up in the live tab list. Both coordinates it trusted go stale: the MCP tab navigates away from the URL it was opened on, and `find` returns the first tab matching a URL — usually the user's older one. So a session that opened `example.com/a` and clicked through to `/b` exited by closing the user's `/a` tab and leaving its own tab open. Reproduced from the report at the source: the pre-fix function picks tab 1 (the user's) over tab 2 (ours). Every tracked tab now records the identity marker stamped on it (`window.name` / `__mcpTabMarker`, the same one `resolveActiveTab()` proves ownership with), and the close paths resolve that marker to a current index through the new `findTabByMarker()` immediately before each close, so index shifts between closures cannot mis-target either. A tab whose marker is on no tab is left open: a stray MCP tab costs nothing, a closed user tab costs their work — the principle from [#68](https://github.com/achiya-automation/safari-mcp/issues/68), which the explicit-index path in `closeTab()` deliberately does not re-check. The same URL lookup sat in the memory-monitor sweep (`_closeOldestMCPTab`), and the per-session tab cap evicted by the index recorded at open time; both now prove the tab first, and the cap skips the eviction rather than close an unproven tab. `test/cleanup-tab-identity.test.mjs` covers the reported navigation case, two tabs on an identical URL, an unprovable marker, renumbering across consecutive closes, and the named-profile path that still defers to extension-safe cleanup. Reported by [@scarabone](https://github.com/scarabone). No extension change.
331
+
332
+ ## [2.21.13] - 2026-09-22
333
+
334
+ ### Fixed
335
+ - **The cookie and storage tools no longer die with a stuck Apple Events channel.** `safari_get_cookies`, `safari_set_cookie`, `safari_delete_cookies`, `safari_local_storage`, `safari_session_storage` and their set/delete/export/import siblings were the last page-JavaScript tools bound to AppleScript: every one of them went through `do JavaScript`, which first looks the profile window up over Apple Events. On 2026-09-20, with five morning sessions driving the same Safari and every `osascript` waiting out its 30-second timeout, `safari_delete_cookies` answered `Safari profile "…" window not found` while `safari_list_tabs`, `safari_run_script` and `safari_evaluate` on the same tab kept working through the extension — so a cold-session measurement that only needed its cookies cleared could not start. The eleven storage functions now run their page JavaScript through the same extension-first ladder as `safari_evaluate` (`safari.setPageJSRunner`, installed by the host); the AppleScript path is the fallback it always was, and a named profile stays extension-only like every other tool. `test/storage-page-js-runner.test.mjs` fails if any of them reaches for AppleScript directly again. No extension change.
336
+
337
+ ## [2.21.12] - 2026-09-20
338
+
339
+ ### Fixed
340
+ - **A Safari profile whose stored identity carried its window title is no longer rejected forever ([#109](https://github.com/achiya-automation/safari-mcp/issues/109)).** Twice in three days — 2026-09-18 and 2026-09-20 — one profile answered every tool call with `Safari profile extension unavailable` for the better part of an hour while the other three profiles worked and the failing worker was demonstrably alive (its 20-second heartbeat never stopped). Read from inside the running worker: Safari does not load `extension/background.js` as UTF-8. It decodes the file in the system's legacy text encoding — Mac Hebrew on the Mac where this was found, Mac Roman on an English one — so the literal `" — "` in `_canonicalProfileName` arrived as the char codes `20 5d2 20ac 201d 20` and never matched the real em dash in a window title. An identity persisted as `"אוטומציות — עמוד הפתיחה"` therefore never reduced to `"אוטומציות"`, `_verifyProfileMatch` compared the two and refused its own host, and every reconnect refused again. The 2026-09-18 recovery (a sqlite edit that removed the suffix by hand, then a Safari relaunch) worked for exactly that reason and was wrong about why. Every non-ASCII character in the extension's code is now written as an escape (`" \u2014 "`, `\u26a0\ufe0f`), and `test/extension-source-encoding.test.mjs` fails on any raw non-ASCII character outside a comment in `background.js`, `content.js` or `command-content.js` — and proves the defect by running the canonicalizer's own source through a legacy decoder. Found and verified in the running worker by the parallel GBP session on 2026-09-20. Extension 2.10.24.
341
+ - **The host names the workers it counts.** `⚠️ 3 extension workers connected but none proved profile` said nothing about which workers those were, and the advice beneath it prescribed the sqlite write above. The host now keeps a ledger of every worker that reaches `/connect`: how often, whether it was rejected (`426 upgrade_required` and `401` used to be silent — a worker Safari kept from an older build, or one whose bundled token no longer matches, retried forever without a trace), what the profile probe answered it (`match`, `wrong:<window>`, `notfound`, `error:<message>`), and when it verified. The warning prints that ledger, each distinct probe verdict is logged once (`Profile probe from worker 99ad2b3f for "אוטומציות": wrong:עבודה — mcp-profile-check-…`), and the verified line carries the worker id. On 2026-09-20 this is what showed the missing profile's worker among 45 "connected, never asked for a probe" entries — a worker that connects and silently rejects, which is exactly what the encoding defect produces.
342
+ - The bridge-token resource fetch — the one await before `/connect` with no timeout — is bounded to 5 seconds.
343
+
344
+ ### Added
345
+ - **`safari_doctor` reports the extension bridge.** After the permission checklist: whether this process is the extension host, which worker holds the profile lease and when it last polled, the worker ledger above, and what each Safari profile's extension storage holds — stored identity (with its canonical form when a title suffix is present), heartbeat age and badge state — read through `sqlite3 -readonly`, so an outage like #109 is diagnosable from the tool instead of from sqlite by hand. A process that macOS keeps out of Safari's container says so and names the Full Disk Access grant that would open it.
346
+
347
+ ## [2.21.11] - 2026-09-18
348
+
349
+ ### Fixed
350
+ - **One slow page no longer freezes every other check in the session — or blocks a second session driving the same Safari.** Three layers each enforced strict one-at-a-time execution. The Swift daemon read one line from stdin, then waited on that command's semaphore for up to 30 seconds before reading the next, so a single `do JavaScript` against a heavy or still-loading page stalled everything behind it, including native clicks and keystrokes that never touch Apple Events. The Node side had to serialize as well, because responses were matched to callbacks by FIFO queue position — correct only with one request in flight. Measured on a busy profile, a trivial `count of windows` returned `AppleScript execution timed out (30s)` for minutes on end while `safari_list_tabs` kept answering, because the extension path was the only one not stuck behind Apple Events. Every request now carries an id the daemon echoes back, replies are matched by identity and may overtake each other, and the mutex lifts as soon as the running daemon proves it speaks the protocol (an older binary keeps the FIFO fallback). A native command now answers in ~0.5s alongside a 3-second script instead of queueing behind it.
351
+ - **AppleScript execution stays strictly serial, deliberately.** An intermediate version of the fix ran scripts on a concurrent queue and `NSAppleScript` — which is not thread-safe — handed a 3-second script the *next* script's result under its own request id. Silent cross-talk, the worst possible failure for anything that measures. Execution is pinned to one serial queue; Safari processes Apple Events one at a time regardless, so this costs no real throughput. `test/helper-concurrency.test.mjs` fails on either regression.
352
+ - **A busy profile no longer strands the tab `safari_new_tab` just created.** The extension gave Safari 2 seconds to expose a new tab's navigated URL before minting its receipt, and threw `Safari did not expose the new tab navigation before receipt issuance` otherwise — discarding a tab that already existed, was already owned, and whose destination Safari had already accepted. On a loaded profile that left a trail of orphan blank tabs and told the caller creation had failed, which locked a whole session out of opening tabs. Observed in the daemon log afterwards: real `new_tab` calls taking 10.5s, 12.2s and 14.8s, all of which the old budget would have failed. The wait is now 12 seconds (the caller's own budget is 30s, or 75s on a profile), and when even that is exceeded the receipt binds to the requested URL instead of throwing — same-origin navigations match it, and anything landing cross-origin re-mints through `get_tab_receipt` on the still-owned tab.
353
+ - **The daemon no longer exits before answering a one-shot invocation.** With replies emitted asynchronously, `echo '{"script":"…"}' | safari-helper` — the shape used by the AppleScript fallback and by ad-hoc probes — closed stdin immediately and the process exited through the read loop's `exit(0)` before the queued script ever responded, so the caller read nothing at all. Shutdown now drains work already in flight, bounded by one script timeout, and returns immediately when nothing is running.
354
+
355
+ ## [2.21.10] - 2026-09-17
356
+
357
+ ### Documentation
358
+ - **A FAQ section, eight collapsible entries, closing [#9](https://github.com/achiya-automation/safari-mcp/issues/9).** Safari Technology Preview, Private Browsing, multiple windows, which macOS versions are supported, running several instances, what "background" actually means, how this relates to other Safari extensions, and what breaks without "Allow JavaScript from Apple Events". Every answer is anchored in the code or in an existing README section rather than written from memory. Shipped to `main` on 2026-09-16; this is the release that carries it to npm.
359
+ - **The Apple comparison now answers the question the traffic is arriving with.** For two weeks the largest referrer to this repository has been a Hacker News comment linking straight to the `#vs-apples-official-safari-mcp` anchor and saying Apple's server is "not well suited for stealth use cases". The table said nothing about the one mechanical difference behind that: the W3C WebDriver standard requires every remote-controlled session to report `navigator.webdriver` as `true`, so `safaridriver --mcp` does, while safari-mcp evaluates JavaScript in an ordinary tab and reads `false` (checked on Safari 27.0, 2026-09-17). The row states the difference and the note beneath it states the limit — it is not an anti-detection feature, nothing else about the browser is disguised, and the session carries your real logins.
360
+
361
+ ## [2.21.9] - 2026-09-16
362
+
363
+ ### Fixed
364
+ - **The Safari extension app bundle no longer reports a version three months behind the extension it ships.** All eight build configurations in `xcode/Safari MCP/Safari MCP.xcodeproj` carried `MARKETING_VERSION = 2.10.5` while `extension/manifest.json` had moved on to 2.10.17, so a freshly rebuilt app showed 2.10.5 in Safari's extension list while `safari_reload_extension` — which answers with `browser.runtime.getManifest().version` (`extension/background.js`) — reported 2.10.17. With the two numbers disagreeing there was no way to tell from the outside whether an Xcode rebuild had actually replaced the running extension, which is exactly the check a profile reload needs. The bundle's marketing version now tracks the manifest (2.10.18, `CURRENT_PROJECT_VERSION` 4), so the version Safari shows and the version the reload reports are the same string.
365
+ - `test/profile-extension-routing.test.mjs` now also pins that a window title carrying a profile-check suffix (`מחקר אנונימי — mcp-profile-check-<epoch>`) still canonicalizes to the bare profile name, so the probe tab a profile check opens can never be read as a different profile.
366
+
367
+ ## [2.21.8] - 2026-09-15
368
+
369
+ ### Fixed
370
+ - **`safari_reload_extension` no longer times out when the extension worker has gone idle.** A reload prepares a one-shot handoff that pins the active worker's lease, so no other worker can slip in while that worker gets ready to reload. But the pin held even when the active worker had already parked and could never receive the command: the reload itself woke Safari's fresh worker, which was refused every 3s until the reload timed out at 30s. Diagnostic logging showed it live — `verify refused for worker f99a13: lease held by 8a80b9` seven times, then `reload_extension timed out: never delivered; … last poll 56s ago`. A reload that nobody has received no longer pins the lease; the ordinary rule applies (a worker silent for 20s may be replaced), and the undelivered reload moves to the successor, which runs it. A reload already delivered to a worker still fences the lease exactly as before. Covered in `test/profile-extension-routing.test.mjs`.
371
+ - **A command sent right after the extension wakes is no longer lost.** Whenever Safari woke the extension worker, a second `connect()` followed a few seconds after the first had already succeeded: the minute alarm scheduled a retry while the startup connect was still in flight, and a successful connect never cancelled that retry. The duplicate invalidated the healthy poll loop, which then returned without running the command it had just been handed, and the host waited out 30s for an answer that could never come. The host's own keepalive check is sent 3s after each verification, so it landed in that window almost every time — the `keepalive tab check skipped: Extension timeout` line that filled the daemon log every minute — and so could the first command after an idle wake. Diagnostic logging caught it exactly: `list_tabs delivered 30s ago to worker a65e8e … last heartbeat never`, between two verifications of that worker four seconds apart. A successful connect now cancels any pending retry, the alarm does not schedule one while a connect is in flight, and a loop that a reconnect invalidates still runs a command it already received. `test/reconnect-drops-command.test.mjs` covers all three.
372
+ - **A server that lost the bridge port no longer leaves the extension without a bridge until someone restarts it.** When another process holds the extension bridge port at startup, the server runs as a secondary and proxies through that primary — but it never tried the port again, so once the primary exited it kept proxying to nothing and every tool failed. Seen live on the HTTP LaunchAgent daemon: it restarted while a short-lived `node index.js` held 9224, came up as a secondary, and nothing listened on 9224 after that process exited. A secondary whose primary stops answering now takes the port over. `test/bridge-port-takeover.test.mjs` reproduces the sequence with two real server processes on free ports.
373
+ - **`npm test` no longer takes the production bridge ports.** `test/stdio-lifecycle.test.mjs` started a real server on the default ports 9224/9223, so a test run during a daemon restart was exactly what held the port in the incident above. It now runs on free ports, and a guard test fails when any test spawns `index.js` without `SAFARI_MCP_BRIDGE_PORT` and `SAFARI_MCP_BRIDGE_WS_PORT`.
374
+ - **The extension no longer answers every command a second time, five and a half minutes later.** Each command races a 330s wedge guard so a command that never settles cannot park the poll loop, but the guard's timer was never cancelled when the command finished normally. 330s after every command the worker posted "command did not settle" for an id the host had already answered, and the host logged a result for an unknown request each time. The poll loop now cancels the guard however the command ends; `test/long-command-heartbeat.test.mjs` runs the guard with fake timers and checks that a settled command gets no second answer while a wedged one gets exactly one. Manifest 2.10.16.
375
+ - **A refused tab receipt now says which check refused it, and only an origin change is told to rotate with `getReceipt`.** `_resolveReceiptTab` refuses for five different reasons — the extension holds no record of the token, the record is from an earlier browser session, its tab is closed, the tab has moved to a different page that no session owns, or the tab has left the receipt's origin — and all five came back as one sentence, "receipt is forged, stale, ambiguous, or not valid for this origin". The server matches "not valid for this origin" and appended "Likely cause: the tab moved to another origin … Rotate it with getReceipt" to every one of them. On 15.9.26 a receipt minted at 09:34:38 was refused after a daemon restart at 09:35:27 while its tab sat unchanged on the same page: the advice pointed at an origin change that never happened, `getReceipt` was refused with the same sentence, and "ambiguous" pointed at a second tab open at the same URL — which cannot make a receipt ambiguous: since 62644b9 a receipt resolves by its tab id and no URL is compared across tabs. Reproducing it showed the restart is not the cause: with one extension worker, receipts for a single tab and for two identical-URL tabs all resolved to their own tab after clean daemon restarts, and kept resolving across six worker restarts. The one condition the reproduction lacked is that at 09:34 Xcode's DerivedData build product was registered as a second copy of the extension; a copy that did not issue a receipt cannot resolve it, and the refusal now says that ("never issued by this extension instance") instead of blaming the origin. Each refusal names its check, only the origin refusal still carries the phrase the server decorates, and `test/receipt-refusal-reason.test.mjs` runs the real resolver over every refusal path, checks that the server's advice matches the origin case alone, and resolves two same-URL tabs to their own receipts. Manifest 2.10.17 — rebuild the extension app to pick it up.
376
+
377
+ ## [2.21.7] - 2026-09-15
378
+
379
+ ### Fixed
380
+ - **`safari_emulate` emulates the devices in people's hands on iOS 27, and the emulation now survives its own tool call.** The presets were iPhone 14 / iOS 17 strings, but since iOS 26 Safari freezes the OS token of its user agent (`iPhone OS 18_7`) and only `Version/` moves, and iPadOS requests desktop sites, so an iPad sends the Mac user agent and is told apart only by `navigator.maxTouchPoints`. New presets — iPhone 18 Pro, 18 Pro Max, Air, 17, 17e, 16; iPad (A16), iPad Air 11/13, iPad Pro 11/13 — carry the viewport, user agent, `platform` and touch points read from Mobile Safari on the iOS/iPadOS 27.0 simulator; the older names still resolve. The override itself never stuck: the tool set it and then reloaded the page, which hands the page a fresh `navigator`, so every emulation left only a resized window. The reload is gone, and so is the injected viewport meta, which desktop Safari ignores and which would have corrupted a later `safari_inspect_viewport` — together with the `scale` parameter it fed. An unknown device name is refused with the list instead of silently resizing to 375×812 while reporting the requested device, a custom user agent is escaped against backslash break-outs, and the result reports the viewport Safari actually produced — measured after showing the tab for a moment, because a background tab keeps its old layout until it is shown (on Safari 27 a resize to 402px left it at 1512px, media queries included), and noting when the screen is too short for the device's height. `safari_reset_emulation` puts back the window bounds from before the first emulation instead of forcing 1440×900, and removes only the getters emulation added, without reloading; it re-lays out the tab the same way.
381
+ - **Stylesheet scans see constructable stylesheets again on Safari 27.** Safari 27 stopped listing adopted style sheets in `document.styleSheets`, as the CSSOM spec requires (release notes, 174583340), so `safari_css_coverage`, `safari_webkit_compat` and the `env(safe-area-inset-*)` detection in `safari_safe_area_insets` silently lost every rule a web-component page ships that way. They now read `document.adoptedStyleSheets` as well, skipping any sheet an older Safari still lists, and coverage labels those sheets `(adopted)`.
382
+ - **`safari_check_pwa` reflects Home Screen web apps as iOS 26 and later ship them.** Every site added to the Home Screen now opens as a web app by default, with no installability requirements (WebKit, Safari 26.0), so a missing `apple-mobile-web-app-capable` no longer fails a page whose manifest sets the display mode, the manifest check no longer claims the manifest is "required for PWA install prompts" — Safari has none — and the theme-color check stops promising that Safari tints its tab bar with it: on iOS 27.0 a page with `theme-color: #ff0000` on a green background gets green bars, the page background and not the meta tag.
383
+ - **The Safari extension app builds with Xcode 27.** The project targeted macOS 10.14; Xcode 27 accepts deployment targets from 12.0 and stops the build with "The macOS deployment target 'MACOSX_DEPLOYMENT_TARGET' is set to 10.14", so the documented `xcodebuild` recipe failed. The target is now 12.0.
384
+ - **Setup instructions match Safari 27 and macOS 27.** "Allow JavaScript from Apple Events" and "Allow unsigned extensions" live in Safari → Settings → Developer; Safari 27 has no Develop-menu item for either, yet the README, `safari_doctor`, the install banner, CONTRIBUTING and SECURITY sent users there. macOS 27 renamed the Accessibility pane to "Device Control and Data Access" and the screen-capture pane reads "Screen & System Audio Recording"; both names now appear wherever the old ones did. `safari_doctor`'s Screen Recording line says the grant is needed by AppleScript screenshots and `safari_save_pdf` rather than by every screenshot (the extension captures without it), and under launchd it names the `node` binary to grant — a Homebrew node upgrade moves that path, and the grant does not follow. The README's comparison with Apple's `safaridriver --mcp` records that it ships in stable Safari 27.0 and that Apple's setup guide registers it under the name `safari-mcp`, and the troubleshooting table covers the macOS 27.0 issue where an unsigned extension does not appear until it is rebuilt (183044008).
385
+ - **The tool count was still stale in six places the guard never read.** The npm description published with 2.21.6, `glama.json` (the Glama directory listing), `mcp.json`, `.mcp.json` and the examples page said 97, and the postinstall banner said 96: the guard added in 2.21.4 read only the README and `server.json`. All now match the 98 registered tools, except the banner, which drops the number instead of keeping one more copy in step. `test/doc-tool-count.test.mjs` now reads each of them and fails CI when one states a different count, matching phrasings like the banner's "96 native browser tools" and not only "N tools".
386
+ - **`safari_screenshot_element` now works in a profile session.** The server routes it to the extension as `screenshot_element`, and both read-only command lists (the server's and the extension's) named that command, but the extension had no handler for it: every call came back `Unknown command: screenshot_element`. A profile session (`SAFARI_PROFILE`, as in the HTTP LaunchAgent) refuses the AppleScript fallback by design, so on that setup the tool could never return an image, while `safari_screenshot` on the same tab worked. The extension now selects the tab through the same helper as `screenshot` — so the two cannot drift apart — scrolls the element to the centre, captures the tab, gives the user's selected tab back, and crops the capture to the element: scaled by the capture's own width rather than `devicePixelRatio`, clipped to the viewport, and offset by the frame for a same-origin iframe match. A selector that matches nothing is now the error `Element not found: <selector>` instead of text wrapped in an image block, and the image is labelled by its own bytes — the AppleScript path's PNG crop had been sent as `image/jpeg`. `test/screenshot-element-extension.test.mjs` runs the new extension code against fake tabs, a fake page and a fake canvas, and fails whenever a command the server routes to the extension has no handler there. Found on macOS 27 / Safari 27; a code gap, not a Safari change. Manifest 2.10.13 — rebuild the extension app to pick it up.
387
+ - **`safari_click` reaches buttons inside closed shadow roots and same-origin iframes again, by ref, text or selector.** `safari_snapshot` listed both kinds of target, and the click answered `Element not found` for each (live audit, macOS 27 / Safari 27). Two faults stacked. The persistent click bridge runs in the top frame's ISOLATED world, which sees neither child documents nor closed shadow roots — a closed root is reachable only from MAIN, through the getter `content.js` installs at `document_start`, which is how clicks resolved these targets before the bridge replaced the MAIN-world lookup. The bridge's miss then fell to an all-frame fallback that walked open roots only, and that fallback never got its arguments: Safari's `scripting.executeScript` drops `undefined` entries from `args` and shifts the rest left, so a ref-only probe received the ref as its CSS selector and matched nothing (proved live: a text click for `#inner` clicked `#inner`). Every executor now sends `null` in place of `undefined`, and the fallback is one resolver, `_clickFrameAction`, that probes every frame including closed roots and clicks exactly once — in MAIN only when the match sits in a closed root, in ISOLATED otherwise, as before. Clicks the bridge can resolve never reach it. `test/frame-and-closed-shadow-targets.test.mjs` runs the real command cases against jsdom with an `executeScript` fake that drops `undefined` like Safari and hides page globals from ISOLATED. Manifest 2.10.14.
388
+ - **The same argument shift broke `safari_wait_for` by text.** The text arrived in the selector slot, so the wait timed out on text that was already on the page. `safari_double_click` and `safari_right_click` by coordinates route their arguments the same way; their coordinate checks now treat `null` as absent, so a lone `y` cannot turn into a click at `(0, y)`.
389
+ - **`safari_type_text` into a field inside a same-origin iframe no longer types into a different field.** The top frame's deep query found the iframe field, and every typing strategy then went through the top document's `execCommand` — into whichever top-frame field last had focus (reproduced: text meant for the frame's input landed in an input inside a closed shadow root on the parent page). A field that belongs to another document is now a miss in the top frame, and the existing frame fallback types inside its own document.
390
+ - **`safari_select_option` by ref reaches a `<select>` inside a closed shadow root.** `mcpFindRef` walked open roots only, fell back to the ref's stored coordinates and returned the shadow host; the script then threw on the host's missing `options`, and the tool printed an empty result with the value unchanged. `mcpCollectRoots` now uses the same closed-root getter, which also covers the other AppleScript-engine finders built on it.
391
+ - **With the content bridge gone, a click or fill no longer answers "Scheduled" for a target it cannot reach.** When a tab's content-script listener is invalid — every tab that was open during an extension update, and in the live audit after today's reinstall even fresh tabs — `sendContentCommand` scheduled a lookup of the top document only and answered `Scheduled mcp-content-click` before knowing whether it would find anything. Closed-root and iframe targets were skipped silently and neither fallback ran (reproduced: a fill into a closed-root field answered "Scheduled" and left the value unchanged). The target is now resolved before answering, and a miss comes back as `Element not found`, which sends a click through `_clickFrameAction` and a fill through the MAIN-world deep finder. A top-document target is still dispatched after the answer, as before. Manifest 2.10.15.
392
+
393
+ ## [2.21.6] - 2026-09-15
394
+
395
+ ### Fixed
396
+ - **A tab receipt minted while the browser-session epoch had rotated is caught at mint time instead of an hour later (#105).** `browser.storage.session` is the authority for that epoch, but the extension worker read it once and then returned its cached copy for the rest of its life. When the stored epoch rotated under a worker that stayed alive — a Safari session teardown clears it, a racing worker start can replace it — every receipt minted afterwards was stamped with the *old* epoch and handed to the caller as valid. Nothing noticed until the next cold start, where `_hydrateOwnedTabs()` does read storage, found every persisted record stamped with the previous epoch and dropped the whole array at once. That is why the report has two tabs minted five seconds apart dying together, `getReceipt` unable to rotate either, and `safari_switch_tab` calling an index "not opened by this MCP session" for a tab the session had just opened. The epoch is now re-read on every resolution and a value that disagrees with the cache is adopted rather than ignored.
397
+ - **The guard written to catch that could never fire.** `_browserEpochGeneration` was compared at six sites and assigned at exactly one — its own declaration — so the counter never moved: the three bare comparisons inside `_ensureBrowserSessionEpoch` were unreachable outright and the three compound ones survived only on their other clause. Adopting a rotated epoch now increments it, which is what tells an operation that captured the earlier generation to abort instead of persisting a record stamped with an epoch that is no longer current. `test/browser-epoch-rotation.test.mjs` runs the real functions against a fake session store to lock the rotation behaviour, and adds the source contract that would have caught the omission at review: a counter that is snapshotted and compared has to be written somewhere, or every guard built on it is decoration.
398
+
399
+ ## [2.21.5] - 2026-09-14
400
+
401
+ ### Fixed
402
+ - **A page that refuses every JavaScript injection no longer looks like a script that returned nothing (#106).** The extension's evaluate ladder ends in a terminal state whose own text reads "CSP blocked all strategies (script needs DOM). Falling back to AppleScript" — but the server never recognised that marker, so the promised fallback did not run and the marker itself was handed back as the tool's value. With the marker now matched, the AppleScript path actually runs; and when that also comes back empty, `safari_evaluate` raises instead of printing an empty result. This is the case that costs an agent the most: `(no return value)` from a script that never executed is byte-identical to `(no return value)` from a script that ran and returned nothing, so the agent concludes the element was not there and keeps building on it. The error names what happened and points at the paths that still work on such a page (`safari_read_page`, `safari_snapshot`, `safari_get_element`, `safari_extract_links`). A legitimately empty return is untouched: the new guard fires only on the CSP marker, never on emptiness alone, and `test/csp-terminal-state.test.mjs` asserts that distinction.
403
+
404
+ ## [2.21.4] - 2026-09-14
405
+
406
+ ### Fixed
407
+ - **The documented tool count was one short, and now it cannot drift again.** `safari_list_frames` was registered in v2.19.0 and never reached the README: the table listed 97 tools against 98 registrations, the JavaScript category header said 1 where it held 2, and `server.json` — the description the MCP Registry publishes to every directory that ingests it — carried the stale number outward. The count is now 98 everywhere and `safari_list_frames` has its table row. This is the third time these numbers have parted company (80 → 96, 96 → 97, 97 → 98) and each earlier fix corrected digits by hand, so `test/doc-tool-count.test.mjs` now derives the count from the registrations and fails CI when the heading, the table rows, any category header, the prose, the social-preview alt text, the share link, or `server.json` disagrees. Registering a tool and forgetting the docs is a red build now, not something a reader finds months later.
408
+
409
+ ## [2.21.3] - 2026-09-14
410
+
411
+ ### Fixed
412
+ - **`safari_query_all` now says when its `x`/`y` are not page coordinates.** When the main frame matches nothing, the query falls back to every child frame — and each element's `x`/`y` then come from `getBoundingClientRect()` inside *that* frame, so they are relative to the iframe's viewport, not the page. `safari_click`, `safari_double_click`, `safari_right_click`, `safari_native_click` and `safari_drag` all take page coordinates, so an agent that read a match out of an embedded checkout or app shell and clicked its reported position landed somewhere else on the page, silently and only on the pages this fallback exists for. The caveat had been written as a comment in the extension source, where no caller ever reads it: cross-frame matches now carry `frameRelative: true` in the payload and the tool result ends with a line naming the frame and pointing at selectors or a `safari_snapshot` ref instead. Raised by a reader of the write-up on the original find (dev.to #4413737), who asked whether the fix had been anything more than a corrected comment. It had not been.
413
+
414
+ ## [2.21.2] - 2026-09-11
415
+
416
+ ### Fixed
417
+ - **`safari_evaluate` no longer reports an empty-string return as "(no return value)".** The result text was built with a falsy check standing in for an existence check, so three different outcomes printed the same line: a script that returned `undefined`, a script that returned `""`, and an injection that never ran at all because the page's CSP refused it. `(() => 0)()` printed `0` while `(() => "")()` printed `(no return value)`, since `"0"` is a truthy string and `""` is not. An empty return is now shown as `""` and stays distinguishable from no return, which also makes a silently blocked evaluation visible instead of indistinguishable from success. Both `safari_evaluate` and `safari_eval_file` now share one `evalResult` envelope in `response.js` alongside every other tool response.
418
+
419
+ ## [2.21.1] - 2026-09-11
420
+
421
+ ### Fixed
422
+ - **A `safari_switch_tab` by index no longer leaves the previous tab's receipt attached.** A switch by index gets no receipt back, and the session kept the one it had minted for the tab before — which every later command auto-attaches. The switch reported `owned: true` and the next `safari_evaluate` died with "receipt is forged, stale, ambiguous, or not valid for this origin", with no way out but opening another tab (observed on a tab that had navigated across origins). The stale capability is now dropped, so the command targets the tab the switch just selected.
423
+
424
+ ## [2.21.0] - 2026-09-10
425
+
426
+ ### Added
427
+ - **Opt-in tab adoption (`SAFARI_MCP_ALLOW_USER_TABS=1`).** The server touches only tabs it opened itself, which is what stops it from clicking into and closing yours — but it also blocks "read the article I'm looking at" and "fill the form on my screen", where reopening the page throws away the very session state that made your tab worth using. With the flag set, an **explicit** `safari_switch_tab` adopts the tab you name instead of refusing it, and the session then works in it like one of its own. The flag unlocks adoption, not the guards: only `switch_tab` adopts, ambient operations still never land on whatever tab is frontmost, and `safari_close_tab` keeps refusing an adopted tab — closing is the one cost you cannot undo (#68). Adoption is session-local and is never written to the shared ownership file. `safari_doctor` reports the flag's state and every operation on an adopted tab logs `(user tab, opted-in)`. Default off. Design by @turner-moore in #92.
428
+
429
+ ## [2.20.0] - 2026-09-09
430
+
431
+ ### Added
432
+ - **Frame targeting: `safari_list_frames`, and a `frame` option on `safari_evaluate`.** Every command reached only the tab's main document, so a page whose content lives in a cross-origin iframe was unreadable and undrivable: `safari_read_page` returned the outer shell's loader text and `safari_evaluate` ran outside the app entirely. That is the normal shape of a micro-frontend console (GoHighLevel's workflow builder, an embedded checkout, a payment field) — the whole UI is one cross-origin child document, and page-context JS cannot cross into it, so the only remaining option was pixel-level native clicking, which steals focus and cannot verify what it hit. `safari_list_frames` enumerates every document with its `frameId`, URL and text length; passing that id — or a URL substring that matches exactly one frame — as `safari_evaluate`'s `frame` runs the script inside that document, with full read, mutate and `.click()` access. Ambiguous substrings are refused rather than guessed. MAIN world first, ISOLATED as the fallback for frames whose CSP blocks `eval`.
433
+
434
+
435
+ ## [2.19.1] - 2026-09-08
436
+
437
+ ### Fixed
438
+ - **A wedged extension worker no longer holds the profile "connected" forever.** A worker stuck inside one command kept beating every 5s for hours after that command's hard deadline had passed; each beat refreshed the poll clock, so the host's "HTTP poll timeout" never fired, no successor could take the lease, and every tool call died with "Extension timeout". A heartbeat now counts as a poll only while a command dispatched to that worker is still awaited, and a command that passes the hard ceiling drops that worker's lease at once instead of waiting for the stale timer.
439
+ - **The extension bounds a command that never settles (330s) and releases its poll loop.** A `handleCommand` that never resolved — a tab that stops answering, a runtime call that hangs — parked the poll loop for good: `/poll` went silent, `connectToServer` waited on the same claim, and only a Safari restart brought the profile back. Past the host's own ceiling (`max(4× timeout, 180s)`, longest tool timeout 75s) the worker answers with an error, releases the claim and keeps polling. Manifest 2.10.10.
440
+
441
+ ## [2.19.0] - 2026-09-06
442
+
443
+ ### Added
444
+ - **Keepalive tab (`SAFARI_MCP_KEEPALIVE_TAB=1`).** Safari parks an idle extension worker, and the first command afterwards waited for the 1-minute alarm (measured: `new_tab` 18s). The daemon now serves a tiny page at `/keepalive` on its bridge port and keeps exactly one such tab open in the profile window; its content script relays wake-ups instantly. Never creates a window — only a tab in an existing one.
445
+ - **Profile-window self-heal (`SAFARI_MCP_OPEN_WINDOW_CMD`).** When the profile window stays absent for three detection cycles (a reboot, a closed window — 198 refusals in one log), the daemon runs the configured command with the profile name, at most every 2 minutes, then rediscovers the window. The command must open the window without focusing Safari.
446
+
447
+ ### Fixed
448
+ - **A receipt rotated by `safari_navigate` keeps working under its old name.** Callers routinely kept the first receipt and ignored the fresh one in the navigate result (nine consecutive "not valid for this origin" failures in one session); the daemon now maps old → new transparently.
449
+ - **`safari_new_tab` reports when it had to close the session's oldest tab** (`evictedTab` + a note) instead of saying so on stderr only.
450
+ - **A parked profile worker gets one alarm cycle (75s) before it counts as disconnected** — the daemon used to flag it after 30s and re-verify every minute (61 flaps in two hours) for no benefit.
451
+ - **The profile-window opener launches Safari in the background first** when it is not running (never hidden — a hidden Safari has no reachable menu bar).
452
+ - **Extension: a content-script ping makes a backed-off worker retry the bridge immediately**, and the daemon releases pending wake polls while it has no verified worker — after a daemon restart the profile re-verifies in seconds instead of sitting in a reconnect backoff (measured 9 minutes on 4.9.26). Manifest 2.10.9.
453
+
454
+ ## [2.18.1] - 2026-09-04
455
+
456
+ ### Security
457
+ - **`qs` 6.15.3 → 6.16.0** (transitive, via `express` in HTTP mode) — closes GHSA advisories for DoS via attacker-controlled `isBuffer` and array-limit bypass through bracket-key comma parsing (Dependabot #101).
458
+
459
+ ## [2.18.0] - 2026-09-04
460
+
461
+ ### Added
462
+ - **`safari_screenshot` can downscale before returning (`maxWidth`, or `SAFARI_MCP_SCREENSHOT_MAX_WIDTH` for a daemon-wide default).** Retina captures are 3024px wide — about 1,900 tokens each even after the API's own cap; 1280 keeps text readable at a third fewer tokens, 800 is plenty for layout checks. Uses the system `sips`, no new dependency; the original is returned untouched on any failure.
463
+ - **`receipt` on 14 more tools** (`safari_navigate`, `go_back`, `go_forward`, `reload`, `snapshot`, `query_all`, `get_element`, `scroll_to`, `screenshot_element`, `click_and_read`, `right_click`, `clear_field`, `fill_form`, `replace_editor`). `snapshot` and `clear_field` already forwarded it internally, but their schemas dropped it silently.
464
+ - **`safari_navigate` returns a fresh `receipt` when the navigation changed origin.** A receipt is bound to the origin it was minted on, so navigating your own tab to another site stranded every following call on "not valid for this origin" (~80 failures a week on one machine). That error now also says how to recover.
465
+ - **Daemon log lines carry a wall-clock prefix** (`SAFARI_MCP_HTTP=1` only), so focus-restore traces can be matched to the operation that was running.
466
+
467
+ ### Changed
468
+ - **Tab results are compact.** `list_tabs` no longer echoes `"active": false`, empty titles, or titles beyond 80 characters — roughly a third of its bytes; it was returning up to 30KB per call.
469
+ - **Tool descriptions steer toward the receipt workflow:** keep the receipt from `safari_new_tab`, pass it on every call, skip `list_tabs`/`switch_tab`.
470
+
471
+ ### Fixed
472
+ - **In a named profile, a parked extension worker no longer fails the first command after idle.** Safari suspends the idle worker; 30s later the daemon declared it gone and rejected everything queued with "Extension disconnected: HTTP poll timeout" — while nothing could have run those commands instead (a profile has no AppleScript fallback). Queued commands now wait for the worker's wake (Safari's 1-minute alarm at the latest), and `new_tab`/`list_tabs` get 75s to outlive that cycle.
473
+ - **Extension: screenshots put the user's selected tab back.** `captureVisibleTab` needs the owned tab selected; the extension path left it selected afterwards, so a user browsing the same window lost their tab on every screenshot (the AppleScript path already restored it).
474
+ - **Extension: a hardened site's injection block is remembered per origin.** business.facebook.com stalls script injection; the per-tab memory was cleared on every navigation, so the first `evaluate` after each navigate paid the ~10s probe again (356 evaluates ≥10s in one week). The origin now goes straight to the content bridge for six hours. Extension manifest 2.10.8.
475
+ - **A tab survives an MCP reconnect or daemon restart.** `SESSION_ID` was a fresh `randomUUID` on every start, so after any reconnect every tool fell through to the user's active tab and was stopped by the ownership guard. The HTTP daemon now persists its session identity to disk (stdio stays random per process), and a receipt minted before three restarts still reads and writes the right tab. Signal exits are logged with signal, ppid and uptime instead of appearing as an orphaned `Cleanup` line.
476
+ - **Background connection hardening.** Content-script wake-ups carry an HMAC token derived from the bridge token; a successor worker may take over only within a 20s grace and never while a mutation is already dispatched to the active worker; queued commands whose request timer expired are dropped instead of being delivered out of band. 40+ new tests across bridge auth, profile routing and worker keepalive.
477
+ - **The "profile extension unavailable" diagnosis names the real cause.** After three distinct workers fail profile proof, the daemon prints once that `mcpVerifiedProfile` in extension storage holds a nonce-suffixed value (`"<profile> — mcp-profile-check-<nonce>"`) instead of the bare profile name, the exact fix command, and the warning that a daemon restart cannot help because the stuck worker lives inside Safari (read the storage DB together with its WAL — `mode=ro` returns a stale value).
478
+
479
+ ## [2.17.1] - 2026-09-01
480
+
481
+ ### Fixed
482
+ - **Clicks now reach controls inside nested open Shadow DOM.** The persistent content bridge previously searched only `document`, so text, selector, snapshot-ref, and coordinate clicks stopped at a custom-element host even though snapshots could see the real control. Click resolution and hit-testing now recurse through open shadow roots, with regression coverage for nested PartnerStack/Impact-style components.
483
+ - **A hot-reloaded content bridge can no longer dispatch the same click twice.** Safari may retain an older message listener while installing the updated content script; both listeners used to execute the DOM mutation even though only the first response was returned. Listener generations are now revocable, so exactly one active bridge may handle a click, fill, or evaluation command.
484
+
485
+ ## [2.17.0] - 2026-08-28
486
+
487
+ ### Added
488
+ - **`SAFARI_MCP_RAISE_ON_NAVIGATE=1` lets navigation foreground Safari, for agents whose job is *showing* a page.** Voice assistants and demo drivers answer "open YouTube" by navigating, and the focus guard immediately handed the foreground back to the previous app — undoing the very raise the agent asked for. Under the flag, `navigate`/`navigateAndRead` raise the front window and `restoreFocusIfStolen` yields. Off by default: the background-operation posture, and every existing setup, is unchanged. Contributed by [@shinyobjectz](https://github.com/shinyobjectz) ([#96](https://github.com/achiya-automation/safari-mcp/pull/96)).
489
+ - **`safari_run_script` can safely recover OAuth popups opened from cross-origin iframes.** The new `clickAndOpenPopup` action accepts one selector or snapshot ref, proves that it resolves to exactly one visible element across all frames, installs a one-shot `window.open` capture in that frame's MAIN world, dispatches one click, and opens the captured HTTP(S) destination through the profile-scoped WebExtension with `active: false` and the exact owned source tab as `openerTabId`. Safari must confirm that direct opener relationship before the new tab receives ownership or a receipt; otherwise only that just-created tab is closed and the flow fails. CAPTCHA/challenge targets fail closed, ambiguous targets are never clicked, popup mutations are never retried, and the result exposes only origin+path plus the opaque tab receipt — never OAuth query or fragment data.
490
+
491
+ ### Security
492
+ - **The `/proxy-command` local-token gate compared the shared secret with `!==`.** That comparison returns as soon as two bytes differ, so reply latency leaked how many leading bytes matched — a byte-at-a-time oracle that recovers the whole token from an unprivileged local process, which is exactly the caller the gate exists to keep out (a hostile `postinstall`, say). The comparison now runs through `crypto.timingSafeEqual` behind a length check, and a non-string header — absent, or sent twice so Node yields an array — fails closed instead of throwing where `timingSafeEqual` rejects unequal lengths. Covered by two tests in `test/injection-safety.test.mjs`, verified to fail when the old comparison is put back.
493
+
494
+ ### Changed
495
+ - **Compatible dependencies brought current.** `ws` 8.21.1 → 8.21.3 (the only runtime dependency), and dev: `@types/node` 26.1.1 → 26.4.0, `eslint` 10.8.0 → 10.9.1, and `globals` 17.8.0 → 17.11.0. `jsdom` remains on 29.1.1 because version 30 drops Node 20, which this project still supports and tests.
496
+
497
+ ### Fixed
498
+ - **The binary npm ships ran only on Apple Silicon Macs with macOS 26 — everyone else got "helper process exited" on every single tool call.** `safari-helper` is a prebuilt Mach-O, and it had been compiled with a bare `swiftc -O`, which stamps the *build* machine's architecture and SDK into the output: arm64-only, `minos 26.0`. dyld then refuses to load it on Intel Macs and on every macOS older than 26. Because the helper is spawned lazily on first use, there was no install-time error and no useful message — just a helper that died at launch behind every tool the user tried. Two people hit this independently from opposite directions ([#96](https://github.com/achiya-automation/safari-mcp/pull/96) reported the macOS 15 dyld rejection; [#98](https://github.com/achiya-automation/safari-mcp/pull/98) tried to add an x86_64 build). The shipped binary is now **universal (arm64 + x86_64) targeting macOS 13**, `scripts/build-helper.sh` pins both knobs so a future rebuild can't silently re-narrow them, and a new test in `test/helper-binary-portability.test.mjs` fails on a single-architecture or too-new binary — verified to fail against the binary this release replaces.
499
+ - **`readPage` reported an SPA that was still painting as an empty page.** `innerText` and the TreeWalker fallback both see an empty body mid-render, so the read returned `title + ""` and downstream agents concluded the page was broken. The read now gives the page up to ~2s (4 tries, 700ms apart) to produce any text before returning the honestly-empty result. Contributed by [@shinyobjectz](https://github.com/shinyobjectz) ([#96](https://github.com/achiya-automation/safari-mcp/pull/96)).
500
+ - **An OFF→ON toggle mid-`connect` left the old poll loop running beside its successor, and a dequeued command could execute twice over.** The extension had no way to tell an intentional reconnect's `AbortError` from a real one, so the invalidated attempt carried on with a still-true `isConnected`. Poll loops now carry a generation stamp that is bumped *before* the abort, an invalidated attempt hands off to one fresh generation after releasing the re-entrancy lock, and `_commandExecutionTail` holds sole execution ownership until the in-flight command's result POST completes — so the successor loop cannot dequeue a second non-idempotent command in parallel. A prepared reload handoff is also kept by object identity while its exact command is still pending, so an ACK lost after arming no longer blocks every future reload on a still-healthy worker.
501
+ - **A new tab's receipt could be minted against `about:blank`.** Safari can resolve `tabs.update()` with the requested URL while `tabs.get()` still reports the bootstrap URL, and a receipt issued in that window was unusable on the very next command. Receipt issuance now waits for Safari to actually expose the navigation.
502
+ - **A second retained Safari worker could steal the bridge from a healthy worker and immediately invalidate fresh tab receipts.** The first verified worker now keeps an activity-based lease; another worker is rejected without disabling the lease holder unless the holder is stale or `safari_reload_extension` grants that exact successor a short-lived, one-use handoff capability. Reload stores the capability only long enough to cross `runtime.reload()`, and the host arms it only after the old worker acknowledges the command. The profile handshake still carries a code-capability protocol marker, while reload remains tab-independent: it inherits no receipt, resolves no target tab, activates no window, and grants ownership to nothing.
503
+ - **A valid tab receipt could not recover an owned form after OAuth opened a second Safari window.** `switch_tab` reinterpreted the caller's index inside the popup/current window and rejected it even though the receipt had already resolved to one exact owned tab globally. Receipt-based switching now targets that concrete tab id directly across profile windows, accepts a receipt without an index, updates only the MCP session's logical target, and never activates or focuses a Safari tab/window. After an origin-changing OAuth redirect, argument-free `getReceipt` likewise prefers the exact cached/most-recent tab the session already owns across windows instead of the active tab in an older window. Index-only switching remains scoped to the session window, and neither recovery path mints a receipt for an unowned tab.
504
+ - **Opaque tab receipts were lost when Safari suspended the extension worker on SPAs or duplicate URLs.** Recovery required the tab's full URL digest to remain byte-identical and globally unique, so a `history.pushState` route change—or a second PartnerStack tab at the same URL—made the original receipt unusable after the worker woke. V3 receipts now bind to a per-Safari-run epoch plus the concrete tab/window identity, refresh URL identity after safe recovery, and keep the original origin boundary immutable. The epoch lives only in `storage.session`: worker suspension preserves it, a browser-session boundary invalidates it, and an unavailable or failed session store blocks authority instead of falling back to restart-persistent local state. Generation guards and serialized authority writes prevent races from republishing stale state, and every unowned write fails closed instead of mutating the active user tab.
505
+ - **The Node 20 CI job crashed before two jsdom-backed suites could load.** A bulk dependency update bypassed the existing Dependabot major-version guard and moved `jsdom` 29.1.1 → 30.0.1; jsdom 30 requires Node 22.22.2, 24.15.0, or 26+, while the project still promises and tests Node 20. The dev dependency is restored to 29.1.1, and a repository test now ties that ceiling to the Node 20 matrix row so a future manual bulk update fails with the compatibility reason instead of `webidl.util.markAsUncloneable is not a function` deep inside undici.
506
+ - **`safari_doctor` reported a healthy machine as broken whenever the Mac was under load.** The daemon/Accessibility/Screen-Recording checks all hang off one 3-second preflight probe, so a helper that merely answered *late* — swap thrashing, a dozen concurrent MCP hosts — was recorded as "not responding", and the two permission checks that depend on it collapsed to "unknown". Doctor then printed 3/6 with instructions to reinstall safari-mcp and re-grant permissions that had never been revoked. The probe is now retried once with an 8-second window before the daemon is declared down; an immediate re-run of the same command returned 6/6, which is exactly the false alarm this removes.
507
+ - **Native clicks silently did nothing on macOS 26 (issue #29).** `safari_native_click` posts a CGEvent, and on Tahoe those events are filtered on their way to a background window: the call returned success, the coordinate was verifiably correct, and the control simply never activated — the worst failure shape, since every caller believed it had clicked. `performNativeClick` now tries an Accessibility press first and only falls through to CGEvent when that finds nothing. The AX path does not travel the HID/CGEvent route at all; it asks the app to activate the control directly, and WebKit turns that into an `isTrusted` DOM click, which is what trust-gated forms actually require. Two helper commands come with it for the cases a coordinate cannot address: `axpress` presses a Safari button by title anywhere in the AX tree (immune to z-order and focus), and `axpressWindow` first locates a Safari window by title, raises it from inside the helper, then presses — so it targets the automation window by name rather than "window 1", and never routes through `osascript`. Both are helper-level commands; no MCP tool is wired to them yet.
508
+ - **`safari_doctor` kept steering callers away from a click path that now works.** The macOS 26 banner told every user to reach for `safari_evaluate` or extension clicks on trust-gated forms — advice written when raw CGEvent was the only path native clicks had. With the Accessibility press landing first, `safari_native_click` handles those forms itself, so the banner was sending people around a working door. It now says clicks are covered and scopes the remaining warning to native keyboard and hover, which do still travel CGEvent.
509
+
510
+ ## [2.16.3] - 2026-08-23
511
+
512
+ ### Fixed
513
+ - **The startup banner printed nothing at all from 2.16.2 onward.** The runtime tool count added in 2.16.2 read `server` at module scope, but `server` is a local of the per-session `buildServer()` factory — so the banner threw a `ReferenceError` that its own best-effort `catch` swallowed, silently taking the version line and the GitHub link with it. The banner is now a function that receives the server it counts, invoked from `buildServer()` and limited to once per process. CI additionally gates on ESLint's `no-undef`, which had already flagged the bad reference before it shipped; the rest of the lint backlog stays advisory.
514
+ - **`safari_switch_tab` could be talked into a tab the session never opened.** A tab that redirects away from the URL we registered (`/dashboard` → `/login`, any 302) stopped matching by URL, so the pre-check fell back to "is this index tracked?" — but `_openedTabs` is keyed by tab *index*, and Safari renumbers every index whenever any tab closes, so a stale key could name one of the user's tabs. The pre-check now requires the tracked index **and** the origin it was opened on, matching the second factor the extension already enforces. This is the only ownership check standing on the AppleScript fallback path.
515
+ - **A profile-scoped Safari MCP could become unusable after Apple Events error `-1743`.** Extension workers now discover profile-specific local bridge ports, verify against an existing background tab without opening or focusing a window, migrate the legacy poisoned profile verdict, and may safely carry commands when Apple Events is unavailable only after the profile match is proven.
516
+ - **Stateless MCP calls could lose their own form tab, and synthetic clicks failed on Meta Direct Support.** An exact, marked extension-owned tab can now be safely adopted after a transport/session change; duplicate URLs prefer the caller's owned tab; isolated-world click/fill handling dispatches from the real leaf target and preserves `preventDefault`; and `new_tab` returns ownership before slow authenticated pages finish loading.
517
+ - **The extension installation guide could disable the extension it had just built.** The documented ad-hoc deep-sign step has been removed in favor of a clean Apple Development-signed build, with an explicit warning not to overwrite the wrapper and embedded-extension signatures.
518
+
519
+ ## [2.16.2] - 2026-08-20
520
+
521
+ ### Fixed
522
+ - **Every "how many tools" surface said something different.** The code registers **97** tools, but the startup banner said 96, `package.json` and `glama.json` said 96, and `.mcp.json`/`mcp.json` still said 80 — the last of which is what the GitHub repo description and downstream directories (mcp.so, Glama) had been mirroring since launch. All of them now say 97, and the startup banner no longer carries a hardcoded number at all: it counts the registered tools at runtime, so it cannot drift again.
523
+
524
+ ## [2.16.1] - 2026-08-18
525
+
526
+ ### Fixed
527
+ - **Screenshots failed on macOS 26 (Tahoe) with a misleading "Screen Recording permission may have been lost" error.** Tahoe broke `screencapture -l<windowId>` for Safari — it exits 1 with "could not create image from window" for every window, while a plain full-screen capture from the same process succeeds, so permissions were never the problem. When the by-id capture fails, the server now falls back to a full-screen capture cropped to the Safari window's bounds (scaled by `devicePixelRatio`). A locked screen is detected up front and reported as such instead of returning a solid-black image.
528
+
529
+ ## [2.16.0] - 2026-08-14
530
+
531
+ ### Added
532
+ - **`safari_query_all` now sees inside cross-origin iframes.** When the main frame matches nothing, the extension re-runs the query across all frames (same fallback click/fill already use) and merges the results instead of reporting "no matches" — embedded editors and third-party widget lists (e.g. GoHighLevel's workflow list) become queryable. Each element now also reports `x`/`y` (center point, relative to its own frame's viewport) and `frame` (the frame's URL) so callers can tell which frame a match came from. Extension 2.10.3 — reload the extension after updating.
533
+
534
+ ### Fixed
535
+ - **Screenshots from an MCP-owned background tab either failed with a false Screen Recording error or captured the user's selected tab.** `safari_screenshot` deliberately skipped window capture for background tabs, then fell into an async canvas fallback that Safari AppleScript cannot await. `safari_screenshot_element` took the opposite path and cropped the selected tab of the window, which could expose unrelated personal content. Both tools now reuse the existing select-capture-restore guard: the owned tab is selected only inside the background window, Safari is never raised, and the user's previous tab is restored even when capture fails.
536
+
537
+ ## [2.15.12] - 2026-08-05
538
+
539
+ ### Fixed
540
+ - **The WebKit memory guard could never fire in multi-instance setups (#83).** The monitor bailed out for every instance that was not the extension host (the one process that won the port-9224 bind race) — but the host can only sweep tabs *it* opened, so tabs held by the other instances were unreachable by any sweeper and the guard was inert exactly where it was needed. The `_isExtensionHost` gate was redundant with the existing cross-instance `memory-monitor.lock` (atomic `wx` create + stale reclaim), which already guarantees a single sweeper per cycle; the gate is gone, and every instance can now sweep its own tabs, still one at a time.
541
+ - **Concurrent instances silently dropped each other's tab-ownership entries (#82).** `_saveOwnershipFile` wrote a snapshot of only the writing process's in-memory Set over the shared `~/.safari-mcp/owned-tabs.json`, so with two live instances the second writer erased every entry the first added after the second hydrated — spurious "no tabs opened yet" refusals and lost restart recovery (fail-safe, but wrong). Saves now merge with the on-disk state (newest timestamp wins) and propagate deletions explicitly so removals aren't resurrected by the merge. The residual read-vs-rename race window shrinks from process-lifetime to sub-millisecond, and losing it still only ever *loses* ownership, never grants it.
542
+ - **The profile-window poll never backed off (#81).** With `SAFARI_PROFILE` set and that profile's window closed, the background verification loop retried every 3 seconds forever — and because a genuinely absent window returns the same answer as a flaky detection, the "retry once with a plain `osascript` subprocess" fallback fired on every cycle: ~1,200 process spawns and log lines per hour, per instance, with no cap on `/tmp/safari-mcp-profile.log`. The poll now backs off exponentially per consecutive miss (3s → 6s → … → 60s cap, reset on the first successful detection), the subprocess fallback disarms after 3 consecutive misses (re-armed by any success, so it still covers the flaky-helper case it was built for), and the "window not found" warning logs on the transition into the missing state and then at most once per 5 minutes.
543
+ - **`restore-trace.log` no longer lives inside the installed package (#81).** It was written to `__dirname` — wiped on reinstall, read-only in container setups, and mutable state inside `node_modules` either way. It now lives with the rest of the state in `~/.safari-mcp/`.
544
+
545
+ ## [2.15.11] - 2026-07-29
546
+
547
+ ### Fixed
548
+ - **All HTTP-daemon clients shared one extension session (#76).** Every client of a shared daemon sent the extension the same process-wide `SESSION_ID`, so the extension keyed all of them as ONE session and could serve one client another client's cached tab. The extension id is now a composite of the process id and the per-connection MCP session id, so per-session isolation holds across the extension bridge too. (Entry backfilled — the release shipped without one.)
549
+
550
+ ## [2.15.10] - 2026-07-28
551
+
552
+ ### Security
553
+ - **`npm audit`: 0 vulnerabilities** (was 1 high + 2 moderate). Bumped `@modelcontextprotocol/sdk` to 1.30.0 and pinned `@hono/node-server` to `^2.0.5` via an npm override — the SDK accepts `^1.19.9 || ^2.0.5`, but npm's resolver never crosses the major on its own, so the serve-static path-traversal advisory (GHSA, Windows-only; not reachable in safari-mcp, which is macOS-only and never serves static files) kept resolving to 1.x. Also cleared a high-severity `brace-expansion` unbounded-expansion DoS advisory via in-range `npm audit fix`.
554
+
555
+ ## [2.15.9] - 2026-07-28
556
+
557
+ ### Fixed
558
+ - **`safari_save_pdf` was broken end to end in daemon mode — four stacked failures, each unmasked by fixing the previous one.** The tool now works and is verified against a live page; the first three fixes also harden the screenshot fallback paths, which shared them:
559
+ - **PATH:** launchd agents and MCP hosts commonly run with a trimmed PATH (e.g. `/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin`), and `do shell script` inherits it — so every capture path that spawned a bare `screencapture` died with `sh: screencapture: command not found` (127). All `screencapture` invocations plus the `ioreg` idle-time probe — the only two spawned binaries living in `/usr/sbin` — now use absolute paths.
560
+ - **Screen Recording TCC:** with PATH fixed, capture failed with `could not create image from window`. Spawning `screencapture` from the node daemon (directly or via an `osascript` subprocess) attributes the TCC check to node, which has no Screen Recording grant under launchd — only the signed `safari-helper` does (`safari_doctor` was already green because its preflight runs in the helper). Every capture now routes through `osascriptFast` (NSAppleScript inside the helper), so the shell inherits the helper's grant; the element-screenshot crop path got the same helper fallback behind its direct `execFile` attempt.
561
+ - **PNG→PDF conversion:** the converter ran `python3 -c 'from Quartz import …'`, but current macOS ships pyobjc for neither the system nor the homebrew python3 — `ModuleNotFoundError: Quartz`. Replaced ~30 lines of embedded Python with a single macOS-native call: `/usr/bin/sips -s format pdf`.
562
+ - **Wrong tab captured:** `screencapture -l` grabs the window's *selected* tab, and `savePDF` never selected the session's target tab — so the PDF showed whatever tab the user last left in front, rendered at the target page's width. The measure/resize/capture sequence is now wrapped in `_withTargetTabFronted`, which selects our tab within the window (no app-level focus steal) and restores the user's selection afterwards.
563
+
564
+ ## [2.15.8] - 2026-07-26
565
+
566
+ ### Fixed
567
+ - **`safari_close_tab` could close one of the user's tabs.** With no tab index of its own, the close path fell back to `close current tab of window` — the tab the user is actually looking at. "No index of its own" is exactly what a session re-initialised after a transport drop reports while its own tab is still open, so the fallback fired at the worst moment; it closed a user's tab during a real run (#68). This is the destructive sibling of #64, and the fail-open sat in all three layers with one shape — *no ownership recorded* read as permission rather than as refusal: `close_tab` was listed among the ownership-exempt "tab management" operations next to `new_tab`/`list_tabs`/`switch_tab` (the only one of the four that destroys a user tab, and the only one with no compensating check), the AppleScript engine fell back to the front document, and the extension engine's "no tabs owned yet → allow" backward-compatibility branch let the close through. The read paths keep that leniency on purpose — a wrong read costs information, so "read the page I'm looking at" still works for a session that never opened a tab — but the destructive path now closes a tab it can prove it owns or throws. Blanking a window's last tab is pinned to the same proven index, internal cleanup names its tab explicitly, and the extension checks the tab it actually removes rather than the one the guard happened to resolve (#68).
568
+
569
+ ## [2.15.7] - 2026-07-24
570
+
571
+ ### Fixed
572
+ - Stdio servers now clean up and exit when their client closes stdin without sending a termination signal, preventing stale Safari MCP process trees from accumulating after sessions end. Thanks to @jgimeno for the fix (#67).
573
+
574
+ ## [2.15.6] - 2026-07-23
575
+
576
+ ### Fixed
577
+ - **A session that lost its transport could run caller JavaScript on the user's current tab.** Every fail-closed branch in the tab layer keys on `hasOwnedTab`, which lives in per-MCP-session state. In HTTP-daemon mode a dropped transport makes the client re-initialise, which mints a new session id, and `_st()` hands it a fresh empty state — `hasOwnedTab` false, `activeTabMarker` null. So the guards all read "this session owns nothing" at precisely the moment an agent is mid-task and already owns a tab, and the next op falls through to the front document: whatever the user is looking at. Reproduced live — a `safari_evaluate` issued right after a transport drop returned a user tab's DOM, which is the report in #64. The session state dies; the marker stamped on the tab does not, so the guard now uses it: with no marker of its own, a run refuses any front document whose `window.name` carries an `MCP_` marker (a tab some MCP session opened and this one does not own) and fails closed with no retry. An unmarked front document stays reachable, so "read the page I'm looking at" still works for a session that genuinely never opened a tab (#64).
578
+
579
+ ## [2.15.5] - 2026-07-22
580
+
581
+ ### Fixed
582
+ - **Two paths could run caller-supplied JavaScript on a tab this session does not own.** The atomic identity guard — the only check that does not depend on how the tab index was resolved — was built at a single call site instead of where the script is assembled, so two targeted paths went without it: `runJS`'s ghost-recovery retry dropped the prefix (the retry runs precisely when the index has already proven wrong, making the least trustworthy path the only unchecked one), and `runJSLarge` never carried it at all — that is `safari_upload_file` and `safari_paste_image`, the largest payloads in the toolset. The guard now lives in `_tabIdentityGuard()` and every tab-targeted path uses it; `runJSLarge` fails closed instead of retrying, since re-running a file payload on a freshly guessed tab is the exact guess the guard exists to prevent (#64).
583
+
584
+ ## [2.15.4] - 2026-07-21
585
+
586
+ ### Fixed
587
+ - **A tracked tab index past the end of the window no longer retargets the session at a user tab.** When the tracked index exceeded the window's tab count (the user closed a tab, or tore one into its own window), `resolveActiveTab()` clamped the index to the *last* tab in the window — which is whatever the user happens to have open there — and logged it as a "proactive fix". Every subsequent navigate/click/fill then landed on that tab, destroying page state (#54). The clamp predates the identity marker (`window.name` / `__mcpTabMarker`, v2.8.3) and was never rewired when its neighbouring branches were; it now fails closed like they do — the session drops ownership and returns `null` instead of guessing (#59).
588
+
589
+ ## [2.15.3] - 2026-07-15
590
+
591
+ ### Fixed
592
+ - Clicks and synthetic events are now dispatched with the owning tab fronted (`_withTargetTabFronted`), so they land on our tab and element instead of whatever tab was frontmost.
593
+ - `typeText` fires per-character key events on ARIA comboboxes, so async typeahead lists actually load.
594
+ - The focus-helper FIFO stays aligned when a request times out — a stale callback no longer swallows a later daemon reply and cascade-times-out `doctor`/`newTab`. Thanks to @jrepp (#53).
595
+
596
+ ## [2.15.2] - 2026-07-05
597
+
598
+ ### Fixed
599
+ - **Clean installs were broken since 2.14.0 — `ERR_MODULE_NOT_FOUND: transport.js`.** `index.js` imports `./transport.js`, but the file was missing from the `package.json` `files` allowlist, so every published tarball from 2.14.0 through 2.15.1 omitted it. A fresh `npx safari-mcp` (with no local git checkout) exited immediately and the MCP client saw "Connection closed". `transport.js` is now published. Thanks to @e3nemyMine for the precise report (#50). Workaround for older releases: pin `safari-mcp@2.13.0`.
600
+
601
+ ### Internal
602
+ - Added `test/packaging.test.mjs` — asserts every relative import in a published JS file is itself published, so an imported-but-unshipped file turns CI red instead of shipping a broken tarball.
603
+
604
+ ## [2.15.1] - 2026-07-03
605
+
606
+ ### Fixed
607
+ - **Shared HTTP mode (`SAFARI_MCP_HTTP`) now self-heals when a session drops.** A request carrying an unknown/expired `Mcp-Session-Id` returned **HTTP 400**, which wedged the MCP client permanently on `"No valid session"` — every shared Claude Code session died the moment its session dropped (idle SSE close, daemon restart, eviction) with no recovery. It now returns **HTTP 404** per the StreamableHTTP spec, so the client transparently re-initializes a fresh session. (A no-session-id, non-`initialize` request still returns 400.)
608
+
609
+ ## [2.15.0] - 2026-07-03
610
+
611
+ ### Added
612
+ - **Shared HTTP transport (opt-in `SAFARI_MCP_HTTP`)** — run a single Safari MCP daemon that many Claude Code sessions share over StreamableHTTP, instead of a process per session (~17→1 in heavy use; lower memory and startup cost). The default transport stays **stdio**, so existing npm users see **zero behavior change** — this is fully opt-in. Set `SAFARI_MCP_HTTP=1` (and optional `SAFARI_MCP_HTTP_PORT`) to enable. Design notes in `docs/http-transport-design.md`.
613
+
614
+ ### Changed
615
+ - **`safari_doctor`** now reports the macOS version and flags macOS 26+ (Tahoe), where `CGEvent.postToPid` native clicks/keys can silently no-op even with Accessibility granted (issue #29). Bug reports now carry the single most relevant diagnostic fact, and users on the affected range are steered toward `safari_evaluate` / extension-based clicks for trust-gated forms.
616
+
617
+ ### Internal
618
+ - Extracted the tab-ownership state machine into `ownership-state.js` with dedicated behavioral tests asserting cross-client isolation and TTL expiry (#39).
619
+
620
+ ## [2.14.0] - 2026-06-18
621
+
622
+ iOS/WebKit web-dev validation tools, a permission-chain diagnostic, and a reliability +
623
+ tooling hardening pass (see PR #37). 96 tools total.
624
+
625
+ ### Added
626
+ - **`safari_inspect_viewport`** — validate the `<meta name=viewport>` tag against iOS Safari best practices (device-width, initial-scale, disabled-zoom/WCAG 1.4.4, viewport-fit).
627
+ - **`safari_safe_area_insets`** — read live `safe-area-inset` values + `viewport-fit`/`env()` usage (notch / Dynamic Island).
628
+ - **`safari_check_pwa`** — audit iOS "Add to Home Screen" / PWA readiness (apple-touch-icon incl. 180×180, manifest, theme-color, status bar, splash).
629
+ - **`safari_webkit_compat`** — check every CSS property on the page against THIS Safari via `CSS.supports()` (unsupported props, missing `-webkit-` prefixes, known rendering quirks).
630
+ - **`safari_doctor`** — one-shot diagnosis of the macOS permission + daemon chain (Apple Events / Accessibility / Screen Recording / native helper / codesign identity), with the exact System Settings fix per failure.
631
+
632
+ ### Fixed
633
+ - **Native clicks no longer report phantom success (issue #29).** `safari-helper` now runs `CGPreflightPostEventAccess()` before posting CGEvents (click/hover/keyboard); when Accessibility / post-event access is missing it returns an actionable error instead of reporting "clicked" while the page never reacted.
634
+ - **`safari_evaluate` could return the literal `[object Promise]`** for scripts whose value is a thenable without a literal `await`/`.then` (e.g. `Promise.resolve(x)`, an async IIFE). It now detects that at runtime and resolves via the async poller.
635
+ - **Element screenshots cropped wrong on Retina** — `safari_screenshot_element` now scales the crop region by `devicePixelRatio`.
636
+ - **`postinstall` codesign re-sign failed silently.** It now warns loudly when the helper can't be re-signed to the stable identifier and verifies the result; fixed a latent bug where `codesign -d` (without `--verbose`) never emitted `Identifier=`, so the early-return/verify never fired. Added a runtime codesign-identity check at startup (catches `npm ci` / `--ignore-scripts` / Docker installs that skip postinstall).
637
+
638
+ ### Changed
639
+ - Internal: extracted `response.js` (MCP-response helpers — replaced 82 hand-written envelopes), `injected-validators.js`, and `injected-escape.js`; added an `evalReturningJSON` builder.
640
+ - Tooling: added `jsconfig.json` (checkJs), ESLint + Prettier + TypeScript with `lint`/`format`/`typecheck` scripts; `npm test` now uses `--test-force-exit`.
641
+ - Tests: +17 behavioral tests (`evaluate-wrapping`, `injection-safety`, `validators` via jsdom) → 32 total.
642
+ - Removed the stale, hand-maintained `index.d.ts`.
643
+
644
+ ## [2.13.0] - 2026-06-14
645
+
646
+ A second correctness/safety + dedup pass following a deep re-audit, and a third
647
+ full-codebase pass (2026-06-11) closing the tab-ownership enforcement gaps end to end.
648
+
649
+ ### Fixed — third pass (2026-06-11)
650
+
651
+ #### Tab safety
652
+ - **~20 page-mutating tools called the engine directly with no ownership guard** (`safari_click_and_wait`, `safari_fill_and_submit`, `safari_set_cookie`/`safari_delete_cookies`, all local/session-storage writers, `safari_import_storage`, `safari_drag`, `safari_upload_file`, `safari_paste_image`, `safari_emulate`/`safari_reset_emulation`, `safari_select_option`, `safari_react_select_set`, `safari_mock_route`, `safari_throttle_network`, `safari_override_geolocation`, `safari_handle_dialog`, `safari_resize`) — while `safari_click`/`safari_fill` were guarded via `extensionOrFallback`. All now call `_assertTabOwnership()` first.
653
+ - **`safari_run_script` enforces ownership PER STEP while the batch runs.** The single pre-flight check could be defeated mid-batch: `evaluate` was exempt (arbitrary JS in an unowned tab via batching), and a `switchTab`/`navigate` step could move to the user's tab before a `click` executed. `navigate` steps now register ownership of their destination exactly like the standalone tool, and a refused step aborts the whole batch.
654
+ - **`_isURLOwned`'s path-prefix match required no segment boundary** — owning `https://site.com/org` also "owned" `https://site.com/org-evil` on the same origin. Matching now requires a real `/` boundary. The matching semantics moved to `ownership-match.js` with a unit suite locking them.
655
+ - **The ownership TTL is enforced during the session (touch-on-use)**, not only at file-load — a long-lived session no longer accumulates permanently-owned URLs; entries the session stops asserting against expire after 30 minutes.
656
+ - **`_injectHelpersfast()` could inject the MCP helpers into the user's front tab** when tab tracking was lost (it skipped runJS's resolution for speed and dropped its guard with it). Now guarded; the background-injection failure is logged instead of swallowed.
657
+ - **Extension: owned-tab state survives MV3 service-worker restarts** (`storage.session`). A worker restart wiped the in-memory Map, silently re-enabling the "no tabs owned yet" compatibility path — i.e. no guard at all — until the next `new_tab`.
658
+ - **Extension: `navigate_and_read` never updated the session tab cache**, so the next command inside the 3s cache window resolved against the pre-navigation URL and could fall through to the user's active tab.
659
+ - **Extension: a URL match in another window no longer silently retargets the profile window** (a URL collision with a tab in the personal window redirected every subsequent command there). The profile window is re-adopted only when the original window is actually gone.
660
+ - **Extension: `close_tab`'s last-tab guard resolved its target from a second `tabs.query`** — a TOCTOU window against concurrent tab changes. The count and the target now come from the same query.
661
+
662
+ #### Robustness
663
+ - **Swift daemon: GCD thread leak on AppleScript timeouts.** Every 30s timeout left a thread blocked in `executeAndReturnError` forever; enough of them exhausted the global pool and wedged the daemon silently. The daemon now counts in-flight executions and exits for a clean respawn once 8 are stuck (the Node watchdog restarts it).
664
+ - **Swift daemon: no `autoreleasepool` around the command loop** — command-line Swift never drains the implicit top-level pool, so every `NSAppleScript`/`NSDictionary` accumulated until process exit. The loop body now drains per command.
665
+ - **Swift daemon: explicit `exit(0)` on stdin EOF** — threads still blocked inside AppleScript kept the process alive as an orphan holding Apple Events/Accessibility grants after the parent Node process died.
666
+ - **Swift daemon: the mouse-restore no longer jumps to (0,0)** when the saved cursor position can't be read (hover + legacy click paths) — the restore is skipped instead.
667
+ - **Extension: `connect()` re-entrancy lock** — the startup promise and the keepalive alarm could race two poll loops into existence on a cold worker start.
668
+ - **Extension: `evaluate`'s script-injection result key is unguessable now** (`crypto.randomUUID`); the `Date.now()`-based name let a hostile page pre-seed a fabricated result object and steer the agent.
669
+ - **Extension: `__mcpGetShadowRoot` is non-writable/non-enumerable** — page scripts can no longer replace it to feed fake shadow roots into snapshots.
670
+ - **HTTP bridge: an oversized request body is no longer parsed.** `end` still fires after `destroy()`, so the JSON of a >10MB body was parsed anyway and a second `writeHead` threw `ERR_HTTP_HEADERS_SENT`.
671
+ - **`owned-tabs.json` writes are atomic** (tmp + rename) — two concurrent MCP instances could interleave partial writes and corrupt the shared ownership file.
672
+ - **Proxy-token write failures are logged** — a silent failure left every secondary instance getting 403 on `/proxy-command` with no trace.
673
+
674
+ #### Correctness
675
+ - **`safari_press_key` sent a bogus `code` for special keys** (`KeyEnter`, `KeyArrowUp`, … instead of the W3C `Enter`, `ArrowUp`); apps that route on `event.code` (Notion, Monaco, Google Docs) ignored the key entirely. Digits map to `Digit1`-style codes now too.
676
+ - **Lexical fill (Strategy 2) silently broke on values containing a double-quote or newline** — the value was interpolated into a JSON literal with JS-string escaping only, and `parseEditorState`'s silent catch hid the failure. That site now uses proper dual-layer (JSON-then-JS) encoding.
677
+ - **`safari_set_cookie`: `path`/`domain`/`expires` were embedded raw**, then "escaped" with a quote-only replace (no backslash-first) — legitimate values broke the injected JS. Every attribute goes through `escJsSingleQuote()` now.
678
+ - **`safari_mock_route`: `contentType` was interpolated with no escaping**; `status` is coerced to a number.
679
+ - **`runJSLarge` and `listTabs` ignored the tab marker** and only re-resolved by URL — after a redirect cleared the tracked URL, large-payload ops (upload/paste) could target a stale index, and `list_tabs` reset tracking, causing spurious "tab tracking lost" errors.
680
+ - **`_validateFilePath` rejected existing files under `/var/folders/`** — `realpathSync` resolves them to `/private/var/folders/…`, which wasn't on the allowlist.
681
+ - **In-page capture buffers are bounded** (console 2,000 / network 5,000 entries) — a chatty SPA grew them without limit, degrading the page (the same memory pressure the WebKit monitor exists to contain).
682
+
683
+ ### Added — third pass (2026-06-11)
684
+ - `ownership-match.js` + `test/ownership-match.test.mjs` — the tab-ownership matching/TTL semantics extracted pure and locked by 12 CI-safe unit tests (including the `/org` vs `/org-evil` boundary).
685
+ - `scripts/contract-clipboard-restore.mjs` and `scripts/contract-focus-restore.mjs` — manual contract tests for the two historically regressing areas (clipboard restore, focus restore). Not in `npm test`: they need a GUI/pasteboard.
686
+ - `npm test` now also runs the unit suites in `test/` (escaping + ownership) alongside the smoke test.
687
+
688
+ ### Changed — third pass (2026-06-11)
689
+ - `engines.node` raised to `>=20` (Node 18 is EOL; CI tests 20/22/24).
690
+ - Hebrew comments in `index.js` translated to English (public package).
691
+ - Dead `_lastNewTabAt`/`NEW_TAB_GRACE_MS` removed; stale comments corrected (idle threshold is 2.5s, helper kill threshold is 5, `newTab`'s count query is not atomic with creation).
692
+
693
+ ### Fixed
694
+
695
+ #### Tab safety
696
+ - **`safari_run_script` and `safari_native_click`/`_type`/`_keyboard` bypassed the tab-ownership guard.** That guard lived only inside `extensionOrFallback`; these tools call the engine directly, so a `fill`/`click` step (or an OS-level native click) could land on the user's tab. The guard is extracted to `_assertTabOwnership()` and applied to `run_script` (per page-mutating step, unless the batch opens its own tab first) and the native tools.
697
+ - **`runJS`'s fallback guard required `SAFARI_PROFILE`.** Without a profile, `getFallbackTarget()` returns `"front document"` (the user's active tab), so the `_hasOwnedTab && SAFARI_PROFILE` condition was exactly backwards — it disabled the guard precisely where it mattered most. Now keys on `_hasOwnedTab` alone, matching `runJSLarge` and the ghost-recovery path.
698
+
699
+ #### Clipboard
700
+ - **The user's clipboard could be left holding the tool's text** if the process was signalled to exit inside the 2-second native-paste restore window. A new `flushClipboardRestore()` runs synchronously in the shutdown handler.
701
+
702
+ #### Daemon / robustness
703
+ - **Orphaned `safari-helper` daemons** under the consecutive-timeout kill path (the kill timer and the `exit` handler both scheduled a respawn). `startHelper()` is now idempotent and the kill-path respawn is guarded.
704
+ - **Shutdown could hang** — `_cleanupTabs()` is now capped at 3s (`Promise.race`) so a wedged daemon can't block exit.
705
+ - **An EPIPE on a `pbcopy` stdin write could crash the whole server** (it reached `uncaughtException` → `process.exit(1)`). All four clipboard writers now go through a single `_pbcopy()` helper with a stdin `error` handler.
706
+ - **Native-helper stdin writes** (click/hover/keyboard) now splice their queue callback out on a write error, preventing a FIFO desync where every later response is shifted by one.
707
+ - **`safari-helper` (Swift): a `keyCode` outside 0…65535 trapped the daemon** on the `UInt16()` conversion. Now validated.
708
+
709
+ #### State
710
+ - **Ownership TTL never expired** — `_saveOwnershipFile` rewrote every entry's timestamp to `now` on each save, so the 30-minute TTL leaked ownership across sessions (potentially onto the user's tabs). Original timestamps are now preserved.
711
+ - **A timed-out extension command was not removed from the HTTP poll queue**, so the extension could execute a stale `navigate`/`click` long after the caller gave up. The timeout now prunes the queue.
712
+
713
+ #### Other
714
+ - **`safari_screenshot_element` crop used a hardcoded 74px toolbar height** instead of the dynamic value, offsetting crops on Sequoia+ (~90px chrome).
715
+ - **`safari_run_script` rejected ~10 actions that exist as tools** (`verifyState`, `reactSelectSet`, `nativeClick`, `uploadFile`, …) — added to the dispatch map.
716
+
717
+ ### Changed
718
+ - **String escaping deduplicated.** ~50 hand-inlined copies of the security-relevant `\\`-then-`'` recipe are replaced by `escJsSingleQuote()` / `escAppleScriptString()`, with `test/escaping.test.mjs` locking each helper to the historical inline pattern (escaping order is what prevents JS-string / AppleScript breakout).
719
+
720
+ ## [2.12.0] - 2026-06-02
721
+
722
+ A correctness + security pass across the engine, server, and extension.
723
+
724
+ ### Fixed
725
+
726
+ #### Async tools that never actually waited (`do JavaScript` can't await a Promise)
727
+ Several tools passed an `async` IIFE straight to AppleScript `do JavaScript`, which returns the moment the synchronous portion finishes — handing back an unsettled Promise (`[object Promise]`) instead of the result. This is the same constraint already handled for `safari_evaluate`/`safari_wait_for`; these tools now poll page state from the Node side:
728
+ - **`safari_navigate_and_read`** was fully broken — it returned `[object Promise]` instead of the page content. Now polls `readyState`, then reads.
729
+ - **`safari_go_back` / `safari_go_forward`** navigated but never updated the tracked URL, so the next operation could target the wrong tab.
730
+ - **`safari_reload`** reloaded but never waited for load or refreshed the URL.
731
+ - **`safari_click_and_wait`** clicked but never waited; **`safari_fill_and_submit`** submitted but didn't wait for the result page; **`safari_scroll_to`** (text mode) scrolled once instead of looping; **`safari_emulate` / `safari_reset_emulation`** didn't wait for the reload.
732
+ - **`safari_get_indexed_db` / `safari_list_indexed_dbs`** returned `[object Promise]` — now routed through the async poller.
733
+ - **`safari_screenshot_element`** (canvas path) returned a Promise and never fell through to the reliable screencapture+crop fallback; the `safari_screenshot` canvas fallback and `safari_upload_file` drop-fallback had the same flaw.
734
+
735
+ #### Injection / escaping correctness
736
+ - **`safari_mock_route`**: escape order was reversed (`'`→`\'` before `\`→`\\`), double-escaping quotes and breaking the injected JS. Backslash is now escaped first.
737
+ - **`safari_set_cookie` / `safari_set_local_storage` / `safari_set_session_storage` / `safari_delete_cookies`**: keys/values containing a backslash produced invalid JS (only `'` was escaped). Backslash is now escaped first.
738
+ - **`safari_get_computed_style`**: CSS property names were interpolated into injected JS unsanitized — now escaped.
739
+ - **`safari_navigate` / `safari_new_tab` / `safari_navigate_and_read`**: URLs were only quote-escaped — a backslash or newline could break out of the AppleScript string literal (potential AppleScript injection). Now backslash-escaped and CR/LF stripped.
740
+ - **Extension snapshot**: page-controlled attribute values (`aria-label`, `title`, `value`, `href`, …) are now HTML-escaped, so a crafted attribute can't inject a fake `ref=`/`role=` into the snapshot and steer the agent to the wrong element.
741
+ - **Extension ref lookup**: attribute values are escaped and the query is guarded, so a page-controlled `aria-label`/`name`/`placeholder` containing `"` no longer throws a DOMException that surfaced as a misleading "element not found".
742
+
743
+ #### Filesystem safety
744
+ - **`safari_save_pdf`**: now validates the output path (allowlist + sensitive-path block) — it could previously overwrite any file. The Python conversion receives paths via `argv` instead of interpolating them into source (the old shell-style escaping was wrong for a Python `-c` string and broke on any path containing a quote).
745
+ - **`_validateFilePath`**: the `..` check was dead (`path.resolve()` already strips `..`); it now rejects traversal in the raw input and resolves symlinks, so a symlink under `/Users/` pointing outside the allowlist is caught.
746
+ - **Temp-file leaks**: `safari_screenshot_element` (crop) reconstructed the wrong filename and leaked it on error; `safari_upload_file` never deleted the PNG produced by image conversion. Both now clean up.
747
+
748
+ #### Tab safety & focus
749
+ - **Tab-ownership same-origin hole**: once the session opened a single tab on an origin (github.com, google.com, …), *every* tab on that origin — including the user's own — counted as owned, so a click/fill could land in the user's tab. The over-broad rule was removed; same-origin redirects remain covered by the path-prefix check.
750
+ - **`safari_wait_for_new_tab`** never registered the found tab as owned, so the next interaction (e.g. after an OAuth popup) was blocked by the tab-safety guard. It now tracks ownership.
751
+ - **Focus restore** runs in `finally` inside `extensionOrFallback`, so a failed operation that brought Safari to the front still hands focus back.
752
+ - **Clipboard restore** for native paste runs in `finally` — if the helper daemon dies mid-paste, the user's clipboard is restored instead of being left with the tool's text.
753
+
754
+ #### Robustness
755
+ - **HTTP body-size guard** could call `res.writeHead(413)` twice on one oversized request (`ERR_HTTP_HEADERS_SENT`); guarded with `res.headersSent`.
756
+ - **Extension poll loop**: a single malformed `/poll` body used to tear down the loop and trigger a multi-second reconnect — it's now skipped. The safety-timeout path uses `continue` instead of re-entering `pollForCommands()` (no overlapping loops).
757
+ - **Extension navigate**: sparse pages that are OAuth/redirect callbacks (`code=`/`token=`/`state=` in the URL) are no longer hard-reloaded — the reload dropped POST data and could re-submit forms.
758
+ - **`safari_get_local_storage` / `safari_get_session_storage`** no longer throw on a key whose value is `null`.
759
+ - Window IDs are validated numeric before reaching `do shell script "screencapture -l<id>"`.
760
+ - Stale-detection and proxy-recheck timers are `unref()`'d, so they never keep the Node process alive on their own.
761
+ - **Extension Trusted-Types policy** registers only `createScript` now (dropped the unused, world-accessible `createHTML`/`createScriptURL` pass-throughs).
762
+
763
+ ### Deferred (tracked, intentionally not changed here)
764
+ - The local HTTP/WebSocket bridge has no auth token — any local process can drive it. The CORS guard already blocks web pages (browsers always send an `Origin`), but a no-`Origin` local request passes. A proper fix needs a native-messaging handshake or a Unix-domain socket and is tracked separately, to avoid breaking the extension transport.
765
+ - `manifest.json` `host_permissions: ["<all_urls>"]` is broader than the `http(s)` the bridge needs; narrowing it may force a permission re-grant on installed extensions, so it's deferred.
766
+
767
+ ## [2.11.9] - 2026-05-28
768
+
769
+ ### Fixed
770
+
771
+ - **MCP `initialize` handshake no longer blocks on profile-window detection at startup.** When launched with `SAFARI_PROFILE=<name>`, the server used to run `await refreshTargetWindow(true)` on the module's top-level await before the stdio loop began responding to the MCP `initialize` request. That call shells out to AppleScript to enumerate Safari windows and match the profile — typically ~50–200ms, but it could exceed 30s if Safari was busy (Spotlight indexing, heavy tab churn, AppleScript daemon stalled). When it did, Claude Code's 30-second MCP handshake timeout fired, the server was killed, and `safari-*` tools silently disappeared from the conversation's tool catalog until the user started a new Claude Code session. The detection now runs in a fire-and-forget async IIFE so module init completes immediately; tool calls that arrive before it finishes already trigger lazy refresh inside `getTargetWindowRef()`, so the targeting behaviour is unchanged.
772
+
773
+ ## [2.11.7] - 2026-05-26
774
+
775
+ ### Fixed
776
+
777
+ - **Focus theft eliminated on macOS Tahoe.** Three independent gaps in the focus-preservation pipeline let Safari steal the user's foreground app during routine tool calls (`safari_navigate`, `safari_read_page`, `safari_snapshot`, `safari_screenshot`, and any tool that ultimately ran an AppleScript). On Tahoe, Safari implicitly activates itself when an AppleScript mutates one of its windows (`set URL`, `set bounds`, `set current tab`) and `screencapture -l<id>` flashes the window forward mid-capture, so the pre-existing save/restore had race windows that became visible to the user every few calls.
778
+ - **`osascriptFast` is now focus-guarded.** It is the hot path (~5ms via the persistent Swift daemon, 18× faster than the subprocess fallback) and is called from `safari_navigate`, `safari_snapshot`, the tab-resolution layer, the profile-window detector, and dozens of internal helpers. It previously had no guard at all — only the slower `osascript` subprocess wrapper saved and restored the frontmost app. Added a mirror guard gated on `!_focusGuardActive` so nested calls inside `extensionOrFallback` / `runJSLarge` still skip duplicate save+restore work.
779
+ - **Awaited restores.** Three sites (`osascript` subprocess, `runJSLarge`, `screenshot`'s screencapture path) previously called `_helperActivateApp(prev).catch(() => {})` without awaiting. `NSRunningApplication.activate()` is async at the OS level, so the function returned to user-space while Safari was still frontmost — keystrokes during the ~5–50ms race landed in Safari. All three now `await restoreFocusIfStolen(prev)`.
780
+ - **Verify-and-hide fallback inside `restoreFocusIfStolen`.** macOS Tahoe's window-server policy can silently block `NSRunningApplication.activate()`, leaving the previously activated app stuck behind Safari. The function now: activates the saved bundle → settles 5ms (Tahoe needs time to honor the activate) → re-reads frontmost → falls back to `_helperHideSafari()` only if Safari is still on top. Hiding Safari is reliable because the OS auto-picks the next app — which is the one we saved.
781
+ - **Background profile-window polling no longer participates in focus-guard.** Every 3 seconds the server polls `tell application "Safari" to return name of window N` to detect profile-window changes. Once `osascriptFast` became focus-guarded this poll became a tiny ~5ms window during which a manual user switch to Safari could be misread as "Safari stole focus" and trigger the hide fallback against them. The polling now passes `noFocusGuard: true` because the script is read-only and provably can't activate Safari.
782
+
783
+ ## [2.11.6] - 2026-05-26
784
+
785
+ ### Security
786
+
787
+ - **Bumped transitive `qs` 6.15.0 → 6.15.2** via `npm audit fix` to close [Dependabot alert #18](https://github.com/achiya-automation/safari-mcp/security/dependabot/18). `qs` ships with Express (pulled in by `@modelcontextprotocol/sdk` for the HTTP control surface); `qs.stringify` would crash with a `TypeError` on null/undefined entries inside comma-format arrays when `encodeValuesOnly: true`. `safari-mcp` does not set that option, so this was not exploitable in our code path, but the upgrade clears the alert and any downstream user that does set it. No API changes.
788
+
789
+ ## [2.11.5] - 2026-05-26
790
+
791
+ ### Security
792
+
793
+ - **Bumped `ws` 8.20.1 → 8.21.0** to pick up the upstream fix for a remote memory-exhaustion DoS (CVE-class issue, responsibly disclosed by Nadav Magier). A peer streaming a high volume of tiny fragments or data chunks over modest network traffic could OOM a `ws` server or client. `safari-mcp` uses `ws` for the Safari extension WebSocket bridge, so the receiving side now caps retained fragments and chunks. No API changes.
794
+
795
+ ## [2.11.4] - 2026-05-25
796
+
797
+ ### Fixed
798
+
799
+ - **`/proxy-command` no longer leaks commands to the wrong Safari profile.** Secondary MCP instances and external HTTP clients can call this endpoint to route a command through the primary instance's extension WebSocket. The endpoint sent every command straight to `sendToExtension()` without checking `SAFARI_PROFILE`, so when the host instance was configured to target a specific profile but the connected extension belonged to a different profile window (e.g. the user's "personal" profile happened to be the one that won the extension-connect race), the command executed in the wrong profile — silently. A real example: a skill ran 8 parallel safari-mcp instances, the MCP tools failed to register, the skill fell back to direct `POST /proxy-command` calls, and every Reddit action ran against the personal profile's Reddit session instead of the dedicated automation profile. `/proxy-command` now returns HTTP 503 with a clear message when `SAFARI_PROFILE` is set on the host, pointing callers at the `safari_*` MCP tools — those route through AppleScript when a profile is configured and stay inside the configured profile window. Secondary instances running under the same `SAFARI_PROFILE` already skipped `/proxy-command` (because `_preferAppleScript` forced the AppleScript path), so they're unaffected; the gate only blocks callers that would have crossed the profile boundary.
800
+
801
+ ## [2.11.3] - 2026-05-19
802
+
803
+ ### Fixed
804
+
805
+ - **`safari_select_option` now reaches native `<select>` elements inside iframes and shadow DOM.** The tool resolved its target with a plain top-frame `document.querySelector(selector)`, so a `<select>` rendered inside an iframe (for example an embedded Salesforce/Lightning support form) or a shadow root was unreachable — every call returned `Element not found`, even though `safari_snapshot` had captured the element and `safari_click` could resolve it. `safari_select_option` now accepts a `ref` (from `safari_snapshot`): the ref path resolves the element through `mcpFindRef` — the same deep finder `click` uses, which traverses shadow roots and same-origin frames — and the selector path falls back to `mcpQuerySelectorDeep`. Pass `ref` for any select a top-document selector cannot reach.
806
+
807
+ ## [2.11.2] - 2026-05-18
808
+
809
+ ### Fixed
810
+
811
+ - **Concurrent MCP instances no longer kill each other on startup.** Each `safari-mcp` process used to `SIGTERM` every other instance running more than 10 seconds, to clear "stale" processes from previous sessions. But concurrent instances are supported by design — the first to bind the HTTP port becomes the extension host and the rest proxy commands through it — so this kill was wrong: with multiple Claude Code sessions open, or a restart racing the previous instance, each new process disconnected the others mid-task and the MCP server showed up as "not connected". The cross-instance kill is removed entirely; every instance is already cleaned up by its own MCP client on shutdown.
812
+ - **`safari_evaluate` now resolves single-line async scripts that end in a bare expression.** A script such as `const r = await fetch(url); r.status` — multiple statements separated by `;` on one line — returned `(no return value)`: the return-injection only scanned newline-separated lines, so a single line beginning with `const`/`let` was left without a return slot and the async IIFE discarded the trailing expression. `evaluate` now also splits at the last top-level `;` — skipping `;` inside strings, template literals and `for (;;)` headers — so the final expression becomes the awaited result.
813
+
814
+ ## [2.11.1] - 2026-05-18
815
+
816
+ ### Fixed
817
+
818
+ - **Blank tabs opened via `safari_new_tab` no longer trip "no tabs opened yet" after an MCP process restart.** A tab opened without a URL stays on `about:blank`, which has no unique identity and so was never written to the persisted ownership file (`~/.safari-mcp/owned-tabs.json`). When the host recycled the MCP process, the in-memory `_openedTabs` map was wiped and nothing in the ownership file restored it — every subsequent navigate/click/read was blocked with `Tab safety: no tabs opened yet`, even though the session had legitimately opened a tab. Opening a blank tab now persists a `__mcp-blank-tab__` sentinel (TTL-bounded like every other ownership entry). The sentinel is never a real tab URL, so it cannot falsely match a user's page in `_isURLOwned()`; it only keeps blank-tab ownership alive across a restart.
819
+ - **Unhandled promise rejections no longer crash the MCP process.** A single failed async operation — a proxy fetch to the primary instance mid-restart, or an aborted fetch timeout — bubbled to the `uncaughtException` handler (Node's default path for unhandled rejections) and exited the whole process, disconnecting every concurrent session. A dedicated `unhandledRejection` handler now logs the failure and continues: the failed operation stays localized, the process stays healthy.
820
+
821
+ ## [2.11.0] - 2026-05-17
822
+
823
+ ### Fixed
824
+
825
+ - **Tab targeting no longer drifts to the user's tab during concurrent browsing.** When the user switched Safari tabs while the agent was working, `resolveActiveTab()` could silently resolve to the wrong tab — the agent's reads, clicks and navigations landed on the user's page. Root cause was a chain of fragile heuristics (cached index → tracked URL → `window.__mcpTabMarker`), each of which breaks under concurrent activity: indices shift when the user inserts a tab, the tracked URL is ambiguous when the user has a same-domain tab open, and `window.__mcpTabMarker` is wiped by every navigation. Tab identity reworked:
826
+ - The session tab is now marked with `window.name` as well as `window.__mcpTabMarker`. `window.name` survives full same-origin navigations, redirects and reloads, so the marker is no longer lost on every page load.
827
+ - `resolveActiveTab()` finds the marked tab with a single AppleScript call that loops every tab internally — was N separate daemon round-trips, slow and prone to mis-resolving when a daemon call hiccupped mid-scan. Falls back to a reliable `osascript` subprocess if the daemon call fails.
828
+ - **Fail-safe:** when the marker and URL can no longer positively identify the session tab, resolution refuses to return a stale index — `runJS` throws a clear re-anchor error instead of silently operating on whatever tab now sits at that index.
829
+ - `navigate()` captures its tab index once and targets it explicitly for every internal `runJS`, instead of re-resolving mid-navigation. A cross-origin load transiently clears `window.name` and the tracked URL is stale until the new page settles, which previously made `navigate` lose its own tab.
830
+ - `newTab()` polls `document.readyState` from the Node side before stamping the marker. The previous in-page wait loop was an `async` IIFE that `do JavaScript` never awaits, so it returned immediately and the marker was stamped onto a still-loading page and lost.
831
+ - Tab-ghost recovery now matches Safari's typographic apostrophe (`Can’t`, U+2019); the plain-ASCII check never matched, so `Can’t get tab N` errors silently skipped recovery.
832
+
833
+ - **`safari_click` no longer reports success when the click was silently ignored.** Sites that gate handlers on `event.isTrusted` (Clutch, G2, Cloudflare-class WAFs) drop synthetic `dispatchEvent` / `.click()` events without error, so `click()` returned "Clicked: …" while nothing happened. `click()` now captures a synchronous page fingerprint (URL, element count, DOM size, focused element) on both sides of the click and reports whether a React handler fired or the page observably changed. When a synthetic click triggers no handler and no effect — re-checked once after a 320ms async grace window — it escalates automatically to a real OS-level CGEvent click (`isTrusted: true`) instead of falsely claiming success.
834
+ - **`safari_evaluate` now resolves async scripts instead of returning "(undefined)".** AppleScript `do JavaScript` returns the moment the synchronous portion of a script finishes — it never awaits a Promise — so any script using `await`, `.then()` or a leading `async` had its result discarded. Async scripts are now started fire-and-forget into a page global, and that global is polled synchronously from the Node side until the work settles (the same mechanism `navigate()` uses). The expression normalizer is shared between the sync and async paths: a multi-line script whose last line is `})()` no longer crashes with a `return })()` syntax error, and `fetch(` on its own is no longer misclassified as async (an un-awaited fetch is fire-and-forget), so a sync IIFE that merely mentions `fetch` keeps its return value.
835
+ - **`safari_wait_for` actually waits now.** Its in-page wait loop was an `async` IIFE that `do JavaScript` never awaits, so the tool checked the page exactly once and returned immediately — reporting success without ever waiting. The wait loop now runs on the Node side, re-evaluating a single synchronous check against the page each tick until the selector/text appears or the timeout elapses.
836
+ - **`navigate` no longer reports a stale page as a successful navigation.** The URL is set through the Swift helper daemon; a cold or crashed daemon could make that `set URL` silently no-op. `navigate` then polled `document.readyState`, saw the OLD page already `complete`, and returned it as if the navigation had succeeded. `navigate` now records the pre-navigation URL — if the page never leaves it, it retries the `set URL` once through the daemon-independent `osascript` subprocess, then throws a clear error if the page still did not move instead of silently returning the wrong page.
837
+
838
+ ### Added
839
+
840
+ - **Visibility spoofing keeps backgrounded tabs rendering.** The agent's tab is almost always backgrounded while the user browses, and many SPAs (the Meta/Facebook developer console is the canonical case) blank or stop laying out their main content when `document.visibilityState` is `hidden`. Every stamped tab now has `document.visibilityState` / `document.hidden` pinned to `visible` / `false` and `visibilitychange` events suppressed, so a backgrounded automation tab keeps rendering normally.
841
+
842
+ ### Changed
843
+
844
+ - Swift-helper daemon requests are serialized on the Node side so FIFO response/callback matching holds regardless of the helper's execution model.
845
+
846
+ ## [2.10.9] - 2026-05-14
847
+
848
+ ### Fixed
849
+
850
+ - **Stable codesign identifier for Accessibility-permission persistence.** The shipped `safari-helper` binary is adhoc-signed with a hash-based identifier (e.g. `safari-helper-555549441c166aa237e130ddbe3d95629266ecaf`). macOS TCC keys Accessibility grants by that identifier, so every `npm install` / rebuild silently invalidated any previously-granted approval — the helper kept reporting success but CGEvent injections never reached non-frontmost Safari content (no `isTrusted` events fired on the page). The PartnerStack network application drawer was the canonical reproducer. `scripts/postinstall.cjs` now re-signs the helper with the fixed identifier `com.achiya-automation.safari-mcp` (preserving entitlements) so the Accessibility grant persists across upgrades. README now documents the one-time `Accessibility → +` step explicitly under "Granting Accessibility to safari-helper".
851
+
852
+ ## [2.10.8] - 2026-05-14
853
+
854
+ ### Fixed
855
+
856
+ - **Dynamic toolbar height for native click coordinates.** `_getSafariWindowGeometry` previously hardcoded `toolbarHeight: 74` for screen→viewport translation. On modern Safari (Sequoia+) the actual chrome above content is ~90 px, so `safari_native_click` was landing ~16 px above its target — close enough to hit a row but often missing button hit-targets, so the click silently no-op'd. Now computes `outerHeight - innerHeight` from JS at call time and uses that, with a 50–200 px sanity range and fallback to 74 if JS is unreachable. Restores reliable native_click on PartnerStack's network application drawer and any layout where buttons sit close to whitespace.
857
+
858
+ ## [2.10.7] - 2026-05-14
859
+
860
+ ### Fixed
861
+
862
+ - **Vue 3 v-model checkbox/radio sync.** `mcpClick` was calling `target.click()` and dispatching a synthetic click event for checkboxes and radios, but in some production-stripped Vue 3 apps (PartnerStack network application drawer is the canonical case) the v-model reactive binding silently dropped the state update — the DOM `.checked` flipped, but Vue's internal proxy state never updated, so the next form submission saw the OLD selection. Belt-and-suspenders: after the click, explicitly redispatch `input` and `change` events with `composed: true` (crosses Shadow DOM and Vue Teleport portals) and reset React's `_valueTracker` for the shared React-checkbox case. Restores reliable Next/Submit progression on multi-step Vue forms that gate validation on checkbox state.
863
+
864
+ ## [2.10.6] - 2026-05-14
865
+
866
+ ### Added
867
+
868
+ - **`safari_react_select_set`** — set a value in a react-select v5 dropdown by walking React fiber up from the target element to find the Select component, then invoking `onChange` directly with the matching option. Bypasses the menu UI entirely. Critical for forms where `safari_click` on the dropdown chevron stops responding after a few rows (Cloudflare custom token form is the canonical case — the indicator's pointer/click handlers silently no-op past row 4 even though the elements still have valid React fibers). Match priority: exact label → exact value → case-insensitive label. Returns `{ok, selected}` on success, or `{ok:false, error:'option not found', available:[…]}` listing up to 30 labels on miss. Either `ref` or `selector` required.
869
+ - **`safari_react_select_list_options`** — companion read-only tool. Returns `{ok, total, options:[{label,value}…]}` without opening the menu. Useful when `set` returns "option not found" and you need to see the exact labels (e.g. `Email Routing Rules` vs `Email Routing`).
870
+ - **`mcpReactSelectFindInstance` / `mcpReactSelectFlatten` / `mcpReactSelectSet` / `mcpReactSelectListOptions`** — underlying page-injected helpers. Bumps `__mcpVersion` to 6 so existing pages re-inject on next `ensureHelpers`.
871
+
872
+ ### Implementation notes
873
+
874
+ The fiber walk has two passes: outer DOM-parent traversal (up to 25 levels) and inner fiber `.return` traversal (up to 60 hops) at each DOM level. This covers portal-rendered Select components where the React tree and DOM tree diverge. Grouped options (`{label, options:[…]}`) are flattened before matching. The synthetic action object passed to `onChange(target, action)` mirrors react-select's own `{action:'select-option', option, name}` shape so consumers that branch on `action.action` behave correctly.
875
+
876
+ ### Fixed
877
+
878
+ - `ensureHelpers` check now requires `mcpReactSelectSet` in addition to `mcpClickWithReact` and `mcpFindText`, forcing re-injection on pages still holding the v5 helpers.
879
+
880
+ ## [2.10.5] - 2026-05-12
881
+
882
+ ### Security
883
+
884
+ - **Upgrade `fast-uri` 3.1.0 → 3.1.2 (CVE-2026-6321 / GHSA-q3j6-qgpj-74h6).** Resolves host-confusion via percent-encoded authority delimiters and path-traversal via percent-encoded dot segments. fast-uri is transitively pulled through `hono`'s URL parsing on the extension's lightweight HTTP surface.
885
+ - **Upgrade `hono` 4.12.14 → 4.12.18.** Rolls up multiple advisories — CSS declaration injection via JSX SSR style object values, JWT NumericDate claim validation in `verify()`, cache middleware ignoring `Vary: Authorization` / `Vary: Cookie`, JSX tag/attribute name HTML injection, non-breaking-space cookie-name bypass, `setCookie` cookie-name validation, IPv4-mapped IPv6 matching in `ipRestriction()`, repeated-slash bypass in `serveStatic`, path traversal in `toSSG()`, and `bodyLimit()` bypass for chunked / unknown-length requests.
886
+ - **Upgrade `ip-address` 10.1.0 → 10.2.0.** XSS in `Address6` HTML-emitting methods.
887
+
888
+ ### CI
889
+
890
+ - **`npm audit` gate now fails the build on `high` or `critical` advisories in production dependencies.** Previously the gate logged but did not fail. Catches future Dependabot misses earlier.
891
+
892
+ No user-facing behavior changes. Recommended reinstall for transitive-dependency hardening.
893
+
894
+ ## [2.10.4] - 2026-05-08
895
+
896
+ ### Fixed
897
+
898
+ - **`safari_fill` no longer loses middle paragraphs in ProseMirror/Tiptap editors with no view access (Hashnode-style).**
899
+ When a ProseMirror-based editor doesn't expose its `view` via `pmViewDesc` or React Fiber walk (Hashnode's contenteditable has neither), `safari_fill` previously fell through to char-by-char `beforeinput` + `execCommand('insertText')` per line. On multi-paragraph content with markdown-like first characters (`>`, `**`, `[`), the editor dropped middle paragraphs silently — the result was the first paragraph + a chain of empty paragraphs + the last paragraph. The fix verifies actual content length after the char-by-char pass; if the rendered text is less than 60% of the expected value length, it clears the editor and re-fills via `execCommand('insertHTML')` with paragraph-wrapped HTML. The new return marker `Filled CE (ProseMirror insertHTML fallback, <actual>/<expected>)` makes the path observable.
900
+ Originally surfaced cross-posting a dev.to article body to a Hashnode draft — char-by-char filled 446 chars out of an expected 6800+, retaining only the first and last paragraphs.
901
+
902
+ - **`safari_fill` synthetic-paste path now explicitly clears pre-existing content before paste.**
903
+ X's `tweetTextarea_0` at `/intent/post?text=...` pre-fills the textarea with the URL's `text` parameter before the page settles. Previous fill logic positioned cursor at the end of the existing content (via `selectNodeContents` + collapse) but didn't delete the selection before dispatching the synthetic `paste` event — most editors replace selection on paste, but X's React handler appended, resulting in duplicated text (`<URL prefill> <safari_fill value>`). The fix adds an explicit `document.execCommand('delete', false, null)` after the selection is set and before the `ClipboardEvent('paste')` dispatch. Affects any contenteditable whose initial content needs to be replaced via the synthetic-paste path (Quill in some configurations, X composer with URL-prefilled text, similar React-driven editors).
904
+
905
+ ## [2.10.3] - 2026-05-06
906
+
907
+ ### Fixed
908
+
909
+ - **Permanent tab-safety guard: `safari_navigate` (and friends) can no longer overwrite the user's active tab when MCP tab tracking is lost mid-session.**
910
+ Previously, a 30-second `NEW_TAB_GRACE_MS` window guarded against fallback to "current tab of window" only briefly after `safari_new_tab`. After the grace expired, if `_activeTabIndex` was lost (e.g. the tab-ghost recovery path in `runJS` nullified it), `navigate` silently fell back to the user's current tab via `getFallbackTarget()` — and clobbered whatever page the user was working on.
911
+ The fix introduces a session-scoped `_hasOwnedTab` flag set permanently the first time `safari_new_tab` succeeds. Once true, the four entry points that can target a tab — `_assertNotFallingBackToUserTab` (used by `navigate` and `navigateAndRead`), `runJS`'s tab-ghost fallback path, and `runJSLarge` — refuse to fall back to the user's current tab. They throw a descriptive error instead, prompting the caller to re-open a tab via `safari_new_tab`.
912
+ Sessions that never call `safari_new_tab` (e.g. tools that operate on the user's current tab intentionally) are unaffected — the front-document fallback still works for them.
913
+ Originally surfaced by an incident where `safari_navigate('https://old.reddit.com/...')` called ~30 minutes into a session navigated the user's localhost dev tab (which they had clicked back to between commands) instead of the MCP-owned tab.
914
+
915
+
916
+
917
+ ### Fixed
918
+
919
+ - **`safari_fill` now handles Quill editors (the LinkedIn share composer 2026 reality).**
920
+ LinkedIn migrated their post composer from ProseMirror to Quill in 2026, which made
921
+ the v2.10.0 ProseMirror-targeted fix inapplicable to LinkedIn. Worse, fill attempts
922
+ on Quill's contenteditable surface crashed the Swift helper daemon and dismissed the
923
+ composer dialog. The fix detects `.ql-editor` ancestors first, locates the Quill
924
+ instance via `.ql-container.__quill` (Quill 2.x) or by walking React Fiber
925
+ (`memoizedProps.quill` / `stateNode.quill`), then commits the value through
926
+ `quill.setContents(delta, 'api')` — bypassing the clipboard, generating no synthetic
927
+ events, and respecting Quill's internal Delta state. If the Quill instance can't be
928
+ located via direct or Fiber access, fill routes to `__NATIVE_PASTE_DIALOG__` (CGEvent
929
+ Cmd+V) — Quill respects real isTrusted clipboard events. Verified post-fill that the
930
+ Quill text actually committed; on mismatch the function returns the same fallback
931
+ signal the wrapper uses for ProseMirror dialog-paste fallback.
932
+
933
+ ## [2.10.1] - 2026-05-01
934
+
935
+ ### Fixed
936
+
937
+ - **Tab tracking bug — new_tab + navigate could overwrite the user's active tab.** When
938
+ `safari_new_tab(url)` was called with a URL that didn't load (file:// blocked by Safari,
939
+ network error, etc.), the new tab stayed at about:blank, the marker injection ran in a
940
+ context that was wiped by the next navigation, and the very next `safari_navigate` lost
941
+ track of which tab was ours and silently fell back to "current tab of window" — i.e. the
942
+ user's active tab. Real-world impact: testing v2.10.0 on the developer's own machine
943
+ overwrote two of his open tabs (Chatwoot Meta Dashboard, n8n executions).
944
+
945
+ Fixes:
946
+ - New `_lastNewTabAt` grace window (30s) — within this window, ANY mutating operation
947
+ that would otherwise fall back to the user's tab now throws a clear error pointing
948
+ back to safari_new_tab. No more silent retargeting.
949
+ - `safari_navigate` re-injects `window.__mcpTabMarker` after every successful navigation,
950
+ so subsequent `resolveActiveTab` marker checks find the tab even after JS context
951
+ was wiped by the navigation.
952
+
953
+ - **Trusted Types pages (Google Search Console, modern Google admin, banks).** Strategy 2
954
+ of the extension's `evaluate` flow used to call `trustedTypes.createPolicy("mcpEval", …)`
955
+ AFTER the page loaded, which fails on pages that reject new policy creation post-load.
956
+ Now the content script (MAIN world, document_start) pre-registers `__mcpTrustedPolicy`
957
+ BEFORE the page sets `require-trusted-types-for`, and Strategy 2 reuses it. Pages that
958
+ used to silently fail under CSP-strict rules now have a working evaluation path. Take
959
+ effect: reload the Safari extension after upgrading.
960
+
961
+ ## [2.10.0] - 2026-05-01
962
+
963
+ ### Added
964
+
965
+ - **`safari_verify_state` tool — verify framework state before Submit.** Modern editors
966
+ (ProseMirror, Lexical, Closure, React-controlled inputs) keep state separately from the
967
+ DOM. `el.value` or `el.textContent` can show new text while the framework store still
968
+ holds the old value, so a Submit click sends stale data. Call `safari_verify_state`
969
+ AFTER `safari_fill` and BEFORE clicking Submit; it returns
970
+ `{match, mode, actual, expected, hint?}`. Modes: input, prosemirror, lexical, closure,
971
+ contenteditable. The `hint` field surfaces `_valueTracker` desync — the most common
972
+ Featured.com / Next.js RSC failure mode.
973
+
974
+ - **Auto-conversion of webp/heic/tiff uploads when the target rejects them.** `safari_upload_file`
975
+ now reads the input's `accept` attribute. If the format isn't accepted (Quora's classic
976
+ `accept="image/png,image/jpeg"` rejects webp), the file is converted to PNG via macOS
977
+ `sips` (no extra deps) before encoding. No-op when `accept` is empty, `image/*`, or
978
+ already includes the source format.
979
+
980
+ - **Native `<select>` guard in `safari_click`.** LinkedIn-style "select your industry"
981
+ dropdowns look custom but are real `<select>` elements. Calling `.click()` on them
982
+ hands off to the OS option list, which blocks AppleScript until dismissed → tool
983
+ timeout. The click pipeline now detects `SELECT` early and throws a directive error
984
+ pointing at `safari_select_option` plus the first 8 option labels.
985
+
986
+ ### Fixed
987
+
988
+ - **`safari_fill` standard input/textarea path — Featured.com / HubSpot Formik / React 18.**
989
+ Three coupled bugs caused silent value-mismatch on Next.js RSC and Formik forms:
990
+ 1. **`focus` was dispatched LAST** (after `blur` + `focusout`). Formik's onBlur
991
+ validation runs on focused-state transition; firing focus after blur left the field
992
+ in a stale state and validation never re-ran.
993
+ 2. **Plain `Event('input')` instead of `InputEvent`.** React 18's reconciler checks
994
+ `inputType` and `data` on input events; without them, the controlled component's
995
+ internal store rejects the change as "not a real edit."
996
+ 3. **No `composed: true`.** Events stayed inside Shadow DOM and never reached the
997
+ framework's listeners on the host.
998
+
999
+ All three fixed: focus first, real `InputEvent` with `inputType:"insertReplacementText"`
1000
+ + `data`, `composed: true` on every dispatched event, and post-fill verification that
1001
+ routes to native CGEvent Cmd+V paste if `el.value` doesn't match expected.
1002
+
1003
+ - **`safari_fill` ProseMirror dispatch verification.** LinkedIn's PM occasionally accepts
1004
+ the `tr.insertText` dispatch but rolls it back on the next tick (its readOnly plugin
1005
+ reasserts state). The dispatcher now reads back `view.state.doc.textContent` after
1006
+ `dispatch()`; if the value isn't present, fill falls through to `__NATIVE_PASTE_DIALOG__`
1007
+ → CGEvent Cmd+V (real isTrusted events).
1008
+
1009
+ - **`safari_fill` Reddit nested Shadow DOM events propagate.** All input/change/blur events
1010
+ ship with `composed: true`, so nested closed-shadow textareas (Reddit appeals reaches
1011
+ 4 levels deep) actually notify host listeners.
1012
+
1013
+ - **`safari_fill_form` batch — was missing `_valueTracker` and InputEvent.** The single-call
1014
+ variant of `fill_form` skipped React state-sync entirely (only the contenteditable branch
1015
+ had treatment). Fixed: same setter + InputEvent + composed dispatch + dialog-aware blur
1016
+ as the per-field `safari_fill`. Also: prototype-correct setter for textarea and select,
1017
+ deep-query through Shadow DOM, and reports `PARTIAL` when post-fill `el.value` doesn't
1018
+ match expected.
1019
+
1020
+ - **Closure / Medium detection broader.** Used to only match `closure_uid_` keys on the
1021
+ element itself or `medium.com` hostname. Now also matches `closure_lm_` keys, walks 10
1022
+ levels of ancestors for closure markers, and falls back on `window.goog.events` /
1023
+ `window.goog.editor` globals — covers Closure-built editors outside Medium.
1024
+
1025
+ - **`mcpReactClick` Fiber walk — React 18 portals (HackerNoon Submit, Radix dropdowns).**
1026
+ The synthetic event used to omit `isDefaultPrevented()` / `isPropagationStopped()` methods
1027
+ React 18 internally checks. Some portal-rendered components silently no-op when those are
1028
+ missing. Now produces a fully-React-18-compatible SyntheticEvent (real
1029
+ `MouseEvent`/`PointerEvent` as `nativeEvent`, working flag accessors, `composed: true`,
1030
+ pageX/Y, screenX/Y, modifier keys). The walk also tries `onPointerDown` → `onMouseDown`
1031
+ → `onMouseUp` → `onPointerUp` → `onClick` in sequence — covers components that open the
1032
+ modal on pointerDown and commit on click. Fiber walk depth doubled (15 → 30) and now
1033
+ also reads `stateNode.props` for forwardRef components.
1034
+
1035
+ ### Documented hard limits (still need manual fallback)
1036
+
1037
+ - **XPC Web Inspector Protocol.** Apple gates access with a private entitlement; no
1038
+ legitimate workaround exists. `safari_evaluate` continues to use AppleScript `do JavaScript`.
1039
+ - **Trusted Types pages (Google Search Console, modern Google admin consoles).** Pages
1040
+ with `require-trusted-types-for 'script'` reject both `do JavaScript` and extension-issued
1041
+ evals when the policy is enforced page-wide. Recommended fallback is `safari_snapshot` +
1042
+ `ref`-based interactions which don't require JS execution.
1043
+
1044
+ ## [2.9.3] - 2026-04-22
1045
+
1046
+ ### Added
1047
+
1048
+ - **Lexical editor support (LinkedIn share composer, Meta/Shopify apps).** `safari_fill`
1049
+ locates the Lexical editor instance via three cascading strategies: (A) `[data-lexical-editor="true"]`
1050
+ ancestor with a `__lexicalEditor` property, (B) DOM-ancestor walk for the same property on
1051
+ nested wrappers, (C) React Fiber walk — duck-types any object on props/state/stateNode that
1052
+ exposes both `parseEditorState` and `setEditorState`. Once found, it drives the editor via
1053
+ its own API — entirely in-page, no CGEvent, no focus shift. Two fill strategies, both pure
1054
+ DOM events (the dialog stays open):
1055
+ 1. Dispatch `beforeinput` with `inputType:"insertFromPaste"` + a synthetic `DataTransfer`.
1056
+ Lexical's `handleBeforeInput` reads `dataTransfer.getData('text/plain')` and commits
1057
+ through `editor.update()` internally, so state + DOM stay in sync.
1058
+ 2. Fallback: `editor.parseEditorState()` + `editor.setEditorState()` with a minimal
1059
+ `root → paragraph → text` doc. Used when Lexical's paste path ignores the synthetic
1060
+ event (some wrapper configurations).
1061
+
1062
+ Why this matters: LinkedIn's composer is a `[role="dialog"]` with a `focusout` listener
1063
+ that dismisses the modal. Our previous CGEvent Cmd+V path pasted the text correctly but
1064
+ caused the dialog to close mid-paste (the Safari window-activation side-effect briefly
1065
+ fired `focusout` on the editor). Lexical's own API never touches focus, so the dialog
1066
+ stays open and the Post button becomes enabled.
1067
+
1068
+ ### Fixed
1069
+
1070
+ - **`safari_fill` now survives inside dialog-hosted rich editors.** Three issues previously
1071
+ made LinkedIn posting impossible:
1072
+ 1. The contenteditable fallback dispatched a `blur` event at the end — LinkedIn's composer
1073
+ listens for `focusout` and dismissed the dialog, so every fill closed the post box.
1074
+ 2. When ProseMirror was detected but its `EditorView` could not be reached via `pmViewDesc`
1075
+ or the React Fiber walk, fill fell back to `beforeinput`+`execCommand` char-by-char.
1076
+ Those events are `isTrusted:false` and ProseMirror's paste handler rejects them — text
1077
+ never landed in editor state.
1078
+ 3. The synthetic `ClipboardEvent('paste')` returned "Filled CE (synthetic paste)" even when
1079
+ ProseMirror called `preventDefault` without accepting the payload.
1080
+
1081
+ Primary fix is the Lexical path above. For ProseMirror editors whose view is not reachable,
1082
+ contenteditables inside `[role="dialog"]` now route to `_nativeTypeViaClipboard` (CGEvent
1083
+ Cmd+V, `isTrusted:true`) as a last resort. The `blur` dispatch is removed — React detects
1084
+ the change from `input` alone.
1085
+
1086
+ ### Changed
1087
+
1088
+ - Default contenteditable fill no longer dispatches `blur`. This also fixes silent dismissal
1089
+ of other popover editors (Twitter/X composer, Medium inline-reply) that treated the blur
1090
+ as "user clicked away".
1091
+
1092
+ ## [2.9.2] - 2026-04-21
1093
+
1094
+ ### Documentation
1095
+
1096
+ - Added **Commercial Support** section to README — priority bug fixes, integration
1097
+ consulting, private deployment support, and training workshops for teams building
1098
+ on Safari MCP. Part of the OSS-to-services lead funnel pattern (Plausible, Cal.com,
1099
+ Documenso, Supabase).
1100
+
1101
+ ## [2.9.1] - 2026-04-20
1102
+
1103
+ ### Added
1104
+
1105
+ - **`safari_reload_extension` — hot-reload the Safari extension from disk.** After editing
1106
+ `extension/background.js` or `extension/content.js`, call this tool to trigger
1107
+ `browser.runtime.reload()` inside the extension. Safari re-reads the files from disk and
1108
+ the WebSocket auto-reconnects within ~2 seconds. Eliminates the manual toggle dance in
1109
+ Safari → Preferences → Extensions after every code change. This is the final piece that
1110
+ makes safari-mcp self-updating — once v2.9.1+ is loaded once, all future extension code
1111
+ changes deploy with a single MCP call.
1112
+
1113
+ ## [2.9.0] - 2026-04-20
1114
+
1115
+ ### Added
1116
+
1117
+ - **`safari_snapshot` — auto-detect open top-layer modals/dialogs.** When a dialog is visible
1118
+ (dialog[open], [role="dialog"], [aria-modal="true"], Radix/Headless/MUI containers, or
1119
+ Google's `c-wiz[role="dialog"]` / `[jscontroller][aria-modal]` overlays), the snapshot
1120
+ now walks the modal FIRST so its refs appear at the top of the tree. Solves the pattern
1121
+ where clicking a button opens a dialog but `snapshot` returns only the page behind it
1122
+ (common with Google Business Profile, Google Drive editors, Airtable rich dialogs).
1123
+ Deduplicates nested modals — the outermost visible modal wins.
1124
+
1125
+ ## [2.8.9] - 2026-04-20
1126
+
1127
+ ### Security
1128
+
1129
+ - Bump `hono` override from `^4.12.12` to `^4.12.14` to silence dependabot alert #9
1130
+ (GHSA: hono/jsx SSR HTML injection via improperly handled JSX attribute names).
1131
+ Not exploitable at runtime — safari-mcp only loads `StdioServerTransport` and does
1132
+ not render JSX on the server — but the pin is refreshed for clean `npm audit`.
1133
+
1134
+ ## [2.8.8] - 2026-04-20
1135
+
1136
+ ### Changed
1137
+
1138
+ - **`safari_replace_editor` — React wrapper onChange sync for Monaco embeds.** Two-channel
1139
+ write strategy: Monaco `model.setValue()` for the visual + walk the React fiber up from
1140
+ `.monaco-editor` until a component with `onChange` + `value` props is found, then call
1141
+ its `onChange(text)` to sync React state. Solves the "DOM updated, state stale" pattern
1142
+ on sites that wrap Monaco in React (Airtable automations, custom admin UIs) where the
1143
+ "Save" button reads from React state, not from the Monaco model.
1144
+ - Preflight returns a structured JSON status (`{domOk, reactSynced, reactGuarded, hasWrapper, ...}`)
1145
+ so callers can distinguish plain Monaco embeds (`Monaco(model)`) from React-wrapped ones
1146
+ (`Monaco(model+react)`) and gracefully fall back to the native-paste CGEvent path when the
1147
+ wrapper's `onChange` is guarded (readOnly / permission check / no-op).
1148
+ - Verification tightened: the React sync is only reported successful when the wrapper's
1149
+ `value` prop actually changes after the `onChange` call. If `onChange` silently swallows
1150
+ the write (common on readOnly previews), `reactGuarded=true` is reported and the fallback
1151
+ CGEvent Cmd+A/Cmd+V path runs — no false positives.
1152
+
1153
+ ## [2.8.5] - 2026-04-19
1154
+
1155
+ ### Changed
1156
+
1157
+ - **README: above-the-fold rewrite applied** — research-backed overhaul of the hero section based on patterns from the top non-corporate MCP projects (Context7 49K⭐, Serena 23K⭐, Desktop Commander 5.9K⭐, BrowserMCP 6K⭐):
1158
+ - **Tagline:** shortened from 11 words ("The only MCP server for Safari — native browser automation for AI agents") to a Serena-style category claim: **"The browser for your coding agent."** A second italic line (*"Your real Safari, logged in — no Chrome, no heat, no headless."*) carries the three wedges.
1159
+ - **Badges:** reduced from ~10 above the fold to 4 core badges (npm version, downloads, MIT, macOS). Registry/Glama/Awesome/HackerNoon/CLI-Anything moved to the "Listed On" section at the bottom where they belong.
1160
+ - **"❌ Without / ✅ With Safari MCP" block** added immediately after the hero — Context7's killer pattern. Framed against the three real alternatives (Playwright, Chrome DevTools MCP, headless scrapers) instead of the defensive "Why not just use X" question.
1161
+ - **80-tool list collapsed into `<details>`** — the full tool table is still there for depth, but no longer dominates the scroll experience. Top-level content is now skimmable in under 30 seconds.
1162
+ - **Star-scolding block removed** — the "Less than 1% star it" block was an anti-pattern per every top README analyzed. Kept the silent star-history chart at the bottom, which is what Context7/Desktop Commander/Serena all do.
1163
+ - **"What agents unlock with Safari MCP" section** added — Serena-style framing of the capabilities an LLM actually benefits from (authenticated sessions, framework-aware form setters, background operation, batched workflow calls).
1164
+ - **Community count corrected** — "2,000+ monthly" → "6,000+ monthly" to match current npm downloads (~1,500/week × 4).
1165
+
1166
+ No API, tool, or code changes — documentation/positioning only.
1167
+
1168
+ ## [2.8.4] - 2026-04-16
1169
+
1170
+ ### Fixed
1171
+
1172
+ - **`SESSION_ID is not defined` runtime error on `safari_new_tab`** — introduced by v2.8.3's bulletproof tab marker. The marker code at `safari.js:2151` references `SESSION_ID`, but that const was only declared in `index.js` (not exported), so the separate `safari.js` ES module threw `ReferenceError: SESSION_ID is not defined` whenever a new tab went through the marker path. Symptom: `safari_new_tab` returned `SESSION_ID is not defined` but the tab still opened in Safari — subsequent calls then failed the tab-ownership safety check, making the MCP unusable for form-driven workflows (HubSpot AEO, Semrush AI Visibility, GTmetrix, etc.). Fix: declare a local `const SESSION_ID = randomUUID().slice(0, 8)` in `safari.js` (each ES module gets its own, which is fine — the marker only needs per-process uniqueness).
1173
+
1174
+ ## [2.8.3] - 2026-04-14
1175
+
1176
+ ### Fixed
1177
+
1178
+ - **Tab tracking: bulletproof identity via `window.__mcpTabMarker`** — discovered during the v2.8.2 launch campaign that `safari_evaluate` could occasionally land on the wrong tab when `safari_new_tab` and `safari_evaluate` were called more than ~500 ms apart and a popup/redirect added a new tab in the meantime. Root cause: `resolveActiveTab` relied on URL prefix matching, which fails when the page redirects (e.g. LinkedIn `/feed/` → `/feed/?shareActive=true`) or when query strings change. Fix: every `safari_new_tab` now writes a unique marker into `window.__mcpTabMarker`, and `resolveActiveTab` uses that marker as the primary identification strategy. The URL/domain matching remains as a fallback for tabs created before the marker was set. Marker survives same-tab navigation, query changes, and history pushState.
1179
+ - **Resolve cache reduced from 500 ms to 100 ms** — was masking the multi-tab race when calls were spaced more than 100 ms apart but less than 500 ms. The marker check above is cheap (~5 ms), so the tighter cache adds negligible latency.
1180
+
1181
+ ## [2.8.2] - 2026-04-14
1182
+
1183
+ ### Added
1184
+
1185
+ - **README: Featured on HackerNoon** — added prominent badge and quote linking to the new technical deep-dive [I Had to Reverse-Engineer React, Shadow DOM, and CSP to Automate Safari Without Chrome](https://hackernoon.com/i-had-to-reverse-engineer-react-shadow-dom-and-csp-to-automate-safari-without-chrome) (published 2026-04-14). The article walks through the three hardest problems behind safari-mcp: React's `_valueTracker` workaround, recursive Shadow DOM traversal with MutationObserver caching, and the 4-strategy CSP fallback chain.
1186
+
1187
+ ## [2.8.1] - 2026-04-14
1188
+
1189
+ ### Added
1190
+
1191
+ - **Auto-sync to MCP Registry on release** — `.github/workflows/release.yml` now publishes to `registry.modelcontextprotocol.io` on every GitHub release using `mcp-publisher` with GitHub OIDC. Previously, `server.json` had to be bumped manually and the publisher run by hand, which meant versions 2.7.7 → 2.8.0 never made it to the registry.
1192
+
1193
+ ## [2.8.0] - 2026-04-14
1194
+
1195
+ ### Added
1196
+
1197
+ - **Postinstall welcome banner** (`scripts/postinstall.cjs`) — printed once after `npm install`, shows next-step setup and a discoverable star CTA. Skipped silently in CI and when `SAFARI_MCP_SILENT_INSTALL=1` is set.
1198
+ - **Once-per-day startup banner** in `index.js` — written to stderr (never stdout, so MCP protocol is untouched) on the first server start of the day. Includes version, capability summary, and a one-line star link. Suppressed by `SAFARI_MCP_QUIET=1`.
1199
+ - **`smithery.yaml`** — Smithery deployment config, points at the existing `smithery-entry.js` (no top-level `await`).
1200
+
1201
+ ### Changed
1202
+
1203
+ - **README revamp for discoverability:**
1204
+ - New social-proof badge row: MCP Registry, Glama, Awesome MCP, CLI-Anything.
1205
+ - Prominent star CTA block right after Quick Start (was buried at line 568).
1206
+ - New "Why Safari MCP and Not the Other Safari MCP Projects?" comparison table — clarifies how this project differs from `lxman/safari-mcp-server`, `Epistates/MCPSafari`, and `HayoDev/safari-devtools-mcp`.
1207
+ - Removed duplicate "vs. Chrome DevTools MCP / Playwright MCP" section.
1208
+ - **GitHub topics** updated for better organic discovery — added `claude-code`, `safari-mcp`, `mcp` to the topic set.
1209
+
1210
+ ## [2.7.14] - 2026-04-12
1211
+
1212
+ ### Fixed
1213
+
1214
+ - **`safari-helper` now includes `com.apple.security.automation.apple-events` entitlement.** This helps macOS correctly identify the binary's intent and surface the TCC Automation prompt more reliably on first launch from an IDE. Previously, the ad-hoc signature had no entitlements, causing some setups to silently deny Apple Events without ever prompting.
1215
+ - Added troubleshooting note for "Not authorized" errors after `npm update` — updating changes the binary's cdhash, which causes macOS to silently revoke Automation permission. Users need to re-grant via the `osascript` one-liner.
1216
+ - Entitlements file (`safari-helper.entitlements`) now ships with the npm package for users building from source.
1217
+
1218
+ ## [2.7.14] - 2026-04-12
1219
+
1220
+ ### Fixed
1221
+
1222
+ - `safari_press_key` Enter on contenteditable now has a **native fallback** when the JS keydown isn't handled (isTrusted:false rejection by Discord/Slack/etc.). The fallback briefly activates Safari (~80ms), sends a real keystroke, then immediately restores the previous frontmost app — total visual flash <130ms, imperceptible to most users. This closes the last gap in Discord automation: text insertion via `cmd+v` (Slate state-aware) + Enter submission via native fallback. The fallback ONLY fires when the JS path fails (returns `__ENTER_NOT_HANDLED__`), so apps that accept synthetic events still use the zero-focus-steal JS path.
1223
+
1224
+ ## [2.7.13] - 2026-04-12
1225
+
1226
+ ### Fixed
1227
+
1228
+ - `safari_press_key` Enter on contenteditable no longer inserts a line break. Modern editors (Discord Slate, Slack, Notion, Medium) handle Enter in their own keydown handler to trigger submit/send. The old fallback `execCommand('insertLineBreak')` was double-acting — the app tries to submit AND MCP adds a newline, corrupting the editor state and preventing actual submission. Now:
1229
+ - **INPUT** → form submit (unchanged)
1230
+ - **TEXTAREA** → insertLineBreak (unchanged)
1231
+ - **ContentEditable + Enter** → keydown event only, let the app decide (fixed)
1232
+ - **ContentEditable + Shift+Enter** → insertLineBreak (newline, as expected)
1233
+
1234
+ ## [2.7.12] - 2026-04-12
1235
+
1236
+ ### Added
1237
+
1238
+ - `safari_native_type` tool — inserts text into any editor via OS-level clipboard paste (CGEvent Cmd+V targeted to Safari window). Unlike `safari_fill` which writes to the DOM directly (breaking ProseMirror/Slate/Draft.js internal state), `safari_native_type` goes through the browser's real paste pipeline. The framework processes the paste event natively, so its model stays in sync with the DOM. After calling `safari_native_type`, pressing Enter via `safari_native_keyboard` will actually submit the form — because the framework state matches the visible content. Saves and restores the user's clipboard. No focus stealing.
1239
+
1240
+ ### Why this matters
1241
+
1242
+ This closes the last gap in the Discord/Slack automation chain:
1243
+ 1. `safari_hover` → find server by tooltip name
1244
+ 2. `safari_click` → enter channel
1245
+ 3. `safari_native_type` → paste message into ProseMirror editor (state-aware)
1246
+ 4. `safari_native_keyboard {key: "enter"}` → submit (no focus steal)
1247
+
1248
+ Previously step 3 used `safari_fill` which worked visually but the text wasn't "really there" from Discord's perspective — leading to empty submissions on Enter.
1249
+
1250
+ ## [2.7.11] - 2026-04-12
1251
+
1252
+ ### Added
1253
+
1254
+ - `safari_native_keyboard` tool — OS-level keyboard event via macOS CGEvent, targeted to the Safari window ID without activating Safari. Produces `isTrusted: true` events that bypass React trust checks in Discord ProseMirror, Slack virtualized editors, and similar trust-gated UIs. Supports all common keys (enter, tab, escape, arrows, letters, digits, punctuation) and modifiers (cmd, shift, alt, ctrl). **No focus stealing** — runs entirely in the background.
1255
+
1256
+ ### Fixed
1257
+
1258
+ - Operations that required a real keypress previously had no zero-focus-steal path; users (and automation agents) had to fall back to `osascript "tell application \"Safari\" to activate"` which brings Safari to the foreground and interrupts whatever the user is doing. `safari_native_keyboard` closes this gap so pressing Enter in Discord, Slack, or any ProseMirror-backed editor no longer pops Safari in front of the user.
1259
+
1260
+ ## [2.7.10] - 2026-04-12
1261
+
1262
+ ### Added
1263
+
1264
+ - `safari_native_hover` tool — OS-level mouse move via macOS CGEvent. Triggers real `:hover` and `mouseenter` handlers on obfuscated UIs (Discord sidebars, portal-rendered tooltips) where JS-dispatched events aren't enough. Dwells for a configurable duration then restores the cursor position. Complements `safari_native_click`.
1265
+
1266
+ ### Fixed
1267
+
1268
+ - **Tab ownership now survives MCP process restarts.** Previously, every time Claude Code (or any other MCP client) recycled the Safari MCP server, the in-memory `_ownedTabURLs` set was wiped, causing `⚠️ Tab safety: no tabs opened yet` errors on the next tool call. Ownership is now persisted to `~/.safari-mcp/owned-tabs.json` with a 30-minute TTL.
1269
+ - **`safari-helper` now targets macOS 12.0+ instead of macOS 26.** The daemon was shipped in v2.7.9 compiled with `minos 26.0`, which silently failed to launch on macOS 15 and earlier (#15 root cause). Rebuilt with `swiftc -target arm64-apple-macos12.0` so it runs on Monterey through Tahoe.
1270
+
1271
+ ## [2.7.9] - 2026-04-11
1272
+
1273
+ ### Fixed
1274
+
1275
+ - Remove `pgrep -E` flag that doesn't exist on macOS — memory monitor was emitting `pgrep: illegal option -- E` on stderr on every check (#15)
1276
+ - Move Safari extension popup inline `<script>` into `popup/popup.js` so MV3 `script-src 'self'` CSP stops blocking it; popup was stuck on "Checking..." indefinitely (#18, thanks @mikhailkogan17)
1277
+ - Re-sign `safari-helper` daemon with an explicit ad-hoc signature (replaces the linker-signed fallback) so macOS TCC has a stable cdhash to anchor Automation permissions
1278
+
1279
+ ### Documentation
1280
+
1281
+ - README: add **Automation → Safari** to the macOS Permissions table, plus instructions for granting it to the parent IDE and the `osascript` one-shot workaround (#16)
1282
+ - README: add `codesign --sign - --force --deep` step to the extension build instructions so Safari will actually load the bundle produced by `xcodebuild` (#17)
1283
+
1284
+ ### Security
1285
+
1286
+ - Pin `hono` to `^4.12.12` and `@hono/node-server` to `^1.19.13` via `package.json` overrides, silencing 6 transitive dependabot advisories (not exploitable at runtime — safari-mcp only loads `StdioServerTransport`)
1287
+ - Add `.github/CODEOWNERS` and expand Dependabot to cover `github-actions` ecosystem
1288
+ - Publishing to npm now uses OIDC Trusted Publisher instead of long-lived `NPM_TOKEN`; releases gate on a manual-approval `npm-publish` environment
1289
+
1290
+ ## [2.7.3] - 2026-04-01
1291
+
1292
+ ### Fixed
1293
+
1294
+ - Prevent Safari from auto-launching when closed — `tell application "Safari"` in AppleScript starts Safari automatically; added `pgrep` check before every osascript call to return an error instead of launching Safari
1295
+
1296
+ ## [2.7.2] - 2026-03-31
1297
+
1298
+ ### Changed
1299
+
1300
+ - Replace Hebrew text in code comments and author headers with English
1301
+ - Use Unicode escapes for locale-dependent UI strings (Cancel button, error detection)
1302
+ - Remove unused popup.js (logic is inline in popup.html)
1303
+ - Add `lang="en"` to popup.html for accessibility
1304
+
1305
+ ## [2.5.3] - 2026-03-31
1306
+
1307
+ ### Fixed
1308
+
1309
+ - Tab targeting: always re-resolve tab by URL before every command (RESOLVE_CACHE_MS → 0). Cached indices go stale when tabs are opened/closed by other sessions, causing commands to land on wrong tabs
1310
+
1311
+ ## [2.5.2] - 2026-03-31
1312
+
1313
+ ### Fixed
1314
+
1315
+ - Type text in cross-origin iframes: Extension now falls back to `allFrames: true` when typing in main frame fails, preventing the AppleScript path from stealing focus
1316
+
1317
+ ## [2.5.1] - 2026-03-31
1318
+
1319
+ ### Fixed
1320
+
1321
+ - Click in cross-origin iframes: Extension now falls back to `allFrames: true` when element not found in main frame, enabling clicks on buttons inside Intercom, Zendesk, and other cross-origin iframe widgets — zero focus stealing
1322
+
1323
+ ## [2.5.0] - 2026-03-31
1324
+
1325
+ ### Added
1326
+
1327
+ - CGEvent native keyboard support in Swift helper — send keystrokes to Safari without activating the window or stealing focus
1328
+ - Cross-origin iframe typing: `typeText` and `pressKey` (Cmd+V) now detect when the active element is an iframe and use native CGEvent paste instead of JavaScript
1329
+
1330
+ ### Fixed
1331
+
1332
+ - Focus stealing: `_nativeTypeViaClipboard` and `pressKey` Cmd+V for iframes no longer activate Safari or use System Events — all done via background CGEvent targeting
1333
+
1334
+ ## [2.1.5] - 2026-03-30
1335
+
1336
+ ### Fixed
1337
+
1338
+ - Memory protection: prevent system crashes from WebKit memory leaks in long-running sessions
1339
+
1340
+ ## [2.1.4] - 2026-03-29
1341
+
1342
+ ### Fixed
1343
+
1344
+ - ClipboardEvent paste fallback for modern editors that block synthetic input events
1345
+
1346
+ ## [2.1.3] - 2026-03-29
1347
+
1348
+ ### Fixed
1349
+
1350
+ - Singleton process management: kill stale MCP instances on startup
1351
+ - Sibling instance detection: don't kill instances started by Claude Code VSCode
1352
+
1353
+ ## [2.1.2] - 2026-03-29
1354
+
1355
+ ### Added
1356
+
1357
+ - Closure/Medium editor fill via `execCommand` line-by-line insertion
1358
+ - Native paste for Closure/Medium editors via System Events `Cmd+V`
1359
+ - Demo GIF in README
1360
+
1361
+ ### Fixed
1362
+
1363
+ - Closure/Medium fill without focus stealing
1364
+ - Closure/Medium editor fill via synthetic clipboard paste
1365
+
1366
+ ## [2.1.1] - 2026-03-28
1367
+
1368
+ ### Added
1369
+
1370
+ - Official MCP Registry support (`server.json`)
1371
+ - `mcpName` field for registry identification
1372
+ - `mcp.json` for Cursor Directory / Open Plugins
1373
+
1374
+ ## [2.1.0] - 2026-03-28
1375
+
1376
+ ### Added
1377
+
1378
+ - `safari_native_click` tool: OS-level mouse click via CGEvent (produces `isTrusted` events)
1379
+ - Window-targeted native click: no mouse movement, no focus steal
1380
+ - Extension reconnect with exponential backoff
1381
+ - Architecture documentation for the dual-engine system
1382
+
1383
+ ### Fixed
1384
+
1385
+ - Native click saves/restores mouse position (no cursor stealing)
1386
+ - Window bounds fallback to direct osascript
1387
+ - `navigate()` properly waits for page load via sync polling
1388
+
1389
+ ## [2.0.1] - 2026-03-23
1390
+
1391
+ ### Added
1392
+
1393
+ - Closed Shadow DOM support with screenshot verification
1394
+ - React `_valueTracker` reset for LinkedIn/React app compatibility
1395
+ - Fuzzy matching in `select_option` for RTL text and dashes
1396
+ - CSP fallback strategy chain for `evaluate`
1397
+ - Smart loading detection with auto hard reload
1398
+ - Disabled element detection in `click` with clear error messages
1399
+ - Per-session tab tracking with profile separation
1400
+ - `glama.json` server metadata
1401
+
1402
+ ### Changed
1403
+
1404
+ - Click text matching: 3-layer matching (exact, deepest, contains)
1405
+ - `switch_tab` performs visual switch with stale ref warnings
1406
+ - Richer `snapshot` output
1407
+ - Closure editor fill improvements
1408
+
1409
+ ### Fixed
1410
+
1411
+ - Tab targeting: commands run on the correct tab after `switch_tab`
1412
+ - Extension blocked in personal profile to prevent window focus jumping
1413
+ - Extension skipped when `SAFARI_PROFILE` is set (AppleScript avoids focus steal)
1414
+ - LinkedIn ProseMirror view detection and paste behavior
1415
+ - Medium editor: auto-detection, clear error on fill failure, character-by-character mode
1416
+ - `fill_form`, `type_text`, `press_key`, `scroll`, and `click` bugs from deep audit
1417
+ - Checkbox React state synchronization
1418
+ - `select_option` retry via AppleScript fallback
1419
+ - Screenshot fallback respects `_preferAppleScript`
1420
+ - AppleScript `clearField` for contenteditable elements
1421
+ - `requestSubmit` used instead of `form.submit` for WAF compatibility
1422
+
1423
+ ### Performance
1424
+
1425
+ - Extension v2.1 with HTTP polling, profiles, and command queue
1426
+
1427
+ ## [2.0.0] - 2026-03-19
1428
+
1429
+ ### Added
1430
+
1431
+ - Safari Web Extension engine: 5-20ms operations with real cookies and logins
1432
+ - Dual-engine architecture: Extension (preferred) + AppleScript daemon (fallback)
1433
+ - WebSocket bridge connecting Safari Extension to MCP tools
1434
+ - Pure JS React click with full PointerEvent sequence and Fiber fallback
1435
+ - OS-level click for React/Airtable/virtual DOM apps via CGEvent
1436
+ - Tab tracking by URL to prevent hijacking user tabs
1437
+ - Profile separation via `SAFARI_PROFILE` environment variable
1438
+
1439
+ ### Changed
1440
+
1441
+ - Extension always targets the MCP tab, not the active tab
1442
+ - Reverted to AppleScript-first for `newTab` to preserve cookies/logins
1443
+
1444
+ ### Fixed
1445
+
1446
+ - Handle `EADDRINUSE` on WebSocket port 9223 gracefully
1447
+ - Click on `<a>` tags with href navigates directly as fallback
1448
+ - React click with coordinates on synthetic events and parent traversal
1449
+ - Evaluate return values and virtual DOM scroll-to-text
1450
+ - Tab tracking: resolve by URL in single osascript call
1451
+ - Screenshot: switch to target tab before capture, restore after
1452
+ - Critical bugs in type casting, evaluate returns, virtual DOM clicks, and new tab navigation
1453
+ - Removed broken persistent osascript process (136x faster)
1454
+
1455
+ ### Performance
1456
+
1457
+ - Tab caching and `world:MAIN` context for faster execution
1458
+ - `click_and_read` combined operation
1459
+ - TreeWalker text search with cached click helpers
1460
+ - Click payload reduced from 3KB to 200B with retry pattern
1461
+ - Pre-inject helpers on navigate
1462
+ - Cached tab resolve with attribute-aware text search
1463
+ - Combined navigate + newTab into single osascript calls
1464
+
1465
+ ## [1.0.0] - 2026-03-18
1466
+
1467
+ ### Added
1468
+
1469
+ - Initial release with 80 MCP tools for native Safari browser automation
1470
+ - Navigation: `navigate`, `go_back`, `go_forward`, `reload`, `new_tab`, `close_tab`, `switch_tab`, `list_tabs`
1471
+ - Interaction: `click`, `fill`, `select_option`, `press_key`, `type_text`, `hover`, `drag`, `scroll`, `double_click`, `right_click`
1472
+ - Forms: `fill_form`, `fill_and_submit`, `detect_forms`, `clear_field`, `upload_file`
1473
+ - Reading: `read_page`, `snapshot`, `get_source`, `get_element`, `query_all`, `extract_links`, `extract_images`, `extract_tables`, `extract_meta`
1474
+ - Screenshots: `screenshot`, `screenshot_element`, `save_pdf`
1475
+ - JavaScript: `evaluate`, `run_script`, `click_and_read`, `click_and_wait`, `navigate_and_read`
1476
+ - Network: `start_network_capture`, `network`, `network_details`, `clear_network`, `mock_route`, `clear_mocks`, `throttle_network`
1477
+ - Storage: `get_cookies`, `set_cookie`, `delete_cookies`, `local_storage`, `set_local_storage`, `delete_local_storage`, `session_storage`, `set_session_storage`, `delete_session_storage`, `get_indexed_db`, `list_indexed_dbs`, `export_storage`, `import_storage`
1478
+ - Console: `start_console`, `get_console`, `console_filter`, `clear_console`
1479
+ - Accessibility: `accessibility_snapshot`, `analyze_page`, `get_computed_style`
1480
+ - Clipboard: `clipboard_read`, `clipboard_write`, `paste_image`
1481
+ - Emulation: `emulate`, `resize`, `reset_emulation`, `override_geolocation`
1482
+ - Waiting: `wait`, `wait_for`, `wait_for_new_tab`
1483
+ - Other: `handle_dialog`, `performance_metrics`, `css_coverage`, `replace_editor`
1484
+ - Built on AppleScript + JavaScript injection via `osascript`
1485
+ - Tab safety: per-session tracking to never hijack user tabs
1486
+ - macOS-native: zero browser overhead, no Chrome/Chromium dependency
1487
+
1488
+ [2.1.5]: https://github.com/achiya-automation/safari-mcp/compare/v2.1.4...v2.1.5
1489
+ [2.1.4]: https://github.com/achiya-automation/safari-mcp/compare/v2.1.3...v2.1.4
1490
+ [2.1.3]: https://github.com/achiya-automation/safari-mcp/compare/v2.1.2...v2.1.3
1491
+ [2.1.2]: https://github.com/achiya-automation/safari-mcp/compare/v2.1.1...v2.1.2
1492
+ [2.1.1]: https://github.com/achiya-automation/safari-mcp/compare/v2.1.0...v2.1.1
1493
+ [2.1.0]: https://github.com/achiya-automation/safari-mcp/compare/v2.0.1...v2.1.0
1494
+ [2.0.1]: https://github.com/achiya-automation/safari-mcp/compare/v2.0.0...v2.0.1
1495
+ [2.0.0]: https://github.com/achiya-automation/safari-mcp/compare/v1.0.0...v2.0.0
1496
+ [1.0.0]: https://github.com/achiya-automation/safari-mcp/releases/tag/v1.0.0