Compare commits

..

10 Commits

46 changed files with 980 additions and 614 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Bump Next.js to 16.4.3, keeping the dev-mode OOM patch.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Split llms-full.txt into parts by size so large sites no longer fail with "content too large"
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Follow site and space redirects when the MCP getPage tool resolves a page URL.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Let analytics tools like GA4 track outbound link clicks by using native link navigation.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Resolve the published content with the full URL in a single lookup and always send the visitor country.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep lists, paragraphs and code blocks as HTML in Updates RSS feeds, instead of running all the text together
+3 -3
View File
@@ -110,7 +110,7 @@
},
"packages/gitbook": {
"name": "gitbook",
"version": "0.28.0",
"version": "0.28.1",
"dependencies": {
"@base-ui/react": "catalog:",
"@cloudflare/workers-types": "^4.20251011.0",
@@ -356,7 +356,7 @@
},
"catalog": {
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.206.0",
"@gitbook/api": "0.208.0",
"@scalar/api-client-react": "^1.3.46",
"@tsconfig/node20": "^20.1.6",
"@tsconfig/strictest": "^2.0.6",
@@ -724,7 +724,7 @@
"@fortawesome/fontawesome-svg-core": ["@fortawesome/fontawesome-svg-core@7.2.0", "", { "dependencies": { "@fortawesome/fontawesome-common-types": "7.2.0" } }, "sha512-6639htZMjEkwskf3J+e6/iar+4cTNM9qhoWuRfj9F3eJD6r7iCzV1SWnQr2Mdv0QT0suuqU8BoJCZUyCtP9R4Q=="],
"@gitbook/api": ["@gitbook/api@0.206.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-ctgnDSQ26ZeZvdU/Zb1xxU97yMquKnhGiA0QblAIzKUmfi/3aYmWYHAwXwvEg0wtBrEtrjzme9pXgX/ACWnANA=="],
"@gitbook/api": ["@gitbook/api@0.208.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-i5rnGYNvgp8PDGd9FRLUjOx5gS/D7mFfikwp0Lsem4pgEG8cqBtZsDaYbLBdAdupOuZBLJtmEut51zhttok6OQ=="],
"@gitbook/browser-types": ["@gitbook/browser-types@workspace:packages/browser-types"],
+1 -1
View File
@@ -48,7 +48,7 @@
"@tsconfig/strictest": "^2.0.6",
"@tsconfig/node20": "^20.1.6",
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.206.0",
"@gitbook/api": "0.208.0",
"@scalar/api-client-react": "^1.3.46",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
+20
View File
@@ -1,5 +1,25 @@
# gitbook
## 0.28.1
### Patch Changes
- 7e096d5: Bump Next.js to 16.4.3, keeping the dev-mode OOM patch.
- f61578f: Preconnect each asset origin once, skip same-origin icon URLs, and open the fonts preconnect in CORS mode so font requests can reuse it.
- a512777: Forward the visitor's user agent on ask and Assistant calls so questions are classified by who asked.
- 508f1bc: Load the inline expression runtime only on pages whose code blocks or text use expressions, so other pages ship less JavaScript.
- bd431f1: Split llms-full.txt into parts by size so large sites no longer fail with "content too large"
- a5d58bc: Follow site and space redirects when the MCP getPage tool resolves a page URL.
- e745c88: Add a search input to filter models by name on OpenAPI models pages.
- 96c5683: Let analytics tools like GA4 track outbound link clicks by using native link navigation.
- 347a1cc: Set `Partitioned` on visitor cookies set inside an iframe so authenticated embeds work cross-site.
- ea01850: Support a secondary brand colour for secondary buttons and `$secondary` text, background, icon and tag colours. Sites without one render as before.
- c00a7b3: Resolve the published content with the full URL in a single lookup and always send the visitor country.
- b7b8ae6: Keep lists, paragraphs and code blocks as HTML in Updates RSS feeds, instead of running all the text together
- 4a72ead: Only apply a site preview customization override to the section or variant it was made for.
- 38f60f2: Render soft line breaks in paragraphs that contain buttons.
- be658e1: Truncate long tab titles one by one and show the selected tab's full title, instead of hiding tabs behind a "…" menu
## 0.28.0
### Minor Changes
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "gitbook",
"version": "0.28.0",
"version": "0.28.1",
"private": true,
"dependencies": {
"@base-ui/react": "catalog:",
@@ -1,4 +1,3 @@
import { cookies } from 'next/headers';
import type { NextRequest } from 'next/server';
import { NextResponse } from 'next/server';
@@ -9,7 +8,7 @@ import {
} from '@/app/utils';
import { getVisitorAuthBasePath } from '@/lib/data';
import { resolveUpstreamAuthURL } from '@/lib/site-auth-urls';
import { getVisitorAuthCookieName } from '@/lib/visitors';
import { getVisitorAuthClearCookieHeaders } from '@/lib/visitors';
/**
* Clear the site-scoped auth session cookies and redirect to the upstream auth provider
@@ -20,18 +19,11 @@ export async function GET(
{ params }: { params: Promise<RouteLayoutParams> }
) {
const resolvedParams = await params;
const [{ context }, siteURLData, cookieStore] = await Promise.all([
const [{ context }, siteURLData] = await Promise.all([
getDynamicSiteContext(resolvedParams),
getSiteURLDataFromParams(resolvedParams),
cookies(),
]);
cookieStore.delete(
getVisitorAuthCookieName(
getVisitorAuthBasePath(new URL(request.nextUrl.toString()), siteURLData)
)
);
const noLogoutFallbackURL = context.linker.toAbsoluteURL(context.linker.toPathInSite(''));
const logoutURL = resolveUpstreamAuthURL({
siteAuthURL: context.site.urls.logout,
@@ -41,5 +33,12 @@ export async function GET(
location: request.nextUrl.searchParams.get('location') ?? '/',
});
return NextResponse.redirect(logoutURL ?? noLogoutFallbackURL);
const response = NextResponse.redirect(logoutURL ?? noLogoutFallbackURL);
// Appended as raw headers: `cookies()` keeps one cookie per name.
for (const header of getVisitorAuthClearCookieHeaders(
getVisitorAuthBasePath(new URL(request.nextUrl.toString()), siteURLData)
)) {
response.headers.append('set-cookie', header);
}
return response;
}
@@ -1,6 +1,10 @@
import type { NextRequest } from 'next/server';
import { type RouteLayoutParams, getStaticSiteContext } from '@/app/utils';
import {
type RouteLayoutParams,
getSiteURLDataFromParams,
getStaticSiteContext,
} from '@/app/utils';
import { serveAskMarkdown } from '@/routes/markdownAsk';
export const dynamic = 'force-static';
@@ -18,8 +22,9 @@ export async function GET(
) {
const { question: encodedQuestion, goal: encodedGoal } = await params;
const { context } = await getStaticSiteContext(await params);
const { askVisitorAgent } = getSiteURLDataFromParams(await params);
const question = decodeURIComponent(encodedQuestion);
const goal = decodeURIComponent(encodedGoal);
return serveAskMarkdown(context, question, { goal });
return serveAskMarkdown(context, question, { goal, visitorAgent: askVisitorAgent });
}
@@ -1,6 +1,10 @@
import type { NextRequest } from 'next/server';
import { type RouteLayoutParams, getStaticSiteContext } from '@/app/utils';
import {
type RouteLayoutParams,
getSiteURLDataFromParams,
getStaticSiteContext,
} from '@/app/utils';
import { serveAskMarkdown } from '@/routes/markdownAsk';
export const dynamic = 'force-static';
@@ -11,7 +15,8 @@ export async function GET(
) {
const { question: encodedQuestion } = await params;
const { context } = await getStaticSiteContext(await params);
const { askVisitorAgent } = getSiteURLDataFromParams(await params);
const question = decodeURIComponent(encodedQuestion);
return serveAskMarkdown(context, question);
return serveAskMarkdown(context, question, { visitorAgent: askVisitorAgent });
}
@@ -1,451 +0,0 @@
'use client';
import assertNever from 'assert-never';
import * as React from 'react';
import {
AIMessageRole,
AIMessageStepPhase,
type AIStreamResponse,
type AIMessageContext,
type AIStreamResponseToolCallPending,
SiteInsightsDisplayContext,
} from '@gitbook/api';
import { getInsightsSession } from '../Insights';
import { ConfirmControlDef, ConfirmControlOutputSchema } from './controls/ConfirmControl';
import { type RenderAIMessageOptions, streamAIChatResponse } from './server-actions';
import { getTools } from './tools';
import {
type AIChatMessageActivity,
type StreamAIChatInput,
type StreamAIChatResponse,
globalState,
} from './useAIChat';
import { useLeaveAgentFeedbackTool, useLeaveUserFeedbackTool } from './useLeaveFeedbackTools';
import { useNavigateToPageTool } from './useNavigateToPageTool';
import {
type ResponseToRate,
useSubmitAssistantFeedbackTool,
} from './useSubmitAssistantFeedbackTool';
import { useSubmitPageFeedbackTool } from './useSubmitPageFeedbackTool';
import { useLanguage } from '@/intl/client';
import { tString } from '@/intl/translate';
/**
* Streams AI responses and runs the assistant's tools; mounted by `AIChatProvider` on first use.
*/
export function AIChatEngine(props: {
renderMessageOptions?: RenderAIMessageOptions;
withPageFeedback: boolean;
messageContextRef: React.RefObject<AIMessageContext>;
responseToRateRef: React.RefObject<ResponseToRate>;
reportedAgentFeedbackRef: React.RefObject<boolean>;
postMessageRef: React.RefObject<((input: { message: string }) => void) | null>;
engineRef: React.RefObject<StreamAIChatResponse | null>;
pendingStreams: StreamAIChatInput[];
}) {
const {
renderMessageOptions,
withPageFeedback,
messageContextRef,
responseToRateRef,
reportedAgentFeedbackRef,
postMessageRef,
engineRef,
pendingStreams,
} = props;
const language = useLanguage();
const displayContext = renderMessageOptions?.asEmbeddable
? SiteInsightsDisplayContext.Embed
: SiteInsightsDisplayContext.Site;
const getResponseToRate = React.useCallback(() => responseToRateRef.current, []);
// Built-in tools exposed to the assistant (e.g. navigating to a page, submitting page or
// assistant feedback). Each tool has a stable identity, so it can be referenced directly from
// the streaming callback.
const navigateToPageTool = useNavigateToPageTool();
const submitPageFeedbackTool = useSubmitPageFeedbackTool({ displayContext });
const submitAssistantFeedbackTool = useSubmitAssistantFeedbackTool({
displayContext,
getResponseToRate,
});
const leaveAgentFeedbackTool = useLeaveAgentFeedbackTool({
asEmbeddable: renderMessageOptions?.asEmbeddable,
displayContext,
reportedRef: reportedAgentFeedbackRef,
});
const leaveUserFeedbackTool = useLeaveUserFeedbackTool({
asEmbeddable: renderMessageOptions?.asEmbeddable,
displayContext,
});
// The assistant-feedback tool is always available (it mirrors the chat's own thumbs up/down
// rating), while the tools carrying the reader's own feedback are gated on the site's
// "Was this helpful?" setting.
const builtInTools = React.useMemo(() => {
const tools = [navigateToPageTool, submitAssistantFeedbackTool, leaveAgentFeedbackTool];
if (withPageFeedback) {
tools.push(submitPageFeedbackTool, leaveUserFeedbackTool);
}
return tools;
}, [
navigateToPageTool,
submitAssistantFeedbackTool,
leaveAgentFeedbackTool,
leaveUserFeedbackTool,
submitPageFeedbackTool,
withPageFeedback,
]);
// Stream a message with the AI backend
const streamResponse = React.useCallback(
async (input: StreamAIChatInput) => {
globalState.setState((state) => {
return {
...state,
followUpSuggestions: [],
control: null,
responding: true,
loading: true,
error: false,
messages: [
...state.messages,
{
role: AIMessageRole.Assistant,
content: null, // Placeholder for streaming response
activity: getDefaultAIChatMessageActivity(),
},
],
};
});
// A stream becomes stale once a newer turn (or a clear) has replaced its
// query. Because `responding` clears on `response_finish` — before follow-up
// suggestions finish streaming — the user can start a new turn while this one
// is still wrapping up. A stale stream must not mutate the shared
// loading/responding state, which now belongs to the active turn; otherwise
// it would make the UI look idle mid-response. (`userQuery` is only set for
// user-initiated turns, not tool-call continuations.)
const isSuperseded = () =>
!!input.userQuery && globalState.getState().query !== input.userQuery;
// Execute a tool call
const executeToolCall = async (event: AIStreamResponseToolCallPending) => {
const tools = getTools(builtInTools);
const toolDef = tools.find((tool) => tool.name === event.toolCall.tool);
if (!toolDef || !('execute' in toolDef)) {
throw new Error(`Tool ${event.toolCall.tool} not found`);
}
try {
const result = await toolDef.execute(event.toolCall.input);
await streamResponse({
toolCall: {
tool: event.toolCall.tool,
toolCallId: event.toolCallId,
output: result.output,
summary: result.summary,
},
});
} catch (error) {
await streamResponse({
toolCall: {
tool: event.toolCall.tool,
toolCallId: event.toolCallId,
output: {
error: error instanceof Error ? error.message : 'Unknown error',
},
summary: {
icon: 'bomb',
text: 'An error occurred while executing the tool',
},
},
});
}
};
let toolToExecute: AIStreamResponseToolCallPending | null = null;
try {
const tools = getTools(builtInTools);
const stream = await streamAIChatResponse({
message: input.message,
toolCall: input.toolCall,
messageContext: messageContextRef.current,
previousResponseId: globalState.getState().responseId ?? undefined,
session: await getInsightsSession(),
tools: tools.map((tool) => ({
name: tool.name,
description: tool.description,
// Issue with the schema generated by Zod and Next.js serialization.
inputSchema: tool.inputSchema,
})),
options: {
withLinkPreviews: renderMessageOptions?.withLinkPreviews ?? true,
withToolCalls: renderMessageOptions?.withToolCalls ?? true,
asEmbeddable: renderMessageOptions?.asEmbeddable ?? false,
},
});
// Process streaming response
for await (const data of stream) {
if (!data) continue;
if (isSuperseded()) {
// Chat was cleared or a newer turn started; stop processing.
break;
}
const event = data.event;
switch (event.type) {
case 'response_finish': {
globalState.setState((state) => ({
...state,
responseId: event.response.id ?? null,
// Mark as not responding when the response is finished
// Even if the stream might continue as we receive 'response_followup_suggestion'
responding: false,
error: false,
}));
break;
}
case 'response_followup_suggestion': {
globalState.setState((state) => ({
...state,
followUpSuggestions: [
...state.followUpSuggestions,
...event.suggestions,
],
}));
break;
}
case 'response_tool_call_pending': {
const toolDef = tools.find((tool) => tool.name === event.toolCall.tool);
if (!toolDef) {
throw new Error(`Tool ${event.toolCall.tool} not found`);
}
if ('createControl' in toolDef) {
globalState.setState((state) => ({
...state,
control: toolDef.createControl({
context: {
toolCall: event.toolCall,
toolCallId: event.toolCallId,
},
input: event.toolCall.input as any,
language,
send: async (result) => {
await streamResponse({
toolCall: {
tool: event.toolCall.tool,
toolCallId: event.toolCallId,
output: result.output,
summary: result.summary,
},
});
},
}),
}));
break;
}
const confirmation = 'confirmation' in toolDef && toolDef.confirmation;
if (confirmation) {
// The confirmation can be a static object or a function that
// derives it from the AI-provided input (e.g. dynamic context).
// The function call is awaited because, for embed-registered
// tools, it arrives as an async proxy over the postMessage channel.
const resolvedConfirmation =
typeof confirmation === 'function'
? await confirmation(event.toolCall.input)
: confirmation;
const supportingContext =
typeof resolvedConfirmation.context === 'string'
? resolvedConfirmation.context.slice(0, 512)
: undefined;
globalState.setState((state) => ({
...state,
control: ConfirmControlDef.createControl({
context: {
toolCall: event.toolCall,
toolCallId: event.toolCallId,
},
input: {
label: resolvedConfirmation.label,
icon: resolvedConfirmation.icon,
context: supportingContext,
},
language,
send: async (result) => {
const output = ConfirmControlOutputSchema.parse(
result.output
);
switch (output.result) {
case 'cancelled': {
await streamResponse({
toolCall: {
tool: event.toolCall.tool,
toolCallId: event.toolCallId,
output: { cancelled: true },
summary: {
icon: 'forward',
text: tString(
language,
'tool_call_skipped',
resolvedConfirmation.label
),
},
},
});
break;
}
case 'confirmed':
await executeToolCall(event);
break;
default:
assertNever(output.result);
}
},
}),
}));
break;
}
toolToExecute = event;
break;
}
}
// Update the assistant message with streamed content
globalState.setState((state) => ({
...state,
messages: [
...state.messages.slice(0, -1),
{
role: AIMessageRole.Assistant,
content: data.content,
activity: updateAIChatMessageActivity(
state.messages[state.messages.length - 1]?.activity ??
getDefaultAIChatMessageActivity(),
event
),
},
],
}));
}
// If a newer turn replaced this one while we were finishing (e.g.
// streaming follow-up suggestions after `response_finish`), abandon this
// stale stream without executing leftover tools or clearing the shared
// loading/responding state, which now belongs to the active turn.
if (isSuperseded()) {
return;
}
// Execute the tool call if it doesn't require confirmation.
// When a tool call (or control) keeps the turn going, `loading`
// stays true: either the recursive `streamResponse` will clear it
// when its stream settles, or it is cleared below once the loop ends
// (e.g. while waiting on a user confirmation control).
if (toolToExecute) {
await executeToolCall(toolToExecute);
} else {
globalState.setState((state) => ({
...state,
responding: false,
loading: false,
error: false,
}));
// Turn settled: send the next queued follow-up (oldest first). Held back while a
// control is pending, since posting would throw; it flushes after that resolves.
const { queuedMessages, control: activeControl } = globalState.getState();
const [next, ...rest] = queuedMessages;
if (next !== undefined && !activeControl) {
globalState.setState((state) => ({ ...state, queuedMessages: rest }));
postMessageRef.current?.({ message: next });
}
}
} catch (error) {
console.error('Error streaming AI response', error);
// Don't surface a stale stream's error onto the active turn.
if (!isSuperseded()) {
globalState.setState((state) => ({
...state,
responding: false,
loading: false,
error: true,
}));
}
}
},
[
messageContextRef.current,
renderMessageOptions?.withLinkPreviews,
renderMessageOptions?.withToolCalls,
renderMessageOptions?.asEmbeddable,
language,
builtInTools,
]
);
engineRef.current = streamResponse;
// Send what was posted while this module was loading.
React.useEffect(() => {
for (const input of pendingStreams.splice(0)) {
void streamResponse(input);
}
}, [streamResponse, pendingStreams]);
return null;
}
function updateAIChatMessageActivity(
activity: AIChatMessageActivity,
event: AIStreamResponse
): AIChatMessageActivity {
switch (event.type) {
case 'response_step_start': {
return {
...activity,
currentPhase: event.phase,
hasFinalAnswer:
activity.hasFinalAnswer || event.phase === AIMessageStepPhase.FinalAnswer,
};
}
case 'response_document': {
// A commentary phase can start without ever producing anything visible. Only a
// commentary step that emits document content is a real preamble worth collapsing
// behind the activity heading, so flag it here rather than on phase start.
return {
...activity,
hasCommentary:
activity.hasCommentary ||
(activity.currentPhase === AIMessageStepPhase.Commentary &&
event.blocks.length > 0),
};
}
case 'response_tool_call': {
return {
...activity,
toolCount: activity.toolCount + 1,
};
}
default:
return activity;
}
}
function getDefaultAIChatMessageActivity(): AIChatMessageActivity {
return {
currentPhase: undefined,
toolCount: 0,
hasCommentary: false,
hasFinalAnswer: false,
};
}
@@ -1,4 +1,6 @@
'use server';
import { headers } from 'next/headers';
import {
type AIMessageContext,
AIMessageRole,
@@ -12,6 +14,7 @@ import {
import { streamRenderAIMessage } from './api';
import type { RenderAIMessageOptions } from './types';
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
import { getAskForwardedHeaders, getAskVisitorAgent } from '@/lib/ask-visitor';
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
import { fetchServerActionSiteContext, getServerActionBaseContext } from '@/lib/server-actions';
import { traceErrorOnly } from '@/lib/tracing';
@@ -72,7 +75,8 @@ export async function* streamAIChatResponse({
? SiteCoreChannelType.Embed
: SiteCoreChannelType.Site,
},
}
},
{ headers: getAskForwardedHeaders(getAskVisitorAgent(await headers())) }
);
return await streamRenderAIMessage(context, rawStream, options);
+404 -47
View File
@@ -1,26 +1,39 @@
'use client';
import dynamic from 'next/dynamic';
import assertNever from 'assert-never';
import * as React from 'react';
import * as zustand from 'zustand';
import {
AIMessageRole,
AIMessageStepPhase,
type AIStreamResponse,
type AIStreamResponseToolCallPending,
type AIToolCallResult,
SiteInsightsDisplayContext,
type SiteInsightsEventAskView,
} from '@gitbook/api';
import { useTrackEvent } from '../Insights';
import { getInsightsSession, useTrackEvent } from '../Insights';
import { type UpdateSearchState, useSetSearchState } from '../Search';
import { addRecentSearchQuery } from '../Search/recent-queries';
import type { AnyAIControl } from './controls';
import { ConfirmControlDef, ConfirmControlOutputSchema } from './controls/ConfirmControl';
import { setIntercomLauncherHidden } from './intercom';
import { type AIChatReference, serializeReferences } from './references';
import type { RenderAIMessageOptions } from './server-actions';
import { type RenderAIMessageOptions, streamAIChatResponse } from './server-actions';
import { getTools } from './tools';
import { useAIMessageContextRef } from './useAIMessageContext';
import type { ResponseToRate } from './useSubmitAssistantFeedbackTool';
import { useLeaveAgentFeedbackTool, useLeaveUserFeedbackTool } from './useLeaveFeedbackTools';
import { useNavigateToPageTool } from './useNavigateToPageTool';
import {
type ResponseToRate,
useSubmitAssistantFeedbackTool,
} from './useSubmitAssistantFeedbackTool';
import { useSubmitPageFeedbackTool } from './useSubmitPageFeedbackTool';
import { useCurrentContent } from '@/components/hooks';
import { useLanguage } from '@/intl/client';
import { tString } from '@/intl/translate';
const noopSetSearchState: UpdateSearchState = () => Promise.resolve(new URLSearchParams());
@@ -176,28 +189,10 @@ export type AIChatController = {
) => () => void;
};
export type StreamAIChatInput = {
/** Text message to send to the AI backend */
message?: string;
/** User-typed prompt; compared against state.query to abort stale streams */
userQuery?: string;
/** Tool call to send to the AI backend */
toolCall?: AIToolCallResult;
};
export type StreamAIChatResponse = (input: StreamAIChatInput) => Promise<void>;
const AIChatEngine = dynamic(() => import('./AIChatEngine').then((mod) => mod.AIChatEngine), {
ssr: false,
});
// Module-level like `globalState`, so a remounted provider still sends what was queued.
const pendingStreams: StreamAIChatInput[] = [];
const AIChatControllerContext = React.createContext<AIChatController | null>(null);
// Global state store for AI chat
export const globalState = zustand.create<AIChatState>(() => {
const globalState = zustand.create<AIChatState>(() => {
return {
opened: false,
responseId: null,
@@ -249,6 +244,10 @@ export function AIChatProvider(props: {
const trackEvent = useTrackEvent();
const setSearchStateInURL = useSetSearchState();
const { siteSpaceId } = useCurrentContent();
const language = useLanguage();
const displayContext = renderMessageOptions?.asEmbeddable
? SiteInsightsDisplayContext.Embed
: SiteInsightsDisplayContext.Site;
// The embed keeps its state in its own routes, not in URL search params.
const setSearchState = renderMessageOptions?.asEmbeddable
@@ -259,22 +258,48 @@ export function AIChatProvider(props: {
// (before it overwrites the store's responseId/query), so the self-feedback tool rates that
// previous response rather than the one this reaction turn produces.
const responseToRateRef = React.useRef<ResponseToRate>({ responseId: null, query: null });
const getResponseToRate = React.useCallback(() => responseToRateRef.current, []);
// Findings reported to the site's team are capped at one per conversation, so the assistant
// cannot flood the inbox over a long chat.
const reportedAgentFeedbackRef = React.useRef(false);
// Streaming, tools and their schemas load on first use to keep them out of the initial bundle.
const [engineRequested, setEngineRequested] = React.useState(() => pendingStreams.length > 0);
const engineRef = React.useRef<StreamAIChatResponse | null>(null);
const streamResponse = React.useCallback((input: StreamAIChatInput) => {
if (engineRef.current) {
void engineRef.current(input);
return;
// Built-in tools exposed to the assistant (e.g. navigating to a page, submitting page or
// assistant feedback). Each tool has a stable identity, so it can be referenced directly from
// the streaming callback.
const navigateToPageTool = useNavigateToPageTool();
const submitPageFeedbackTool = useSubmitPageFeedbackTool({ displayContext });
const submitAssistantFeedbackTool = useSubmitAssistantFeedbackTool({
displayContext,
getResponseToRate,
});
const leaveAgentFeedbackTool = useLeaveAgentFeedbackTool({
asEmbeddable: renderMessageOptions?.asEmbeddable,
displayContext,
reportedRef: reportedAgentFeedbackRef,
});
const leaveUserFeedbackTool = useLeaveUserFeedbackTool({
asEmbeddable: renderMessageOptions?.asEmbeddable,
displayContext,
});
// The assistant-feedback tool is always available (it mirrors the chat's own thumbs up/down
// rating), while the tools carrying the reader's own feedback are gated on the site's
// "Was this helpful?" setting.
const builtInTools = React.useMemo(() => {
const tools = [navigateToPageTool, submitAssistantFeedbackTool, leaveAgentFeedbackTool];
if (withPageFeedback) {
tools.push(submitPageFeedbackTool, leaveUserFeedbackTool);
}
pendingStreams.push(input);
setEngineRequested(true);
}, []);
return tools;
}, [
navigateToPageTool,
submitAssistantFeedbackTool,
leaveAgentFeedbackTool,
leaveUserFeedbackTool,
submitPageFeedbackTool,
withPageFeedback,
]);
// Event listeners storage
const eventsRef = React.useRef<Map<AIChatEvent['type'], AIChatEventListener[]>>(new Map());
@@ -283,7 +308,6 @@ export function AIChatProvider(props: {
const onOpen = React.useCallback(
(trigger?: AskAITrigger) => {
setIntercomLauncherHidden(true);
setEngineRequested(true);
if (!renderMessageOptions?.asEmbeddable) {
trackEvent({ type: 'ask_view', trigger });
}
@@ -324,6 +348,307 @@ export function AIChatProvider(props: {
// Lets `streamResponse` flush a queued follow-up via `onPostMessage`, which is defined later.
const postMessageRef = React.useRef<((input: { message: string }) => void) | null>(null);
// Stream a message with the AI backend
const streamResponse = React.useCallback(
async (input: {
/** Text message to send to the AI backend */
message?: string;
/** User-typed prompt; compared against state.query to abort stale streams */
userQuery?: string;
/** Tool call to send to the AI backend */
toolCall?: AIToolCallResult;
}) => {
globalState.setState((state) => {
return {
...state,
followUpSuggestions: [],
control: null,
responding: true,
loading: true,
error: false,
messages: [
...state.messages,
{
role: AIMessageRole.Assistant,
content: null, // Placeholder for streaming response
activity: getDefaultAIChatMessageActivity(),
},
],
};
});
// A stream becomes stale once a newer turn (or a clear) has replaced its
// query. Because `responding` clears on `response_finish` — before follow-up
// suggestions finish streaming — the user can start a new turn while this one
// is still wrapping up. A stale stream must not mutate the shared
// loading/responding state, which now belongs to the active turn; otherwise
// it would make the UI look idle mid-response. (`userQuery` is only set for
// user-initiated turns, not tool-call continuations.)
const isSuperseded = () =>
!!input.userQuery && globalState.getState().query !== input.userQuery;
// Execute a tool call
const executeToolCall = async (event: AIStreamResponseToolCallPending) => {
const tools = getTools(builtInTools);
const toolDef = tools.find((tool) => tool.name === event.toolCall.tool);
if (!toolDef || !('execute' in toolDef)) {
throw new Error(`Tool ${event.toolCall.tool} not found`);
}
try {
const result = await toolDef.execute(event.toolCall.input);
await streamResponse({
toolCall: {
tool: event.toolCall.tool,
toolCallId: event.toolCallId,
output: result.output,
summary: result.summary,
},
});
} catch (error) {
await streamResponse({
toolCall: {
tool: event.toolCall.tool,
toolCallId: event.toolCallId,
output: {
error: error instanceof Error ? error.message : 'Unknown error',
},
summary: {
icon: 'bomb',
text: 'An error occurred while executing the tool',
},
},
});
}
};
let toolToExecute: AIStreamResponseToolCallPending | null = null;
try {
const tools = getTools(builtInTools);
const stream = await streamAIChatResponse({
message: input.message,
toolCall: input.toolCall,
messageContext: messageContextRef.current,
previousResponseId: globalState.getState().responseId ?? undefined,
session: await getInsightsSession(),
tools: tools.map((tool) => ({
name: tool.name,
description: tool.description,
// Issue with the schema generated by Zod and Next.js serialization.
inputSchema: tool.inputSchema,
})),
options: {
withLinkPreviews: renderMessageOptions?.withLinkPreviews ?? true,
withToolCalls: renderMessageOptions?.withToolCalls ?? true,
asEmbeddable: renderMessageOptions?.asEmbeddable ?? false,
},
});
// Process streaming response
for await (const data of stream) {
if (!data) continue;
if (isSuperseded()) {
// Chat was cleared or a newer turn started; stop processing.
break;
}
const event = data.event;
switch (event.type) {
case 'response_finish': {
globalState.setState((state) => ({
...state,
responseId: event.response.id ?? null,
// Mark as not responding when the response is finished
// Even if the stream might continue as we receive 'response_followup_suggestion'
responding: false,
error: false,
}));
break;
}
case 'response_followup_suggestion': {
globalState.setState((state) => ({
...state,
followUpSuggestions: [
...state.followUpSuggestions,
...event.suggestions,
],
}));
break;
}
case 'response_tool_call_pending': {
const toolDef = tools.find((tool) => tool.name === event.toolCall.tool);
if (!toolDef) {
throw new Error(`Tool ${event.toolCall.tool} not found`);
}
if ('createControl' in toolDef) {
globalState.setState((state) => ({
...state,
control: toolDef.createControl({
context: {
toolCall: event.toolCall,
toolCallId: event.toolCallId,
},
input: event.toolCall.input as any,
language,
send: async (result) => {
await streamResponse({
toolCall: {
tool: event.toolCall.tool,
toolCallId: event.toolCallId,
output: result.output,
summary: result.summary,
},
});
},
}),
}));
break;
}
const confirmation = 'confirmation' in toolDef && toolDef.confirmation;
if (confirmation) {
// The confirmation can be a static object or a function that
// derives it from the AI-provided input (e.g. dynamic context).
// The function call is awaited because, for embed-registered
// tools, it arrives as an async proxy over the postMessage channel.
const resolvedConfirmation =
typeof confirmation === 'function'
? await confirmation(event.toolCall.input)
: confirmation;
const supportingContext =
typeof resolvedConfirmation.context === 'string'
? resolvedConfirmation.context.slice(0, 512)
: undefined;
globalState.setState((state) => ({
...state,
control: ConfirmControlDef.createControl({
context: {
toolCall: event.toolCall,
toolCallId: event.toolCallId,
},
input: {
label: resolvedConfirmation.label,
icon: resolvedConfirmation.icon,
context: supportingContext,
},
language,
send: async (result) => {
const output = ConfirmControlOutputSchema.parse(
result.output
);
switch (output.result) {
case 'cancelled': {
await streamResponse({
toolCall: {
tool: event.toolCall.tool,
toolCallId: event.toolCallId,
output: { cancelled: true },
summary: {
icon: 'forward',
text: tString(
language,
'tool_call_skipped',
resolvedConfirmation.label
),
},
},
});
break;
}
case 'confirmed':
await executeToolCall(event);
break;
default:
assertNever(output.result);
}
},
}),
}));
break;
}
toolToExecute = event;
break;
}
}
// Update the assistant message with streamed content
globalState.setState((state) => ({
...state,
messages: [
...state.messages.slice(0, -1),
{
role: AIMessageRole.Assistant,
content: data.content,
activity: updateAIChatMessageActivity(
state.messages[state.messages.length - 1]?.activity ??
getDefaultAIChatMessageActivity(),
event
),
},
],
}));
}
// If a newer turn replaced this one while we were finishing (e.g.
// streaming follow-up suggestions after `response_finish`), abandon this
// stale stream without executing leftover tools or clearing the shared
// loading/responding state, which now belongs to the active turn.
if (isSuperseded()) {
return;
}
// Execute the tool call if it doesn't require confirmation.
// When a tool call (or control) keeps the turn going, `loading`
// stays true: either the recursive `streamResponse` will clear it
// when its stream settles, or it is cleared below once the loop ends
// (e.g. while waiting on a user confirmation control).
if (toolToExecute) {
await executeToolCall(toolToExecute);
} else {
globalState.setState((state) => ({
...state,
responding: false,
loading: false,
error: false,
}));
// Turn settled: send the next queued follow-up (oldest first). Held back while a
// control is pending, since posting would throw; it flushes after that resolves.
const { queuedMessages, control: activeControl } = globalState.getState();
const [next, ...rest] = queuedMessages;
if (next !== undefined && !activeControl) {
globalState.setState((state) => ({ ...state, queuedMessages: rest }));
postMessageRef.current?.({ message: next });
}
}
} catch (error) {
console.error('Error streaming AI response', error);
// Don't surface a stale stream's error onto the active turn.
if (!isSuperseded()) {
globalState.setState((state) => ({
...state,
responding: false,
loading: false,
error: true,
}));
}
}
},
[
messageContextRef.current,
renderMessageOptions?.withLinkPreviews,
renderMessageOptions?.withToolCalls,
renderMessageOptions?.asEmbeddable,
language,
builtInTools,
]
);
// Post a message to the AI chat
const onPostMessage = React.useCallback(
async (input: { message: string }) => {
@@ -422,7 +747,6 @@ export function AIChatProvider(props: {
const onClear = React.useCallback(() => {
responseToRateRef.current = { responseId: null, query: null };
reportedAgentFeedbackRef.current = false;
pendingStreams.length = 0;
globalState.setState((state) => ({
opened: state.opened,
responding: false,
@@ -539,18 +863,6 @@ export function AIChatProvider(props: {
return (
<AIChatControllerContext.Provider value={controller}>
{children}
{engineRequested ? (
<AIChatEngine
renderMessageOptions={renderMessageOptions}
withPageFeedback={withPageFeedback}
messageContextRef={messageContextRef}
responseToRateRef={responseToRateRef}
reportedAgentFeedbackRef={reportedAgentFeedbackRef}
postMessageRef={postMessageRef}
engineRef={engineRef}
pendingStreams={pendingStreams}
/>
) : null}
</AIChatControllerContext.Provider>
);
}
@@ -606,3 +918,48 @@ function getLatestAssistantMessage(messages: AIChatMessage[]) {
return null;
}
function updateAIChatMessageActivity(
activity: AIChatMessageActivity,
event: AIStreamResponse
): AIChatMessageActivity {
switch (event.type) {
case 'response_step_start': {
return {
...activity,
currentPhase: event.phase,
hasFinalAnswer:
activity.hasFinalAnswer || event.phase === AIMessageStepPhase.FinalAnswer,
};
}
case 'response_document': {
// A commentary phase can start without ever producing anything visible. Only a
// commentary step that emits document content is a real preamble worth collapsing
// behind the activity heading, so flag it here rather than on phase start.
return {
...activity,
hasCommentary:
activity.hasCommentary ||
(activity.currentPhase === AIMessageStepPhase.Commentary &&
event.blocks.length > 0),
};
}
case 'response_tool_call': {
return {
...activity,
toolCount: activity.toolCount + 1,
};
}
default:
return activity;
}
}
function getDefaultAIChatMessageActivity(): AIChatMessageActivity {
return {
currentPhase: undefined,
toolCount: 0,
hasCommentary: false,
hasFinalAnswer: false,
};
}
@@ -6,11 +6,10 @@ import { useDebounceCallback } from 'usehooks-ts';
import type { CustomizationThemedCodeTheme, DocumentBlockCode } from '@gitbook/api';
import type { BlockProps } from '../Block';
import { type InlineExpressionVariables, useEvaluateInlineExpression } from '../InlineExpression';
import type { InlineExpressionVariables } from '../InlineExpression/types';
import { CodeBlockRenderer } from './CodeBlockRenderer';
import type { HighlightTheme, RenderedInline } from './highlight-tokens';
import { plainHighlight } from './plain-highlight';
import { useAdaptiveVisitor } from '@/components/Adaptive';
import { useInViewportListener } from '@/components/hooks/useInViewportListener';
import { useScrollListener } from '@/components/hooks/useScrollListener';
import { Button, ToggleChevron } from '@/components/primitives';
@@ -20,6 +19,8 @@ import { type ClassValue, tcls } from '@/lib/tailwind';
export type ClientBlockProps = Pick<BlockProps<DocumentBlockCode>, 'block' | 'style'> & {
inlines: RenderedInline[];
inlineExprVariables: InlineExpressionVariables;
/** Only set for blocks with inline expressions, keeping `@gitbook/expr` out of the bundle. */
evaluateInlineExpression?: (expression: string) => string;
mode: BlockProps<DocumentBlockCode>['context']['mode'];
themes?: CustomizationThemedCodeTheme;
embedded?: boolean;
@@ -34,18 +35,12 @@ export const CODE_BLOCK_DEFAULT_COLLAPSED_LINE_COUNT = 10;
* It allows us to defer some load to avoid blocking the rendering of the whole page with block highlighting.
*/
export function ClientCodeBlock(props: ClientBlockProps) {
const { block, mode, style, inlines, inlineExprVariables, themes, embedded, commentKey } =
const { block, mode, style, inlines, evaluateInlineExpression, themes, embedded, commentKey } =
props;
const blockRef = useRef<HTMLDivElement>(null);
const isInViewportRef = useRef(false);
const [isInViewport, setIsInViewport] = useState(false);
const getAdaptiveVisitorClaims = useAdaptiveVisitor();
const visitorClaims = getAdaptiveVisitorClaims();
const evaluateInlineExpression = useEvaluateInlineExpression({
visitorClaims,
variables: inlineExprVariables,
});
const plainTheme = useMemo(
() => plainHighlight(block, inlines, { evaluateInlineExpression, themes }),
[block, inlines, evaluateInlineExpression, themes]
@@ -0,0 +1,18 @@
'use client';
import { ClientCodeBlock, type ClientBlockProps } from './ClientCodeBlock';
import { useAdaptiveVisitor } from '@/components/Adaptive';
import { useEvaluateInlineExpression } from '@/components/DocumentView/InlineExpression/useEvaluateInlineExpression';
/**
* Code block with inline expressions; its own module because it pulls in `@gitbook/expr`.
*/
export function ClientCodeBlockWithExpressions(props: ClientBlockProps) {
const getAdaptiveVisitorClaims = useAdaptiveVisitor();
const evaluateInlineExpression = useEvaluateInlineExpression({
visitorClaims: getAdaptiveVisitorClaims(),
variables: props.inlineExprVariables,
});
return <ClientCodeBlock {...props} evaluateInlineExpression={evaluateInlineExpression} />;
}
@@ -0,0 +1,18 @@
'use client';
import dynamic from 'next/dynamic';
import type { ClientBlockProps } from './ClientCodeBlock';
// Keeps `@gitbook/expr` out of the eager bundle; `ssr: true` keeps values in the HTML.
const ClientCodeBlockWithExpressions = dynamic(
() =>
import('./ClientCodeBlockWithExpressions').then(
(mod) => mod.ClientCodeBlockWithExpressions
),
{ ssr: true }
);
export function ClientCodeBlockWithExpressionsLazy(props: ClientBlockProps) {
return <ClientCodeBlockWithExpressions {...props} />;
}
@@ -10,6 +10,7 @@ import type { BlockProps } from '../Block';
import { Blocks } from '../Blocks';
import { getCommentKeyProp, getCommentMarkerProps } from '../utils';
import { ClientCodeBlock } from './ClientCodeBlock';
import { ClientCodeBlockWithExpressionsLazy } from './ClientCodeBlockWithExpressionsLazy';
import { CodeBlockRenderer } from './CodeBlockRenderer';
import { highlight } from './highlight';
import { type RenderedInline, getInlines } from './highlight-tokens';
@@ -130,8 +131,11 @@ export async function CodeBlock(
{isMermaid ? (
<MermaidCodeBlockLazy
{...clientProps}
hasInlineExpression={hasInlineExpression}
mermaidRuntimeURL={getAssetURL(MERMAID_RUNTIME_PATH)}
/>
) : hasInlineExpression ? (
<ClientCodeBlockWithExpressionsLazy {...clientProps} />
) : (
<ClientCodeBlock {...clientProps} />
)}
@@ -8,6 +8,7 @@ import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useSta
import { createPortal } from 'react-dom';
import { type ClientBlockProps, ClientCodeBlock } from './ClientCodeBlock';
import { ClientCodeBlockWithExpressions } from './ClientCodeBlockWithExpressions';
import { getPlainCodeBlock } from './highlight-tokens';
import { MermaidPanZoomControls } from './MermaidPanZoomControls';
import { useHasBeenInViewport } from '@/components/hooks/useHasBeenInViewport';
@@ -20,6 +21,7 @@ import { tcls } from '@/lib/tailwind';
export function MermaidCodeBlock(
props: ClientBlockProps & {
mermaidRuntimeURL: string;
hasInlineExpression: boolean;
}
) {
const { block, mode, style, mermaidRuntimeURL } = props;
@@ -169,7 +171,11 @@ export function MermaidCodeBlock(
}, []);
if (error) {
return <ClientCodeBlock {...props} />;
return props.hasInlineExpression ? (
<ClientCodeBlockWithExpressions {...props} />
) : (
<ClientCodeBlock {...props} />
);
}
// The live diagram subtree. It is portaled into a stable host that moves between the
@@ -11,6 +11,8 @@ const MermaidCodeBlock = dynamic(
{ ssr: true }
);
export function MermaidCodeBlockLazy(props: ClientBlockProps & { mermaidRuntimeURL: string }) {
export function MermaidCodeBlockLazy(
props: ClientBlockProps & { mermaidRuntimeURL: string; hasInlineExpression: boolean }
) {
return <MermaidCodeBlock {...props} />;
}
@@ -12,6 +12,7 @@ import { getSelectAction } from './selectAction';
import { SelectActionButton } from './SelectActionButton';
import { isSiteAuthLoginHref } from '@/lib/auth-login-link';
import { resolveContentRefFallback, resolveContentRefInDocument } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
// Editor button sizes render one step smaller here; the editor default (`large`) keeps the previous `medium`.
const BUTTON_SIZE_MAP: Record<
@@ -23,6 +24,28 @@ const BUTTON_SIZE_MAP: Record<
large: 'medium',
};
// Only content buttons take the site's secondary colour; the `secondary` variant also styles site chrome.
const SECONDARY_COLOR_CLASSES = tcls(
'bg-secondary',
'depth-flat:bg-secondary-base',
'text-secondary',
'hover:bg-secondary-hover',
'hover:not-disabled:depth-flat:bg-secondary-hover',
'hover:not-disabled:text-secondary',
'contrast-more:bg-secondary-subtle',
'disabled:text-secondary/8',
'border-secondary',
'hover:border-secondary-hover',
'disabled:border-secondary',
'shadow-secondary/6',
'dark:shadow-secondary-1',
'contrast-more:border-secondary-12',
'contrast-more:hover:outline-secondary-12',
'contrast-more:hover:border-secondary-12',
'contrast-more:focus-visible:border-secondary-12',
'contrast-more:focus-visible:outline-secondary-12'
);
export function InlineButton(props: InlineProps<api.DocumentInlineButton>) {
const { inline, context } = props;
@@ -31,6 +54,7 @@ export function InlineButton(props: InlineProps<api.DocumentInlineButton>) {
variant: inline.data.kind,
icon: inline.data.icon as IconName | undefined,
size: BUTTON_SIZE_MAP[inline.data.size ?? 'large'],
className: inline.data.kind === 'secondary' ? SECONDARY_COLOR_CLASSES : undefined,
};
const ButtonImplementation = () => {
@@ -3,7 +3,7 @@ import * as React from 'react';
import type { DocumentInlineExpression } from '@gitbook/api';
import type { InlineProps } from '../Inline';
import { InlineExpressionValue } from './InlineExpressionValue';
import { InlineExpressionValueLazy } from './InlineExpressionValueLazy';
/**
* Render an inline expression.
@@ -25,7 +25,7 @@ export function InlineExpression(props: InlineProps<DocumentInlineExpression>) {
return (
<React.Suspense fallback={null}>
<InlineExpressionValue expression={data.expression} variables={variables} />
<InlineExpressionValueLazy expression={data.expression} variables={variables} />
</React.Suspense>
);
}
@@ -0,0 +1,18 @@
'use client';
import dynamic from 'next/dynamic';
import type { InlineExpressionVariables } from './types';
// Keeps `@gitbook/expr` out of the eager bundle; `ssr: true` keeps values in the HTML.
const InlineExpressionValue = dynamic(
() => import('./InlineExpressionValue').then((mod) => mod.InlineExpressionValue),
{ ssr: true }
);
export function InlineExpressionValueLazy(props: {
expression: string;
variables: InlineExpressionVariables;
}) {
return <InlineExpressionValue {...props} />;
}
@@ -1,3 +1,2 @@
export * from './InlineExpression';
export * from './types';
export * from './useEvaluateInlineExpression';
@@ -1,6 +1,6 @@
'use client';
import type React from 'react';
import React from 'react';
import type { CustomizationThemedCodeTheme } from '@gitbook/api';
import {
@@ -12,6 +12,10 @@ import {
import { ClientPlainCodeBlock } from '../CodeBlock/ClientPlainCodeBlock';
import type { DocumentContext } from '../DocumentView';
import { matchesText } from '../Table/searchMatch';
import { MIN_RECORDS_FOR_SEARCH } from '../Table/shouldShowSearch';
import { Input } from '@/components/primitives';
import { tString, useLanguage } from '@/intl/client';
// Only what survives the RSC boundary. Rebuilding the renderers on the client is what lets this
// whole subtree sit behind a `next/dynamic` chunk instead of the route's eager entry.
@@ -74,14 +78,51 @@ export function OpenAPIBlockClient(props: OpenAPIBlockClientProps) {
);
case 'webhook':
return <BaseOpenAPIWebhook data={props.data} context={context} className={className} />;
case 'schemas':
case 'schemas': {
const SchemasComponent =
mode !== 'print' && props.data.schemas.length >= MIN_RECORDS_FOR_SEARCH
? OpenAPISchemasWithSearch
: BaseOpenAPISchemas;
return (
<BaseOpenAPISchemas
<SchemasComponent
data={props.data}
grouped={props.grouped}
context={context}
className={className}
/>
);
}
}
}
function OpenAPISchemasWithSearch(props: React.ComponentProps<typeof BaseOpenAPISchemas>) {
const { data, ...rest } = props;
const language = useLanguage();
const [query, setQuery] = React.useState('');
// A models page can hold hundreds of schemas; keep typing responsive while the list re-renders.
const deferredQuery = React.useDeferredValue(query).trim();
const schemas = data.schemas.filter(({ name }) => matchesText(name, deferredQuery));
return (
<div className="flex min-w-0 flex-1 flex-col gap-4">
<Input
label={tString(language, 'search')}
value={query}
onValueChange={setQuery}
leading="magnifying-glass"
clearButton
sizing="small"
keyboardShortcut={false}
/>
{schemas.length > 0 ? (
// `grouped` keeps the list layout when the search narrows it down to one model.
<BaseOpenAPISchemas {...rest} data={{ ...data, schemas }} grouped />
) : (
<div className="mb-14 py-8 text-center text-sm text-tint">
{tString(language, 'search_no_results_for', deferredQuery)}
</div>
)}
</div>
);
}
@@ -141,7 +141,8 @@ const TabItemList = memo(function TabItemList(props: {
onSelect: (tabId: string) => void;
}) {
const { tabs, activeTabId, onSelect } = props;
const { containerRef, itemRef, overflowing, isMeasuring } = useListOverflow();
// The active tab's width decides how many others fit, so a new selection re-measures.
const { containerRef, itemRef, overflowing, isMeasuring } = useListOverflow(activeTabId);
const overflowingTabs = useMemo(
() =>
Array.from(overflowing, (id) => {
@@ -181,6 +182,7 @@ const TabItemList = memo(function TabItemList(props: {
key={tab.id}
ref={itemRef}
isActive={tab.id === activeTabId}
isMeasuring={isMeasuring}
tab={tab}
onSelect={onSelect}
/>
@@ -239,10 +241,11 @@ function TabsDropdownMenu(props: {
const TabItem = memo(function TabItem(props: {
ref: React.Ref<HTMLButtonElement>;
isActive: boolean;
isMeasuring: boolean;
tab: TabsItem;
onSelect: (tabId: string) => void;
}) {
const { ref, tab, isActive, onSelect } = props;
const { ref, tab, isActive, isMeasuring, onSelect } = props;
return (
<TabButton
ref={ref}
@@ -250,7 +253,20 @@ const TabItem = memo(function TabItem(props: {
aria-selected={isActive}
aria-controls={tab.id}
id={getTabButtonId(tab.id)}
title={tab.title}
onClick={() => onSelect(tab.id)}
wrapperClassName={
isActive
? // Keeps room for the overflow menu button.
'max-w-[calc(100%-3rem)]'
: isMeasuring
? // Measured after the active tab, at their narrowest, so the menu only takes
// the tabs that can't fit even truncated.
'order-1 max-w-28'
: // Equal shares capped at their own width, so no tab drops below that
// narrowest size; the high grow leaves the strip's filler only the leftover.
'min-w-0 max-w-max basis-0 grow-[1000]'
}
>
{tab.icon && <Icon icon={tab.icon} className="size-4 shrink-0" />}
<span className="min-w-0 truncate">{tab.title}</span>
@@ -264,9 +280,10 @@ const TabItem = memo(function TabItem(props: {
function TabButton(
props: Omit<ComponentPropsWithRef<'button'>, 'type'> & {
isActive?: boolean;
wrapperClassName?: string;
}
) {
const { isActive, ...rest } = props;
const { isActive, wrapperClassName, ...rest } = props;
return (
<div
className={tcls(
@@ -310,14 +327,15 @@ function TabButton(
'[:has(+_&.active-tab)]:after:border-transparent',
'[:has(&_+)]:after:border-transparent',
]
: null
: null,
wrapperClassName
)}
>
<button
{...rest}
type="button"
className={tcls(
'relative inline-flex max-w-full items-center gap-1.5 px-4 py-2.5 font-medium text-sm transition-[color]',
'relative inline-flex min-w-0 max-w-full items-center gap-1.5 px-4 py-2.5 font-medium text-sm transition-[color]',
props.className
)}
/>
@@ -38,12 +38,21 @@ export function Text(props: { text: DocumentText }) {
{children}
</Mark>
);
}, leaf.text)}
}, withSoftBreaks(leaf.text))}
</React.Fragment>
);
});
}
// Paragraphs with buttons are flex containers, where a `\n` alone can't move the next items to a new line.
function withSoftBreaks(text: string): React.ReactNode {
const lines = text.split('\n');
// Keep `\n` in the same text node as a preceding `\r`: split apart, the HTML parser reads the lone `\r` as an extra line.
return lines.flatMap((line, index) =>
index < lines.length - 1 ? [`${line}\n`, <span key={index} className="basis-full" />] : line
);
}
const MARK_STYLES = {
bold: Bold,
italic: Italic,
@@ -49,7 +49,7 @@ import { defaultCustomization } from '@/lib/utils';
function preloadFont(fontData: FontData) {
if (fontData.type === 'custom') {
ReactDOM.preconnect(GITBOOK_FONTS_URL);
ReactDOM.preconnect(GITBOOK_FONTS_URL, { crossOrigin: 'anonymous' });
fontData.preloadSources
.flatMap((face) => face.sources)
.forEach(({ url, format }) => {
@@ -92,6 +92,30 @@ export async function CustomizationRootLayout(props: {
// (undefined) and keeps a neutral page background.
const tintBaseStep =
theme === CustomizationTheme.Bold ? undefined : theme === CustomizationTheme.Muted ? 2 : 1;
const tintScale = {
light: {
color: tintColor ? tintColor.light : DEFAULT_TINT_COLOR,
options: {
baseStep: tintBaseStep,
mix: mixColor && { color: mixColor.color.light, ratio: mixColor.ratio.light },
},
},
dark: {
color: tintColor ? tintColor.dark : DEFAULT_TINT_COLOR,
options: {
darkMode: true,
baseStep: tintBaseStep,
mix: mixColor && { color: mixColor.color.dark, ratio: mixColor.ratio.dark },
},
},
};
const secondaryColor = customization.styling.secondaryColor;
const secondaryScale = secondaryColor
? {
light: { color: secondaryColor.light, options: {} },
dark: { color: secondaryColor.dark, options: { darkMode: true } },
}
: tintScale;
const { infoColor, successColor, warningColor, dangerColor } = getSemanticColors(customization);
const fontData = getFontData(customization.styling.font, 'content');
// Temporarily add a if here while the cache is being warmed up.
@@ -178,7 +202,8 @@ export async function CustomizationRootLayout(props: {
>{`
:root, .light, .dark [data-color-scheme$="light"], .dark [data-follow-color-scheme="true"]:has([data-color-scheme$="light"]) {
${generateColorVariable('primary', customization.styling.primaryColor.light)}
${generateColorVariable('tint', tintColor ? tintColor.light : DEFAULT_TINT_COLOR, { baseStep: tintBaseStep, mix: mixColor && { color: mixColor.color.light, ratio: mixColor.ratio.light } })}
${generateColorVariable('tint', tintScale.light.color, tintScale.light.options)}
${generateColorVariable('secondary', secondaryScale.light.color, secondaryScale.light.options)}
${generateColorVariable('neutral', DEFAULT_TINT_COLOR)}
--header-background: ${
@@ -205,7 +230,8 @@ export async function CustomizationRootLayout(props: {
.dark, :root:not(.dark) [data-color-scheme^="dark"], :root:not(.dark) [data-follow-color-scheme="true"]:has([data-color-scheme^="dark"]) {
${generateColorVariable('primary', customization.styling.primaryColor.dark, { darkMode: true })}
${generateColorVariable('tint', tintColor ? tintColor.dark : DEFAULT_TINT_COLOR, { darkMode: true, baseStep: tintBaseStep, mix: mixColor && { color: mixColor?.color.dark, ratio: mixColor.ratio.dark } })}
${generateColorVariable('tint', tintScale.dark.color, tintScale.dark.options)}
${generateColorVariable('secondary', secondaryScale.dark.color, secondaryScale.dark.options)}
${generateColorVariable('neutral', DEFAULT_TINT_COLOR, { darkMode: true })}
--header-background: ${hexToRgb(customization.header.backgroundColor?.dark ?? tintColor?.dark ?? customization.styling.primaryColor.dark)};
@@ -1,6 +1,7 @@
'use server';
import { createStreamableValue } from 'ai/rsc';
import { headers } from 'next/headers';
import type * as React from 'react';
import type {
@@ -13,6 +14,7 @@ import type {
import { DocumentView } from '../DocumentView';
import { isAIEnabled, isAISearchEnabled } from '@/components/utils/isAIChatEnabled';
import { getAskForwardedHeaders, getAskVisitorAgent } from '@/lib/ask-visitor';
import type { GitBookSiteContext } from '@/lib/context';
import { throwIfDataError } from '@/lib/data';
import { toEmbeddableLinkForPublishedContent } from '@/lib/embeddable-linker';
@@ -77,7 +79,8 @@ export async function streamAskQuestion({
},
session,
},
{ format: 'document' }
{ format: 'document' },
{ headers: getAskForwardedHeaders(getAskVisitorAgent(await headers())) }
);
const spacePromises = new Map<string, Promise<Revision>>();
@@ -64,11 +64,12 @@ export async function SiteLayout(props: {
// Scripts are disabled when tracking is disabled
const scripts = withTracking ? context.scripts : [];
ReactDOM.preconnect(GITBOOK_API_PUBLIC_URL);
ReactDOM.preconnect(GITBOOK_ICONS_URL);
if (GITBOOK_ASSETS_URL) {
ReactDOM.preconnect(GITBOOK_ASSETS_URL);
}
// React dedupes preconnects by href, so reduce to the origin; relative URLs are same-origin.
[GITBOOK_API_PUBLIC_URL, GITBOOK_ICONS_URL, GITBOOK_ASSETS_URL].forEach((url) => {
if (url && URL.canParse(url)) {
ReactDOM.preconnect(new URL(url).origin);
}
});
// Start the search-index download from the HTML itself. `crossOrigin` must match the
// client `fetch()` (cors + same-origin credentials) or the preload is ignored and the
@@ -30,8 +30,10 @@ interface OverflowState {
* shows *because* items overflow (a "more" menu, say) has to be rendered ahead of the items in that
* phase: the measurement discounts the space taken before the first item, so a list that fits on its
* own is not reported as overflowing merely because that menu was reserving room for itself.
*
* The list is measured again whenever `remeasureKey` changes.
*/
export function useListOverflow(): OverflowState {
export function useListOverflow(remeasureKey?: unknown): OverflowState {
const containerRef = useRef<HTMLDivElement>(null);
const [overflowing, setOverflowing] = useState<Set<string>>(new Set());
// Measuring is a request/completed pair of counters rather than a boolean, because a boolean
@@ -58,6 +60,12 @@ export function useListOverflow(): OverflowState {
const requestMeasure = useCallback(() => setMeasureRequest((request) => request + 1), []);
const [measuredKey, setMeasuredKey] = useState(remeasureKey);
if (measuredKey !== remeasureKey) {
setMeasuredKey(remeasureKey);
setMeasureRequest((request) => request + 1);
}
// Measure on mount and when container size changes
useEffect(() => {
if (!containerRef.current) {
@@ -0,0 +1,48 @@
import { describe, expect, it } from 'bun:test';
import { getAskForwardedHeaders, getAskVisitorAgent } from './ask-visitor';
describe('getAskVisitorAgent', () => {
it('should read the User-Agent and Signature-Agent headers', () => {
expect(
getAskVisitorAgent(
new Headers({
'user-agent': 'claude-code/2.0.0',
'signature-agent': '"https://chatgpt.com"',
})
)
).toEqual({ userAgent: 'claude-code/2.0.0', signatureAgent: '"https://chatgpt.com"' });
});
it('should omit missing or empty headers', () => {
const agent = getAskVisitorAgent(new Headers({ 'user-agent': '' }));
expect(agent).toEqual({});
expect('userAgent' in agent).toBe(false);
});
it('should truncate overly long headers', () => {
const agent = getAskVisitorAgent(new Headers({ 'user-agent': 'a'.repeat(2000) }));
expect(agent.userAgent).toHaveLength(512);
});
});
describe('getAskForwardedHeaders', () => {
it('should forward the visitor agent in X-Original headers', () => {
expect(
getAskForwardedHeaders({
userAgent: 'claude-code/2.0.0',
signatureAgent: '"https://chatgpt.com"',
})
).toEqual({
'X-Original-User-Agent': 'claude-code/2.0.0',
'X-Original-Signature-Agent': '"https://chatgpt.com"',
});
});
it('should omit headers the visitor did not send', () => {
expect(getAskForwardedHeaders({ userAgent: 'curl/8.7.1' })).toEqual({
'X-Original-User-Agent': 'curl/8.7.1',
});
expect(getAskForwardedHeaders()).toEqual({});
});
});
+36
View File
@@ -0,0 +1,36 @@
/**
* Headers identifying who asked a question, forwarded so the API can classify the asker
* (human, agent, bot) the same way it classifies insights events.
*/
export interface AskVisitorAgent {
userAgent?: string;
signatureAgent?: string;
}
// Bounds the header values, as they end up in the static route path of `?ask=`.
const MAX_HEADER_LENGTH = 512;
/**
* Read the visitor's `User-Agent` and `Signature-Agent` from the request headers.
* Missing headers are omitted rather than set to undefined, so the result can be rison-encoded.
*/
export function getAskVisitorAgent(headers: Pick<Headers, 'get'>): AskVisitorAgent {
const userAgent = headers.get('user-agent')?.slice(0, MAX_HEADER_LENGTH);
const signatureAgent = headers.get('signature-agent')?.slice(0, MAX_HEADER_LENGTH);
return {
...(userAgent ? { userAgent } : {}),
...(signatureAgent ? { signatureAgent } : {}),
};
}
/**
* Request headers forwarding the visitor's agent on ask and Assistant API calls.
* Our own `User-Agent` is left as is: the API relies on it to know the published site is calling.
*/
export function getAskForwardedHeaders(agent: AskVisitorAgent = {}): Record<string, string> {
return {
...(agent.userAgent ? { 'X-Original-User-Agent': agent.userAgent } : {}),
...(agent.signatureAgent ? { 'X-Original-Signature-Agent': agent.signatureAgent } : {}),
};
}
+8 -1
View File
@@ -1,5 +1,6 @@
import type { SearchAIAnswer, SearchAIAnswerSource } from '@gitbook/api';
import { type AskVisitorAgent, getAskForwardedHeaders } from '@/lib/ask-visitor';
import type { GitBookSiteContext } from '@/lib/context';
import { throwIfDataError } from '@/lib/data';
import { resolvePageId } from '@/lib/pages';
@@ -15,6 +16,11 @@ export interface StreamSiteAskOptions {
* Used by the backend to steer the answer.
*/
goal?: string;
/**
* Headers of the visitor asking the question, used by the backend to classify the asker.
*/
visitorAgent?: AskVisitorAgent;
}
/**
@@ -45,7 +51,8 @@ export async function streamSiteAskAnswer(
currentSiteSpace: context.siteSpace.id,
},
},
{ format: 'markdown' }
{ format: 'markdown' },
{ headers: getAskForwardedHeaders(options.visitorAgent) }
);
let latestAnswer: SearchAIAnswer | null = null;
+2
View File
@@ -14,6 +14,7 @@ export const textColorToStyle = {
cyan: ['text-[#007c7c] dark:text-[#6bcac9]'],
orange: ['text-[#ae4300] dark:text-[#eea471]'],
$primary: ['text-primary-subtle contrast-more:text-primary'],
$secondary: ['text-secondary-subtle contrast-more:text-secondary'],
$info: ['text-info-subtle contrast-more:text-info'],
$success: ['text-success-subtle contrast-more:text-success'],
$warning: ['text-warning-subtle contrast-more:text-warning'],
@@ -33,6 +34,7 @@ export const backgroundColorToStyle = {
cyan: ['bg-[#ddf8f8] dark:bg-[#093b3b]'],
orange: ['bg-[#ffecdc] dark:bg-[#492a13]'],
$primary: ['bg-primary'],
$secondary: ['bg-secondary'],
$info: ['bg-info'],
$success: ['bg-success'],
$warning: ['bg-warning'],
+7
View File
@@ -23,6 +23,7 @@ import type {
import { GITBOOK_URL } from './env';
import { type ImageResizer, createImageResizer } from './images';
import { type GitBookLinker, createLinker, linkerForPublishedURL } from './links';
import type { AskVisitorAgent } from '@/lib/ask-visitor';
import {
type GitBookDataFetcher,
createDataFetcher,
@@ -104,6 +105,12 @@ export type SiteURLData = Pick<
/** Whether the request comes from ChatGPT. Only set for Markdown and LLM routes. */
isChatGPT?: boolean;
/**
* Headers of the visitor asking through `?ask=`, forwarded to the API to classify the asker.
* Only set for the ask route, which is static and can't read the request headers.
*/
askVisitorAgent?: AskVisitorAgent;
};
/**
+4
View File
@@ -15,6 +15,7 @@ import {
} from '@/lib/agentFeedback';
import { submitAgentFeedback } from '@/lib/agentFeedback/server';
import { renderAskSourcesMarkdown, streamSiteAskAnswer } from '@/lib/ask';
import { getAskVisitorAgent } from '@/lib/ask-visitor';
import type { GitBookSiteContext } from '@/lib/context';
import { getExposableError, throwIfDataError } from '@/lib/data';
import { fromPageMarkdown, getMarkdownForPageInSpace, toPageMarkdown } from '@/lib/markdownPage';
@@ -261,8 +262,11 @@ export function createSiteMcpTools(
const trimmedGoal = goal?.trim() || undefined;
// The MCP server is stateless, so the `clientInfo` from `initialize` isn't
// available here: rely on the HTTP user agent, as the `ask_question` event does.
const answer = await streamSiteAskAnswer(context, trimmedQuestion, {
goal: trimmedGoal,
visitorAgent: getAskVisitorAgent(request.headers),
});
trackMcpEvent({
+27 -1
View File
@@ -2,7 +2,13 @@ import { describe, expect, it } from 'bun:test';
import type { PublishedSiteContent } from '@gitbook/api';
import { getPreviewCookieResponse, getPreviewRequestIdentifier, isPreviewRequest } from './preview';
import {
getPreviewCookieResponse,
getPreviewRequestIdentifier,
isPreviewRequest,
parsePreviewCustomizationCookie,
serializePreviewCustomizationCookie,
} from './preview';
describe('isPreviewRequest', () => {
it('should return true for preview requests', () => {
@@ -65,3 +71,23 @@ describe('getPreviewCookieResponse', () => {
expect(cookie.options?.path).toBe('/docs/');
});
});
describe('parsePreviewCustomizationCookie', () => {
const customization = "(styling:(primaryColor:(dark:'#ff0000',light:'#ff0000')))";
const value = serializePreviewCustomizationCookie({ customization, siteSpace: 'sitesp_a' });
it('returns the override for the site space it was created for', () => {
expect(parsePreviewCustomizationCookie(value, 'sitesp_a')).toBe(customization);
});
it('ignores the override for another site space', () => {
expect(parsePreviewCustomizationCookie(value, 'sitesp_b')).toBeUndefined();
expect(parsePreviewCustomizationCookie(value, 'sitesp')).toBeUndefined();
});
it('ignores a cookie not bound to a site space', () => {
expect(
parsePreviewCustomizationCookie(encodeURIComponent(customization), 'sitesp_a')
).toBeUndefined();
});
});
+28
View File
@@ -30,6 +30,34 @@ export function getPreviewRequestIdentifier(requestURL: URL): string {
throw new Error('Not a preview request');
}
/**
* Serialize a customization override into the preview cookie value.
* The override holds the full settings of the site space it was created for,
* so it is bound to that site space to not leak into the other ones of the preview.
*/
export function serializePreviewCustomizationCookie(args: {
customization: string;
siteSpace: string;
}): string {
return `${args.siteSpace}:${encodeURIComponent(args.customization)}`;
}
/**
* Get the customization override from the preview cookie value,
* only if it was created for the given site space.
*/
export function parsePreviewCustomizationCookie(
value: string,
siteSpace: string
): string | undefined {
const prefix = `${siteSpace}:`;
if (!value.startsWith(prefix)) {
return undefined;
}
return decodeURIComponent(value.slice(prefix.length));
}
/**
* Get a cookie for the preview request.
*/
+57 -6
View File
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'bun:test';
import type { JwtPayload } from 'jwt-decode';
import { NextResponse } from 'next/server';
import {
type ResponseCookies,
@@ -234,21 +235,66 @@ describe('getResponseCookiesForVisitorAuth write policy', () => {
const base64url = (value: object) => Buffer.from(JSON.stringify(value)).toString('base64url');
const token = `${base64url({ alg: 'none' })}.${base64url({ exp: 2_000_000_000 })}.sig`;
const requestHeaders = new Headers();
it('persists a token that arrived in the URL', () => {
expect(getResponseCookiesForVisitorAuth('/', { source: 'url', token })).toHaveLength(1);
const visitorTokenLookup = { source: 'url', token } as const;
expect(
getResponseCookiesForVisitorAuth({ basePath: '/', visitorTokenLookup, requestHeaders })
).toHaveLength(1);
});
it('only accepts a token that arrived in the URL', () => {
const fromVACookie = { source: 'visitor-auth-cookie', basePath: '/', token } as const;
const fromCustomCookie = { source: 'gitbook-visitor-cookie', token } as const;
// @ts-expect-error a token read back from a VA cookie must never be persisted again
const buildFromVACookie = () => getResponseCookiesForVisitorAuth('/', fromVACookie);
// @ts-expect-error a custom visitor cookie is owned by the customer's backend
const buildFromCustom = () => getResponseCookiesForVisitorAuth('/', fromCustomCookie);
const buildFromVACookie = () =>
getResponseCookiesForVisitorAuth({
basePath: '/',
// @ts-expect-error a token read back from a VA cookie must never be persisted again
visitorTokenLookup: fromVACookie,
requestHeaders,
});
const buildFromCustom = () =>
getResponseCookiesForVisitorAuth({
basePath: '/',
// @ts-expect-error a custom visitor cookie is owned by the customer's backend
visitorTokenLookup: fromCustomCookie,
requestHeaders,
});
expect([buildFromVACookie, buildFromCustom]).toHaveLength(2);
});
it('partitions the cookie only inside an iframe, and clears both kinds', async () => {
const env = process.env as Record<string, string | undefined>;
const previousEnv = env.NODE_ENV;
env.NODE_ENV = 'production';
// A fresh module instance, as `NODE_ENV` is read once at import.
const visitors = (await import(`./visitors?${'production'}`).finally(() => {
env.NODE_ENV = previousEnv;
})) as typeof import('./visitors');
const setCookie = (secFetchDest: string) => {
const response = new NextResponse();
for (const cookie of visitors.getResponseCookiesForVisitorAuth({
basePath: '/',
visitorTokenLookup: { source: 'url', token },
requestHeaders: new Headers({ 'sec-fetch-dest': secFetchDest }),
})) {
response.cookies.set(cookie.name, cookie.value, cookie.options);
}
return response.headers.get('set-cookie');
};
expect(setCookie('iframe')).toContain('Partitioned');
expect(setCookie('document')).not.toContain('Partitioned');
const clear = `${getVisitorAuthCookieName('/')}=; Path=/; Max-Age=0; Secure; SameSite=None`;
expect(visitors.getVisitorAuthClearCookieHeaders('/')).toEqual([
`${clear}; Partitioned`,
clear,
]);
});
});
describe('getResponseCookiesForVisitorAuth chunking', () => {
@@ -261,7 +307,12 @@ describe('getResponseCookiesForVisitorAuth chunking', () => {
};
const write = (basePath: string, token: string, previous: ResponseCookies = []) =>
getResponseCookiesForVisitorAuth(basePath, { source: 'url', token }, previous);
getResponseCookiesForVisitorAuth({
basePath,
visitorTokenLookup: { source: 'url', token },
requestCookies: previous,
requestHeaders: new Headers(),
});
const read = (cookies: ResponseCookies, urlPath = '/') =>
getVisitorToken({
+48 -15
View File
@@ -15,6 +15,7 @@ const VISITOR_AUTH_PARAM = 'jwt_token';
const VISITOR_PARAM_PREFIX = 'visitor.';
export const VISITOR_TOKEN_COOKIE = 'gitbook-visitor-token';
const VISITOR_UNSIGNED_CLAIMS_PREFIX = 'gitbook-visitor-public';
const IS_SECURE = process.env.NODE_ENV === 'production';
/**
* Typing for a cookie, matching the internal type of Next.js.
@@ -28,6 +29,7 @@ export type ResponseCookie = {
secure: boolean;
maxAge: number;
path: string;
partitioned: boolean;
}>;
};
@@ -146,7 +148,10 @@ export function getVisitorData({
}): VisitorDataLookup {
const visitorToken = getVisitorToken({ cookies, headers, url });
const unsignedClaims = getVisitorUnsignedClaims({ cookies, url });
const visitorParamsCookie = getResponseCookieForVisitorParams(unsignedClaims.fromVisitorParams);
const visitorParamsCookie = getResponseCookieForVisitorParams({
visitorParamsClaims: unsignedClaims.fromVisitorParams,
requestHeaders: headers,
});
return {
visitorToken,
@@ -318,9 +323,13 @@ function parseVisitorQueryParamValue(value: string): ClaimPrimitive {
/**
* Returns to cookie response to use in order to persist visitor params that were passed to the URL.
*/
function getResponseCookieForVisitorParams(
visitorParamsClaims: Record<string, ClaimPrimitive>
): ResponseCookie | undefined {
function getResponseCookieForVisitorParams({
visitorParamsClaims,
requestHeaders,
}: {
visitorParamsClaims: Record<string, ClaimPrimitive>;
requestHeaders: Headers;
}): ResponseCookie | undefined {
if (Object.keys(visitorParamsClaims).length === 0) {
return undefined;
}
@@ -328,10 +337,20 @@ function getResponseCookieForVisitorParams(
return {
name: VISITOR_UNSIGNED_CLAIMS_PREFIX,
value: JSON.stringify(visitorParamsClaims),
options: {
sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined,
secure: process.env.NODE_ENV === 'production',
},
options: getVisitorCookieCrossSiteOptions(requestHeaders),
};
}
/**
* Attributes letting visitor cookies be stored inside a cross-site iframe (authenticated embeds).
* `Partitioned` (CHIPS) is kept to iframes: Safari drops partitioned cookies after cross-site
* redirect chains (WebKit 306194), which top-level login flows go through.
*/
function getVisitorCookieCrossSiteOptions(requestHeaders: Headers) {
return {
sameSite: IS_SECURE ? ('none' as const) : undefined,
secure: IS_SECURE,
partitioned: IS_SECURE && requestHeaders.get('sec-fetch-dest') === 'iframe',
};
}
@@ -344,11 +363,17 @@ function getResponseCookieForVisitorParams(
* custom `gitbook-visitor-token` cookie is owned by the customer's backend and is never copied,
* to keep a single source of truth.
*/
export function getResponseCookiesForVisitorAuth(
basePath: string,
visitorTokenLookup: Extract<VisitorTokenLookup, { source: 'url' }>,
requestCookies: RequestCookies = []
): ResponseCookies {
export function getResponseCookiesForVisitorAuth({
basePath,
visitorTokenLookup,
requestCookies = [],
requestHeaders,
}: {
basePath: string;
visitorTokenLookup: Extract<VisitorTokenLookup, { source: 'url' }>;
requestCookies?: RequestCookies;
requestHeaders: Headers;
}): ResponseCookies {
let decoded: JwtPayload;
try {
decoded = jwtDecode(visitorTokenLookup.token);
@@ -361,8 +386,7 @@ export function getResponseCookiesForVisitorAuth(
const value = getVisitorAuthCookieValue(basePath, visitorTokenLookup.token);
const options = {
httpOnly: true,
sameSite: process.env.NODE_ENV === 'production' ? ('none' as const) : undefined,
secure: process.env.NODE_ENV === 'production',
...getVisitorCookieCrossSiteOptions(requestHeaders),
maxAge: getVisitorAuthCookieMaxAge(decoded),
};
@@ -392,6 +416,15 @@ export function getVisitorAuthCookieName(basePath: string): string {
return getPathScopedCookieName(VISITOR_TOKEN_COOKIE, basePath);
}
/**
* `Set-Cookie` values clearing the visitor authentication cookie. Browsers keep partitioned and
* unpartitioned cookies apart, so both are cleared whenever `Partitioned` can be set.
*/
export function getVisitorAuthClearCookieHeaders(basePath: string): string[] {
const header = `${getVisitorAuthCookieName(basePath)}=; Path=/; Max-Age=0${IS_SECURE ? '; Secure; SameSite=None' : ''}`;
return IS_SECURE ? [`${header}; Partitioned`, header] : [header];
}
/**
* Get the value of the visitor authentication cookie for a given base path and token.
*/
+23 -7
View File
@@ -23,6 +23,7 @@ import {
} from './lib/tracking';
import { AI_CATALOG_PATH, AI_CATALOG_WELL_KNOWN_PATH } from '@/lib/aiCatalog/paths';
import { getAPITokenFromCookies, getAPITokenResponseCookies } from '@/lib/api-token-cookie';
import { type AskVisitorAgent, getAskVisitorAgent } from '@/lib/ask-visitor';
import { isChatGPTRequest } from '@/lib/chatgpt';
import { MAX_CHUNKED_COOKIE_LENGTH } from '@/lib/chunked-cookies';
import type { SiteURLData } from '@/lib/context';
@@ -51,6 +52,8 @@ import {
getPreviewCookieResponse,
getPreviewRequestIdentifier,
isPreviewRequest,
parsePreviewCustomizationCookie,
serializePreviewCustomizationCookie,
} from '@/lib/preview';
import {
type ResponseCookies,
@@ -350,11 +353,12 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
) {
if (visitorToken?.source === 'url') {
cookies.push(
...getResponseCookiesForVisitorAuth(
getVisitorAuthBasePath(siteRequestURL, siteURLData),
visitorToken,
request.cookies.getAll()
)
...getResponseCookiesForVisitorAuth({
basePath: getVisitorAuthBasePath(siteRequestURL, siteURLData),
visitorTokenLookup: visitorToken,
requestCookies: request.cookies.getAll(),
requestHeaders: request.headers,
})
);
}
@@ -421,7 +425,9 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
const customizationCookie = request.cookies.get(MiddlewareHeaders.Customization);
const customization =
siteRequestURL.searchParams.get('customization') ??
(customizationCookie ? decodeURIComponent(customizationCookie.value) : undefined);
(customizationCookie
? parsePreviewCustomizationCookie(customizationCookie.value, siteURLData.siteSpace)
: undefined);
if (
allowCustomizationOverride &&
customization &&
@@ -434,7 +440,10 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
cookies.push(
getPreviewCookieResponse({
name: MiddlewareHeaders.Customization,
value: encodeURIComponent(customization),
value: serializePreviewCustomizationCookie({
customization,
siteSpace: siteURLData.siteSpace,
}),
mode,
siteRequestURL,
siteURLData,
@@ -470,11 +479,14 @@ async function serveSiteRoutes(requestURL: URL, request: NextRequest) {
events,
isAiAgent,
isChatGPT,
askVisitorAgent,
} = encodePathInSiteContent(siteURLData, request);
routeType = routeTypeFromPathname ?? routeType;
// Only set for Markdown and LLM routes, so these request-specific variants are cached separately.
stableSiteURLData.isAiAgent = isAiAgent;
stableSiteURLData.isChatGPT = isChatGPT;
// Splits the cache of `?ask=` answers per user agent, so each asker is classified correctly.
stableSiteURLData.askVisitorAgent = askVisitorAgent;
// Apply a forced theme (`?theme=`/cookie). For the docs embed we thread it through the
// route context (`embedTheme`) so those routes stay statically rendered — it becomes part
@@ -800,6 +812,8 @@ function encodePathInSiteContent(
isAiAgent?: boolean;
/** Only set for Markdown and LLM routes, where the output content type depends on ChatGPT. */
isChatGPT?: boolean;
/** Only set for the ask route, where the API classifies the asker from these headers. */
askVisitorAgent?: AskVisitorAgent;
} {
let pathname = removeLeadingSlash(removeTrailingSlash(siteURLData.pathname));
@@ -941,6 +955,8 @@ function encodePathInSiteContent(
// Left undefined for non-agents to avoid splitting the static cache for them.
isAiAgent: isAiAgent || undefined,
isChatGPT: isChatGPTRequest(request) || undefined,
askVisitorAgent:
typeof ask === 'string' ? getAskVisitorAgent(request.headers) : undefined,
// TODO: track pageId / spaceId when possible
// We don't do it at the moment as we can't easily extract it from the URL.
events: ask
+10 -1
View File
@@ -1,5 +1,6 @@
import { isAIEnabled } from '@/components/utils/isAIChatEnabled';
import { renderAskSourcesMarkdown, streamSiteAskAnswer } from '@/lib/ask';
import type { AskVisitorAgent } from '@/lib/ask-visitor';
import type { GitBookSiteContext } from '@/lib/context';
import { linkerWithMarkdownPages } from '@/lib/links';
import { fromPageMarkdown, toPageMarkdown } from '@/lib/markdownPage';
@@ -14,6 +15,11 @@ export interface ServeAskMarkdownOptions {
* passed via the `?goal=` search parameter. Used by the backend to steer the answer.
*/
goal?: string;
/**
* Headers of the visitor asking the question, forwarded to the backend to classify the asker.
*/
visitorAgent?: AskVisitorAgent;
}
/**
@@ -41,7 +47,10 @@ export async function serveAskMarkdown(
return 'You forgot to pass a question in the `?ask=` parameter. Append a question to the URL in the `?ask=<question>` search parameter to get a complete answer and associated sources.';
}
const latestAnswer = await streamSiteAskAnswer(context, question, { goal });
const latestAnswer = await streamSiteAskAnswer(context, question, {
goal,
visitorAgent: options.visitorAgent,
});
if (!latestAnswer || !latestAnswer.answer || !('markdown' in latestAnswer.answer)) {
return `We couldn't answer this question.`;
+1 -1
View File
@@ -7,7 +7,7 @@ import { ColorCategory, hexToRgb, scale, shadesOfColor } from '@gitbook/colors';
export const shades = [50, 100, 200, 300, 400, 500, 600, 700, 800, 900];
export const opacities = [0, 4, 8, 12, 16, 24, 40, 64, 72, 88, 96, 100];
export const semanticColors = ['info', 'warning', 'danger', 'success'];
export const semanticColors = ['secondary', 'info', 'warning', 'danger', 'success'];
/**
* Generate a Tailwind color shades from a variable.