Skip to content

Commit 421d3c4

Browse files
committed
fix(signals): let inspect-signals peek at a component injector
A peek could only target an environment injector, so an agent asking for the signals of a component that was not the selected one got the routed graph instead. `inspect-signals` now resolves `component` the way `highlight` does and takes a CSS `selector`, and a selector that matches no component host is refused at once. Refs #367
1 parent b8ea912 commit 421d3c4

7 files changed

Lines changed: 268 additions & 35 deletions

File tree

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

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ Entries are sampled instead of exact in these cases:
229229

230230
### Switch the graph from an agent
231231

232-
The `pangular:highlight` tool also switches the graph to the component it highlights. The picker does not show that choice. Calling `pangular:inspect-signals` with `root` or a route path reads that injector's graph once and does not change what the Signals page shows.
232+
The `pangular:highlight` tool also switches the graph to the component it highlights. The picker does not show that choice. Calling `pangular:inspect-signals` with `root`, a route path, a component the page is not showing, or a CSS `selector` for a component host reads that injector's graph once and does not change what the Signals page shows.
233233

234234
### Find a stuck effect in a root service
235235

@@ -244,15 +244,15 @@ The `pangular:highlight` tool also switches the graph to the component it highli
244244

245245
## Agent tools
246246

247-
| Tool or resource | Kind | What it does |
248-
| -------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------- |
249-
| `pangular:scan-signals` | tool | Signal declarations from source, with signal inputs, models and queries. Pages through a large project with `filter` and `offset`. |
250-
| `pangular:inspect-signals` | tool | The graph the page reported, with edges, resources and history. Takes a host tag, class name, instance id, `root` or a route path. |
251-
| `pangular:watch-signal` | tool | Watches a signal and turns write stacks on or off on a page. |
252-
| `pangular:highlight` | tool | Highlights a component and makes it the target of the graph. |
253-
| `pangular:signal-graph` | resource | The live graph per page. |
247+
| Tool or resource | Kind | What it does |
248+
| -------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
249+
| `pangular:scan-signals` | tool | Signal declarations from source, with signal inputs, models and queries. Pages through a large project with `filter` and `offset`. |
250+
| `pangular:inspect-signals` | tool | The graph of a component or injector, with edges, resources and history. Takes a host tag, class name, instance id, `root`, a route path or a CSS `selector`. |
251+
| `pangular:watch-signal` | tool | Watches a signal and turns write stacks on or off on a page. |
252+
| `pangular:highlight` | tool | Highlights a component and makes it the target of the graph. |
253+
| `pangular:signal-graph` | resource | The live graph per page. |
254254

255-
`inspect-signals` returns the graph of the chosen component. Call `highlight` first to switch it to another component. See [Tools](../agents/tools.md).
255+
`inspect-signals` reads the graph of the component or injector you name, without switching the Signals page. Call `highlight` to switch the page itself. See [Tools](../agents/tools.md).
256256

257257
## Limits and gotchas
258258

‎packages/devtools/src/__tests__/agent-tools.test.ts‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -481,6 +481,101 @@ describe('agent tools', () => {
481481
});
482482
});
483483

484+
it('peeks at a component injector by CSS selector or by a component the tree knows', async () => {
485+
const { ctx, push, call } = await boot();
486+
await push('push-component-tree', {
487+
pageId: 'p1',
488+
roots: [
489+
{
490+
id: 'c1',
491+
name: 'App',
492+
tag: 'app-root',
493+
children: [{ id: 'c4', name: 'Promo', tag: 'app-promo', children: [] }],
494+
},
495+
],
496+
count: 2,
497+
detail: null,
498+
});
499+
await push('push-signal-graph', {
500+
pageId: 'p1',
501+
nodes: [{ id: 'a', kind: 'signal', label: 'count', epoch: 0 }],
502+
edges: [],
503+
componentSelector: 'app-root',
504+
component: { id: 'c1', name: 'App', tag: 'app-root', path: 'app-root' },
505+
});
506+
const promo = {
507+
nodes: [{ id: 'p', kind: 'signal', label: 'discount', epoch: 1 }],
508+
edges: [],
509+
componentSelector: 'app-promo',
510+
component: { id: 'c4', name: 'Promo', tag: 'app-promo', path: 'app-root > app-promo' },
511+
source: 'selected',
512+
};
513+
const asked: Record<string, unknown>[] = [];
514+
const broadcast = vi.spyOn(ctx.rpc, 'broadcast');
515+
broadcast.mockImplementation(async (options: { method: string; args: unknown[] }) => {
516+
if (options.method !== 'pangular:peek-signal-graph') return;
517+
const request = options.args[0] as { requestId: string; selector?: string; id?: string };
518+
asked.push(request);
519+
// The page answers the way answerPeek does: a graph only for a component host.
520+
const found = request.selector === '.promo' || request.id === 'c4';
521+
setTimeout(() => {
522+
void push('signal-graph-peek-result', {
523+
requestId: request.requestId,
524+
pageId: 'p1',
525+
graph: found ? { ...promo, pageId: 'p1' } : null,
526+
});
527+
}, 5);
528+
});
529+
530+
expect(signalJson(await call('inspect-signals', '.promo'))).toMatchObject({
531+
pageId: 'p1',
532+
component: { id: 'c4' },
533+
nodes: [{ label: 'discount' }],
534+
});
535+
expect(asked[0]).toEqual({ requestId: expect.any(String), selector: '.promo' });
536+
// A class name the component tree knows is asked for by instance id, on its page.
537+
expect(signalJson(await call('inspect-signals', 'Promo'))).toMatchObject({
538+
component: { name: 'Promo' },
539+
});
540+
expect(asked[1]).toEqual({ requestId: expect.any(String), id: 'c4', pageId: 'p1' });
541+
// The pushed graph still answers without a peek, and the panel keeps its selection.
542+
expect(signalJson(await call('inspect-signals', 'app-root'))).toMatchObject({
543+
component: { id: 'c1' },
544+
});
545+
expect(asked).toHaveLength(2);
546+
const methods = broadcast.mock.calls.map(([options]) => (options as { method: string }).method);
547+
expect(methods).not.toContain('pangular:select-signal-component');
548+
});
549+
550+
it('refuses a selector that matches no component host without waiting out the peek', async () => {
551+
const { ctx, push } = await boot();
552+
await push('push-signal-graph', {
553+
pageId: 'p1',
554+
nodes: [],
555+
edges: [],
556+
componentSelector: 'app-root',
557+
});
558+
vi.spyOn(ctx.rpc, 'broadcast').mockImplementation(
559+
async (options: { method: string; args: unknown[] }) => {
560+
if (options.method !== 'pangular:peek-signal-graph') return;
561+
const { requestId } = options.args[0] as { requestId: string };
562+
void push('signal-graph-peek-result', { requestId, pageId: 'p1', graph: null });
563+
},
564+
);
565+
const started = Date.now();
566+
const invoke = (args: Record<string, unknown>) =>
567+
ctx.agent.invoke('pangular:inspect-signals', args);
568+
await expect(invoke({ selector: '.nope' })).rejects.toThrow(
569+
/No component host matches the CSS selector `\.nope`/,
570+
);
571+
expect(Date.now() - started).toBeLessThan(500);
572+
// One target at a time, and the schema bounds the selector.
573+
await expect(invoke({ selector: '.a', component: 'app-root' })).rejects.toThrow(
574+
/Pass one of `component`/,
575+
);
576+
await expect(invoke({ selector: 'x'.repeat(501) })).rejects.toThrow(/at most 500/);
577+
});
578+
484579
it('ignores a peek answer for another request or a non-matching injector', async () => {
485580
const { ctx, push, call } = await boot();
486581
await push('push-signal-graph', {

‎packages/devtools/src/__tests__/signal-peek.test.ts‎

Lines changed: 91 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest';
33
import { collectSignalGraph, type SignalDebugNg, type SignalTarget } from '../signal-graph.ts';
44
import { createSignalHistory } from '../signal-history.ts';
55
import { PEEK_EVENT, PEEK_RESULT, registerSignalPeek, toPeekRequest } from '../signal-peek.ts';
6-
import { createSignalPeeks } from '../rpc/signal-peeks.ts';
6+
import { elementId } from '../element-id.ts';
7+
import { createSignalPeeks, signalPeekFor } from '../rpc/signal-peeks.ts';
78

89
class Root {}
910
class Page {}
@@ -112,13 +113,68 @@ describe('registerSignalPeek', () => {
112113
]);
113114
});
114115

116+
it('answers with the graph of the component host a selector or instance id names', async () => {
117+
document.body.innerHTML = page;
118+
const session = fakeRpc();
119+
const collect = vi.fn((wanted: SignalTarget) => collectSignalGraph(fakeNg(), wanted));
120+
registerSignalPeek(session.rpc, 'p1', collect);
121+
const rootId = elementId(document.querySelector('app-root')!);
122+
123+
session.handlers.get(PEEK_EVENT)!({ requestId: 'peek4', selector: 'app-root' });
124+
session.handlers.get(PEEK_EVENT)!({ requestId: 'peek5', id: rootId });
125+
await Promise.resolve();
126+
127+
expect(collect.mock.calls).toEqual([[{ selector: 'app-root' }], [{ id: rootId }]]);
128+
const expected = {
129+
pageId: 'p1',
130+
graph: {
131+
pageId: 'p1',
132+
source: 'selected',
133+
component: { id: rootId, name: 'Root', tag: 'app-root' },
134+
nodes: [{ label: 'app-root' }],
135+
},
136+
};
137+
expect(session.calls).toEqual([
138+
[PEEK_RESULT, expect.objectContaining({ requestId: 'peek4' })],
139+
[PEEK_RESULT, expect.objectContaining({ requestId: 'peek5' })],
140+
]);
141+
expect(session.calls[0]![1]).toMatchObject(expected);
142+
expect(session.calls[1]![1]).toMatchObject(expected);
143+
});
144+
145+
it('answers null instead of the routed graph when no component host matches', async () => {
146+
document.body.innerHTML = `${page}<p class="plain"></p>`;
147+
const session = fakeRpc();
148+
registerSignalPeek(session.rpc, 'p1', (wanted) => collectSignalGraph(fakeNg(), wanted));
149+
for (const [requestId, target] of [
150+
['peek6', { selector: 'app-nope' }],
151+
['peek7', { selector: 'p.plain' }],
152+
['peek8', { selector: '[[bad' }],
153+
['peek9', { id: 'e999' }],
154+
] as const) {
155+
session.handlers.get(PEEK_EVENT)!({ requestId, ...target });
156+
}
157+
await Promise.resolve();
158+
expect(session.calls.map(([, answer]) => answer)).toEqual(
159+
['peek6', 'peek7', 'peek8', 'peek9'].map((requestId) => ({
160+
requestId,
161+
pageId: 'p1',
162+
graph: null,
163+
})),
164+
);
165+
});
166+
115167
it('ignores requests for another page and malformed requests', async () => {
116168
document.body.innerHTML = page;
117169
const session = fakeRpc();
118170
registerSignalPeek(session.rpc, 'p1', (wanted) => collectSignalGraph(fakeNg(), wanted));
119171
session.handlers.get(PEEK_EVENT)!({ requestId: 'peek3', env: 'root', pageId: 'p2' });
120172
session.handlers.get(PEEK_EVENT)!({ env: 'root' });
121173
session.handlers.get(PEEK_EVENT)!(null);
174+
// One target only, and a string each.
175+
session.handlers.get(PEEK_EVENT)!({ requestId: 'peek10', env: 'root', selector: 'app-root' });
176+
session.handlers.get(PEEK_EVENT)!({ requestId: 'peek11', selector: 42 });
177+
session.handlers.get(PEEK_EVENT)!({ requestId: 'peek12', selector: 'x'.repeat(501) });
122178
await Promise.resolve();
123179
expect(session.calls).toEqual([]);
124180
expect(toPeekRequest({ requestId: 'r', env: 'root', pageId: 'p1' }, 'p1')).toEqual({
@@ -133,8 +189,14 @@ describe('createSignalPeeks', () => {
133189

134190
it('resolves with the first graph from the asked page and ignores other pages', async () => {
135191
const peeks = createSignalPeeks();
136-
const sent: { requestId: string; env: string; pageId?: string }[] = [];
137-
const answer = peeks.request((message) => sent.push(message), 'root', 'p1', ['p1'], 1000);
192+
const sent: Record<string, unknown>[] = [];
193+
const answer = peeks.request(
194+
(message) => sent.push(message),
195+
{ env: 'root' },
196+
'p1',
197+
['p1'],
198+
1000,
199+
);
138200
const { requestId } = sent[0]!;
139201
expect(sent[0]).toEqual({ requestId, env: 'root', pageId: 'p1' });
140202
peeks.answer({ requestId, pageId: 'p2', graph: { nodes: [], edges: [] } });
@@ -147,7 +209,7 @@ describe('createSignalPeeks', () => {
147209
let requestId = '';
148210
const answer = peeks.request(
149211
(m) => (requestId = m.requestId),
150-
'root',
212+
{ env: 'root' },
151213
undefined,
152214
['p1', 'p2'],
153215
60_000,
@@ -164,7 +226,7 @@ describe('createSignalPeeks', () => {
164226
let settled = false;
165227
const answer = peeks.request(
166228
(m) => (requestId = m.requestId),
167-
'root',
229+
{ env: 'root' },
168230
undefined,
169231
['p1', 'p2'],
170232
60_000,
@@ -181,8 +243,31 @@ describe('createSignalPeeks', () => {
181243
it('resolves null when no page answers in time', async () => {
182244
vi.useFakeTimers();
183245
const peeks = createSignalPeeks();
184-
const answer = peeks.request(() => {}, 'root', undefined, ['p1'], 1500);
246+
const answer = peeks.request(() => {}, { env: 'root' }, undefined, ['p1'], 1500);
185247
await vi.advanceTimersByTimeAsync(1500);
186248
expect(await answer).toBeNull();
187249
});
188250
});
251+
252+
describe('signalPeekFor', () => {
253+
const hits = [
254+
{ pageId: 'p1', node: { id: 'c3', kind: 'directive' as const } },
255+
{ pageId: 'p2', node: { id: 'c7' } },
256+
];
257+
258+
it('asks for a selector as given, an environment injector, or the first component instance', () => {
259+
expect(signalPeekFor({ selector: 'app-card.featured' }, hits)).toEqual({
260+
target: { selector: 'app-card.featured' },
261+
});
262+
expect(signalPeekFor({ component: '/admin' }, hits)).toEqual({ target: { env: '/admin' } });
263+
expect(signalPeekFor({ component: 'Card' }, hits)).toEqual({
264+
target: { id: 'c7' },
265+
pageId: 'p2',
266+
});
267+
});
268+
269+
it('asks nothing when the component tree has no such component', () => {
270+
expect(signalPeekFor({ component: 'Card' }, [])).toBeNull();
271+
expect(signalPeekFor({ component: 'Card' }, [hits[0]!])).toBeNull();
272+
});
273+
});

‎packages/devtools/src/__tests__/tool-metadata.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ describe('agent tool arguments', () => {
256256
for (const args of [{}, { component: ' ' }]) {
257257
const result = await invoke('pangular_inspect-signals', args);
258258
expect(result.isError).toBe(true);
259-
expect(result.content[0]!.text).toMatch(/Pass `component`/);
259+
expect(result.content[0]!.text).toMatch(/Pass one of `component`.*`selector`/);
260260
expect(result.content[0]!.text).not.toMatch(RAW_ERROR);
261261
}
262262
});

‎packages/devtools/src/rpc/signal-peeks.ts‎

Lines changed: 34 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { isEnvironmentRequest } from '../signal-graph.ts';
2+
import type { SignalPeekTarget } from '../signal-peek.ts';
13
import type { SignalGraph } from '../types.ts';
24

35
type PageGraph = SignalGraph & { pageId?: string };
@@ -22,8 +24,8 @@ export function createSignalPeeks() {
2224
* that never reported a graph) do not count toward that early null.
2325
*/
2426
function request(
25-
send: (message: { requestId: string; env: string; pageId?: string }) => void,
26-
env: string,
27+
send: (message: SignalPeekTarget & { requestId: string; pageId?: string }) => void,
28+
target: SignalPeekTarget,
2729
pageId: string | undefined,
2830
pages: readonly string[],
2931
timeoutMs: number,
@@ -39,7 +41,7 @@ export function createSignalPeeks() {
3941
resolve(graph);
4042
};
4143
pending.set(requestId, { pageId, waiting: new Set(pages), done });
42-
send(pageId ? { requestId, env, pageId } : { requestId, env });
44+
send(pageId ? { requestId, ...target, pageId } : { requestId, ...target });
4345
});
4446
}
4547

@@ -60,3 +62,32 @@ export function createSignalPeeks() {
6062

6163
return { request, answer };
6264
}
65+
66+
/** A component tree match, as `findComponents` returns it. */
67+
interface ComponentHit {
68+
pageId: string;
69+
node: { id: string; kind?: string };
70+
}
71+
72+
/**
73+
* What inspect-signals asks the page for when no pushed graph matches: the
74+
* CSS `selector` as given, an environment injector for `root`, a route path
75+
* or an injector id, or the first component instance `hits` found for a tag,
76+
* class name or instance id. `pageId` is the page that instance is on. Null
77+
* when nothing can be asked: the component tree has no such component.
78+
*/
79+
export function signalPeekFor(
80+
args: { component?: string; selector?: string },
81+
hits: readonly ComponentHit[],
82+
): { target: SignalPeekTarget; pageId?: string } | null {
83+
if (args.selector !== undefined) return { target: { selector: args.selector } };
84+
const wanted = args.component ?? '';
85+
if (isEnvironmentRequest(wanted)) return { target: { env: wanted } };
86+
const hit = hits.find((entry) => entry.node.kind !== 'directive');
87+
return hit ? { target: { id: hit.node.id }, pageId: hit.pageId } : null;
88+
}
89+
90+
/** The inspect-signals refusal for a CSS selector that matched no component host. */
91+
export function noSelectorMatchText(selector: string, pageId: string | undefined): string {
92+
return `No component host matches the CSS selector \`${selector}\`${pageId ? ` on page \`${pageId}\`` : ''}, so there is no signal graph to read. The selector must match the host element of a component. Pass a class name or instance id from pangular:list-components as \`component\` instead.`;
93+
}

0 commit comments

Comments
 (0)