diff --git a/packages/client-core/__tests__/observe-requests.test.ts b/packages/client-core/__tests__/observe-requests.test.ts index 9aa17a0bd..a4180cbef 100644 --- a/packages/client-core/__tests__/observe-requests.test.ts +++ b/packages/client-core/__tests__/observe-requests.test.ts @@ -150,6 +150,55 @@ describe('watching what the transport did', () => { expect(refreshed.filter((event) => !(event as { joined: boolean }).joined)).toHaveLength(1); }); + /** + * The refresh has a duration and nothing reported it. Without a closing + * event the waterfall can say a request hit the credential refresh but not + * how long it sat there, which is the only number that makes an auth stall + * distinguishable from a slow server. + */ + it('closes the refresh so its duration is measurable', async () => { + const seen = recorder(); + let token = 't0'; + const client = fakeClient((config) => { + if (config.headers?.['Authorization'] === 'Bearer t0') throw new HttpFailure(401); + + return { ok: true }; + }); + const auth: AuthProvider = { + credentials: () => ({ Authorization: `Bearer ${token}` }), + refresh: () => { + token = 't1'; + + return Promise.resolve(); + }, + }; + const rest = new RestTransport({ client, auth, sleep: () => Promise.resolve(), observer: seen.observe }); + + await rest.execute({ meta: list, args: {} }); + + const kinds = seen.events.map((event) => event.type); + + expect(kinds).toContain('refresh'); + expect(kinds).toContain('refreshed'); + expect(kinds.indexOf('refreshed')).toBeGreaterThan(kinds.indexOf('refresh')); + }); + + it('closes the refresh even when it fails', async () => { + const seen = recorder(); + const client = fakeClient(() => { + throw new HttpFailure(401); + }); + const auth: AuthProvider = { + credentials: () => ({ Authorization: 'Bearer t0' }), + refresh: () => Promise.reject(new Error('refresh is down')), + }; + const rest = new RestTransport({ client, auth, sleep: () => Promise.resolve(), observer: seen.observe }); + + await expect(rest.execute({ meta: list, args: {} })).rejects.toThrow(); + + expect(seen.events.map((event) => event.type)).toContain('refreshed'); + }); + it('costs an unwatched transport nothing but an undefined field', async () => { const client = fakeClient(() => ({ ok: true })); const rest = new RestTransport({ client }); diff --git a/packages/client-core/src/transport.ts b/packages/client-core/src/transport.ts index ae5de63bd..70c7df8dc 100644 --- a/packages/client-core/src/transport.ts +++ b/packages/client-core/src/transport.ts @@ -273,6 +273,14 @@ export type RequestEvent = | { readonly type: 'attempt'; readonly attempt: number } /** A 401 sent this request to the credential refresh. */ | { readonly type: 'refresh'; readonly joined: boolean } + /** + * The refresh this request was waiting on has finished, either way. + * + * Paired with `refresh` so the wait has a duration. Without it a watcher can + * say a request hit the credential refresh but not how long it sat there, + * which is the only number that tells an auth stall apart from a slow server. + */ + | { readonly type: 'refreshed'; readonly ok: boolean } | { readonly type: 'retry'; readonly attempt: number; @@ -484,7 +492,10 @@ export class RestTransport implements Transport { if (generation === this.generation) { try { await this.refresh(watch); + watch?.({ type: 'refreshed', ok: true }); } catch { + watch?.({ type: 'refreshed', ok: false }); + // The refresh failed, so the 401 stands. Reporting the refresh's own // error here would replace "you are not authorized" with whatever // the token endpoint said, which is not what the caller asked for. diff --git a/packages/client-devtools/__tests__/panel.test.ts b/packages/client-devtools/__tests__/panel.test.ts index 2bd37b86e..ee9209cbd 100644 --- a/packages/client-devtools/__tests__/panel.test.ts +++ b/packages/client-devtools/__tests__/panel.test.ts @@ -77,6 +77,8 @@ describe('the inspector', () => { const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); await h.settle(); + goTo('queries'); + // Not "rendered but empty": there is no detail element at all, which is // what gives the list the full width it needs for a query key. expect(shadow().querySelector('.detail')).toBeNull(); @@ -100,6 +102,8 @@ describe('the inspector', () => { const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); await h.settle(); + goTo('queries'); + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( new Event('click', { bubbles: true }), ); @@ -704,6 +708,8 @@ describe('the detail pane', () => { const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); await h.settle(); + goTo('queries'); + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( new Event('click', { bubbles: true }), ); @@ -727,6 +733,8 @@ describe('the detail pane', () => { const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); await h.settle(); + goTo('queries'); + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( new Event('click', { bubbles: true }), ); @@ -881,6 +889,8 @@ describe('sort and selection are per tab', () => { const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); await h.settle(); + goTo('queries'); + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( new Event('click', { bubbles: true }), ); @@ -1406,3 +1416,957 @@ describe('the filter operators', () => { devtools.dispose(); }); }); + +describe('the launcher, fully dressed', () => { + it('goes amber while an optimistic write is pending', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body }); + + h.cache.overlays.add( + new Map([['Order:1', { kind: 'merge', source: { total: 99 } } as const]]), + undefined, + ['Order[]'], + ); + devtools.actions.invalidateTag('Order[]'); + await Promise.resolve(); + + expect(shadow().querySelector('button')?.getAttribute('data-pulse')).toBe('pending'); + + unmount(); + devtools.dispose(); + }); + + /** + * A stuck optimistic write is a bug you want to see; a request in flight is + * Tuesday. So pending outranks fetching, and a real error outranks both. + */ + it('lets an error outrank a pending write', async () => { + const h = harness(); + + h.fail('GET /orders', new Error('nope')); + + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body }); + + h.cache.overlays.add( + new Map([['Order:1', { kind: 'merge', source: { total: 99 } } as const]]), + undefined, + [], + ); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + expect(shadow().querySelector('button')?.getAttribute('data-pulse')).toBe('error'); + + stop(); + unmount(); + devtools.dispose(); + }); + + it('carries the vitals beside the mark', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + const vitals = shadow().querySelector('.launcher-vitals')?.textContent ?? ''; + + // Records held, queries mounted. The counts a glance should answer. + expect(vitals).toContain('3'); + expect(vitals).toContain('ent'); + expect(vitals).toContain('1'); + expect(vitals).toContain('mnt'); + + stop(); + unmount(); + devtools.dispose(); + }); + + it('counts pending writes in the vitals only when there are some', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body }); + + expect(shadow().querySelector('.launcher-vitals')?.textContent).not.toContain('pend'); + + h.cache.overlays.add( + new Map([['Order:1', { kind: 'merge', source: {} } as const]]), + undefined, + [], + ); + devtools.actions.invalidateTag('Order[]'); + await Promise.resolve(); + + expect(shadow().querySelector('.launcher-vitals')?.textContent).toContain('pend'); + + unmount(); + devtools.dispose(); + }); +}); + +describe('the launcher, out of the way', () => { + /** The collision in the corner that started all of this. */ + it('lifts itself above a framework dev badge already in the corner', () => { + const badge = document.createElement('nextjs-portal'); + + document.body.append(badge); + + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body }); + + expect(shadow().querySelector('.root')?.getAttribute('data-offset')).toBe('badge'); + + unmount(); + badge.remove(); + devtools.dispose(); + }); + + it('sits in the corner when nothing else is there', () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body }); + + expect(shadow().querySelector('.root')?.getAttribute('data-offset')).toBe('none'); + + unmount(); + devtools.dispose(); + }); + + it('takes an explicit offset over anything it guessed', () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, offset: 96 }); + + const root = shadow().querySelector('.root') as HTMLElement | null; + + expect(root?.style.bottom).toBe('96px'); + + unmount(); + devtools.dispose(); + }); +}); + +describe('the near-miss banner', () => { + /** + * The threshold, stated: flag per raised tag, not per cause. A tag that + * reached no mounted query and has a near miss gets a banner even when the + * same cause reached something through a different tag. + * + * `orderCreate` invalidates `Order:{res.id}` and nothing else. The list + * carries `Order[]`, so the tag resolves fine, reaches nothing, and the + * screen stays stale with no error anywhere. That is the defect this whole + * package exists to explain, and the trace should say so where it happened. + */ + it('flags a raised tag that reached nothing but nearly matched', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + await h.cache.mutate(ops.orderCreate, { body: { total: 30 } }); + h.flush(); + await h.settle(); + + goTo('trace'); + + const banner = shadow().querySelector('.nearmiss'); + + expect(banner).not.toBeNull(); + expect(banner?.textContent).toContain('Order:9'); + expect(banner?.textContent).toContain('Order[]'); + // The relation, and the fix, both already computed by tag.ts. + expect(banner?.textContent).toContain('instance-vs-collection'); + + stop(); + unmount(); + devtools.dispose(); + }); + + it('says nothing when every raised tag reached something', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + // `orderUpdate` raises `Order[]`, which the list carries and is reached by. + await h.cache.mutate(ops.orderUpdate, { path: { id: 1 } }); + h.flush(); + await h.settle(); + + goTo('trace'); + + const banners = [...shadow().querySelectorAll('.nearmiss')].filter((node) => + node.textContent?.includes('Order[]'), + ); + + expect(banners).toHaveLength(0); + + stop(); + unmount(); + devtools.dispose(); + }); + + it('stays quiet for a tag that reached nothing and resembles nothing', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + // Nothing carries a Customer tag, and it is not a near miss for Order[]. + devtools.actions.invalidateTag('Customer[]'); + h.flush(); + await h.settle(); + + goTo('trace'); + + expect(shadow().querySelector('.nearmiss')).toBeNull(); + + stop(); + unmount(); + devtools.dispose(); + }); +}); + +describe('the vitals strip', () => { + it('reports the counters that say whether anything is leaking', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + const vitals = shadow().querySelector('.vitals'); + const read = (key: string): string | undefined => + vitals?.querySelector(`[data-vital="${key}"]`)?.textContent ?? undefined; + + expect(vitals).not.toBeNull(); + expect(read('entities')).toContain('3'); + expect(read('mounted')).toContain('1'); + expect(read('store')).toContain('v'); + expect(read('tags')).toBeDefined(); + // Tombstones and stamped tags are both bounded caches; a number that keeps + // climbing is the shape of a leak, and neither was visible anywhere. + expect(read('tombstones')).toBeDefined(); + + stop(); + unmount(); + devtools.dispose(); + }); + + it('flags pending optimistic writes in the strip only when there are some', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + expect(shadow().querySelector('[data-vital="pending"]')).toBeNull(); + + h.cache.overlays.add( + new Map([['Order:1', { kind: 'merge', source: {} } as const]]), + undefined, + [], + ); + devtools.actions.invalidateTag('Order[]'); + await Promise.resolve(); + + expect(shadow().querySelector('[data-vital="pending"]')?.textContent).toContain('1'); + + unmount(); + devtools.dispose(); + }); +}); + +describe('density', () => { + it('switches the panel to compact rows and back', () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const press = (): void => + shadow() + .querySelector('[data-act="density"]') + ?.dispatchEvent(new Event('click', { bubbles: true })) as unknown as void; + + expect(shadow().querySelector('.panel')?.getAttribute('data-density')).toBe('comfortable'); + + press(); + expect(shadow().querySelector('.panel')?.getAttribute('data-density')).toBe('compact'); + + press(); + expect(shadow().querySelector('.panel')?.getAttribute('data-density')).toBe('comfortable'); + + unmount(); + devtools.dispose(); + }); +}); + +describe('the keyboard', () => { + const key = (init: KeyboardEventInit): void => { + document.dispatchEvent(new KeyboardEvent('keydown', { ...init, bubbles: true })); + }; + + it('closes the inspector on escape', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + goTo('queries'); + + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( + new Event('click', { bubbles: true }), + ); + expect(shadow().querySelector('.detail')).not.toBeNull(); + + key({ key: 'Escape' }); + + expect(shadow().querySelector('.detail')).toBeNull(); + + stop(); + unmount(); + devtools.dispose(); + }); + + it('switches tabs by number', () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const current = (): string | null | undefined => + [...shadow().querySelectorAll('.bar button')] + .find((node) => node.getAttribute('aria-selected') === 'true') + ?.textContent; + + expect(current()).toBe('trace'); + + key({ key: '3' }); + + expect(current()).toBe('queries'); + + unmount(); + devtools.dispose(); + }); + + it('toggles the panel with the mount shortcut', () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body }); + + expect(shadow().querySelector('.panel')).toBeNull(); + + key({ key: 'F', metaKey: true, shiftKey: true }); + + expect(shadow().querySelector('.panel')).not.toBeNull(); + + key({ key: 'F', metaKey: true, shiftKey: true }); + + expect(shadow().querySelector('.panel')).toBeNull(); + + unmount(); + devtools.dispose(); + }); + + it('freezes and releases the view on f', () => { + const controls = new TransportControls({ sleep: () => Promise.resolve() }); + const h = harness(); + const devtools = attach(h.cache, { now: counter(), controls }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + key({ key: 'f' }); + + expect(shadow().querySelector('[data-act="freeze"]')?.getAttribute('aria-pressed')).toBe( + 'true', + ); + + key({ key: 'f' }); + + expect(shadow().querySelector('[data-act="freeze"]')?.getAttribute('aria-pressed')).toBe( + 'false', + ); + + unmount(); + devtools.dispose(); + }); + + /** + * Typing "3" into the filter box must filter, not jump to the third tab. + * A devtools panel that eats keystrokes out of its own input is worse than + * one with no shortcuts at all. + */ + it('keeps its hands off keys typed into an input', () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const input = shadow().querySelector('.bar input'); + + input?.dispatchEvent(new KeyboardEvent('keydown', { key: '3', bubbles: true })); + + expect( + [...shadow().querySelectorAll('.bar button')].find( + (node) => node.getAttribute('aria-selected') === 'true', + )?.textContent, + ).toBe('trace'); + + unmount(); + devtools.dispose(); + }); + + it('does nothing at all once unmounted', () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + unmount(); + devtools.dispose(); + + // No shadow root to read any more; the assertion is that this does not throw. + expect(() => { + key({ key: '3' }); + }).not.toThrow(); + }); +}); + +describe('the request waterfall', () => { + function wired(): { log: RequestLog; rest: RestTransport } { + const log = new RequestLog(20, counter()); + let calls = 0; + const rest = new RestTransport({ + client: { + request(): Promise { + calls += 1; + + return calls === 1 + ? (Promise.reject(new HttpFail(503)) as Promise) + : (Promise.resolve({ ok: true }) as Promise); + }, + }, + sleep: () => Promise.resolve(), + random: () => 0, + observer: log.observer, + }); + + return { log, rest }; + } + + it('draws a bar per request, proportional to the slowest one', async () => { + const { log, rest } = wired(); + const h = harness(); + const devtools = attach(h.cache, { now: counter(), requests: log }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + await rest.execute({ + meta: { method: 'GET', path: '/orders', provides: [], invalidates: [] }, + args: {}, + }); + + goTo('network'); + + const bar = shadow().querySelector('tr.row .wf'); + + expect(bar).not.toBeNull(); + // Segments are widths, so the sum is the whole bar. + expect(bar?.querySelectorAll('i').length).toBeGreaterThan(0); + + unmount(); + devtools.dispose(); + }); + + it('shows the backoff as its own segment, distinct from the wire', async () => { + const { log, rest } = wired(); + const h = harness(); + const devtools = attach(h.cache, { now: counter(), requests: log }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + await rest.execute({ + meta: { method: 'GET', path: '/orders', provides: [], invalidates: [] }, + args: {}, + }); + + goTo('network'); + + expect(shadow().querySelector('tr.row .wf .backoff')).not.toBeNull(); + + unmount(); + devtools.dispose(); + }); +}); + +describe('the overlay stack, acted on', () => { + it('rolls a pending write back off the stack', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + h.cache.overlays.add( + new Map([['Order:1', { kind: 'merge', source: { total: 99 } } as const]]), + undefined, + ['Order[]'], + ); + + goTo('overlay'); + + expect(shadow().querySelectorAll('.layer')).toHaveLength(1); + + shadow() + .querySelector('[data-act="rollback"]') + ?.dispatchEvent(new Event('click', { bubbles: true })); + + expect(devtools.overlays()).toHaveLength(0); + expect(shadow().querySelectorAll('.layer')).toHaveLength(0); + + unmount(); + devtools.dispose(); + }); + + it('shows the base record beside what the patch makes of it', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + h.cache.overlays.add( + new Map([['Order:1', { kind: 'merge', source: { total: 999 } } as const]]), + undefined, + [], + ); + + goTo('overlay'); + + const diff = shadow().querySelector('.layer .diff')?.textContent ?? ''; + + expect(diff).toContain('10'); + expect(diff).toContain('999'); + + stop(); + unmount(); + devtools.dispose(); + }); +}); + +describe('holding a query in a state', () => { + it('holds it in loading, marks it, and gives the real record back', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + goTo('queries'); + + const key = h.cache.key(ops.orderList); + const row = [...shadow().querySelectorAll('tr.row')].find((node) => + node.textContent?.includes(key), + ); + + row?.dispatchEvent(new Event('click', { bubbles: true })); + + shadow() + .querySelector('[data-act="hold-loading"]') + ?.dispatchEvent(new Event('click', { bubbles: true })); + + expect(shadow().querySelector('.held')).not.toBeNull(); + expect(shadow().querySelector('.detail')?.textContent).toContain('Held in loading'); + // The cache itself is untouched: the record still says what it said. + expect(devtools.detail(key)?.status).toBe('success'); + + shadow() + .querySelector('[data-act="release"]') + ?.dispatchEvent(new Event('click', { bubbles: true })); + + expect(shadow().querySelector('.held')).toBeNull(); + + stop(); + unmount(); + devtools.dispose(); + }); + + it('writes the hold to the trace, so it is not mistaken for the app', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + goTo('queries'); + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( + new Event('click', { bubbles: true }), + ); + shadow() + .querySelector('[data-act="hold-error"]') + ?.dispatchEvent(new Event('click', { bubbles: true })); + + goTo('trace'); + + const yours = [...shadow().querySelectorAll('.cause[data-kind="action"]')]; + + expect(yours.some((node) => node.textContent?.includes('hold'))).toBe(true); + + stop(); + unmount(); + devtools.dispose(); + }); +}); + +describe('reaching the explanation', () => { + it('jumps from a query row to its explanation', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + await h.cache.mutate(ops.orderCreate, { body: { total: 30 } }); + h.flush(); + await h.settle(); + + goTo('queries'); + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( + new Event('click', { bubbles: true }), + ); + + shadow() + .querySelector('[data-act="why"]') + ?.dispatchEvent(new Event('click', { bubbles: true })); + + const text = shadow().textContent ?? ''; + + // Explain, already pointed at the pair you were looking at, rather than + // asking you to type an exact query key from memory. + expect(text).toContain('outcome: missed'); + expect(text).toContain('instance-vs-collection'); + + stop(); + unmount(); + devtools.dispose(); + }); + + it('refetches and invalidates the selected row from the keyboard', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + goTo('queries'); + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( + new Event('click', { bubbles: true }), + ); + + const before = h.calls.length; + + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'r', bubbles: true })); + await h.settle(); + + expect(h.calls.length).toBeGreaterThan(before); + + document.dispatchEvent(new KeyboardEvent('keydown', { key: 'i', bubbles: true })); + h.flush(); + await h.settle(); + + goTo('trace'); + + expect( + [...shadow().querySelectorAll('.cause[data-kind="action"]')].some((node) => + node.textContent?.includes('invalidate'), + ), + ).toBe(true); + + stop(); + unmount(); + devtools.dispose(); + }); +}); + +describe('promoting a pending write', () => { + it('commits the overlay to the base store by hand', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + h.cache.overlays.add( + new Map([['Order:1', { kind: 'merge', source: { total: 777 } } as const]]), + undefined, + [], + ); + + goTo('overlay'); + + shadow() + .querySelector('[data-act="promote"]') + ?.dispatchEvent(new Event('click', { bubbles: true })); + + expect(devtools.overlays()).toHaveLength(0); + // Promoted means written, so the base record now carries it. + expect(devtools.baseRecord('Order:1')?.['total']).toBe(777); + + stop(); + unmount(); + devtools.dispose(); + }); +}); + +describe('closing the last gaps', () => { + it('draws the auth wait as its own segment', async () => { + const log = new RequestLog(20, counter()); + let token = 't0'; + const rest = new RestTransport({ + client: { + request(config: { headers?: Record }): Promise { + return config.headers?.['Authorization'] === 'Bearer t0' + ? (Promise.reject(new HttpFail(401)) as Promise) + : (Promise.resolve({ ok: true }) as Promise); + }, + }, + auth: { + credentials: () => ({ Authorization: `Bearer ${token}` }), + refresh: () => { + token = 't1'; + + return Promise.resolve(); + }, + }, + sleep: () => Promise.resolve(), + observer: log.observer, + }); + + const h = harness(); + const devtools = attach(h.cache, { now: counter(), requests: log }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + await rest.execute({ + meta: { method: 'GET', path: '/orders', provides: [], invalidates: [] }, + args: {}, + }); + + goTo('network'); + + expect(shadow().querySelector('tr.row .wf .auth')).not.toBeNull(); + + unmount(); + devtools.dispose(); + }); + + it('writes a curl line for the selected request', async () => { + const log = new RequestLog(20, counter()); + const rest = new RestTransport({ + client: { + request(): Promise { + return Promise.resolve({ ok: true }) as Promise; + }, + }, + observer: log.observer, + }); + + const h = harness(); + const devtools = attach(h.cache, { now: counter(), requests: log }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + await rest.execute({ + meta: { method: 'GET', path: '/orders', provides: [], invalidates: [] }, + args: {}, + }); + + goTo('network'); + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( + new Event('click', { bubbles: true }), + ); + + const curl = shadow().querySelector('[data-curl]')?.textContent ?? ''; + + expect(curl).toContain("curl -X GET"); + expect(curl).toContain('/orders'); + // Never the real credential, which the log does not keep in the first place. + expect(curl).toContain('$TOKEN'); + + unmount(); + devtools.dispose(); + }); + + /** + * The mock's argument, finally built: a devtools edit is an overlay entry. + * It never writes the base store, so undo is removing it rather than + * applying an inverse, and a stream frame that evicts the row takes it with + * it exactly as it would a real optimistic write. + */ + it('edits an entity field by pushing a patch onto the overlay stack', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + goTo('entities'); + + const row = [...shadow().querySelectorAll('tr.row')].find((node) => + node.textContent?.includes('Order:1'), + ); + + row?.dispatchEvent(new Event('click', { bubbles: true })); + + const field = shadow().querySelector('[data-act="edit-field"]') as HTMLInputElement | null; + const value = shadow().querySelector('[data-act="edit-value"]') as HTMLInputElement | null; + + expect(field).not.toBeNull(); + + if (field !== null && value !== null) { + field.value = 'total'; + value.value = '4242'; + } + + shadow() + .querySelector('[data-act="edit-apply"]') + ?.dispatchEvent(new Event('click', { bubbles: true })); + + expect(devtools.overlays()).toHaveLength(1); + expect(devtools.foldedRecord('Order:1')?.['total']).toBe(4242); + // The base is untouched, which is the whole point. + expect(devtools.baseRecord('Order:1')?.['total']).toBe(10); + + stop(); + unmount(); + devtools.dispose(); + }); + + it('marks a query stale without refetching it', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + goTo('queries'); + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( + new Event('click', { bubbles: true }), + ); + + const before = h.calls.length; + + shadow() + .querySelector('[data-act="force-stale"]') + ?.dispatchEvent(new Event('click', { bubbles: true })); + await h.settle(); + + expect(devtools.queries()[0]?.stale).toBe(true); + // Stale, not refetched: no request went out. + expect(h.calls.length).toBe(before); + + stop(); + unmount(); + devtools.dispose(); + }); +}); + +describe('the remaining shortcuts', () => { + const key = (init: KeyboardEventInit): void => { + document.dispatchEvent(new KeyboardEvent('keydown', { ...init, bubbles: true })); + }; + + it('focuses the filter box on slash and on the jump shortcut', () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + key({ key: '/' }); + expect(shadow().activeElement?.tagName).toBe('INPUT'); + + (shadow().activeElement as HTMLElement | null)?.blur(); + + key({ key: 'k', metaKey: true }); + expect(shadow().activeElement?.tagName).toBe('INPUT'); + + unmount(); + devtools.dispose(); + }); + + it('pops the top overlay on undo', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + h.cache.overlays.add( + new Map([['Order:1', { kind: 'merge', source: {} } as const]]), + undefined, + [], + ); + h.cache.overlays.add( + new Map([['Order:2', { kind: 'merge', source: {} } as const]]), + undefined, + [], + ); + + key({ key: 'z', metaKey: true }); + + expect(devtools.overlays()).toHaveLength(1); + // The top of the stack went, not the bottom. + expect(devtools.overlays()[0]?.patches[0]?.key).toBe('Order:1'); + + unmount(); + devtools.dispose(); + }); + + it('goes fullscreen and back on the fullscreen key', () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + key({ key: 'F11' }); + expect(shadow().querySelector('.panel')?.getAttribute('data-mode')).toBe('full'); + + key({ key: 'F11' }); + expect(shadow().querySelector('.panel')?.getAttribute('data-mode')).toBe('bottom'); + + unmount(); + devtools.dispose(); + }); + + it('explains the selected row on enter', async () => { + const h = harness(); + const devtools = attach(h.cache, { now: counter() }); + const unmount = mountPanel(devtools, { parent: document.body, open: true }); + + const stop = h.cache.subscribe(ops.orderList, undefined, () => undefined); + await h.settle(); + + await h.cache.mutate(ops.orderCreate, { body: { total: 30 } }); + h.flush(); + await h.settle(); + + goTo('queries'); + [...shadow().querySelectorAll('tr.row')][0]?.dispatchEvent( + new Event('click', { bubbles: true }), + ); + + key({ key: 'Enter' }); + + expect(shadow().textContent).toContain('outcome: missed'); + + stop(); + unmount(); + devtools.dispose(); + }); +}); diff --git a/packages/client-devtools/__tests__/requests.test.ts b/packages/client-devtools/__tests__/requests.test.ts index 433f2dfd7..6c649da79 100644 --- a/packages/client-devtools/__tests__/requests.test.ts +++ b/packages/client-devtools/__tests__/requests.test.ts @@ -163,3 +163,45 @@ describe('the request log', () => { expect(log.dropped).toBe(1); }); }); + +describe('the credential refresh, timed', () => { + it('measures how long a request sat waiting on the refresh', async () => { + const log = new RequestLog(20, counter()); + let token = 't0'; + const rest = new RestTransport({ + client: { + request(config: { headers?: Record }): Promise { + return config.headers?.['Authorization'] === 'Bearer t0' + ? (Promise.reject(new Failure(401)) as Promise) + : (Promise.resolve({ ok: true }) as Promise); + }, + }, + auth: { + credentials: () => ({ Authorization: `Bearer ${token}` }), + refresh: () => { + token = 't1'; + + return Promise.resolve(); + }, + }, + sleep: () => Promise.resolve(), + observer: log.observer, + }); + + await rest.execute({ meta: list, args: {} }); + + const [entry] = log.entries(); + + expect(entry?.refreshes).toBe(1); + // The clock ticks once per read, so any wait at all is a positive number. + expect(entry?.authMs).toBeGreaterThan(0); + }); + + it('reports no auth time for a request that never met a 401', async () => { + const { log, rest } = wired(() => ({ ok: true })); + + await rest.execute({ meta: list, args: {} }); + + expect(log.entries()[0]?.authMs).toBe(0); + }); +}); diff --git a/packages/client-devtools/__tests__/zero-cost.test.ts b/packages/client-devtools/__tests__/zero-cost.test.ts index f99df459d..0dbfab823 100644 --- a/packages/client-devtools/__tests__/zero-cost.test.ts +++ b/packages/client-devtools/__tests__/zero-cost.test.ts @@ -201,12 +201,23 @@ describe('the panel entry point', () => { // API underneath it. `size-limit` holds the finer-grained ceilings on each // module on its own; this one is the number an application actually pays. // - // Raised from 12 kB to 14 kB for the causal trace, the overlay-stack view - // and the network view, and again to 16 kB for the control rail and the - // facet chips. Two increases in one body of work is worth a deliberate - // look rather than a third nudge: either the panel earns its size or it - // wants splitting the way `./requests` and `./control` already were. - expect(panel.gzipped - production.gzipped).toBeLessThan(16_000); + // Re-baselined once, deliberately, rather than nudged a fourth time. + // + // The original 12 kB was written for a panel of eight plain tables. This + // one has a causal trace, a network view, the overlay stack, a control + // rail, facet chips, a vitals strip and a keyboard layer. The question the + // earlier increases deferred was whether to split instead, and the answer + // is no: the panel is one closure over shared UI state (tab, filter, + // selection, sort, facets, density) and every renderer reads it, so + // splitting would mean threading that state through an interface and + // paying for it on both sides. There is also nothing here a consumer could + // decline to import; you do not want "the panel without the network tab". + // The parts that *could* be declined were split out already, and they are + // `./requests` and `./control`. + // + // 20 kB leaves room to finish the remaining views without moving it again. + // If it needs a fifth increase, that is the signal to split for real. + expect(panel.gzipped - production.gzipped).toBeLessThan(20_000); }); }); diff --git a/packages/client-devtools/package.json b/packages/client-devtools/package.json index 8e605a821..963b0bf4c 100644 --- a/packages/client-devtools/package.json +++ b/packages/client-devtools/package.json @@ -50,7 +50,7 @@ { "name": "inspection API", "path": "dist/index.js", - "limit": "6 kB", + "limit": "6.5 kB", "gzip": true, "ignore": [ "@forge-go/client-core" @@ -68,7 +68,7 @@ { "name": "panel", "path": "dist/panel.js", - "limit": "12 kB", + "limit": "16 kB", "gzip": true, "ignore": [ "@forge-go/client-core" @@ -98,7 +98,7 @@ "dist/index.js", "dist/overlay.js" ], - "limit": "9.5 kB", + "limit": "10 kB", "gzip": true, "ignore": [ "@forge-go/client-core" diff --git a/packages/client-devtools/src/actions.ts b/packages/client-devtools/src/actions.ts index 4dc705e25..8add42f2c 100644 --- a/packages/client-devtools/src/actions.ts +++ b/packages/client-devtools/src/actions.ts @@ -2,7 +2,17 @@ import type { QueryCache } from '@forge-go/client-core'; import type { EventLog } from './log.js'; /** The kinds an `ActionLog` can carry. Kept beside the calls that record them. */ -type ActionKind = 'refetch' | 'invalidate' | 'invalidateTag' | 'evict' | 'drop' | 'clear'; +type ActionKind = + | 'refetch' + | 'invalidate' + | 'invalidateTag' + | 'evict' + | 'drop' + | 'clear' + | 'rollback' + | 'hold' + | 'release' + | 'stale'; /** * The half that writes. @@ -38,6 +48,49 @@ export interface DevtoolsActions { drop(key: string): boolean; /** Drop every entity, every skeleton and every registry entry. */ clear(): void; + /** + * Take one pending optimistic write off the stack. + * + * Removal, not an inverse. That is the whole of rollback in `OverlayStack` + * and it is what keeps it correct when an earlier layer fails after a later + * one has already landed: an inverse recorded for the second was computed + * against a base that already included the first. + */ + rollback(id: number): boolean; + /** + * Commit one pending optimistic write to the base store by hand. + * + * What the runtime does when a mutation settles, minus the response. A + * `create` is never promoted; its temp key exists only to be rendered, so + * promoting a layer that minted one writes its merges and drops the create. + */ + promote(id: number): boolean; + /** + * Mark one query behind the server without asking for it again. + * + * `invalidate` raises the query's tags, which reaches every query sharing + * them and refetches the mounted ones. This marks exactly one, and leaves + * the request for whenever something next needs it, which is the state you + * want when you are trying to see what a stale read looks like. + */ + forceStale(key: string): boolean; + /** + * Push one hand-written field change onto the overlay stack. + * + * Deliberately an overlay and not a store write. See `editBar` in the panel: + * this rides the same machinery a pending optimistic mutation does, which is + * what makes it reversible by removal and correctly beaten by an evicting + * stream frame. Returns the overlay id, for the undo. + */ + patchEntity(key: string, fields: Readonly>): number; + /** + * Record that the panel is holding a query in a state it did not reach. + * + * Nothing in the cache moves. This exists so the trace says a held query was + * held by you, on the same terms as every other action here. + */ + hold(key: string, state: string): void; + release(key: string): void; } /** @@ -117,5 +170,59 @@ export function createActions( record('clear', '*'); cache.clear(); }, + + rollback(id) { + const entry = cache.overlays.take(id); + + if (entry === undefined) return false; + + record('rollback', `overlay #${String(id)}`); + // The stack changed under everything reading through it, so say so. + cache.notifyChanged(); + + return true; + }, + + promote(id) { + const entry = cache.overlays.take(id); + + if (entry === undefined) return false; + + record('rollback', `promote overlay #${String(id)}`); + cache.overlays.promote(entry); + cache.notifyChanged(); + + return true; + }, + + forceStale(key) { + const entry = cache.registry.get(key); + + if (entry === undefined) return false; + + record('stale', key); + cache.registry.markStale(entry); + cache.notifyChanged(); + + return true; + }, + + patchEntity(key, fields) { + record('rollback', `patch ${key}`); + + const id = cache.overlays.add(new Map([[key, { kind: 'merge', source: { ...fields } }]]), undefined, []); + + cache.notifyChanged(); + + return id; + }, + + hold(key, state) { + record('hold', `${key} in ${state}`); + }, + + release(key) { + record('release', key); + }, }; } diff --git a/packages/client-devtools/src/devtools.ts b/packages/client-devtools/src/devtools.ts index 36f005abd..875883599 100644 --- a/packages/client-devtools/src/devtools.ts +++ b/packages/client-devtools/src/devtools.ts @@ -173,6 +173,12 @@ export interface Devtools { /** The pending optimistic writes, bottom of the stack first. */ overlays(): readonly OverlaySnapshot[]; + /** One record as the store holds it, before any overlay is folded over it. */ + baseRecord(key: string): Readonly> | undefined; + /** Push a hand-written field change onto the overlay stack. */ + patchEntity(key: string, fields: Readonly>): number; + /** The same record, with the pending overlays folded over it. */ + foldedRecord(key: string): Readonly> | undefined; /** * What the transport did, newest last. Empty when nothing is wired. @@ -525,6 +531,9 @@ export function attach(cache: QueryCache, options: DevtoolsOptions = {}): Devtoo detail: (key) => read.detail(cache, key), records: () => read.records(cache), overlays: () => read.overlays(cache), + baseRecord: (key) => read.baseRecord(cache, key), + patchEntity: (key, fields) => actions.patchEntity(key, fields), + foldedRecord: (key) => read.foldedRecord(cache, key), requests: () => options.requests?.entries() ?? [], controls: options.controls, revalidation: options.revalidation, diff --git a/packages/client-devtools/src/inspect.ts b/packages/client-devtools/src/inspect.ts index a7e5fd70b..476607239 100644 --- a/packages/client-devtools/src/inspect.ts +++ b/packages/client-devtools/src/inspect.ts @@ -389,6 +389,31 @@ export function binderView( return binderSnapshot(binder); } +/** + * One entity record as the store holds it, with no overlay folded over it. + * + * A plain copy of the fields, on the same terms as `entities`: reading it + * neither opens the record nor moves it in the LRU order. + */ +export function baseRecord( + cache: QueryCache, + key: string, +): Readonly> | undefined { + const found = cache.store.getRecord(key); + + return found === undefined ? undefined : { ...found.data }; +} + +/** The same record with every pending overlay folded over it. */ +export function foldedRecord( + cache: QueryCache, + key: string, +): Readonly> | undefined { + const found = cache.overlays.effective(key); + + return found === undefined ? undefined : { ...found.data }; +} + /** * The pending optimistic writes, bottom of the stack first. * diff --git a/packages/client-devtools/src/panel.ts b/packages/client-devtools/src/panel.ts index 1593fac62..4d44d2b69 100644 --- a/packages/client-devtools/src/panel.ts +++ b/packages/client-devtools/src/panel.ts @@ -1,4 +1,6 @@ import { capture } from './frames.js'; +import { nearMisses } from './tag.js'; +import type { NearMiss } from './tag.js'; import type { Devtools } from './devtools.js'; import type { EntitySnapshot, @@ -30,8 +32,25 @@ export interface PanelOptions { readonly parent?: Element; /** Start with the panel open. Defaults to false -- a button in the corner. */ readonly open?: boolean; + /** + * How far off the bottom edge to sit, in pixels. + * + * Set this and nothing is guessed. Left unset, the launcher looks for a + * framework's own dev badge in the same corner and lifts itself above one if + * it finds it, because the bottom right is a crowded address. + */ + readonly offset?: number; } +/** + * Dev badges that already own the bottom-right corner. + * + * Matched by element name rather than by position: reading layout would mean + * measuring, and measuring on mount is how a devtools panel starts causing the + * reflows it exists to help you find. + */ +const BADGES = 'nextjs-portal, #__next-build-watcher, [data-nextjs-toast], vite-error-overlay'; + type Tab = | 'trace' | 'network' @@ -171,6 +190,18 @@ const CSS = ` .launcher { width: 30px; height: 30px; padding: 0; display: grid; place-items: center; position: relative; border-radius: 8px; background: #14181f; border: 1px solid #2e3542; box-shadow: 0 6px 22px rgba(0,0,0,.34); color: #e3e7ee; } +.root[data-offset="badge"] { bottom: 62px; } +.launcher-dock { display: flex; align-items: center; background: #14181f; + border: 1px solid #2e3542; border-radius: 9px; padding: 5px; + box-shadow: 0 6px 22px rgba(0,0,0,.34); } +.launcher-dock .launcher { box-shadow: none; border: 0; background: transparent; } +.launcher-vitals { display: none; align-items: center; gap: 4px; padding: 0 8px 0 8px; + margin-left: 3px; border-left: 1px solid #242a35; color: #8992a2; font-size: 10.5px; + white-space: nowrap; } +.launcher-vitals b { color: #e3e7ee; font-weight: 500; } +.launcher-dock:hover .launcher-vitals, .launcher-dock:focus-within .launcher-vitals { + display: flex; } +.launcher[data-pulse="pending"]::after { border-color: #ffb648; } .launcher:hover { background: #1a1f28; } .launcher svg { width: 15px; height: 15px; display: block; } .launcher::after { content: ""; position: absolute; inset: -2px; border-radius: 10px; @@ -205,6 +236,31 @@ const CSS = ` .detail-head .what { color: #8a8a98; font-size: 10px; letter-spacing: .13em; text-transform: uppercase; } .detail-head .spacer { flex: 1; } +.wf { display: flex; height: 8px; min-width: 90px; border-radius: 2px; background: #2b2b33; + overflow: hidden; } +.wf i { display: block; height: 100%; } +.wf .wire { background: #62a8ff; } +.wf .auth { background: #ae8cff; } +.wf .backoff { background: repeating-linear-gradient(90deg, #45454f 0 3px, transparent 3px 6px); } +.wf .pending { width: 100%; background: repeating-linear-gradient(90deg, #35353d 0 4px, + transparent 4px 8px); } +.diff { line-height: 1.6; } +.diff .was { color: #ff8f8f; } +.diff .now { color: #8ce99a; } +.diff .same { color: #6b6b78; } +.held { color: #ff6a2b; } +.held-banner { border: 1px solid rgba(255,106,43,.45); background: rgba(255,106,43,.08); + border-radius: 5px; padding: 7px 9px; color: #ff6a2b; margin-bottom: 8px; } +.vitals { display: flex; overflow-x: auto; border-bottom: 1px solid #35353d; } +.vital { padding: 5px 12px; border-right: 1px solid #2b2b33; white-space: nowrap; } +.vital .k { display: block; color: #6b6b78; font-size: 9.5px; letter-spacing: .12em; + text-transform: uppercase; } +.vital .v { color: #e6e6e6; font-size: 13px; } +.vital .n { color: #6b6b78; font-size: 10px; margin-left: 5px; } +.vital[data-vital="pending"] .v { color: #ffb648; } +.panel[data-density="compact"] td, .panel[data-density="compact"] th { padding: 1px 6px; } +.panel[data-density="compact"] .vital { padding: 3px 10px; } +.panel[data-density="compact"] .cause { padding: 5px 4px 5px 24px; } .rail { display: flex; gap: 7px; align-items: center; flex-wrap: wrap; padding: 5px 6px; border-bottom: 1px solid #35353d; } .rail .spacer { flex: 1; } @@ -250,6 +306,9 @@ button[aria-selected="true"] { background: #4b5bd6; border-color: #4b5bd6; } .effect { position: relative; margin-top: 6px; padding-left: 14px; color: #9a9aa8; } .effect::before { content: ""; position: absolute; left: -12px; top: 8px; width: 20px; height: 1px; background: #35353d; } +.nearmiss { margin-top: 8px; padding: 6px 9px; border: 1px solid rgba(255,182,72,.28); + background: rgba(255,182,72,.06); border-radius: 5px; color: #ffb86b; } +.nearmiss .warn { text-transform: uppercase; letter-spacing: .1em; font-size: 10px; } .layer { border: 1px solid #45454f; border-radius: 6px; padding: 8px 10px; margin-bottom: 8px; } .patch { display: flex; gap: 8px; margin-top: 4px; } .patch .kind { min-width: 46px; text-align: right; color: #8a8a98; } @@ -302,16 +361,41 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = shadow.append(style); const root = doc.createElement('div'); + root.className = 'root'; + + // Explicit beats guessed. Guessed beats colliding with the framework's badge. + if (options.offset !== undefined) { + root.style.bottom = `${String(options.offset)}px`; + root.setAttribute('data-offset', 'set'); + } else { + const crowded = doc.querySelector(BADGES) !== null; + + root.setAttribute('data-offset', crowded ? 'badge' : 'none'); + } + shadow.append(root); parent.append(host); let open = options.open ?? false; - let tab: Tab = 'queries'; + // The first tab, and the same one `1` selects. The trace is what the panel + // is for; a list of queries is what every other devtools panel opens on. + let tab: Tab = 'trace'; let filter = ''; let scheduled = false; let mode: Mode = 'bottom'; let frozen = false; + let compact = false; + /** + * Queries the panel is holding in a state they did not reach. + * + * Panel-local on purpose. Nothing here writes the cache, so the real record + * is untouched and comes back whole on release; there is no state to unwind + * and no way for a held query to outlive the panel that held it. Every hold + * and release goes to the trace as an action, so a spinner you caused never + * reads as a spinner the application caused. + */ + const holds = new Map(); /** * The row selected on each list tab, and the column each list tab is @@ -374,7 +458,12 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = */ const rows = ( headers: readonly string[], - items: readonly { readonly key: string; readonly cells: readonly string[] }[], + items: readonly { + readonly key: string; + readonly cells: readonly string[]; + /** Drawn into the last cell. For a bar, which is not a string. */ + readonly extra?: HTMLElement; + }[], ): HTMLElement => { const node = doc.createElement('table'); const head = doc.createElement('tr'); @@ -433,6 +522,9 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = }); for (const cell of item.cells) tr.append(el('td', undefined, cell)); + + if (item.extra !== undefined) tr.lastElementChild?.append(item.extra); + node.append(tr); } @@ -682,6 +774,72 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = node.append(pills(one.tags, 'raises when it settles')); + for (const patch of one.patches) node.append(diffOf(patch.key)); + + const act = el('div', 'buttons'); + const rollback = el('button', undefined, 'roll back'); + + rollback.setAttribute('data-act', 'rollback'); + rollback.addEventListener('click', (event) => { + event.stopPropagation(); + devtools.actions.rollback(one.id); + render(); + }); + const promote = el('button', undefined, 'promote'); + + promote.setAttribute('data-act', 'promote'); + promote.addEventListener('click', (event) => { + event.stopPropagation(); + devtools.actions.promote(one.id); + render(); + }); + act.append(rollback, promote); + node.append(act); + + return node; + }; + + /** + * The base record beside what the stack makes of it. + * + * `store.getRecord` is the base and `overlays.effective` is the fold, so this + * is the actual before and after rather than a re-derivation of the patch. + * Only changed fields are listed; a record with forty fields and one edit + * should read as one edit. + */ + const diffOf = (key: string): HTMLElement => { + const node = el('div', 'diff'); + const base = devtools.baseRecord(key); + const folded = devtools.foldedRecord(key); + + node.append(el('div', 'same', key)); + + if (folded === undefined) { + node.append(el('div', 'was', 'deleted by this overlay')); + + return node; + } + + if (base === undefined) { + node.append(el('div', 'now', 'created by this overlay, no base record')); + + return node; + } + + let changed = 0; + + for (const [field, next] of Object.entries(folded)) { + const before = base[field]; + + if (Object.is(before, next)) continue; + + changed += 1; + node.append(el('div', 'was', `- ${field}: ${String(before)}`)); + node.append(el('div', 'now', `+ ${field}: ${String(next)}`)); + } + + if (changed === 0) node.append(el('div', 'same', 'no field actually moves')); + return node; }; @@ -719,6 +877,60 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = for (const effect of one.effects) node.append(el('div', 'effect', describe(effect))); + for (const miss of missedBy(one)) node.append(missBanner(miss)); + + return node; + }; + + /** + * The near misses worth interrupting you about, for one cause. + * + * Flagged per raised tag, not per cause. A tag that reached no mounted query + * and closely resembles one somebody carries gets a banner even when the same + * cause reached something through a different tag, because the tag that + * missed is still wrong and the one that landed is what hides it. Suppressing + * on "the cause reached something" would silence exactly the case this is + * for: a mutation raising two tags where only one of them works. + * + * A tag that reached nothing and resembles nothing is not flagged. That is an + * invalidation for a query nobody has open, which is ordinary. + */ + const missedBy = (one: Block): readonly NearMiss[] => { + const raised = raisedBy(one.entry); + + if (raised.length === 0) return []; + + const landed = new Set(); + + for (const effect of one.effects) { + if (effect.kind === 'invalidated') for (const tag of effect.matched) landed.add(tag); + } + + const missed = raised.filter((tag) => !landed.has(tag)); + + if (missed.length === 0) return []; + + // What anything currently carries, mounted or merely remembered: a query + // that is only remembered still refetches on mount, so a near miss against + // it is just as much a near miss. + const carried = devtools.tags().map((row) => row.tag); + + return nearMisses(missed, carried, 3); + }; + + const missBanner = (miss: NearMiss): HTMLElement => { + const node = el('div', 'nearmiss'); + + node.append(el('span', 'warn', 'near miss')); + node.append( + el( + 'span', + undefined, + ` ${miss.invalidated} reached nothing, and ${miss.carried} is carried ` + + `(${miss.relation}). ${miss.hint}`, + ), + ); + return node; }; @@ -816,9 +1028,10 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = cells: [ entry.key, String(entry.mounts), - entry.stale ? 'stale' : entry.settled ? 'fresh' : 'empty', + holds.get(entry.key) ?? (entry.stale ? 'stale' : entry.settled ? 'fresh' : 'empty'), entry.tags.join(' '), ], + ...(holds.has(entry.key) ? { extra: el('span', 'held', ' held') } : {}), })); body.append(rows(['key', 'mounts', 'state', 'tags'], items)); @@ -1015,9 +1228,11 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = const requests = narrow(requestSource, REQUEST_FACETS).slice().reverse(); + const slowest = requestSource.reduce((most, one) => Math.max(most, one.duration ?? 0), 1); + body.append( rows( - ['request', 'status', 'try', 'ms'], + ['request', 'status', 'try', 'ms', ''], requests.map((one) => ({ key: String(one.id), cells: [ @@ -1029,7 +1244,9 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = : String(one.status ?? 'failed'), `${String(one.attempts)}/${String(one.limit)}`, one.duration === undefined ? '' : String(one.duration), + '', ], + extra: waterfall(one, slowest), })), ), ); @@ -1198,6 +1415,112 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = * entity, `clear` off the global bar. `invalidateTag` is the one left to the * console, because it takes a tag rather than a row. */ + /** + * The two forced states, and the one rule that makes them safe. + * + * A faked state has to be impossible to mistake for a real one and reversible + * without the cache having to unwind anything. Holding it in a register the + * panel owns satisfies both: the row says held, the pane says held, the trace + * says you did it, and release is a map delete. + */ + /** + * Straight to the explanation for this query. + * + * `explain` used to need an exact query key typed from memory into the + * filter box, which is a strange thing to ask of the one tab that exists to + * answer a question you already have. + */ + const whyBar = (key: string): HTMLElement => { + const bar = el('div', 'buttons'); + const why = el('button', undefined, 'why did this not refetch?'); + + why.setAttribute('data-act', 'why'); + why.addEventListener('click', () => { + filter = key; + tab = 'explain'; + render(); + }); + bar.append(why); + + return bar; + }; + + const holdBar = (key: string): HTMLElement => { + const bar = el('div', 'buttons'); + + const stale = el('button', undefined, 'force stale'); + + stale.setAttribute('data-act', 'force-stale'); + stale.addEventListener('click', () => { + devtools.actions.forceStale(key); + render(); + }); + bar.append(stale); + + for (const state of ['loading', 'error'] as const) { + const button = el('button', undefined, `hold ${state}`); + + button.setAttribute('data-act', `hold-${state}`); + button.addEventListener('click', () => { + holds.set(key, state); + devtools.actions.hold(key, state); + render(); + }); + bar.append(button); + } + + return bar; + }; + + /** + * Edit one field, as an overlay entry. + * + * The argument the whole state-manipulation section rests on: a devtools + * edit rides the same stack a pending mutation does, so it never writes the + * base store, undo is removing the entry rather than applying an inverse, + * and a stream frame that evicts the row takes this with it exactly as it + * would take a real optimistic write. A merge over a base record that is + * gone patches nothing, and that rule is already in `OverlayStack`. + */ + const editBar = (key: string): HTMLElement => { + const bar = el('div', 'buttons'); + const field = doc.createElement('input'); + const value = doc.createElement('input'); + + field.setAttribute('data-act', 'edit-field'); + field.placeholder = 'field'; + field.setAttribute('aria-label', 'Field to edit'); + value.setAttribute('data-act', 'edit-value'); + value.placeholder = 'value'; + value.setAttribute('aria-label', 'New value'); + + const apply = el('button', undefined, 'patch'); + + apply.setAttribute('data-act', 'edit-apply'); + apply.addEventListener('click', () => { + const name = field.value.trim(); + + if (name === '') return; + + // JSON first so a number stays a number, falling back to the raw string + // for the common case of typing a word rather than a quoted one. + let parsed: unknown = value.value; + + try { + parsed = JSON.parse(value.value) as unknown; + } catch { + parsed = value.value; + } + + devtools.patchEntity(key, { [name]: parsed }); + render(); + }); + + bar.append(field, value, apply); + + return bar; + }; + const entityBar = (key: string): HTMLElement => buttonBar([ [ @@ -1217,8 +1540,36 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = return; } + const held = holds.get(key); + + if (held !== undefined) { + const banner = el('div', 'held-banner'); + + banner.append( + el( + 'div', + undefined, + `Held in ${held} by devtools. The real record is untouched in the cache ` + + 'and comes back the moment you release.', + ), + ); + + const release = el('button', undefined, 'release'); + + release.setAttribute('data-act', 'release'); + release.addEventListener('click', () => { + holds.delete(key); + devtools.actions.release(key); + render(); + }); + banner.append(release); + body.append(banner); + } + body.append(el('h4', undefined, detail.key)); body.append(actionBar(detail)); + body.append(holdBar(key)); + body.append(whyBar(key)); body.append(field('operation', detail.operation)); body.append(field('status', detail.status)); body.append(field('fetching', String(detail.fetching))); @@ -1253,6 +1604,8 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = const renderEntityDetail = (body: HTMLElement, key: string): void => { const record: EntitySnapshot | undefined = devtools.entity(key); + if (record !== undefined) body.append(editBar(key)); + if (record === undefined) { body.append(el('p', 'dim', `${key} is not in the store.`)); @@ -1352,6 +1705,24 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = field('duration', one.duration === undefined ? 'still in flight' : `${String(one.duration)}`), ); + const curl = el('pre', 'curl'); + + curl.setAttribute('data-curl', ''); + curl.textContent = + `curl -X ${one.method} '${one.operation.slice(one.method.length + 1)}' \\\n` + + ` -H 'authorization: Bearer $TOKEN' \\\n` + + ` -H 'accept: application/json'${one.args === '' || one.args === '{}' ? '' : ` \\\n -d '${one.args}'`}`; + body.append(el('h4', undefined, 'as curl')); + body.append(curl); + body.append( + el( + 'p', + 'dim', + 'The credential is a placeholder. This log never keeps the real one, ' + + 'which is why it is cheap enough to leave on.', + ), + ); + body.append(el('h4', undefined, 'retry policy')); body.append(el('p', one.outcome === 'failed' ? 'warn' : 'dim', retryStory(one))); @@ -1440,9 +1811,12 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = if (record.status === 'error') errors += 1; } + const counts = devtools.store(); + const pending = devtools.overlays().length; + button.innerHTML = MARK; button.setAttribute('aria-label', 'Open Forge devtools'); - button.setAttribute('data-pulse', pulse(fetching, errors)); + button.setAttribute('data-pulse', pulse(fetching, errors, pending)); if (errors > 0) button.append(el('span', 'badge', String(errors))); @@ -1451,7 +1825,23 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = render(); }); - return button; + // The three numbers a glance should answer, revealed on hover so the + // resting state is still one 30px tile. `pend` appears only when there is + // something pending: a permanent `0 pend` teaches you to stop reading it. + const vitals = el('div', 'launcher-vitals'); + + vitals.append(el('b', undefined, String(counts.records)), el('span', undefined, 'ent')); + vitals.append(el('b', undefined, String(counts.mounted)), el('span', undefined, 'mnt')); + + if (pending > 0) { + vitals.append(el('b', undefined, String(pending)), el('span', undefined, 'pend')); + } + + const dock = el('div', 'launcher-dock'); + + dock.append(button, vitals); + + return dock; }; /** @@ -1563,6 +1953,96 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = return bar; }; + /** + * The counters that say whether anything is leaking. + * + * `StoreSnapshot` carries nine of these and the old header showed three of + * them as a sentence. Tombstones and stamped tags are both bounded caches, so + * a number that keeps climbing is the shape of a leak, and neither was + * visible anywhere before this. + * + * `pending` appears only when the overlay stack is non-empty. A permanent + * `0 pending` teaches you to stop reading the strip. + */ + const vitalsStrip = (): HTMLElement => { + const counts = devtools.store(); + const pending = devtools.overlays().length; + const strip = el('div', 'vitals'); + + const cell = (key: string, label: string, value: string, note?: string): void => { + const node = el('div', 'vital'); + + node.setAttribute('data-vital', key); + node.append(el('span', 'k', label)); + node.append(el('span', 'v', value)); + + if (note !== undefined) node.append(el('span', 'n', note)); + + strip.append(node); + }; + + cell('entities', 'entities', String(counts.records), `v${String(counts.version)}`); + cell('mounted', 'mounted', String(counts.mounted), `of ${String(counts.remembered)}`); + cell('store', 'store', `v${String(counts.version)}`, `f${String(counts.frameVersion)}`); + + if (pending > 0) cell('pending', 'pending', String(pending), 'writes'); + + cell('tags', 'tags', String(counts.indexedTags), `${String(counts.stampedTags)} stamped`); + cell('tombstones', 'tombstones', String(counts.tombstones)); + cell('tracked', 'tracked', String(counts.tracked)); + + return strip; + }; + + /** + * One request, drawn to scale against the slowest one on screen. + * + * Two segments, and only two, because only two are measured. The transport + * reports attempt boundaries and the backoff between them, so the wire time + * and the waiting are real numbers. It does not report when a response + * started decoding or when the store committed it, and a bar that split + * those out would be drawing a shape nobody measured. + */ + const waterfall = (one: RequestSnapshot, slowest: number): HTMLElement => { + const bar = el('div', 'wf'); + + if (one.duration === undefined) { + bar.append(el('i', 'pending')); + + return bar; + } + + const waited = one.retries.reduce((total, retry) => total + retry.delay, 0); + const wire = Math.max(0, one.duration - waited - one.authMs); + const scale = (ms: number): string => `${String((ms / slowest) * 100)}%`; + + if (one.authMs > 0) { + const auth = el('i', 'auth'); + + auth.style.width = scale(one.authMs); + auth.title = `${String(Math.round(one.authMs))}ms waiting on the credential refresh`; + bar.append(auth); + } + + const sent = el('i', 'wire'); + + sent.style.width = scale(wire); + sent.title = `${String(Math.round(wire))}ms on the wire`; + bar.append(sent); + + if (waited > 0) { + const held = el('i', 'backoff'); + + held.style.width = scale(waited); + held.title = `${String(Math.round(waited))}ms backing off across ${String( + one.retries.length, + )} retry(s)`; + bar.append(held); + } + + return bar; + }; + /** One icon button on the rail. Icon only, so the tooltip carries the name. */ const railButton = ( paths: string, @@ -1695,11 +2175,14 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = * from succeeding, so a real error or a request in flight is the more useful * thing to be told about while it is on. */ - const pulse = (fetching: boolean, errors: number): string => { + const pulse = (fetching: boolean, errors: number, pending: number): string => { const mode = devtools.controls?.mode; if (mode === 'offline') return 'offline'; if (errors > 0) return 'error'; + // A stuck optimistic write is a bug you want to see. A request in flight + // is Tuesday. So pending outranks fetching, and an error outranks both. + if (pending > 0) return 'pending'; if (fetching) return 'fetching'; if (mode === 'slow') return 'slow'; @@ -1740,6 +2223,7 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = const panel = el('div', 'panel'); panel.setAttribute('data-mode', mode); + panel.setAttribute('data-density', compact ? 'compact' : 'comfortable'); const bar = el('div', 'bar'); @@ -1801,6 +2285,19 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = bar.append(clearLog); bar.append(dockBar()); + const density = el('button', 'ico tip'); + + density.innerHTML = icon(''); + density.setAttribute('data-act', 'density'); + density.setAttribute('data-tip', 'Compact rows'); + density.setAttribute('aria-label', 'Compact rows'); + density.setAttribute('aria-pressed', String(compact)); + density.addEventListener('click', () => { + compact = !compact; + render(); + }); + bar.append(density); + const close = el('button', 'ico tip tip-r'); close.innerHTML = icon(''); @@ -1813,6 +2310,7 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = bar.append(close); const rail = controlRail(); + const vitals = vitalsStrip(); const split = el('div', 'split'); const list = el('div', 'list'); const key = selected.get(tab); @@ -1827,7 +2325,7 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = split.append(detail); } - panel.append(bar); + panel.append(bar, vitals); if (rail !== undefined) panel.append(rail); @@ -1860,12 +2358,148 @@ export function mountPanel(devtools: Devtools, options: PanelOptions = {}): () = else void Promise.resolve().then(run); }; + /** + * The shortcuts, on the document rather than on the panel. + * + * The panel lives in a shadow root and does not hold focus, so a listener + * bound inside it would only fire once you had already clicked into it, + * which is exactly when you do not need a shortcut. + * + * Nothing fires while you are typing. A devtools panel that eats a `3` out + * of its own filter box is worse than one with no shortcuts at all, so any + * event whose composed path contains an input or a textarea is left alone. + */ + const typing = (event: KeyboardEvent): boolean => { + for (const node of event.composedPath()) { + const name = (node as Partial).tagName; + + if (name === 'INPUT' || name === 'TEXTAREA') return true; + } + + return false; + }; + + const onKey = (event: KeyboardEvent): void => { + if (typing(event)) return; + + const meta = event.metaKey || event.ctrlKey; + + // Toggling the panel is the only one that works while it is closed. + if (meta && event.shiftKey && event.key.toLowerCase() === 'f') { + event.preventDefault(); + open = !open; + render(); + + return; + } + + // Jump to the filter box. The mock drew a command palette here; the filter + // box already parses `status:4xx`, `>100ms` and `tag:`, so a palette would + // be a second front door to the same room. + if (open && ((meta && event.key.toLowerCase() === 'k') || (!meta && event.key === '/'))) { + event.preventDefault(); + (root.querySelector('.bar input') as HTMLInputElement | null)?.focus(); + + return; + } + + // Pop the top of the overlay stack. Removal is the whole of rollback, so + // undo here means what undo means everywhere else in this package. + if (open && meta && event.key.toLowerCase() === 'z') { + const stack = devtools.overlays(); + const top = stack[stack.length - 1]; + + if (top === undefined) return; + + event.preventDefault(); + devtools.actions.rollback(top.id); + render(); + + return; + } + + if (open && event.key === 'F11') { + event.preventDefault(); + mode = mode === 'full' ? 'bottom' : 'full'; + render(); + + return; + } + + if (!open || meta || event.altKey) return; + + if (event.key === 'Enter') { + const picked = selected.get(tab); + + if (picked === undefined) return; + + filter = picked; + tab = 'explain'; + render(); + + return; + } + + if (event.key === 'Escape') { + if (selected.get(tab) === undefined) return; + + selected.delete(tab); + render(); + + return; + } + + const slot = Number(event.key); + + if (Number.isInteger(slot) && slot >= 1 && slot <= TABS.length) { + tab = TABS[slot - 1] as Tab; + render(); + + return; + } + + if (event.key.toLowerCase() === 'f') { + frozen = !frozen; + render(); + + return; + } + + // The two actions worth a key, and only for the row you have selected. + const picked = selected.get(tab); + + if (picked !== undefined && (tab === 'queries' || tab === 'trace')) { + if (event.key.toLowerCase() === 'r') { + void devtools.actions.refetch(picked).catch(() => undefined); + render(); + + return; + } + + if (event.key.toLowerCase() === 'i') { + devtools.actions.invalidate(picked); + render(); + + return; + } + } + + if (event.key === ' ') { + event.preventDefault(); + frozen = !frozen; + render(); + } + }; + + doc.addEventListener('keydown', onKey); + const unsubscribe = devtools.subscribe(schedule); render(); return () => { unsubscribe(); + doc.removeEventListener('keydown', onKey); host.remove(); }; } diff --git a/packages/client-devtools/src/requests.ts b/packages/client-devtools/src/requests.ts index 44c703b4f..5eec30637 100644 --- a/packages/client-devtools/src/requests.ts +++ b/packages/client-devtools/src/requests.ts @@ -49,6 +49,14 @@ export interface RequestSnapshot { * one refresh, and only the transport knows which of them asked for it. */ readonly joined: boolean; + /** + * Milliseconds spent waiting on the credential refresh. + * + * Zero for a request that never met a 401. This is what tells an auth stall + * apart from a slow server: both look like one long request from outside, + * and only this says which half of it was queueing behind a token. + */ + readonly authMs: number; } /** The mutable half, while a request is still running. */ @@ -66,6 +74,9 @@ interface Live { retries: { attempt: number; delay: number; status: number | undefined }[]; refreshes: number; joined: boolean; + authMs: number; + /** When the refresh this request is waiting on began. */ + authAt: number | undefined; } /** @@ -119,7 +130,11 @@ export class RequestLog { for (let i = 0; i < this.filled; i++) { const live = this.ring[(this.cursor + this.capacity - this.filled + i) % this.capacity]; - if (live !== undefined) out.push({ ...live, retries: [...live.retries] }); + if (live !== undefined) { + const { authAt: _at, ...snapshot } = live; + + out.push({ ...snapshot, retries: [...live.retries] }); + } } return out; @@ -149,6 +164,8 @@ export class RequestLog { retries: [], refreshes: 0, joined: false, + authMs: 0, + authAt: undefined, }); return; @@ -172,12 +189,21 @@ export class RequestLog { case 'refresh': live.refreshes += 1; + live.authAt = this.now(); // Only ever waited: one request that started a flight is not a joiner, // even if a later 401 on the same request joined one. if (live.refreshes === 1) live.joined = event.joined; else if (!event.joined) live.joined = false; break; + case 'refreshed': + if (live.authAt !== undefined) { + live.authMs += this.now() - live.authAt; + live.authAt = undefined; + } + + break; + case 'settled': live.outcome = event.ok ? 'ok' : 'failed'; live.status = event.status; diff --git a/packages/client-devtools/src/types.ts b/packages/client-devtools/src/types.ts index dac9406c7..ba4e6dd32 100644 --- a/packages/client-devtools/src/types.ts +++ b/packages/client-devtools/src/types.ts @@ -248,7 +248,17 @@ export interface PrincipalLog extends LogBase { */ export interface ActionLog extends LogBase { readonly kind: 'action'; - readonly action: 'refetch' | 'invalidate' | 'invalidateTag' | 'evict' | 'drop' | 'clear'; + readonly action: + | 'refetch' + | 'invalidate' + | 'invalidateTag' + | 'evict' + | 'drop' + | 'clear' + | 'rollback' + | 'hold' + | 'release' + | 'stale'; /** The query key, entity key or tag the action was aimed at. */ readonly target: string; }