Skip to content

Commit 05c6f09

Browse files
authored
fix(forms): tag only the WebMCP call's own changes as agent, and stop flagging shared async sources (#464)
User input during a pending WebMCP call is tagged user, and other forms are no longer blamed on the call. Promises, Subjects, operator-free Subject views and NgRx selects are no longer flagged as duplicate async subscriptions; the remaining flag reads "possible duplicate". Refs #368, #369
1 parent a690c53 commit 05c6f09

18 files changed

Lines changed: 365 additions & 36 deletions

‎app/src/pages/pipes-inspector.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -557,7 +557,7 @@ const KIND_OPTIONS: readonly SelectOption<PipeKind>[] = [
557557
<span class="chip">no source</span>
558558
}
559559
@if (a.duplicate) {
560-
<span class="chip warn">duplicate subscription</span>
560+
<span class="chip warn">possible duplicate subscription</span>
561561
}
562562
@if (a.resubscribing) {
563563
<span class="chip warn">resubscribing</span>

‎apps/docs/src/content/inspectors/forms.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ A Signal Form that sets `experimentalWebMcpTool` (with `provideExperimentalWebMc
3838
| Required changed | Fields whose `required` changed after registration. Angular reads `required` once, so agents still see the old one. |
3939
| Recent calls | The last 5 agent calls with time, duration, the input names and the result (submitted, submit failed or threw). |
4040

41-
Agent calls set the value and submit the form. Those changes show in the timeline with the **agent** origin.
41+
Agent calls set the value and submit the form. Those changes show in the timeline with the **agent** origin. While a call's submit is still running, only changes to that form count as the agent's, and typing in any form, that one included, shows as **user**.
4242

4343
If the app provides `provideExperimentalWebMcpForms()` but the browser has no `modelContext`, Angular registers no tool. The block says so instead.
4444

‎apps/docs/src/content/inspectors/pipes.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ description: Custom, built-in and library pipes, where they are used, live insta
1111

1212
The Pipes tab lists your `@Pipe` classes, the built-in pipes from `@angular/common` that your templates use, and pipes from libraries that the page uses. It shows the live instances on the page, and records calls when you ask it to.
1313

14-
<ngmd-image src="/images/panel/pipes.png" alt="The Pipes tab listing the demo's custom pipes and the built-in pipes it uses, with chips for live instances, NgModule, pure and impure, and below them the async subscriptions with duplicate subscription warnings"></ngmd-image>
14+
<ngmd-image src="/images/panel/pipes.png" alt="The Pipes tab listing the demo's custom pipes and the built-in pipes it uses, with chips for live instances, NgModule, pure and impure, and below them the async subscriptions with possible duplicate subscription warnings"></ngmd-image>
1515

1616
## What it shows
1717

@@ -49,7 +49,7 @@ When several tabs report pipes, the panel of a tab shows that tab's pipes and `|
4949

5050
### Async subscriptions
5151

52-
When templates use `| async`, the tab lists each subscription with its component and latest value. This needs no recording. Each `| async` subscribes on its own. Two on the same source run the work twice, so the tab marks those rows **duplicate subscription**.
52+
When templates use `| async`, the tab lists each subscription with its component and latest value. This needs no recording. Each `| async` subscribes on its own. Two on the same cold source run the work twice, for example two HTTP requests, so the tab marks those rows **possible duplicate subscription**. Sources whose subscribers share one execution are not marked: Promises, Subjects (`BehaviorSubject`, `ReplaySubject` and the rest), an `asObservable()` or `toObservable()` view of one, and NgRx store selects. The page can't see `share()` or `shareReplay()` in a pipe, so a source shared that way is still marked, and you can leave it as it is.
5353

5454
The list keeps 200 rows per tab. When a page has more, the section says how many it shows out of the total.
5555

@@ -129,7 +129,7 @@ Each recording starts from zero, so a second recording measures one interaction
129129

130130
### Remove duplicate subscriptions
131131

132-
Open **Async subscriptions** and look for **duplicate subscription** rows. Subscribe once with `@let`, or turn the observable into a signal with `toSignal()`.
132+
Open **Async subscriptions** and look for **possible duplicate subscription** rows. If the source is not already shared with `share()` or `shareReplay()`, subscribe once with `@let`, or turn the observable into a signal with `toSignal()`.
133133

134134
### Stop resubscribing
135135

extension/ui/assets/browser-agent-rpc-KH4HHvHf-BnK7XyKO.js renamed to extension/ui/assets/browser-agent-rpc-KH4HHvHf-B6yzy_ig.js

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎extension/ui/index.html‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/devtools/CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,8 @@ What remains: `/config` exports `DEFAULT_POPUP_HOTKEY`, `PANGULAR_ACTIONS`, `PAN
219219
- At narrow widths the **Components** toolbar fits on two rows, with its tree actions as icons, and a cut off component name shows its full text on hover and focus (#421).
220220
- The **Forms** tab lists WebMCP tools that are not linked to a form under **Other WebMCP tools**, with the same parts as a form's **WebMCP tool** block (#368).
221221
- The **Forms** tab shows the forms setup errors Angular logs on the page, such as `NG01203`, in a notice above the list (#368).
222+
- The **Forms** timeline tags a change as **agent** only when a WebMCP call wrote it, or when it is in the call's own form while the call runs (#368). Typing in any form while a long WebMCP submit is pending is tagged **user**, not **agent**.
223+
- The **Pipes** tab no longer marks two `| async` usages of a Promise, a Subject, an `asObservable()` view of one or an NgRx store select as duplicates, since their subscribers share one execution (#369). Any other source that two `| async` usages subscribe to shows as **possible duplicate subscription**, and `explain-pipe` says **Possible duplicate subscriptions**, because the page can't see `share()` or `shareReplay()` in a pipe.
222224

223225
### Docs
224226

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// @vitest-environment jsdom
2+
import {
3+
AsyncSubject,
4+
BehaviorSubject,
5+
Observable,
6+
ReplaySubject,
7+
Subject,
8+
interval,
9+
of,
10+
timer,
11+
} from 'rxjs';
12+
import { map, shareReplay, switchMap } from 'rxjs/operators';
13+
import { describe, expect, it } from 'vitest';
14+
import { sharedSource } from '../async-source.ts';
15+
import { angularAtLeast } from './angular-version.ts';
16+
17+
describe('sharedSource', () => {
18+
it('treats Promises and every kind of Subject as shared', () => {
19+
expect(sharedSource(Promise.resolve(1))).toBe(true);
20+
expect(sharedSource(new Subject())).toBe(true);
21+
expect(sharedSource(new BehaviorSubject(1))).toBe(true);
22+
expect(sharedSource(new ReplaySubject(1))).toBe(true);
23+
expect(sharedSource(new AsyncSubject())).toBe(true);
24+
});
25+
26+
it('treats an operator-free view of a Subject as shared', () => {
27+
const subject = new ReplaySubject<number>(1);
28+
expect(sharedSource(subject.asObservable())).toBe(true);
29+
expect(sharedSource(subject.asObservable().pipe())).toBe(true);
30+
});
31+
32+
it('treats a cold observable or one with an operator as not known to be shared', () => {
33+
expect(sharedSource(new Observable((s) => s.next(1)))).toBe(false);
34+
expect(sharedSource(of(1))).toBe(false);
35+
expect(sharedSource(interval(1000).pipe(map((n) => n * 2)))).toBe(false);
36+
// Each subscriber of an operator on a Subject starts its own inner work.
37+
expect(sharedSource(new Subject<void>().pipe(switchMap(() => timer(10))))).toBe(false);
38+
// `shareReplay` keeps its state in a closure, so it stays a possible duplicate.
39+
expect(sharedSource(of(1).pipe(shareReplay(1)))).toBe(false);
40+
});
41+
42+
it('ignores values that are not async sources and survives throwing getters', () => {
43+
expect(sharedSource(undefined)).toBe(false);
44+
expect(sharedSource(null)).toBe(false);
45+
expect(sharedSource('text')).toBe(false);
46+
const hostile = {
47+
get then(): unknown {
48+
throw new Error('boom');
49+
},
50+
get source(): unknown {
51+
throw new Error('boom');
52+
},
53+
};
54+
expect(sharedSource(hostile)).toBe(false);
55+
const loop: Record<string, unknown> = { operator: undefined };
56+
loop['source'] = loop;
57+
expect(sharedSource(loop)).toBe(false);
58+
});
59+
60+
it.runIf(angularAtLeast('19.0'))('treats an NgRx store select as shared', async () => {
61+
await import('@angular/compiler');
62+
const { TestBed } = await import('@angular/core/testing');
63+
const { initAngularTestBed } = await import('./angular-version.ts');
64+
const { Store, createReducer, provideStore } = await import('@ngrx/store');
65+
initAngularTestBed();
66+
TestBed.resetTestingModule();
67+
TestBed.configureTestingModule({
68+
providers: [provideStore({ count: createReducer(1) })],
69+
});
70+
const store = TestBed.inject(Store) as InstanceType<typeof Store<{ count: number }>>;
71+
expect(sharedSource(store)).toBe(true);
72+
expect(sharedSource(store.select((state) => state.count))).toBe(true);
73+
TestBed.resetTestingModule();
74+
});
75+
});

‎packages/devtools/src/__tests__/forms-collector.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,29 @@ Component({
6161
template: `<form [formRoot]="form"><input id="sname" [formField]="form.name" /><button>Go</button></form>`,
6262
})(SignUp);
6363

64+
let releaseSlowSubmit: () => void = () => {};
65+
class SlowSignUp {
66+
form = form(signal({ name: '' }), (p) => required(p.name), {
67+
submission: {
68+
action: () =>
69+
new Promise<undefined>((resolve) => (releaseSlowSubmit = () => resolve(undefined))),
70+
},
71+
experimentalWebMcpTool: { name: 'slow_sign_up', description: 'Create an account slowly' },
72+
});
73+
}
74+
Component({
75+
selector: 'slow-sign-up-form',
76+
imports: [FormField, FormRoot],
77+
template: `<form [formRoot]="form"><input id="slowname" [formField]="form.name" /><button>Go</button></form>`,
78+
})(SlowSignUp);
79+
80+
class SlowPage {}
81+
Component({
82+
selector: 'slow-page',
83+
imports: [Login, Profile, SlowSignUp],
84+
template: `<login-form /><profile-form /><slow-sign-up-form />`,
85+
})(SlowPage);
86+
6487
class Tasks {
6588
model = signal({ name: '', items: [{ n: -1 }] });
6689
form = form(this.model, (p) => required(p.name), {
@@ -471,6 +494,58 @@ describe('forms collector', () => {
471494
});
472495
});
473496

497+
describe('forms collector WebMCP attribution', () => {
498+
it('tags user typing as user while a WebMCP call is still pending, in any form', async () => {
499+
const tools = new Map<string, { execute: (args: unknown) => Promise<unknown> }>();
500+
(navigator as any).modelContext = {
501+
registerTool: async (tool: {
502+
name: string;
503+
execute: (args: unknown) => Promise<unknown>;
504+
}) => {
505+
tools.set(tool.name, tool);
506+
},
507+
};
508+
try {
509+
TestBed.configureTestingModule({ providers: [provideExperimentalWebMcpForms()] });
510+
const h = harness();
511+
const fixture = await mount(SlowPage);
512+
await tick();
513+
h.collector.push();
514+
await tick();
515+
const pending = tools.get('slow_sign_up')!.execute({ name: 'Ada' });
516+
fixture.detectChanges();
517+
await tick(LEASED_PUSH_MS + 100);
518+
const type = (id: string, text: string) => {
519+
const input = document.getElementById(id) as HTMLInputElement;
520+
input.value = text;
521+
input.dispatchEvent(new Event('input', { bubbles: true }));
522+
};
523+
// The call is still pending: typing in other forms, then in its own form.
524+
type('email', '[email protected]');
525+
type('pname', 'Lin');
526+
fixture.detectChanges();
527+
await tick(LEASED_PUSH_MS + 100);
528+
type('slowname', 'Grace');
529+
fixture.detectChanges();
530+
await tick(LEASED_PUSH_MS + 100);
531+
const events = h.lastEvents();
532+
const login = events.filter((e) => e.type === 'value' && e.path === 'email');
533+
expect(login.length).toBeGreaterThan(0);
534+
expect(login.every((e) => e.origin === 'user')).toBe(true);
535+
expect(
536+
events.find((e) => e.formId.startsWith('Profile') && e.type === 'value'),
537+
).toMatchObject({ origin: 'user', detail: '"Lin"' });
538+
const own = events.filter((e) => e.type === 'value' && e.path === 'name');
539+
expect(own.find((e) => e.detail === '"Ada"')).toMatchObject({ origin: 'agent' });
540+
expect(own.find((e) => e.detail === '"Grace"')).toMatchObject({ origin: 'user' });
541+
releaseSlowSubmit();
542+
await pending;
543+
} finally {
544+
delete (navigator as any).modelContext;
545+
}
546+
});
547+
});
548+
474549
describe('forms collector without a server', () => {
475550
it('keeps a paced push that fails out of the unhandled rejections', async () => {
476551
const fixture = await mount(Login);

‎packages/devtools/src/__tests__/forms-webmcp.test.ts‎

Lines changed: 45 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -237,15 +237,58 @@ describe('watchWebMcp', () => {
237237
await tick();
238238
expect(activeInside).toBe(true);
239239
expect(watcher.active()).toBe(false);
240-
expect(watcher.takeActivity()).toBe(true);
241-
expect(watcher.takeActivity()).toBe(false);
240+
const touched = watcher.takeActivity();
241+
expect(touched(second)).toBe('wrote');
242+
expect(touched(first)).toBeUndefined();
243+
expect(watcher.takeActivity()(second)).toBeUndefined();
242244
const tool = watcher.describe(forms).forms.get(second);
243245
expect(tool?.calls).toEqual([
244246
expect.objectContaining({ outcome: 'failed', fields: ['name'], detail: 'name: is required' }),
245247
]);
246248
expect(onChange).toHaveBeenCalled();
247249
});
248250

251+
it('blames only the linked form while a call runs, and every form for a write it cannot place', async () => {
252+
const { tools } = fakeContext();
253+
const watcher = watch();
254+
const target = fieldNode({ name: '' });
255+
const other = fieldNode({ name: '' });
256+
let finish!: () => void;
257+
let linkIt = true;
258+
await (navigator as any).modelContext.registerTool({
259+
name: 'slow',
260+
description: 'Slow submit',
261+
inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: [] },
262+
execute: () => {
263+
if (linkIt) watcher.link(target);
264+
return new Promise<unknown>((resolve) => (finish = () => resolve({ content: [] })));
265+
},
266+
});
267+
void tools.get('slow')!.execute({ name: 'x' });
268+
expect(watcher.takeActivity()(target)).toBe('wrote');
269+
// Still running: only its own form is the agent's.
270+
let touched = watcher.takeActivity();
271+
expect(touched(target)).toBe('running');
272+
expect(touched(other)).toBeUndefined();
273+
finish();
274+
await tick();
275+
// The push after it settles still blames the target, then nothing.
276+
expect(watcher.takeActivity()(target)).toBe('running');
277+
expect(watcher.takeActivity()(target)).toBeUndefined();
278+
279+
linkIt = false;
280+
await (navigator as any).modelContext.registerTool({
281+
name: 'unplaced',
282+
description: 'No form',
283+
inputSchema: { type: 'string' },
284+
execute: async () => ({ content: [] }),
285+
});
286+
void tools.get('unplaced')!.execute('x');
287+
touched = watcher.takeActivity();
288+
expect(touched(other)).toBe('maybe');
289+
expect(touched(undefined)).toBe('maybe');
290+
});
291+
249292
it('masks tokens in the description, error and call detail of a tool no form owns', async () => {
250293
const jwt = ['eyJhbGciOiJIUzI1NiJ9', 'eyJzdWIiOiIxMjM0NSJ9', 'c2lnbmF0dXJlc2ln'].join('.');
251294
const { tools } = fakeContext((tool) =>

0 commit comments

Comments
 (0)