Skip to content

Commit 4f12600

Browse files
khushalsagarChromium LUCI CQ
authored andcommitted
WebMCP: Add modelContext.waitForToolsUntil()
Pages often register tools after asynchronous work, and consumers of the tools have no signal for when registration is complete. waitForToolsUntil(promise) lets a document say that its tools are not ready until the promise settles. The browser exposes each frame's state via RenderFrameHost::GetScriptToolsReadyState(), and notifies changes via WebContentsObserver::ScriptToolsReadyStateChanged(). Which part of the document lifecycle a page has to pass its promises by is still being discussed on the spec (webmachinelearning/webmcp#328). This CL uses DOMContentLoaded as the milestone to read this state, which means promises have to be registered before the Document finishes parsing. Behind the WebMCPWaitForToolsUntil feature (experimental), which implies WebMCP. Bug: 555173199 Test: content_browsertests --gtest_filter=ModelContextUserData* Test: blink_unittests --gtest_filter=ModelContextWaitForToolsUntil* Test: WPT webmcp/imperative/*wait-for-tools-until* Test: WPT webmcp/imperative/detached-frame-waitForToolsUntil.https.html Change-Id: I9ea58b2f78b4315856764013ec56190f5b7ac712 Reviewed-on: https://chromium-review.googlesource.com/c/chromium/src/+/8594281 Reviewed-by: Dominic Farolino <[email protected]> Reviewed-by: Dave Tapuska <[email protected]> Auto-Submit: Khushal Sagar <[email protected]> Commit-Queue: Khushal Sagar <[email protected]> Reviewed-by: Mark Foltz <[email protected]> Cr-Commit-Position: refs/heads/main@{#1736883}
1 parent 401be86 commit 4f12600

24 files changed

Lines changed: 772 additions & 2 deletions

‎android_webview/test/data/web_tests/webexposed/global-interface-listing-expected.txt‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6515,6 +6515,7 @@ interface ModelContext : EventTarget
65156515
method getTools
65166516
method registerTool
65176517
method resumeTool
6518+
method waitForToolsUntil
65186519
setter ontoolactivated
65196520
setter ontoolcancel
65206521
setter ontoolchange

‎content/browser/renderer_host/model_context_user_data.cc‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,14 +6,18 @@
66

77
#include <algorithm>
88

9+
#include "base/feature_list.h"
910
#include "content/browser/bad_message.h"
1011
#include "content/browser/renderer_host/frame_tree_node.h"
1112
#include "content/browser/renderer_host/page_impl.h"
13+
#include "content/browser/renderer_host/render_frame_host_delegate.h"
1214
#include "content/browser/renderer_host/render_frame_host_impl.h"
1315
#include "content/browser/renderer_host/render_frame_host_manager.h"
1416
#include "content/browser/site_instance_impl.h"
1517
#include "content/public/browser/browser_thread.h"
18+
#include "mojo/public/cpp/bindings/message.h"
1619
#include "third_party/blink/public/common/features.h"
20+
#include "third_party/blink/public/common/features_generated.h"
1721
#include "third_party/blink/public/common/script_tools/script_tool_utils.h"
1822
#include "url/origin.h"
1923

@@ -439,6 +443,21 @@ void ModelContextUserData::CancelRemoteScriptTool(
439443
}
440444
}
441445

446+
void ModelContextUserData::SetScriptToolsReady(bool ready) {
447+
if (!IsWebMCPEnabled(render_frame_host()) ||
448+
!base::FeatureList::IsEnabled(
449+
blink::features::kWebMCPWaitForToolsUntil)) {
450+
mojo::ReportBadMessage("WebMCPWaitForToolsUntil is not enabled.");
451+
return;
452+
}
453+
auto& rfh = static_cast<RenderFrameHostImpl&>(render_frame_host());
454+
const auto previous_state = rfh.GetScriptToolsReadyState();
455+
script_tools_waiting_ = !ready;
456+
if (previous_state != rfh.GetScriptToolsReadyState()) {
457+
rfh.delegate()->ScriptToolsReadyStateChanged(&rfh);
458+
}
459+
}
460+
442461
void ModelContextUserData::NotifyToolChange(
443462
const std::vector<url::Origin>& exposed_origins) {
444463
RenderFrameHost& rfh = render_frame_host();

‎content/browser/renderer_host/model_context_user_data.h‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,11 +144,14 @@ class CONTENT_EXPORT ModelContextUserData
144144
ExecuteRemoteScriptToolCallback callback) override;
145145
void CancelRemoteScriptTool(
146146
const blink::ToolInvocationToken& invocation_id) override;
147+
void SetScriptToolsReady(bool ready) override;
147148

148149
std::vector<blink::mojom::ScriptToolPtr>& script_tools() {
149150
return script_tools_;
150151
}
151152

153+
bool script_tools_waiting() const { return script_tools_waiting_; }
154+
152155
private:
153156
friend class DocumentUserData<ModelContextUserData>;
154157
friend class ModelContextPageUserData;
@@ -165,6 +168,10 @@ class CONTENT_EXPORT ModelContextUserData
165168

166169
std::vector<blink::mojom::ScriptToolPtr> script_tools_;
167170

171+
// Whether the document is waiting for script tools to be ready
172+
// via unsettled Promises passed to modelContext.waitForToolsUntil().
173+
bool script_tools_waiting_ = false;
174+
168175
base::WeakPtrFactory<ModelContextUserData> weak_factory_{this};
169176
};
170177

Lines changed: 235 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,235 @@
1+
// Copyright 2026 The Chromium Authors
2+
// Use of this source code is governed by a BSD-style license that can be
3+
// found in the LICENSE file.
4+
5+
#include "content/browser/renderer_host/model_context_user_data.h"
6+
7+
#include <utility>
8+
#include <vector>
9+
10+
#include "base/test/run_until.h"
11+
#include "base/test/scoped_feature_list.h"
12+
#include "content/browser/renderer_host/render_frame_host_impl.h"
13+
#include "content/browser/web_contents/web_contents_impl.h"
14+
#include "content/public/browser/render_frame_host.h"
15+
#include "content/public/browser/render_process_host.h"
16+
#include "content/public/browser/web_contents.h"
17+
#include "content/public/browser/web_contents_observer.h"
18+
#include "content/public/test/browser_test.h"
19+
#include "content/public/test/browser_test_utils.h"
20+
#include "content/public/test/content_browser_test.h"
21+
#include "content/public/test/content_browser_test_utils.h"
22+
#include "content/public/test/no_renderer_crashes_assertion.h"
23+
#include "content/shell/browser/shell.h"
24+
#include "content/test/content_browser_test_utils_internal.h"
25+
#include "mojo/public/cpp/bindings/lib/validation_context.h"
26+
#include "mojo/public/cpp/test_support/fake_message_dispatch_context.h"
27+
#include "mojo/public/cpp/test_support/test_utils.h"
28+
#include "net/dns/mock_host_resolver.h"
29+
#include "net/test/embedded_test_server/embedded_test_server.h"
30+
#include "testing/gmock/include/gmock/gmock.h"
31+
#include "testing/gtest/include/gtest/gtest.h"
32+
#include "third_party/blink/public/common/features_generated.h"
33+
34+
namespace content {
35+
36+
namespace {
37+
38+
using ReadyState = RenderFrameHost::ScriptToolsReadyState;
39+
using Notification = std::pair<RenderFrameHost*, ReadyState>;
40+
41+
// Records each `ScriptToolsReadyStateChanged()` call, with the frame's state
42+
// at the time.
43+
class ScriptToolsReadyObserver : public WebContentsObserver {
44+
public:
45+
explicit ScriptToolsReadyObserver(WebContents* web_contents)
46+
: WebContentsObserver(web_contents) {}
47+
48+
void ScriptToolsReadyStateChanged(RenderFrameHost* rfh) override {
49+
notifications_.emplace_back(rfh, rfh->GetScriptToolsReadyState());
50+
}
51+
52+
const std::vector<Notification>& notifications() const {
53+
return notifications_;
54+
}
55+
56+
void ClearNotifications() { notifications_.clear(); }
57+
58+
private:
59+
std::vector<Notification> notifications_;
60+
};
61+
62+
} // namespace
63+
64+
class ModelContextUserDataBrowserTest : public ContentBrowserTest {
65+
public:
66+
ModelContextUserDataBrowserTest() {
67+
scoped_feature_list_.InitWithFeatures(
68+
{blink::features::kWebMCP, blink::features::kWebMCPWaitForToolsUntil},
69+
{});
70+
}
71+
72+
void SetUpOnMainThread() override {
73+
ContentBrowserTest::SetUpOnMainThread();
74+
host_resolver()->AddRule("*", "127.0.0.1");
75+
// Note: 127.0.0.1 is a secure context, as `document.modelContext` requires.
76+
ASSERT_TRUE(embedded_test_server()->Start());
77+
ASSERT_TRUE(
78+
NavigateToURL(shell(), embedded_test_server()->GetURL("/title1.html")));
79+
}
80+
81+
WebContents* web_contents() { return shell()->web_contents(); }
82+
83+
RenderFrameHost* main_rfh() { return web_contents()->GetPrimaryMainFrame(); }
84+
85+
// Puts the main document in the tools waiting state.
86+
[[nodiscard]] bool MarkScriptToolsWaiting() {
87+
return ExecJs(web_contents(), R"(
88+
window.toolsReady = new Promise(resolve => {
89+
window.resolveToolsReady = resolve;
90+
});
91+
document.modelContext.waitForToolsUntil(window.toolsReady);
92+
)") && WaitForScriptToolsReadyState(ReadyState::kWaiting);
93+
}
94+
95+
// Returns once the main frame has reached `state`.
96+
[[nodiscard]] bool WaitForScriptToolsReadyState(ReadyState state) {
97+
return base::test::RunUntil(
98+
[&]() { return main_rfh()->GetScriptToolsReadyState() == state; });
99+
}
100+
101+
private:
102+
base::test::ScopedFeatureList scoped_feature_list_;
103+
};
104+
105+
// Ensures that a frame reports the expected ready states across document load
106+
// and `waitForToolsUntil()` promises.
107+
IN_PROC_BROWSER_TEST_F(ModelContextUserDataBrowserTest, ReadyStateTransitions) {
108+
EXPECT_FALSE(ModelContextUserData::GetForCurrentDocument(main_rfh()));
109+
EXPECT_EQ(main_rfh()->GetScriptToolsReadyState(), ReadyState::kReady);
110+
111+
ScriptToolsReadyObserver observer(web_contents());
112+
ASSERT_TRUE(MarkScriptToolsWaiting());
113+
ASSERT_TRUE(ExecJs(web_contents(), "window.resolveToolsReady()"));
114+
ASSERT_TRUE(WaitForScriptToolsReadyState(ReadyState::kReady));
115+
EXPECT_THAT(
116+
observer.notifications(),
117+
testing::ElementsAre(Notification(main_rfh(), ReadyState::kWaiting),
118+
Notification(main_rfh(), ReadyState::kReady)));
119+
120+
// Navigating the frame transitions through `kLoading` to `kReady` at
121+
// DOMContentLoaded.
122+
observer.ClearNotifications();
123+
ASSERT_TRUE(
124+
NavigateToURL(shell(), embedded_test_server()->GetURL("/title2.html")));
125+
EXPECT_THAT(
126+
observer.notifications(),
127+
testing::ElementsAre(Notification(main_rfh(), ReadyState::kLoading),
128+
Notification(main_rfh(), ReadyState::kReady)));
129+
}
130+
131+
// Ensures that a document replacement (`javascript:` URL) and `document.open()`
132+
// update the ready state when promises are pending or settled.
133+
// Note: `RenderFrameHost::IsDOMContentLoaded()` is not reset in the browser on
134+
// `javascript:` document replacement or `document.open()`, so the state does
135+
// not transition back through `kLoading` in those cases.
136+
// TODO(crbug.com/555173199): Fix this once the spec resolves on the document
137+
// lifecycle to wait for.
138+
IN_PROC_BROWSER_TEST_F(ModelContextUserDataBrowserTest,
139+
ReplacementDocumentAndDocumentOpen) {
140+
ASSERT_TRUE(MarkScriptToolsWaiting());
141+
ScriptToolsReadyObserver observer(web_contents());
142+
143+
ASSERT_TRUE(
144+
ExecJs(web_contents(),
145+
"location.href = 'javascript:\"<title>replaced</title>\"'"));
146+
ASSERT_TRUE(WaitForScriptToolsReadyState(ReadyState::kReady));
147+
EXPECT_EQ("replaced", EvalJs(web_contents(), "document.title"));
148+
EXPECT_THAT(observer.notifications(), testing::ElementsAre(Notification(
149+
main_rfh(), ReadyState::kReady)));
150+
151+
observer.ClearNotifications();
152+
ASSERT_TRUE(ExecJs(web_contents(), R"(
153+
document.open();
154+
window.toolsReady = new Promise(resolve => {
155+
window.resolveToolsReady = resolve;
156+
});
157+
document.modelContext.waitForToolsUntil(window.toolsReady);
158+
)"));
159+
ASSERT_TRUE(WaitForScriptToolsReadyState(ReadyState::kWaiting));
160+
ASSERT_TRUE(ExecJs(web_contents(), "window.resolveToolsReady()"));
161+
ASSERT_TRUE(WaitForScriptToolsReadyState(ReadyState::kReady));
162+
EXPECT_THAT(
163+
observer.notifications(),
164+
testing::ElementsAre(Notification(main_rfh(), ReadyState::kWaiting),
165+
Notification(main_rfh(), ReadyState::kReady)));
166+
}
167+
168+
// Ensures that a promise created in another document counts as settled once
169+
// that document is destroyed.
170+
IN_PROC_BROWSER_TEST_F(ModelContextUserDataBrowserTest,
171+
PromiseFromRemovedDocumentCountsAsSettled) {
172+
RenderFrameHost* child =
173+
CreateSubframe(static_cast<WebContentsImpl*>(web_contents()), "child",
174+
embedded_test_server()->GetURL("/title1.html"),
175+
/*wait_for_navigation=*/true);
176+
ASSERT_TRUE(child);
177+
178+
// Test a cross-document promise that resolves normally (`a`), one that
179+
// resolves after the child frame is removed (`b`), and one that never
180+
// settles on its own.
181+
ASSERT_TRUE(ExecJs(child, R"(
182+
window.a = Promise.withResolvers();
183+
window.b = Promise.withResolvers();
184+
parent.document.modelContext.waitForToolsUntil(window.a.promise);
185+
parent.document.modelContext.waitForToolsUntil(window.b.promise);
186+
parent.document.modelContext.waitForToolsUntil(new Promise(() => {}));
187+
window.a.resolve();
188+
)"));
189+
ASSERT_TRUE(WaitForScriptToolsReadyState(ReadyState::kWaiting));
190+
191+
ASSERT_TRUE(ExecJs(web_contents(), R"(
192+
const iframe = document.getElementById('child');
193+
const resolveB = iframe.contentWindow.b.resolve;
194+
iframe.remove();
195+
resolveB();
196+
)"));
197+
ASSERT_TRUE(WaitForScriptToolsReadyState(ReadyState::kReady));
198+
}
199+
200+
// Ensures that a crashed renderer reports the correct state.
201+
IN_PROC_BROWSER_TEST_F(ModelContextUserDataBrowserTest, CrashedRenderer) {
202+
ASSERT_TRUE(MarkScriptToolsWaiting());
203+
204+
ScopedAllowRendererCrashes allow_renderer_crashes(web_contents());
205+
RenderProcessHost* process = main_rfh()->GetProcess();
206+
RenderProcessHostWatcher crash_observer(
207+
process, RenderProcessHostWatcher::WATCH_FOR_PROCESS_EXIT);
208+
process->Shutdown(0);
209+
crash_observer.Wait();
210+
211+
EXPECT_TRUE(ModelContextUserData::GetForCurrentDocument(main_rfh()));
212+
EXPECT_EQ(main_rfh()->GetScriptToolsReadyState(), ReadyState::kNoRenderer);
213+
}
214+
215+
// Ensures that a frame where WebMCP is not enabled reports a bad message if it
216+
// updates its script tools ready state.
217+
IN_PROC_BROWSER_TEST_F(ModelContextUserDataBrowserTest,
218+
FrameWithoutToolsPolicyIsKilled) {
219+
// No `allow` attribute, so the `tools` permissions policy is disabled in
220+
// this cross-origin iframe.
221+
RenderFrameHost* child =
222+
CreateSubframe(static_cast<WebContentsImpl*>(web_contents()), "child",
223+
embedded_test_server()->GetURL("b.test", "/title1.html"),
224+
/*wait_for_navigation=*/true);
225+
ASSERT_TRUE(child);
226+
227+
mojo::FakeMessageDispatchContext fake_dispatch_context;
228+
mojo::test::BadMessageObserver bad_message_observer;
229+
ModelContextUserData::GetOrCreateForCurrentDocument(child)
230+
->SetScriptToolsReady(false);
231+
EXPECT_EQ(bad_message_observer.WaitForBadMessage(),
232+
"WebMCPWaitForToolsUntil is not enabled.");
233+
}
234+
235+
} // namespace content

‎content/browser/renderer_host/render_frame_host_delegate.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -269,6 +269,10 @@ class CONTENT_EXPORT RenderFrameHostDelegate {
269269
// The DOMContentLoaded handler in the frame has completed.
270270
virtual void DOMContentLoaded(RenderFrameHostImpl* render_frame_host) {}
271271

272+
// The script tool ready status for this frame has changed.
273+
virtual void ScriptToolsReadyStateChanged(
274+
RenderFrameHostImpl* render_frame_host) {}
275+
272276
// The onload handler in the frame has completed. Only called for the main
273277
// frames.
274278
virtual void DocumentOnLoadCompleted(RenderFrameHostImpl* render_frame_host) {

0 commit comments

Comments
 (0)