From 3ca7f8fb7e68381eca0169c817a326400512330b Mon Sep 17 00:00:00 2001 From: Jessica Winters <10160557+Jesswinters@users.noreply.github.com> Date: Fri, 13 Nov 2026 16:52:40 +0000 Subject: [PATCH 1/2] feat(docs-next): send a HockeyStack goal for each docs search The docs search is a dialog, not a form submit, so HockeyStack cannot see what readers search for on its own. Both search dialogs now send the `Docs Search` goal with the trimmed term as `search_term`, once per search: after typing pauses for a second, or at once when a result is selected, and never twice for the same term. Empty searches send nothing, and the call is skipped until the HockeyStack tag has loaded. Assisted-by: AI --- ARCHITECTURE.md | 1 + packages/docs-next/src/hybrid-search.test.tsx | 41 +++++++++++++++++++ packages/docs-next/src/hybrid-search.tsx | 10 ++++- packages/docs-next/src/search-analytics.ts | 33 +++++++++++++++ packages/docs-next/src/search-dialog.test.tsx | 38 +++++++++++++++++ packages/docs-next/src/search-dialog.tsx | 7 +++- packages/docs-next/test/hockeystack.ts | 11 +++++ 7 files changed, 139 insertions(+), 2 deletions(-) create mode 100644 packages/docs-next/src/search-analytics.ts create mode 100644 packages/docs-next/test/hockeystack.ts diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 2f7e1e32..5ea397ab 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -216,6 +216,7 @@ With `DOCS_ANALYTICS` on (coder.com's consent manager and tag manager, `apps/doc Each vendor is named by origin except jsDelivr, a public CDN for any npm package, which is named only by the one package directory its tag loads (`https://cdn.jsdelivr.net/npm/hockeystack@latest/`). The router applies that policy to archive responses when its own `DOCS_ANALYTICS` is on; `apps/docs/vercel.json`, which cannot vary by environment, keeps the policy above. Widening `script-src` this way is a security decision and needs sign-off before the flag is turned on anywhere. +Both search dialogs send HockeyStack's `Docs Search` goal with a `search_term` property, once per trimmed, non-empty search (after a 1-second pause in typing, or at once when a result is selected), through `useSearchGoal` in `packages/docs-next/src/search-analytics.ts`; it is a no-op until the tag has loaded, and the goal and property names must match the goal set up in HockeyStack. Hardening path, not yet taken: the inline scripts in a static export are fixed at build time, so `csp:check` could emit their SHA-256 hashes and the policy could name them in place of `'unsafe-inline'`. That makes the policy a real barrier to injected inline scripts at the cost of regenerating the header on every build and keeping the router's archive headers in step per version. diff --git a/packages/docs-next/src/hybrid-search.test.tsx b/packages/docs-next/src/hybrid-search.test.tsx index 9679ae6d..4d7301ad 100644 --- a/packages/docs-next/src/hybrid-search.test.tsx +++ b/packages/docs-next/src/hybrid-search.test.tsx @@ -5,8 +5,10 @@ import { FrameworkProvider } from "fumadocs-core/framework"; import { type MetaData, type VirtualFile, loader } from "fumadocs-core/source"; import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; +import { stubHockeyStack } from "../test/hockeystack.js"; import { CORPUS_PARAGRAPHS, FORBIDDEN_ELEMENTS } from "../test/search-xss.js"; import HybridSearchDialog, { hybridSearchClient, preloadSemanticIndex } from "./hybrid-search.js"; +import { SEARCH_GOAL_DELAY_MS } from "./search-analytics.js"; import { createDocsSearchRoute } from "./search.js"; import type { DocsPageData } from "./types.js"; @@ -138,3 +140,42 @@ test("the hybrid dialog renders corpus-shaped hits as text and still highlights assert.equal(dialog?.querySelector(FORBIDDEN_ELEMENTS), null); assert.equal(document.head.querySelector("meta[http-equiv]"), null); }); + +test("the hybrid dialog sends one HockeyStack goal per settled search", async (t) => { + serve({ "/api/search": await corpusIndex() }); + const goals = stubHockeyStack(t); + const warn = console.warn; + console.warn = () => {}; + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + t.after(async () => { + console.warn = warn; + await act(async () => root.unmount()); + container.remove(); + }); + await act(async () => { + root.render( + "/"} + useRouter={() => ({ push() {}, replace() {}, refresh() {}, prefetch() {} }) as never} + useParams={() => ({})} + > + {}} /> + , + ); + }); + const input = document.querySelector('[role="dialog"] input'); + assert.ok(input, "expected the search input to render"); + for (const value of ["w", "work", "workspace"]) { + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, value); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + } + assert.deepEqual(goals, []); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, SEARCH_GOAL_DELAY_MS + 100)); + }); + assert.deepEqual(goals, [["Docs Search", { search_term: "workspace" }]]); +}); diff --git a/packages/docs-next/src/hybrid-search.tsx b/packages/docs-next/src/hybrid-search.tsx index ac84d6f5..d151fcc2 100644 --- a/packages/docs-next/src/hybrid-search.tsx +++ b/packages/docs-next/src/hybrid-search.tsx @@ -14,6 +14,7 @@ import { } from "fumadocs-ui/components/dialog/search"; import type { SharedProps } from "fumadocs-ui/contexts/search"; import { type ComponentProps, useEffect, useMemo, useState } from "react"; +import { useSearchGoal } from "./search-analytics.js"; import { SearchResultItem } from "./search-markdown.js"; import { type SemanticIndex, @@ -105,8 +106,15 @@ export default function HybridSearchDialog({ // Re-run the current query once the semantic index arrives. const deps = useMemo(() => [client, loaded], [client, loaded]); const { search, setSearch, query } = useDocsSearch({ client }, deps); + const sendSearchGoal = useSearchGoal(search); return ( - + diff --git a/packages/docs-next/src/search-analytics.ts b/packages/docs-next/src/search-analytics.ts new file mode 100644 index 00000000..4b6d2b58 --- /dev/null +++ b/packages/docs-next/src/search-analytics.ts @@ -0,0 +1,33 @@ +import { useCallback, useEffect, useRef } from "react"; + +declare global { + interface Window { + HockeyStack?: { goal(name: string, properties: Record): void }; + } +} + +export const SEARCH_GOAL_DELAY_MS = 1000; + +/** + * Sends the HockeyStack `Docs Search` goal once per search: when typing has + * paused for `SEARCH_GOAL_DELAY_MS`, or at once through the returned callback + * when a result is selected, and never twice for the same trimmed term. + */ +export function useSearchGoal(search: string): () => void { + const sent = useRef(""); + const send = useCallback(() => { + const term = search.trim(); + if (!term || term === sent.current) return; + sent.current = term; + if (window.HockeyStack) window.HockeyStack.goal("Docs Search", { search_term: term }); + }, [search]); + useEffect(() => { + if (!search.trim()) { + sent.current = ""; + return; + } + const timer = setTimeout(send, SEARCH_GOAL_DELAY_MS); + return () => clearTimeout(timer); + }, [search, send]); + return send; +} diff --git a/packages/docs-next/src/search-dialog.test.tsx b/packages/docs-next/src/search-dialog.test.tsx index f7be5e41..61b5e557 100644 --- a/packages/docs-next/src/search-dialog.test.tsx +++ b/packages/docs-next/src/search-dialog.test.tsx @@ -4,7 +4,9 @@ import { FrameworkProvider } from "fumadocs-core/framework"; import type { SearchItemType } from "fumadocs-ui/components/dialog/search"; import { act } from "react"; import { createRoot } from "react-dom/client"; +import { stubHockeyStack } from "../test/hockeystack.js"; import { FORBIDDEN_ELEMENTS, highlightedIndexTexts } from "../test/search-xss.js"; +import { SEARCH_GOAL_DELAY_MS } from "./search-analytics.js"; import { ComboboxSearchDialog } from "./search-dialog.js"; const ITEMS: SearchItemType[] = [ @@ -283,3 +285,39 @@ test("a benign hit still highlights the matched word", async (t) => { const mark = document.querySelector('[role="option"] span.text-fd-primary'); assert.equal(mark?.textContent, "workspace"); }); + +test("a search sends one HockeyStack goal with the trimmed term once typing settles", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, ITEMS, { search: "p" }); + await render({ search: "pro" }); + await render({ search: " proxy " }); + assert.deepEqual(goals, []); + await wait(SEARCH_GOAL_DELAY_MS + 100); + assert.deepEqual(goals, [["Docs Search", { search_term: "proxy" }]]); + await render({ search: "proxy", items: [] }); + await wait(SEARCH_GOAL_DELAY_MS + 100); + assert.equal(goals.length, 1, "a re-render with the same term sends nothing"); +}); + +test("selecting a result sends the goal at once and not again when the delay ends", async (t) => { + const goals = stubHockeyStack(t); + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + assert.deepEqual(goals, [["Docs Search", { search_term: "proxy" }]]); + await wait(SEARCH_GOAL_DELAY_MS + 100); + assert.equal(goals.length, 1); +}); + +test("an empty or whitespace-only search sends no goal", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, null, { search: "" }); + await render({ search: " " }); + await wait(SEARCH_GOAL_DELAY_MS + 100); + assert.deepEqual(goals, []); +}); + +test("a search before HockeyStack has loaded does not throw", async (t) => { + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + await wait(SEARCH_GOAL_DELAY_MS + 100); +}); diff --git a/packages/docs-next/src/search-dialog.tsx b/packages/docs-next/src/search-dialog.tsx index 729300dd..c378ba09 100644 --- a/packages/docs-next/src/search-dialog.tsx +++ b/packages/docs-next/src/search-dialog.tsx @@ -27,6 +27,7 @@ import { useState, } from "react"; import { focusAfterNavigation, returnFocusTo } from "./return-focus.js"; +import { useSearchGoal } from "./search-analytics.js"; import { SearchResultItem } from "./search-markdown.js"; const ActiveOptionContext = createContext<(id: string | null) => void>(() => {}); @@ -185,6 +186,7 @@ export function ComboboxSearchDialog({ const listId = useId(); const returnFocus = useReturnFocus(); const { onSelect, ...contentProps } = returnFocus; + const sendSearchGoal = useSearchGoal(search); const [activeOption, setActiveOption] = useState(null); const expanded = items !== null && items.length > 0; return ( @@ -194,7 +196,10 @@ export function ComboboxSearchDialog({ search={search} onSearchChange={onSearchChange} isLoading={isLoading} - onSelect={onSelect} + onSelect={(item) => { + sendSearchGoal(); + onSelect(item); + }} > diff --git a/packages/docs-next/test/hockeystack.ts b/packages/docs-next/test/hockeystack.ts new file mode 100644 index 00000000..f52403c9 --- /dev/null +++ b/packages/docs-next/test/hockeystack.ts @@ -0,0 +1,11 @@ +import type { TestContext } from "node:test"; + +/** Stubs `window.HockeyStack` for one test and returns the goals it records. */ +export function stubHockeyStack(t: TestContext) { + const goals: [string, Record][] = []; + window.HockeyStack = { goal: (name, properties) => goals.push([name, properties]) }; + t.after(() => { + delete window.HockeyStack; + }); + return goals; +} From 86da17dda9424e09ae34075171a462f6b7888367 Mon Sep 17 00:00:00 2001 From: Nick Vigilante Date: Tue, 24 Nov 2026 22:32:55 +0000 Subject: [PATCH 2/2] feat(docs-next): send the search goal only for safe, consented, completed searches The goal sent every typed term to HockeyStack, where it is visible and exportable, so pasted tokens, emails and logs could leave the reader's browser. It now sends a term only while the dialog is open, once the term has results, when it passes one shared filter (no run of 20 or more characters without spaces, no email, at most 100 characters, never truncated), and when Osano reports analytics consent as ACCEPT, failing closed otherwise. The filter runs on every send, because the debounce sends slowly typed terms as growing prefixes. The call is guarded against a HockeyStack tag of another shape, and a dismissed search clears its pending send. Assisted-by: AI --- ARCHITECTURE.md | 55 +++++- packages/docs-next/src/hybrid-search.test.tsx | 64 ++++++- packages/docs-next/src/hybrid-search.tsx | 4 +- .../docs-next/src/search-analytics.test.ts | 36 ++++ packages/docs-next/src/search-analytics.ts | 62 +++++-- packages/docs-next/src/search-dialog.test.tsx | 161 +++++++++++++++++- packages/docs-next/src/search-dialog.tsx | 7 +- packages/docs-next/test/hockeystack.ts | 24 ++- 8 files changed, 386 insertions(+), 27 deletions(-) create mode 100644 packages/docs-next/src/search-analytics.test.ts diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 5ea397ab..9c545add 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -8,7 +8,7 @@ Refer to the package READMEs for per-package detail. Documentation content lives in [`coder/coder`](https://github.com/coder/coder) under `docs/`. This repository is the engine that renders that content: the sync, the remark/rehype transforms, the theme, the UI components, and the Next.js adapter. The engine is implemented as eight `@coder/*` packages in a pnpm + Turborepo monorepo. -The engine holds no content of its own, and nothing here is published to npm; compiled releases go only to `coder/docs-engine-dist` (see [Public releases](#public-releases-2026-10-08)). +The engine holds no content of its own, and nothing here is published to npm; compiled releases go only to this repository's GitHub Releases (see [Public releases](#public-releases-2026-10-08)). ## Package graph @@ -37,8 +37,8 @@ docs-ui ────► docs-config docs-theme (no dependencies) - `@coder/docs-config` is the root contract package and depends on no other workspace package. - `@coder/docs-sources` depends on `docs-config`. - `@coder/docs-transforms` depends on `docs-config` (for the `Manifest` and `DocSource` contracts its pure transforms consume, and the `StaticDocsRenderContext` a static compile resolves the `premium` condition against). -- `@coder/docs-build` depends on `docs-config` and `docs-transforms`. -- `@coder/docs-next` depends on `docs-config`, `docs-ui`, and the dependency-free `version-segment` subpath of `docs-manifest`. +- `@coder/docs-build` depends on `docs-config`, `docs-transforms`, and the `version-segment` subpath of `docs-manifest` (for `isLineAtLeast`, which picks the versions that render the generated REST API reference); its external base for that reference is `swagger2openapi` and `oas-validator`. +- `@coder/docs-next` depends on `docs-config`, `docs-ui`, and the dependency-free `version-segment` subpath of `docs-manifest`; its `openapi` subpath renders the REST API reference with `fumadocs-openapi`. - `@coder/docs-ui` depends on the zod-free `client` subpath of `docs-config` for the `DocsRenderContext` its runtime `Premium`/`Experimental` annotation components read (loading the zod parser only when a fetched context arrives), and on the `version-segment` subpath of `docs-manifest` for the runtime version switcher's links; its external base is `fumadocs-ui`. - `@coder/docs-theme` depends on nothing; it ships plain CSS. - `@coder/docs-manifest` depends on `docs-config` only. @@ -89,6 +89,7 @@ A checked-in site table, `apps/docs/scripts/publish/sites.mjs`, holds each site' The table has room for more than one site, but a publish never fans out to several (`apps/docs/README.md`, "Publishing sites"). The table is checked in rather than kept in variables because the `build` job binds no environment and could read only repository-level values, one per repository. An hourly reconciler compares coder/coder's refs against the manifest and dispatches a publish for any ref that is missing or whose docs content has actually fallen behind, while only ever reporting, never automatically rebuilding, a moved tag, an orphan manifest entry, or engine drift, in one tracking GitHub issue. +The mainline also carries the code-server docs under `code-server/`, from a pinned code-server commit (refer to "code-server docs" below). ### In-product docs @@ -132,6 +133,7 @@ Keeping every subword piece and the first 5,000 or more vocabulary rows as well One version of the docs flows through four stages: 1. **Provider.** A `VersionsProvider` from `@coder/docs-sources` loads the version into a `DocSource`: raw `.md` files, the `manifest.json` sidebar model, resolved images, and optional redirects. + For a version that renders the generated REST API reference, the sync scripts then rewrite that `DocSource` before syncing it (refer to "The REST API reference" below). 2. **Sync.** `syncDocSource` (`@coder/docs-build`) validates the source (dead links, broken images, route collisions, stale manifest entries) and writes a Fumadocs content tree: `.md` files with injected frontmatter, rewritten links and image paths, per-directory `meta.json`, and copied images. Only pages named by the manifest are emitted. 3. **Compile.** `fumadocs-mdx` compiles the synced tree using `createCoderMdxOptions({ renderContext, linkPrefix })` (`@coder/docs-transforms/mdx-config`), of which `coderMdxOptions` is the default instance (no static context, no link prefix — the in-product runtime pipeline): the Coder remark stack (GitHub callouts, Coder tabs, `
` accordions, steps), then `rehype-raw` to reparse the corpus's raw HTML, then the sanitizer, then Shiki highlighting with a fallback language for unbundled fences. @@ -143,6 +145,27 @@ This design rests on a `.md`-only precondition: the sync emits only `.md` files, Emitting `.mdx` would let corpus content execute at compile time and bypass the sanitizer entirely. Refer to "Security: the corpus is untrusted" in the `@coder/docs-transforms` README for the full invariant. +### The REST API reference + +From 2.24 on, and on `main`, the REST API reference is built from coder/coder's Swagger 2.0 document rather than from the Markdown pages its generator writes. +`rendersOpenApi` (`@coder/docs-build`) picks those versions; `OPENAPI_MIN_LINE` is the oldest line, since older documents repeat operation ids. +`DOCS_OPENAPI` set to `0`, `false`, `off` or `no` keeps the Markdown reference for every version, and is the rollback; any value that is not an off or on spelling fails the sync. + +The Swagger document is read from the checkout the docs come from, never fetched. +Both `@coder/docs-sources` providers, given `apiDocument: SWAGGER_PATH`, read `coderd/apidoc/swagger.json` onto the version's `DocSource` as `apiDocument`. +The local tree provider reads it beside the `docs/` tree, so every checkout a sync runs on, the publisher's and the preview's sparse ones included, has to hold `coderd/apidoc` as well as `docs`; the git provider reads it from the worktree it loads the version's docs from, so both come from one commit resolution. +A version with no Swagger document keeps its Markdown reference with a warning, except when `DOCS_PUBLISH=1`, where the sync fails, so a publish never ships the old reference for a version that should have the new one. + +`withOpenApiReference` rewrites the version's `DocSource` before `syncDocSource` sees it: `applyOpenApiReference` converts the document to OpenAPI 3, adds one Markdown stub page per operation under its tag, turns each tag page and the schemas page into lists of links, and adds the setup section to the landing page. +Each stub carries `_openapi: { method }` in its frontmatter; the sync validates that shape and keeps it, and fumadocs-openapi's loader plugin reads it to draw the sidebar's method badge. +It also writes the version's reference data, the converted document plus the route of every operation page, the old anchors, the landing cards and the schema rows, to `.generated/openapi/.json` (`docs.json` in the single-version offline export), which the app reads at render time so the document stays out of the server bundle. +A generated page whose path or route another page already has fails the sync. + +The page route factories take a `renderBody` hook, which may replace a page's compiled Markdown body, add after it, widen it, or extend its table of contents. +`createOpenApiRenderBody` (`@coder/docs-next/openapi`) is that hook for the reference: an operation page renders through fumadocs-openapi from the document pruned to that operation and what it reaches, with code samples built on the server; the tag and schemas pages add a client redirect from the old single-page anchors; the landing page adds its cards. +fumadocs-openapi's API playground never ships: `withoutOpenApiPlayground` (`@coder/docs-next/next-config`) wraps the Next config of `apps/docs` and `apps/offlinedocs` and replaces the playground, its OAuth flows and fetcher, and the server proxy with inert stubs in every bundle, and `playground:check` fails a build whose JavaScript still holds that code. +Every `$ref` must be in-document (`#/...`) at three points, the Swagger document, the converted document, and the renderer's input, because fumadocs-openapi's bundler fetches or reads any other reference. + ## Design decisions These seams are decided and recorded, but not all are implemented yet. @@ -216,7 +239,12 @@ With `DOCS_ANALYTICS` on (coder.com's consent manager and tag manager, `apps/doc Each vendor is named by origin except jsDelivr, a public CDN for any npm package, which is named only by the one package directory its tag loads (`https://cdn.jsdelivr.net/npm/hockeystack@latest/`). The router applies that policy to archive responses when its own `DOCS_ANALYTICS` is on; `apps/docs/vercel.json`, which cannot vary by environment, keeps the policy above. Widening `script-src` this way is a security decision and needs sign-off before the flag is turned on anywhere. -Both search dialogs send HockeyStack's `Docs Search` goal with a `search_term` property, once per trimmed, non-empty search (after a 1-second pause in typing, or at once when a result is selected), through `useSearchGoal` in `packages/docs-next/src/search-analytics.ts`; it is a no-op until the tag has loaded, and the goal and property names must match the goal set up in HockeyStack. +Both search dialogs send HockeyStack's `Docs Search` goal with a `search_term` property, through `useSearchGoal` in `packages/docs-next/src/search-analytics.ts`. +It sends a term once, after a 1-second pause in typing or at once when a result is selected, and only while the dialog is open, for a term that returned at least one result, and when the reader has accepted analytics consent (`window.Osano.cm.getConsent().ANALYTICS === "ACCEPT"`, failing closed on anything else). +`searchGoalTerm` drops a term that is empty, longer than 100 characters, contains a run of 20 or more characters without spaces, or contains an email address, and it runs on every send, so a slowly typed term stops going out once it takes a secret's shape; it never truncates. +The call is a no-op until the tag has loaded, and a tag of another shape or one that throws is ignored. +The Osano API shape is only what the consent bootstrap in `packages/docs-config/src/analytics.ts` already reads; it has not been checked against Osano's documentation. +The goal and property names must match the goal set up in HockeyStack. Hardening path, not yet taken: the inline scripts in a static export are fixed at build time, so `csp:check` could emit their SHA-256 hashes and the policy could name them in place of `'unsafe-inline'`. That makes the policy a real barrier to injected inline scripts at the cost of regenerating the header on every build and keeping the router's archive headers in step per version. @@ -235,11 +263,28 @@ Older refs carry a static table between `RELEASE_CALENDAR_START/END` comments; t ### Public releases (2026-10-08) -The compiled `@coder/*` packages are published only as GitHub release assets on the public repository `coder/docs-engine-dist`, never to the npm registry, and the source stays in this private repository. +The compiled `@coder/*` packages and the offline-docs builder kit are published only as GitHub release assets on this repository, never to the npm registry. +A `v*` tag runs `release-dist.yml`, which builds packages, never an offline export; coder/coder's `offlinedocs/` pins the asset URLs in its `package.json`. +The publish job creates the release with its own `GITHUB_TOKEN`, scoped to `contents: write` in that job only, in the `docs-dist` environment. +While this repository was private, releases targeted a separate public repository, `coder/docs-engine-dist`, through a GitHub App; it never published a release. `apps/dist-release` packs them: every packed manifest keeps `"private": true`, so an accidental `npm publish` is refused. Each `@coder/*` dependency in a packed manifest is pinned to the exact URL of the same release's asset, never a version range, so pnpm never looks for an `@coder/docs-*` name on the registry. The design and Security's requirements are in `docs/superpowers/specs/2026-09-30-public-dist-releases-design.md`. +### code-server docs (2026-11-16) + +The code-server docs, from `docs/` of coder/code-server, are a second source of the mainline build only, served unversioned under `code-server/`. +They are not snapshotted into every Coder version: code-server releases on its own schedule, so a copy frozen into each Coder line and tag would show docs unrelated to that Coder release, and a tag is never rebuilt, so a code-server fix could never reach it. +The router redirects the old versioned code-server URLs to the unversioned pages. + +The mainline syncs a pinned commit, `apps/docs/code-server-docs.json`, rather than code-server's `main`. +The tree builds with the mainline's strictness, so a defect pushed to code-server would otherwise fail the next Coder publish, and the pin means no code-server change reaches readers without a review in this repository. +A bump is a reviewed pull request; it is not automated, because a pull request opened with the job token runs no CI. +A change to only the pin republishes the mainline alone, the one version that carries the code-server docs. + +Freshness is reported, not enforced: the hourly reconciler compares the pinned commit's `docs/` tree with code-server's `main` by the same content id it uses for a release line, and keeps its own `code-server-pin-behind` issue open while the pin is behind, apart from the drift issue, because the pin is behind after most code-server releases and an open drift issue whose body is only edited notifies nobody of a new moved tag or orphan. +CI checks a bump before it merges: the pinned commit must be fetchable and on code-server's `main`, and its `docs/` must pass a strict sync. + ## Open decisions - Search index shape for the multi-version site. diff --git a/packages/docs-next/src/hybrid-search.test.tsx b/packages/docs-next/src/hybrid-search.test.tsx index 9f92cdea..8c903d12 100644 --- a/packages/docs-next/src/hybrid-search.test.tsx +++ b/packages/docs-next/src/hybrid-search.test.tsx @@ -1,12 +1,14 @@ import assert from "node:assert/strict"; -import { afterEach, test } from "node:test"; +import { type TestContext, afterEach, test } from "node:test"; import type { SortedResult } from "fumadocs-core/search"; import { FrameworkProvider } from "fumadocs-core/framework"; import { type MetaData, type VirtualFile, loader } from "fumadocs-core/source"; import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; +import { stubHockeyStack } from "../test/hockeystack.js"; import { CORPUS_PARAGRAPHS, FORBIDDEN_ELEMENTS } from "../test/search-xss.js"; import HybridSearchDialog, { hybridSearchClient, preloadSemanticIndex } from "./hybrid-search.js"; +import { SEARCH_GOAL_DELAY_MS } from "./search-analytics.js"; import { createDocsSearchRoute } from "./search.js"; import type { DocsPageData } from "./types.js"; @@ -191,3 +193,63 @@ test("search keeps keyword and semantic hits to the product it is given", async assert.deepEqual(await pages("coder"), ["/install"], `semantic: ${semantic}`); } }); + +async function typeInto(t: TestContext, terms: string[], closeAfterTyping = false) { + serve({ "/api/search": await corpusIndex() }); + const warn = console.warn; + console.warn = () => {}; + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + t.after(async () => { + console.warn = warn; + await act(async () => root.unmount()); + container.remove(); + }); + const render = (open: boolean) => + act(async () => { + root.render( + "/"} + useRouter={() => ({ push() {}, replace() {}, refresh() {}, prefetch() {} }) as never} + useParams={() => ({})} + > + {}} /> + , + ); + }); + await render(true); + const input = document.querySelector('[role="dialog"] input'); + assert.ok(input, "expected the search input to render"); + for (const value of terms) { + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, value); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + } + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 300)); + }); + if (closeAfterTyping) await render(false); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, SEARCH_GOAL_DELAY_MS + 100)); + }); +} + +test("the hybrid dialog sends one HockeyStack goal for a settled search that has results", async (t) => { + const goals = stubHockeyStack(t); + await typeInto(t, ["w", "work", "workspace"]); + assert.deepEqual(goals, [["Docs Search", { search_term: "workspace" }]]); +}); + +test("the hybrid dialog sends no goal for a search with no results", async (t) => { + const goals = stubHockeyStack(t); + await typeInto(t, ["qzxqzx"]); + assert.deepEqual(goals, []); +}); + +test("the hybrid dialog sends no goal for a search dismissed before the delay ends", async (t) => { + const goals = stubHockeyStack(t); + await typeInto(t, ["workspace"], true); + assert.deepEqual(goals, []); +}); diff --git a/packages/docs-next/src/hybrid-search.tsx b/packages/docs-next/src/hybrid-search.tsx index 87c88909..06114697 100644 --- a/packages/docs-next/src/hybrid-search.tsx +++ b/packages/docs-next/src/hybrid-search.tsx @@ -14,6 +14,7 @@ import { } from "fumadocs-ui/components/dialog/search"; import type { SharedProps } from "fumadocs-ui/contexts/search"; import { useCallback, useEffect, useMemo, useState } from "react"; +import { useSearchGoal } from "./search-analytics.js"; import { SearchResultItem, renderSearchTable, useActiveProduct } from "./search-markdown.js"; import { type SemanticIndex, @@ -113,8 +114,9 @@ export default function HybridSearchDialog({ // oxlint-disable-next-line react-hooks/exhaustive-deps -- `loaded` re-runs the current query once the semantic index arrives. const run = useCallback((query: string) => client.search(query), [client, loaded]); const search = experimental_useSearch(run); + const sendSearchGoal = useSearchGoal(search.search, props.open, search.data); return ( - + diff --git a/packages/docs-next/src/search-analytics.test.ts b/packages/docs-next/src/search-analytics.test.ts new file mode 100644 index 00000000..8954da57 --- /dev/null +++ b/packages/docs-next/src/search-analytics.test.ts @@ -0,0 +1,36 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { searchGoalTerm } from "./search-analytics.js"; + +test("an ordinary term is trimmed and kept", () => { + assert.equal(searchGoalTerm(" workspace proxy "), "workspace proxy"); +}); + +test("an empty or whitespace-only term is dropped", () => { + assert.equal(searchGoalTerm(""), null); + assert.equal(searchGoalTerm(" "), null); +}); + +test("a token-shaped run of 20 or more characters is dropped", () => { + assert.equal(searchGoalTerm("coder_session_AbCdEf0123456789xyz"), null); + assert.equal(searchGoalTerm("a".repeat(20)), null); + assert.equal(searchGoalTerm("token a1b2c3d4e5f6g7h8i9j0"), null); + assert.equal(searchGoalTerm("workspace-proxy-configuration"), null); + assert.equal(searchGoalTerm("a".repeat(19)), "a".repeat(19)); +}); + +test("an email address is dropped", () => { + assert.equal(searchGoalTerm("jo@example.com"), null); + assert.equal(searchGoalTerm("reset password for jo@example.com"), null); +}); + +test("a term over 100 characters is dropped and never truncated", () => { + const spaced = "a b ".repeat(26).trim(); + assert.equal(spaced.length, 103); + assert.equal(searchGoalTerm(spaced), null); + assert.equal(searchGoalTerm(spaced.slice(0, 100).trim())?.length, 99); + const exact = `${"ab ".repeat(33)}a`; + assert.equal(exact.length, 100); + assert.equal(searchGoalTerm(exact), exact); + assert.equal(searchGoalTerm(`${exact}b`), null); +}); diff --git a/packages/docs-next/src/search-analytics.ts b/packages/docs-next/src/search-analytics.ts index 4b6d2b58..0979874d 100644 --- a/packages/docs-next/src/search-analytics.ts +++ b/packages/docs-next/src/search-analytics.ts @@ -1,33 +1,67 @@ +import type { SearchResult } from "fumadocs-core/search/client"; import { useCallback, useEffect, useRef } from "react"; declare global { interface Window { - HockeyStack?: { goal(name: string, properties: Record): void }; + HockeyStack?: { goal?: unknown }; + Osano?: { cm?: { getConsent?: () => unknown } }; } } export const SEARCH_GOAL_DELAY_MS = 1000; +const MAX_TERM_LENGTH = 100; +const SECRET_SHAPED = /[A-Za-z0-9_\-.+/=]{20,}/; +const EMAIL_SHAPED = /\S+@\S+\.\S+/; + +/** The trimmed term when it is safe to send to HockeyStack, else null. */ +export function searchGoalTerm(search: string): string | null { + const term = search.trim(); + if (!term || term.length > MAX_TERM_LENGTH) return null; + if (SECRET_SHAPED.test(term) || EMAIL_SHAPED.test(term)) return null; + return term; +} + +// The Osano API shape is only what the consent bootstrap in docs-config already reads. +function analyticsAccepted(): boolean { + const consent: unknown = window.Osano?.cm?.getConsent?.(); + return ( + typeof consent === "object" && + consent !== null && + "ANALYTICS" in consent && + consent.ANALYTICS === "ACCEPT" + ); +} + +function sendGoal(term: string): void { + try { + if (!analyticsAccepted()) return; + const goal = window.HockeyStack?.goal; + if (typeof goal !== "function") return; + goal.call(window.HockeyStack, "Docs Search", { search_term: term }); + } catch { + // A tag that changed shape must not break the dialog. + } +} /** - * Sends the HockeyStack `Docs Search` goal once per search: when typing has - * paused for `SEARCH_GOAL_DELAY_MS`, or at once through the returned callback - * when a result is selected, and never twice for the same trimmed term. + * Sends the HockeyStack `Docs Search` goal once per search that is open, has + * results for the current term and passes `searchGoalTerm`, when typing has + * paused for `SEARCH_GOAL_DELAY_MS` or at once through the returned callback. */ -export function useSearchGoal(search: string): () => void { +export function useSearchGoal(search: string, open: boolean, data: SearchResult | undefined) { const sent = useRef(""); + const settled = open && data?.query === search && data.items.length > 0; + const term = settled ? searchGoalTerm(search) : null; const send = useCallback(() => { - const term = search.trim(); - if (!term || term === sent.current) return; + if (term === null || term === sent.current) return; sent.current = term; - if (window.HockeyStack) window.HockeyStack.goal("Docs Search", { search_term: term }); - }, [search]); + sendGoal(term); + }, [term]); useEffect(() => { - if (!search.trim()) { - sent.current = ""; - return; - } + if (!open || !search.trim()) sent.current = ""; + if (term === null) return; const timer = setTimeout(send, SEARCH_GOAL_DELAY_MS); return () => clearTimeout(timer); - }, [search, send]); + }, [open, search, term, send]); return send; } diff --git a/packages/docs-next/src/search-dialog.test.tsx b/packages/docs-next/src/search-dialog.test.tsx index 3874f99c..f0812cd7 100644 --- a/packages/docs-next/src/search-dialog.test.tsx +++ b/packages/docs-next/src/search-dialog.test.tsx @@ -9,9 +9,11 @@ import type { import { loader } from "fumadocs-core/source"; import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; +import { stubHockeyStack } from "../test/hockeystack.js"; import { FORBIDDEN_ELEMENTS, corpusIndexTexts } from "../test/search-xss.js"; import { SearchDialog } from "fumadocs-ui/components/dialog/search"; import DocsSearchDialog, { SearchDialogView } from "./search-dialog.js"; +import { SEARCH_GOAL_DELAY_MS } from "./search-analytics.js"; import { createDocsSearchRoute } from "./search.js"; import { SearchResultItem as DocsSearchResultItem } from "./search-markdown.js"; @@ -34,6 +36,7 @@ const ITEMS = [ type DialogProps = Partial[0], "data">> & { items?: SearchResultItem[] | null; + dataQuery?: string; }; function toData(items: DialogProps["items"], query = "proxy"): SearchResult | undefined { @@ -71,7 +74,10 @@ async function mount(t: TestContext, items: DialogProps["items"], props: DialogP onSearchChange={() => {}} {...props} {...next} - data={toData("items" in next ? next.items : items, next.search ?? props.search)} + data={toData( + "items" in next ? next.items : items, + next.dataQuery ?? next.search ?? props.dataQuery ?? props.search, + )} /> , ); @@ -469,3 +475,156 @@ for (const [pathname, expected] of [ assert.deepEqual(names(), expected); }); } + +const settle = () => wait(SEARCH_GOAL_DELAY_MS + 100); +const GOAL = ["Docs Search", { search_term: "proxy" }]; + +test("Docs Search goal: a term with results is sent once, trimmed, after typing settles", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, ITEMS, { search: "p" }); + await render({ search: "pro" }); + await render({ search: " proxy " }); + assert.deepEqual(goals, []); + await settle(); + assert.deepEqual(goals, [GOAL]); + await render({ search: "proxy" }); + await settle(); + assert.equal(goals.length, 1, "a re-render with the same term sends nothing"); +}); + +test("Docs Search goal: selecting a result sends the goal at once and not again when the delay ends", async (t) => { + const goals = stubHockeyStack(t); + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + assert.deepEqual(goals, [GOAL]); + await settle(); + assert.equal(goals.length, 1); +}); + +test("Docs Search goal: a search with no results sends nothing", async (t) => { + const goals = stubHockeyStack(t); + await mount(t, [], { search: "proxy" }); + await settle(); + assert.deepEqual(goals, []); +}); + +test("Docs Search goal: results for an earlier term do not send the current one", async (t) => { + const goals = stubHockeyStack(t); + await mount(t, ITEMS, { search: "proxy", dataQuery: "pro" }); + await press("Enter"); + await settle(); + assert.deepEqual(goals, []); +}); + +test("Docs Search goal: an empty or whitespace-only search sends nothing", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, null, { search: "" }); + await render({ search: " " }); + await settle(); + assert.deepEqual(goals, []); +}); + +for (const [name, term] of [ + ["a token-shaped term", "coder_session_AbCdEf0123456789xyz"], + ["an email address", "who is jo@example.com"], + ["a term over 100 characters", "a b ".repeat(26)], +] as const) { + test(`Docs Search goal: ${name} sends nothing, even with results`, async (t) => { + const goals = stubHockeyStack(t); + await mount(t, ITEMS, { search: term }); + await press("Enter"); + await settle(); + assert.deepEqual(goals, []); + }); +} + +test("Docs Search goal: a 100-character term is sent whole", async (t) => { + const goals = stubHockeyStack(t); + const term = `${"ab ".repeat(33)}a`; + await mount(t, ITEMS, { search: term }); + await settle(); + assert.deepEqual(goals, [["Docs Search", { search_term: term }]]); +}); + +test("Docs Search goal: a term that grows into a token shape stops being sent", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, ITEMS, { search: "abcdefghij" }); + await settle(); + await render({ search: "abcdefghijklmnopqrstuvwxyz" }); + await settle(); + assert.deepEqual(goals, [["Docs Search", { search_term: "abcdefghij" }]]); +}); + +test("Docs Search goal: a search dismissed before the delay ends is not sent", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, ITEMS, { search: "proxy" }); + await render({ open: false }); + await settle(); + assert.deepEqual(goals, []); +}); + +test("Docs Search goal: a dialog reopened with the same term sends it again", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, ITEMS, { search: "proxy" }); + await settle(); + await render({ open: false }); + await render({ open: true }); + await settle(); + assert.deepEqual(goals, [GOAL, GOAL]); +}); + +for (const consent of ["DENY", "NOT_CHOSEN", "absent", "throws"] as const) { + test(`Docs Search goal: analytics consent ${consent} sends nothing`, async (t) => { + const goals = stubHockeyStack(t, consent); + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + await settle(); + assert.deepEqual(goals, []); + }); +} + +function uncaughtErrors(t: TestContext) { + const messages: string[] = []; + const listener = (event: ErrorEvent) => { + event.preventDefault(); + messages.push(event.message); + }; + window.addEventListener("error", listener); + t.after(() => window.removeEventListener("error", listener)); + return messages; +} + +test("Docs Search goal: a goal that is not a function neither throws nor sends", async (t) => { + stubHockeyStack(t); + window.HockeyStack = { goal: "not a function" }; + const errors = uncaughtErrors(t); + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + await settle(); + assert.deepEqual(errors, []); +}); + +test("Docs Search goal: a goal that throws is contained", async (t) => { + stubHockeyStack(t); + let calls = 0; + window.HockeyStack = { + goal: () => { + calls += 1; + throw new Error("tag changed"); + }, + }; + const errors = uncaughtErrors(t); + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + await settle(); + assert.equal(calls, 1); + assert.deepEqual(errors, []); +}); + +test("Docs Search goal: a search before HockeyStack has loaded does not throw", async (t) => { + stubHockeyStack(t); + delete window.HockeyStack; + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + await settle(); +}); diff --git a/packages/docs-next/src/search-dialog.tsx b/packages/docs-next/src/search-dialog.tsx index 2c940745..42118dff 100644 --- a/packages/docs-next/src/search-dialog.tsx +++ b/packages/docs-next/src/search-dialog.tsx @@ -17,6 +17,7 @@ import type { DefaultSearchDialogProps } from "fumadocs-ui/components/dialog/sea import { useI18n } from "fumadocs-ui/contexts/i18n"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { focusAfterNavigation, returnFocusTo } from "./return-focus.js"; +import { useSearchGoal } from "./search-analytics.js"; import { SearchResultItem, renderSearchTable, useActiveProduct } from "./search-markdown.js"; function renderItem(props: Parameters[0] & { onClick: () => void }) { @@ -158,6 +159,7 @@ export function SearchDialogView({ announceDelayMs?: number; }) { const { onSelect, ...contentProps } = useReturnFocus(); + const sendSearchGoal = useSearchGoal(search, open, data); return ( { + sendSearchGoal(); + onSelect(item); + }} > diff --git a/packages/docs-next/test/hockeystack.ts b/packages/docs-next/test/hockeystack.ts index f52403c9..2a65a805 100644 --- a/packages/docs-next/test/hockeystack.ts +++ b/packages/docs-next/test/hockeystack.ts @@ -1,11 +1,27 @@ import type { TestContext } from "node:test"; -/** Stubs `window.HockeyStack` for one test and returns the goals it records. */ -export function stubHockeyStack(t: TestContext) { - const goals: [string, Record][] = []; - window.HockeyStack = { goal: (name, properties) => goals.push([name, properties]) }; +type Consent = "ACCEPT" | "DENY" | "NOT_CHOSEN" | "absent" | "throws"; + +/** Stubs `window.HockeyStack` and Osano's analytics consent for one test and returns the goals recorded. */ +export function stubHockeyStack(t: TestContext, consent: Consent = "ACCEPT") { + const goals: [string, unknown][] = []; + window.HockeyStack = { + goal: (name: string, properties: unknown) => goals.push([name, properties]), + }; + if (consent === "throws") { + window.Osano = { + cm: { + getConsent: () => { + throw new Error("consent unavailable"); + }, + }, + }; + } else if (consent !== "absent") { + window.Osano = { cm: { getConsent: () => ({ ANALYTICS: consent, MARKETING: "ACCEPT" }) } }; + } t.after(() => { delete window.HockeyStack; + delete window.Osano; }); return goals; }