Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/docs-pr-preview.yml
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,8 @@ jobs:
DOCS_ROOT: ${{ github.workspace }}/content/docs
# Fetched above, before the content checkout.
DOCS_RELEASE_SCHEDULE_FILE: ${{ runner.temp }}/release-schedule.json
# Matches publish-version.yml, so previews exercise the same search as production.
DOCS_SEMANTIC_SEARCH: ${{ vars.DOCS_SEMANTIC_SEARCH }}
run: pnpm turbo run build --filter=@coder/offlinedocs

- name: Upload the static export
Expand Down
19 changes: 17 additions & 2 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,23 @@ On the public site each build pass indexes only its own version and the stitch k

With `DOCS_SEMANTIC_SEARCH=1`, `apps/docs/scripts/semantic-index.mjs` runs after the stitch (and after `next build` in `apps/offlinedocs`) and embeds each section of that `api/search` file with the Model2Vec static model `minishlab/potion-base-8M` (MIT), vendored as an int8 table in `apps/docs/semantic-model/`, so no build downloads a model.
It writes `api/search-semantic/meta.json` (vocabulary, pages, sections) and two content-hashed int8 tables under `_next/static/semantic-search/`, so they share the immutable caching and asset prefix of the other build assets.
With `search.hybrid`, `DocsProvider` swaps in a dialog whose client answers from the keyword index at once and fuses in vector results once the semantic index has loaded: vector #1 first, keyword #1 second, then weighted reciprocal rank over both lists.
Vector rank carries 0.75 of the weight, except when a keyword hit contains the whole query (ignoring case), where keyword rank carries 0.75 so the keyword hits for an exact term such as a CLI flag or error message come before the vector-only pages.
The build weights each token by `log(1 + pageCount / (1 + pagesContainingToken))`, counting occurrences once per page so long pages do not distort the frequencies.
This reduces the influence of corpus-wide terms such as "workspace" while retaining distinguishing terms such as "expires".
Both section vectors and browser query embeddings use the resulting weighted token table; the vendored model and table dimensions remain unchanged.
With `search.hybrid`, `DocsProvider` swaps in a dialog whose client answers from the keyword index at once and fuses in vector results once the semantic index has loaded.
Hybrid keyword retrieval requires all informative query words (`threshold: 0`), omitting common English function words while preserving flags and identifiers.
Until the semantic index has loaded (or after it fails), a query that matches no record that way falls back to matching any word, so natural-language questions still return results.
The original query still drives semantic embedding and exact-match promotion.
Weighted reciprocal rank combines matches by full section URL, so evidence for one anchor never boosts a different section on the same page.
Vector rank carries 0.75 of the weight, except when a keyword hit contains the whole query (ignoring case), where keyword rank carries 0.75.
Exact page titles lead, followed by titles containing every query word, exact headings, exact text snippets, and the best vector page.
Titles containing every query word form one tier ordered by fused score, so for a common word such as `workspace` every such title outranks section matches.
The best keyword page is also promoted for queries without a literal keyword match; these pins apply whatever the fused scores, and the fused section ranks order only the pages after them.
Exact comparison ignores case and Markdown emphasis or escapes; query words split only on whitespace and title words on punctuation other than hyphens and underscores, without stemming, so `STUN?`, `self host` and `workspaces` do not match "STUN and NAT", "Self-host" or "workspace"; partial text matches retain their normal fused rank.
Vector candidates include the 30 strongest sections and the best section from each of the 30 strongest pages, so multiple sections can match without long pages crowding out other pages.
Fusion groups sections under their parent pages, keeps the strongest keyword representative for each full URL, and avoids duplicate semantic headings.
The dialog initially shows two matches per page, with the remaining matches available through a keyboard-accessible expansion action ("Show 3 more matches in <page>") that keeps the dialog open, moves the active row to the first revealed match and announces it in a polite live region.
Changing the query collapses the groups again.
Embedding a query is a WordPiece tokenization, a table lookup, and a mean, in plain JavaScript shared with the build (`@coder/docs-next/semantic-search`), so there is no model runtime, worker, or CSP change.

The generated REST API reference (pages under `reference/api/`, not its index page) is indexed by what names an endpoint or schema: the page title and description, the H2 headings (`Get workspace metadata by ID`, `codersdk.Workspace`), any text directly under an H2, and each endpoint's `` `METHOD /path` `` line, moved up to its H2.
Expand Down
5 changes: 3 additions & 2 deletions apps/docs/scripts/semantic-index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import path from "node:path";
import { fileURLToPath } from "node:url";
import {
createEmbeddingModel,
createCorpusEmbeddingModel,
embedSections,
quantize,
sectionsFromExport,
Expand Down Expand Up @@ -40,7 +41,7 @@ export async function buildSemanticIndex(outDir) {
.replace(/\n$/, "")
.split("\n");
const tokens = new Int8Array(await readFile(path.join(modelDir, "tokens.i8")));
const model = createEmbeddingModel(vocab, tokens, dims);
const model = createCorpusEmbeddingModel(sections, createEmbeddingModel(vocab, tokens, dims));

const vectors = quantize(embedSections(sections, model));

Expand All @@ -53,7 +54,7 @@ export async function buildSemanticIndex(outDir) {
format: 1,
model: name,
dims,
tokens: await writeHashed(outDir, "tokens", tokens),
tokens: await writeHashed(outDir, "tokens", model.table),
vectors: await writeHashed(outDir, "vectors", vectors),
vocab,
pages,
Expand Down
69 changes: 69 additions & 0 deletions apps/docs/scripts/semantic-index.test.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import assert from "node:assert/strict";
import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import { fileURLToPath } from "node:url";
import {
createCorpusEmbeddingModel,
createEmbeddingModel,
embedSections,
quantize,
sectionsFromExport,
} from "@coder/docs-next/semantic-search";
import { createSearchAPI } from "fumadocs-core/search/server";
import { buildSemanticIndex } from "./semantic-index.mjs";

test("the published token table and section vectors use the same corpus weights", async (t) => {
const out = await mkdtemp(path.join(os.tmpdir(), "weighted-search-"));
t.after(() => rm(out, { recursive: true, force: true }));
const api = createSearchAPI("advanced", {
indexes: [
{
id: "/login",
url: "/login",
title: "Login",
structuredData: {
headings: [],
contents: [{ content: "Log in to your Coder deployment." }],
},
},
{
id: "/sessions",
url: "/sessions",
title: "Session tokens",
structuredData: {
headings: [{ id: "expiration", content: "Token expiration" }],
contents: [
{
heading: "expiration",
content: "The login session expires after its configured lifetime.",
},
],
},
},
],
});
const raw = await (await api.staticGET()).text();
await mkdir(path.join(out, "api"));
await writeFile(path.join(out, "api/search"), raw);
await buildSemanticIndex(out);
const metaDir = path.join(out, "api/search-semantic");
const meta = JSON.parse(await readFile(path.join(metaDir, "meta.json"), "utf8"));
const tokens = new Int8Array(await readFile(path.resolve(metaDir, meta.tokens)));
const vectors = new Int8Array(await readFile(path.resolve(metaDir, meta.vectors)));
const vendor = new Int8Array(
await readFile(fileURLToPath(new URL("../semantic-model/tokens.i8", import.meta.url))),
);
const { sections } = sectionsFromExport(JSON.parse(raw));
const weighted = createCorpusEmbeddingModel(
sections,
createEmbeddingModel(meta.vocab, vendor, meta.dims),
);
assert.notDeepEqual(tokens, vendor);
assert.deepEqual(tokens, weighted.table);
assert.deepEqual(
vectors,
quantize(embedSections(sections, createEmbeddingModel(meta.vocab, tokens, meta.dims))),
);
});
219 changes: 215 additions & 4 deletions packages/docs-next/src/hybrid-search.test.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
import assert from "node:assert/strict";
import { afterEach, test } from "node:test";
import type { SortedResult } from "fumadocs-core/search";
import { setTimeout as delay } from "node:timers/promises";
import { FrameworkProvider } from "fumadocs-core/framework";
import type { SortedResult } from "fumadocs-core/search";
import { createSearchAPI } from "fumadocs-core/search/server";
import { act, createElement, useState } from "react";
import { type MetaData, type VirtualFile, loader } from "fumadocs-core/source";
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { CORPUS_PARAGRAPHS, FORBIDDEN_ELEMENTS } from "../test/search-xss.js";
import HybridSearchDialog, { hybridSearchClient, preloadSemanticIndex } from "./hybrid-search.js";
import { createDocsSearchRoute } from "./search.js";
import type { DocsPageData } from "./types.js";
import { createRoot } from "react-dom/client";
import HybridSearchDialog, { hybridSearchClient, preloadSemanticIndex } from "./hybrid-search.js";

const KEYWORD: SortedResult[] = [{ id: "/k", type: "page", url: "/k", content: "Keyword" }];
const keyword = { search: async () => KEYWORD };
Expand Down Expand Up @@ -61,6 +63,19 @@ test("search answers with keyword results while the semantic index is missing, a
}
});

test("without the semantic index, a query whose words share no record matches any word", async () => {
serve({});
const warn = console.warn;
console.warn = () => {};
try {
const none = { search: async () => [] };
const client = hybridSearchClient("/missing-any/api/search", undefined, none, keyword);
assert.deepEqual(await client.search("why does my build fail"), KEYWORD);
} finally {
console.warn = warn;
}
});

test("search fuses the semantic index, resolving its tables relative to meta.json, once it has loaded", async () => {
const requested = serve(FILES);
const client = hybridSearchClient("/api/search", undefined, keyword);
Expand All @@ -72,6 +87,202 @@ test("search fuses the semantic index, resolving its tables relative to meta.jso
assert.deepEqual(requested.sort(), Object.keys(FILES).sort());
});

test("keyword retrieval requires the informative query words and preserves literal CLI terms", async () => {
const api = "/precision/api/search";
const keywordIndex = createSearchAPI("advanced", {
indexes: [
{
id: "/browser",
url: "/browser",
title: "File Browser",
structuredData: {
headings: [],
contents: [
{
heading: undefined,
content: "Upload and download workspace files from your browser.",
},
],
},
},
{
id: "/lifecycle",
url: "/lifecycle",
title: "Workspace lifecycle",
structuredData: {
headings: [],
contents: [{ heading: undefined, content: "Start and stop a workspace." }],
},
},
{
id: "/jetbrains",
url: "/jetbrains",
title: "JetBrains",
structuredData: {
headings: [],
contents: [
{ heading: undefined, content: "Connect JetBrains Gateway to your workspace." },
],
},
},
{
id: "/server",
url: "/server",
title: "Server",
structuredData: {
headings: [{ id: "flag", content: "--wildcard-access-url" }],
contents: [],
},
},
{ id: "/flag", url: "/flag", title: "--in", structuredData: { headings: [], contents: [] } },
],
});
serve({
[api]: await (await keywordIndex.staticGET()).text(),
[`${api}-semantic/meta.json`]: JSON.stringify({ ...META, sections: [] }),
"/precision/_next/static/semantic-search/tokens.i8": new Uint8Array([0, 0, 100, 0]),
"/precision/_next/static/semantic-search/vectors.i8": new Uint8Array(),
});
await preloadSemanticIndex(api);
const client = hybridSearchClient(api);
const pages = async (query: string) =>
(await client.search(query)).filter((item) => item.type === "page").map((item) => item.url);
assert.deepEqual(await pages("workspace files"), ["/browser"]);
assert.deepEqual(await pages("connect with JetBrains"), ["/jetbrains"]);
assert.deepEqual(await pages("--wildcard-access-url"), ["/server"]);
assert.deepEqual(await pages("--in"), ["/flag"]);
});

test("the hybrid dialog renders and navigates to multiple matches on the same page", async (t) => {
const url = "/admin/networking/workspace-proxies";
const headings = [
{ id: "deploy-the-proxy", content: "Deploy the proxy" },
{ id: "create-the-proxy", content: "Create the proxy" },
{ id: "select-a-proxy", content: "Select a proxy" },
];
const api = "/sections/api/search";
const keywordIndex = createSearchAPI("advanced", {
indexes: [
{
id: url,
url,
title: "Workspace proxies",
tag: "coder",
structuredData: { headings, contents: [] },
},
],
});
const sections = [
{ page: 0, url: `${url}#requirements`, heading: "Requirements" },
{ page: 0, url: `${url}#run-on-kubernetes`, heading: "Run on Kubernetes" },
];
serve({
[api]: await (await keywordIndex.staticGET()).text(),
[`${api}-semantic/meta.json`]: JSON.stringify({
...META,
vocab: ["[UNK]", "proxy"],
pages: [{ url, title: "Workspace proxies" }],
sections,
}),
"/sections/_next/static/semantic-search/tokens.i8": new Uint8Array([0, 0, 100, 0]),
"/sections/_next/static/semantic-search/vectors.i8": new Uint8Array([127, 0, 120, 0]),
});
await preloadSemanticIndex(api);
const pushed: string[] = [];
const container = document.createElement("div");
document.body.append(container);
const root = createRoot(container);
function Dialog() {
const [open, setOpen] = useState(true);
return <HybridSearchDialog api={api} open={open} onOpenChange={setOpen} />;
}
t.after(async () => {
await act(async () => root.unmount());
container.remove();
});
await act(async () => {
root.render(
<FrameworkProvider
usePathname={() => "/"}
useParams={() => ({})}
useRouter={() => ({
push: (href) => {
pushed.push(href);
},
refresh() {},
})}
>
<Dialog />
</FrameworkProvider>,
);
});
const input = document.querySelector<HTMLInputElement>('[role="dialog"] input');
assert.ok(input);
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, "proxy");
input.dispatchEvent(new Event("input", { bubbles: true }));
});
await act(async () => {
await delay(150);
});
let options = [
...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] [role="option"]'),
];
assert.equal(options.length, 4);
const more = options.find(
(item) => item.textContent === "Show 3 more matches in Workspace proxies",
);
assert.ok(more);
await act(async () => {
more.dispatchEvent(new Event("pointermove", { bubbles: true }));
});
await act(async () => {
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }));
});
assert.equal(pushed.length, 0);
assert.ok(document.querySelector('[role="dialog"]'), "expanding must keep the dialog open");
options = [...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] [role="option"]')];
assert.equal(options.length, 6);
assert.equal(input.getAttribute("aria-activedescendant"), options[3]?.id);
assert.equal(
document.querySelector('[role="dialog"] output')?.textContent,
"Showing 3 more matches in Workspace proxies",
);
for (const heading of [
...headings,
...sections.map((section) => ({ id: section.url.split("#")[1], content: section.heading })),
]) {
const option = options.find((item) => item.textContent === heading.content);
assert.ok(option, `missing section: ${heading.content}`);
assert.ok(option.id);
}
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(
input,
"proxy ",
);
input.dispatchEvent(new Event("input", { bubbles: true }));
});
await act(async () => {
await delay(150);
});
options = [...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] [role="option"]')];
assert.equal(options.length, 4, "a new query must collapse expanded groups");
const moreAgain = options.find((item) => item.textContent?.includes("Show 3 more matches"));
assert.ok(moreAgain);
await act(async () => moreAgain.click());
options = [...document.querySelectorAll<HTMLButtonElement>('[role="dialog"] [role="option"]')];
const expanded = options.find((item) => item.textContent === "Run on Kubernetes");
assert.ok(expanded);
await act(async () => expanded.click());
assert.equal(pushed.at(-1), `${url}#run-on-kubernetes`);
assert.equal(
document.querySelector('[role="dialog"]'),
null,
"an expansion must not swallow a later close",
);
});

async function corpusIndex(): Promise<string> {
const files: VirtualFile<{
pageData: DocsPageData & { structuredData: unknown };
Expand Down
Loading
Loading