From 445aec2be609eb2bb4c434770d842c33271dbcd5 Mon Sep 17 00:00:00 2001 From: erKam Date: Sat, 7 Nov 2026 12:13:10 +0000 Subject: [PATCH 1/2] fix(ui): keep confirms and list saves tied to what they were made for Three places in the panel kept state that no longer matched the screen: - Plugins: a pending confirm survived a change of plugin or page, so Confirm sent plugin A's action to plugin B or another page. The prompt and the last result now reset with the selection, and an action the selected plugin doesn't have is never sent. - SSR & HTTP: each rule or override change sent the whole list as it was before, so two quick changes undid each other, and Add could save twice. Saves now run in order, each on the list the previous one left, and Add is unavailable while its save runs. - Analog: "This request can change data" stayed ticked after a send, so later POST, PUT, PATCH and DELETE calls went out without asking. The tick now covers one request. --- app/src/__tests__/analog-confirm-send.test.ts | 88 +++++++++ app/src/__tests__/network-save-queue.test.ts | 114 +++++++++++ .../__tests__/plugins-confirm-target.test.ts | 182 ++++++++++++++++++ app/src/pages/analog-inspector.ts | 9 +- app/src/pages/network-inspector.ts | 132 ++++++++----- app/src/pages/plugins-inspector.ts | 10 +- apps/docs/src/content/inspectors/analog.md | 2 +- 7 files changed, 489 insertions(+), 48 deletions(-) create mode 100644 app/src/__tests__/analog-confirm-send.test.ts create mode 100644 app/src/__tests__/network-save-queue.test.ts create mode 100644 app/src/__tests__/plugins-confirm-target.test.ts diff --git a/app/src/__tests__/analog-confirm-send.test.ts b/app/src/__tests__/analog-confirm-send.test.ts new file mode 100644 index 00000000..1492cf80 --- /dev/null +++ b/app/src/__tests__/analog-confirm-send.test.ts @@ -0,0 +1,88 @@ +import { TestBed, type ComponentFixture } from '@angular/core/testing'; +import type { DevframeRpcClient } from 'devframe/client'; +import { afterEach, describe, expect, it } from 'vitest'; +import { AnalogInspector } from '../pages/analog-inspector'; + +const project = { analog: true, routes: [], api: [], middleware: [], content: [] }; + +function client() { + const sent: Record[] = []; + const rpc = { + call: (name: string, arg?: Record) => { + if (name === 'analog-project') return Promise.resolve(project); + if (name === 'analog-render') return Promise.resolve({ rows: [], plan: null }); + if (name === 'analog-call-api') { + sent.push(arg ?? {}); + return Promise.resolve({ status: 201, ms: 3, body: '{}' }); + } + return Promise.resolve([]); + }, + callEvent: () => Promise.resolve(), + sharedState: () => Promise.resolve({ value: () => ({}), on: () => () => {} }), + }; + const rpcClient = { connectionMeta: {}, scope: () => ({ rpc }) } as unknown as DevframeRpcClient; + return { rpcClient, sent }; +} + +async function settle(fixture: ComponentFixture) { + for (let i = 0; i < 4; i++) { + await new Promise((resolve) => setTimeout(resolve)); + await fixture.whenStable(); + } +} + +async function render() { + const { rpcClient, sent } = client(); + const fixture = TestBed.createComponent(AnalogInspector); + fixture.componentRef.setInput('rpc', rpcClient); + await settle(fixture); + return { inspector: fixture.componentInstance, sent }; +} + +afterEach(() => { + document.body.innerHTML = ''; +}); + +describe('Analog request playground confirmation', () => { + it('asks again after a confirmed POST is sent', async () => { + const { inspector, sent } = await render(); + inspector.method.set('POST'); + inspector.apiPath.set('/api/v1/products'); + inspector.confirmSend.set(true); + expect(inspector.canSend()).toBe(true); + + await inspector.send(); + expect(sent).toEqual([ + expect.objectContaining({ method: 'POST', path: '/api/v1/products', confirm: true }), + ]); + expect(inspector.confirmSend()).toBe(false); + expect(inspector.needsConfirm()).toBe(true); + + await inspector.send(); + expect(sent).toHaveLength(1); + }); + + it('asks again when the method or the path changes', async () => { + const { inspector } = await render(); + inspector.method.set('POST'); + inspector.apiPath.set('/api/v1/products'); + inspector.confirmSend.set(true); + + inspector.apiPath.set('/api/v1/orders'); + expect(inspector.needsConfirm()).toBe(true); + + inspector.confirmSend.set(true); + inspector.method.set('DELETE'); + expect(inspector.needsConfirm()).toBe(true); + }); + + it('asks again when Try loads another route', async () => { + const { inspector } = await render(); + inspector.method.set('PUT'); + inspector.apiPath.set('/api/v1/products/1'); + inspector.confirmSend.set(true); + + inspector.tryApi({ method: 'PUT', path: '/api/v1/orders/:id', file: 'orders.put.ts' }); + expect(inspector.needsConfirm()).toBe(true); + }); +}); diff --git a/app/src/__tests__/network-save-queue.test.ts b/app/src/__tests__/network-save-queue.test.ts new file mode 100644 index 00000000..34cc5adc --- /dev/null +++ b/app/src/__tests__/network-save-queue.test.ts @@ -0,0 +1,114 @@ +import { TestBed, type ComponentFixture } from '@angular/core/testing'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +interface Pending { + name: string; + list: { id: string; enabled?: boolean }[]; + resolve: () => void; +} + +/** Each save waits until the test answers it, like a slow devtools server. */ +const pending: Pending[] = []; +const sent: string[] = []; +vi.mock('../rpc', () => ({ + rpcCall: (_rpc: unknown, name: string, list: Pending['list']) => { + sent.push(name); + return new Promise((resolve) => pending.push({ name, list, resolve: () => resolve(list) })); + }, +})); + +const { NetworkInspector } = await import('../pages/network-inspector'); + +let fixture: ComponentFixture>; +type HttpRule = ReturnType['rules']>[number]; + +const rule = (id: string, pattern: string): HttpRule => ({ + id, + pattern, + method: '', + target: 'client', + enabled: true, +}); + +const override = (id: string, pattern: string) => ({ + id, + kind: 'client-render' as const, + pattern, + enabled: true, +}); + +/** Lets queued saves start, then answers every save that is waiting, oldest first. */ +async function answerAll() { + for (let i = 0; i < 10; i++) { + await new Promise((resolve) => setTimeout(resolve)); + pending.shift()?.resolve(); + } + await new Promise((resolve) => setTimeout(resolve)); +} + +afterEach(() => { + pending.length = 0; + sent.length = 0; + fixture?.destroy(); + TestBed.resetTestingModule(); +}); + +describe('NetworkInspector rule and override saves', () => { + it('keeps both changes when two rules change before the first save answers', async () => { + fixture = TestBed.createComponent(NetworkInspector); + const inspector = fixture.componentInstance; + inspector.rules.set([rule('a', '/api/a'), rule('b', '/api/b')]); + await fixture.whenStable(); + + inspector.toggleRule('a'); + void inspector.removeRule('b'); + await answerAll(); + + expect(inspector.rules()).toEqual([{ ...rule('a', '/api/a'), enabled: false }]); + }); + + it('adds a rule once when Add is pressed twice during a save', async () => { + fixture = TestBed.createComponent(NetworkInspector); + const inspector = fixture.componentInstance; + await fixture.whenStable(); + inspector.setDraft('pattern', '/api/products'); + inspector.setDraft('status', '500'); + + const first = inspector.addRule(new Event('submit')); + const second = inspector.addRule(new Event('submit')); + await answerAll(); + await Promise.all([first, second]); + + expect(sent).toEqual(['set-http-rules']); + expect(inspector.rules().map((r) => r.pattern)).toEqual(['/api/products']); + }); + + it('keeps both changes when two overrides change before the first save answers', async () => { + fixture = TestBed.createComponent(NetworkInspector); + const inspector = fixture.componentInstance; + inspector.overrides.set([override('a', '/a'), override('b', '/b')]); + await fixture.whenStable(); + + inspector.toggleOverride('a'); + void inspector.removeOverride('b'); + await answerAll(); + + expect(inspector.overrides()).toEqual([{ ...override('a', '/a'), enabled: false }]); + }); + + it('adds an override once when Add is pressed twice during a save', async () => { + fixture = TestBed.createComponent(NetworkInspector); + const inspector = fixture.componentInstance; + await fixture.whenStable(); + inspector.setOverrideDraft('kind', 'client-render'); + inspector.setOverrideDraft('pattern', '/examples/ssr'); + + const first = inspector.addOverride(new Event('submit')); + const second = inspector.addOverride(new Event('submit')); + await answerAll(); + await Promise.all([first, second]); + + expect(sent).toEqual(['set-ssr-overrides']); + expect(inspector.overrides().map((o) => o.pattern)).toEqual(['/examples/ssr']); + }); +}); diff --git a/app/src/__tests__/plugins-confirm-target.test.ts b/app/src/__tests__/plugins-confirm-target.test.ts new file mode 100644 index 00000000..986fc6b7 --- /dev/null +++ b/app/src/__tests__/plugins-confirm-target.test.ts @@ -0,0 +1,182 @@ +import { TestBed, type ComponentFixture } from '@angular/core/testing'; +import type { DevframeRpcClient } from 'devframe/client'; +import { afterEach, describe, expect, it } from 'vitest'; +import { travelView, type TravelSource } from '../../../src/app/devtools/travel-plugin'; +import { PluginsInspector } from '../pages/plugins-inspector'; + +const source = (saved = ['kyoto']): TravelSource => ({ + bookings: () => [ + { + id: 'TRV-1041', + destinationName: 'Kyoto', + startDate: '2026-11-02', + travelers: 2, + total: 3120, + email: 'ada@example.com', + }, + { + id: 'TRV-1042', + destinationName: 'Lisbon', + startDate: '2026-12-10', + travelers: 1, + total: 980, + email: 'grace@example.com', + }, + ], + saved: () => saved, + recentQueries: () => ['beach'], + filters: () => ({ query: '', region: 'Europe', sort: 'price' }), + unsaveAll: () => {}, +}); + +const page = (pageId: string, extra: Record = {}) => ({ + pageId, + url: `http://localhost/${pageId}`, + title: `Travel ${pageId}`, + reportedAt: 5_000, + plugins: [ + { + id: 'travel', + version: '1.0.0', + title: 'Travel store', + description: 'Bookings from the demo TravelStore.', + apiVersion: 1, + status: 'running', + view: travelView(source()), + actions: ['unsave-all'], + ...extra, + }, + ], +}); + +function fakeClient(value: unknown, configs: Record = {}) { + const calls: { name: string; args: unknown[] }[] = []; + const rpc = { + call: (name: string, ...args: unknown[]) => { + calls.push({ name, args }); + return Promise.resolve(name === 'request-plugin-action' ? { ok: true } : []); + }, + callEvent: () => Promise.resolve(), + sharedState: (name: string) => + Promise.resolve({ + value: () => (name === 'plugins' ? value : null), + on: () => () => {}, + }), + }; + const client = { + status: 'connected', + connectionMeta: { configs }, + scope: () => ({ rpc }), + events: { on: () => () => {} }, + } as unknown as DevframeRpcClient; + return { client, calls }; +} + +async function settle(fixture: ComponentFixture) { + for (let i = 0; i < 4; i++) { + await new Promise((resolve) => setTimeout(resolve)); + await fixture.whenStable(); + } +} + +const host = (fixture: ComponentFixture) => fixture.nativeElement as HTMLElement; +const text = (fixture: ComponentFixture) => + (host(fixture).textContent ?? '').replace(/\s+/g, ' '); + +async function mount(value: unknown, configs: Record = {}) { + const fixture = TestBed.createComponent(PluginsInspector); + const fake = fakeClient(value, configs); + fixture.componentRef.setInput('rpc', fake.client); + document.body.append(host(fixture)); + await settle(fixture); + return { fixture, calls: fake.calls }; +} + +function button(fixture: ComponentFixture, name: string): HTMLButtonElement { + const found = [...host(fixture).querySelectorAll('button')].find((b) => + (b.textContent ?? '').replace(/\s+/g, ' ').trim().startsWith(name), + ); + if (!found) throw new Error(`No button ${name}`); + return found; +} + +afterEach(() => { + document.body.innerHTML = ''; +}); + +const queryPage = (pageId: string) => ({ + pageId, + url: `http://localhost/${pageId}`, + title: `Query ${pageId}`, + reportedAt: 4_000, + plugins: [ + { + id: 'query', + version: '5.0.0', + title: 'Query cache', + status: 'running', + view: { + sections: [{ kind: 'text', title: 'Note', text: 'Two queries' }], + actions: [{ name: 'refetch', label: 'Refetch all' }], + }, + actions: ['refetch'], + }, + ], +}); + +const actionCalls = (calls: { name: string; args: unknown[] }[]) => + calls.filter((call) => call.name === 'request-plugin-action').map((call) => call.args[0]); + +describe('the Plugins tab confirm prompt', () => { + it('drops the pending confirm and the old result when another plugin is picked', async () => { + const { fixture, calls } = await mount({ + pages: { p1: page('p1'), p2: queryPage('p2') }, + server: [], + }); + button(fixture, 'Travel store').click(); + await settle(fixture); + fixture.componentInstance.result.set('Done.'); + button(fixture, 'Clear saved destinations').click(); + await settle(fixture); + expect(text(fixture)).toContain('Remove every saved destination from the store?'); + + button(fixture, 'Query cache').click(); + await settle(fixture); + expect(text(fixture)).not.toContain('Remove every saved destination from the store?'); + expect(() => button(fixture, 'Clear saved destinations')).toThrow(); + expect(host(fixture).querySelector('[role="status"].result')?.textContent).toBe(''); + + // Going back does not bring the old prompt back. + button(fixture, 'Travel store').click(); + await settle(fixture); + expect(text(fixture)).not.toContain('Remove every saved destination from the store?'); + expect(actionCalls(calls)).toEqual([]); + }); + + it('drops the pending confirm when another page is picked', async () => { + const { fixture, calls } = await mount({ + pages: { p1: page('p1'), p3: { ...page('p3'), reportedAt: 1 } }, + server: [], + }); + button(fixture, 'Clear saved destinations').click(); + await settle(fixture); + expect(text(fixture)).toContain('Remove every saved destination from the store?'); + + fixture.componentInstance.pageId.set('p3'); + await settle(fixture); + expect(text(fixture)).not.toContain('Remove every saved destination from the store?'); + expect(actionCalls(calls)).toEqual([]); + }); + + it('never sends an action the picked plugin does not have', async () => { + const { fixture, calls } = await mount({ + pages: { p1: page('p1'), p2: queryPage('p2') }, + server: [], + }); + expect(fixture.componentInstance.pluginId()).toBe('query'); + await fixture.componentInstance.run('unsave-all'); + expect(actionCalls(calls)).toEqual([]); + await fixture.componentInstance.run('refetch'); + expect(actionCalls(calls)).toEqual([{ pageId: 'p2', pluginId: 'query', action: 'refetch' }]); + }); +}); diff --git a/app/src/pages/analog-inspector.ts b/app/src/pages/analog-inspector.ts index 3fef1caa..d220026e 100644 --- a/app/src/pages/analog-inspector.ts +++ b/app/src/pages/analog-inspector.ts @@ -6,6 +6,7 @@ import { effect, inject, input, + linkedSignal, signal, untracked, } from '@angular/core'; @@ -2177,7 +2178,11 @@ export class AnalogInspector { readonly method = signal('GET'); readonly apiPath = signal(''); readonly apiBody = signal(''); - readonly confirmSend = signal(false); + /** Confirms one request: cleared when the method or path changes, and after it is sent. */ + readonly confirmSend = linkedSignal({ + source: () => `${this.method()} ${this.apiPath().trim()}`, + computation: () => false, + }); readonly response = signal(null); readonly sending = signal(false); readonly needsConfirm = computed(() => this.method() !== 'GET' && !this.confirmSend()); @@ -2490,6 +2495,7 @@ export class AnalogInspector { tryApi(api: ApiRoute) { this.method.set(api.method === 'ANY' ? 'GET' : api.method); this.apiPath.set(api.path.replace(/:(\w+)/g, '1').replace('**', 'x')); + this.confirmSend.set(false); this.response.set(null); queueMicrotask(() => document.getElementById('api-path')?.focus()); } @@ -2576,6 +2582,7 @@ export class AnalogInspector { this.response.set(result ?? { error: 'No answer from the devtools server.' }); } finally { this.sending.set(false); + this.confirmSend.set(false); } } diff --git a/app/src/pages/network-inspector.ts b/app/src/pages/network-inspector.ts index d7b00b47..0cbb6cc8 100644 --- a/app/src/pages/network-inspector.ts +++ b/app/src/pages/network-inspector.ts @@ -897,6 +897,7 @@ const HTTP_STATUS_OPTIONS: SelectOption[] = [