diff --git a/landing-astro/src/pages/index.astro b/landing-astro/src/pages/index.astro index c9b97fb..e814b60 100644 --- a/landing-astro/src/pages/index.astro +++ b/landing-astro/src/pages/index.astro @@ -10,3 +10,57 @@ const content = workbenchContent.parse(json); + + diff --git a/src/worker/app-health.ts b/src/worker/app-health.ts index 1c16710..d0d7e51 100644 --- a/src/worker/app-health.ts +++ b/src/worker/app-health.ts @@ -4,7 +4,7 @@ import { type AppHealthClientOptions, } from '@saas-maker/app-health'; import { honoMiddleware } from '@saas-maker/app-health/hono'; -import type { Context, Env, MiddlewareHandler } from 'hono'; +import type { Env, MiddlewareHandler } from 'hono'; import { routePath } from 'hono/route'; import type { WorkerEnv } from '../lib/worker-env'; @@ -38,11 +38,11 @@ export function createReaderAppHealthMiddlewares( let cachedEnvironment = ''; let cachedClient: AppHealthClient | null = null; - const resolveClient = (context: Context) => { - const key = context.env.APP_HEALTH_INGEST_KEY?.trim(); + const resolveClient = (env: WorkerEnv) => { + const key = env.APP_HEALTH_INGEST_KEY?.trim(); if (!key) return null; - const environment = context.env.APP_HEALTH_ENVIRONMENT?.trim() || 'production'; + const environment = env.APP_HEALTH_ENVIRONMENT?.trim() || 'production'; if (cachedClient && cachedKey === key && cachedEnvironment === environment) { return cachedClient; } @@ -58,6 +58,15 @@ export function createReaderAppHealthMiddlewares( }); return cachedClient; }; + const recordSavedLink = (env: WorkerEnv) => { + try { + // The request middleware flushes this event with the endpoint summary. + resolveClient(env)?.log('link.saved', { level: 'debug' }); + } catch { + // A telemetry failure must never change the outcome of a saved link. + } + }; + let firstRequest = true; const coldRequests = new WeakSet(); const trackRequest = (request: Request) => { @@ -74,7 +83,7 @@ export function createReaderAppHealthMiddlewares( if (!c.env.APP_HEALTH_INGEST_KEY?.trim() || rate === 0 || Math.random() >= rate) return; const route = routePath(c, -1); if (!isSafeStageRoute(route)) return; - const client = resolveClient(c); + const client = resolveClient(c.env); if (!client) return; const colo = c.req.raw.cf?.colo; client.log('api.stage_timing', { @@ -101,8 +110,9 @@ export function createReaderAppHealthMiddlewares( }; return { - appHealthMiddleware: honoMiddleware({ client: resolveClient }), + appHealthMiddleware: honoMiddleware({ client: (c) => resolveClient(c.env) }), stageTimingMiddleware, + recordSavedLink, trackRequest, }; } @@ -110,5 +120,6 @@ export function createReaderAppHealthMiddlewares( export const { appHealthMiddleware, stageTimingMiddleware: appHealthStageTimingMiddleware, + recordSavedLink, trackRequest: trackAppHealthRequest, } = createReaderAppHealthMiddlewares(); diff --git a/src/worker/routes/__tests__/articles-access.test.ts b/src/worker/routes/__tests__/articles-access.test.ts index 4e7f365..e0c44b5 100644 --- a/src/worker/routes/__tests__/articles-access.test.ts +++ b/src/worker/routes/__tests__/articles-access.test.ts @@ -1,5 +1,7 @@ import { Hono } from 'hono'; -import { beforeEach, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, expect, it, vi } from 'vitest'; +import type { WorkerEnv } from '../../../lib/worker-env'; +import { appHealthMiddleware } from '../../app-health'; const mocks = vi.hoisted(() => ({ auth: vi.fn(), add: vi.fn(), @@ -29,7 +31,7 @@ it('rejects guest capture and reads before database access', async () => { expect(mocks.mark).not.toHaveBeenCalled(); }); it('captures URL-only links and scopes updates to the authenticated account', async () => { - mocks.add.mockResolvedValue({ id: 'one' }); + mocks.add.mockResolvedValue({ id: 'one', existing: false }); const response = await app.request('/api/links', { method: 'POST', headers: { 'Content-Type': 'application/json' }, @@ -49,3 +51,69 @@ it('captures URL-only links and scopes updates to the authenticated account', as ).toBe(404); expect(mocks.mark).toHaveBeenCalledWith('alice', 'other', true); }); + +afterEach(() => vi.unstubAllGlobals()); + +it('ships a content-free log only for new saved links through both capture paths', async () => { + const deliveries = vi + .fn() + .mockImplementation(async () => new Response(null, { status: 202 })); + vi.stubGlobal('fetch', deliveries); + const pending: Promise[] = []; + const ctx = { waitUntil: (work: Promise) => pending.push(work) } as ExecutionContext; + const env = { + APP_HEALTH_INGEST_KEY: 'fixture-ingest-key', + APP_HEALTH_ENVIRONMENT: 'test', + } as WorkerEnv; + const product = new Hono<{ Bindings: WorkerEnv }>(); + product.use('*', appHealthMiddleware); + product.route('/api/links', routes); + product.route('/api/articles', routes); + const save = (path: string, auth: Record) => + product.request( + path, + { + method: 'POST', + headers: { 'Content-Type': 'application/json', ...auth }, + body: JSON.stringify({ + url: 'https://example.test/saved-path', + title: 'Private saved title', + }), + }, + env, + ctx + ); + + mocks.add + .mockResolvedValueOnce({ id: 'browser-link', existing: false }) + .mockResolvedValueOnce({ id: 'extension-link', existing: false }) + .mockResolvedValueOnce({ id: 'extension-link', existing: true }) + .mockRejectedValueOnce(new TypeError('Invalid URL')); + + expect((await save('/api/links', { Cookie: 'session=fixture' })).status).toBe(200); + await Promise.all(pending.splice(0)); + expect((await save('/api/articles', { Authorization: 'Bearer rdr_fixture' })).status).toBe(200); + await Promise.all(pending.splice(0)); + expect(await (await save('/api/links', { Authorization: 'Bearer rdr_fixture' })).json()).toEqual({ + id: 'extension-link', + existing: true, + }); + await Promise.all(pending.splice(0)); + expect((await save('/api/links', { Cookie: 'session=fixture' })).status).toBe(400); + await Promise.all(pending.splice(0)); + mocks.auth.mockResolvedValueOnce(null); + expect((await save('/api/links', {})).status).toBe(401); + await Promise.all(pending.splice(0)); + + const batches = deliveries.mock.calls + .filter(([url]) => String(url) === 'https://ingest.sassmaker.com/v1/logs') + .map(([, request]) => JSON.parse(String(request?.body))); + expect(batches).toHaveLength(2); + const logs = batches.flatMap((batch) => batch.logs); + expect(logs).toHaveLength(2); + for (const log of logs) { + expect(log).toMatchObject({ event: 'link.saved', level: 'debug' }); + expect(log.props).toEqual({}); + expect(Object.keys(log).sort()).toEqual(['event', 'level', 'log_id', 'props', 'timestamp']); + } +}); diff --git a/src/worker/routes/articles.ts b/src/worker/routes/articles.ts index 3c48ce8..3bb4342 100644 --- a/src/worker/routes/articles.ts +++ b/src/worker/routes/articles.ts @@ -4,6 +4,7 @@ import { bodyLimit } from 'hono/body-limit'; import { getAuthenticatedUserId } from '../../lib/auth-api'; import { addLink, getLink, listLinks, setLinkRead } from '../../lib/links-db'; import type { WorkerEnv } from '../../lib/worker-env'; +import { recordSavedLink } from '../app-health'; const links = new Hono<{ Bindings: WorkerEnv; Variables: { userId: string } }>(); @@ -39,7 +40,9 @@ links.post('/', async (c) => { } try { // URL-only capture, including older extension payloads. No imports or AI calls. - return c.json(await addLink(c.get('userId'), body), 200); + const result = await addLink(c.get('userId'), body); + if (result.existing === false) recordSavedLink(c.env); + return c.json(result, 200); } catch (error) { if (error instanceof TypeError || (error instanceof Error && /URL/u.test(error.message))) { return c.json({ error: error.message }, 400); diff --git a/tests/mobile.spec.ts b/tests/mobile.spec.ts index 1630a12..786fd8e 100644 --- a/tests/mobile.spec.ts +++ b/tests/mobile.spec.ts @@ -83,3 +83,47 @@ test('landing states the narrow product and fits the viewport', async ({ page }, fullPage: true, }); }); + +test('landing sign-in reports one fixed event and keeps the ordinary navigation', async ({ + page, +}) => { + await page.addInitScript(() => { + const record = (source: string, ...args: unknown[]) => { + const value = JSON.parse(sessionStorage.getItem('qa-cta-events') ?? '[]'); + sessionStorage.setItem('qa-cta-events', JSON.stringify([...value, [source, ...args]])); + }; + Object.assign(window, { + appHealth: { + track: (...args: unknown[]) => record('app-health', ...args), + flushForNavigation: () => { + record('navigation-flush'); + return new Promise(() => {}); + }, + }, + clarity: (command: string, ...args: unknown[]) => { + if (command === 'event') record('clarity', ...args); + }, + }); + }); + await page.route('**/api/auth/get-session', (route) => route.fulfill({ json: null })); + await page.route('**/api/auth/client-config', (route) => + route.fulfill({ json: { googleClientId: null } }) + ); + await page.goto('/'); + await page + .locator('main a[href="/login"]') + .first() + .evaluate((link: HTMLAnchorElement) => { + link.click(); + link.click(); + }); + await expect(page).toHaveURL(/\/login$/); + await expect(page.getByRole('button', { name: 'Sign in with Google' })).toBeVisible(); + expect( + await page.evaluate(() => JSON.parse(sessionStorage.getItem('qa-cta-events') ?? '[]')) + ).toEqual([ + ['app-health', 'sign_in_opened'], + ['clarity', 'sign_in_opened'], + ['navigation-flush'], + ]); +});