Compare commits

...

30 Commits

Author SHA1 Message Date
taranvohra f720f1dbd6 changeset 2026-09-18 12:23:47 +05:30
taranvohra 59bc231ccd Resolve repository page URLs without an opt-in flag 2026-09-18 12:22:53 +05:30
taranvohra 3c177f04a2 changeset 2026-09-17 20:42:47 +05:30
taranvohra 1d648a9391 Resolve repository page URLs within published sites 2026-09-17 20:42:32 +05:30
Peter White c7d042a733 Add Slapr PR reactions in engineering (#4617) 2026-09-17 14:04:03 +02:00
Tomek e94a5085eb Fix search popover keyboard focus trap (#4615)
Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
2026-09-17 11:21:17 +02:00
Tomek 3ae1524a88 Hide Intercom launcher when Assistant opens (#4614)
Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
2026-09-17 11:20:20 +02:00
Nolann B. b967b248e7 Request insights and visitor endpoints relative to the served origin (#4603) 2026-09-16 20:54:20 +02:00
Nolann B. a9e6814744 Let the AI Assistant report documentation findings to the site's team (#4576) 2026-09-15 18:03:37 +02:00
Brett Jephson 5725da19e2 Honour an explicit select slug on a tab (#4601)
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 13:37:03 +01:00
Peter White 05cff0a03b Hide anchor links on landing pages (#4609) 2026-09-15 09:20:38 +02:00
Nolann B. 1e8c34a426 Let ContentKit webframes dispatch modal and URL actions (#4611) 2026-09-14 15:19:05 +02:00
spastorelli cd881f9ac1 Fix set-cookie in RSC requests conflicting with logout requests (#4606) 2026-09-14 14:45:32 +02:00
Greg Bergé 39316fc205 Add agent actions to the prompt block (#4610)
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-14 12:01:04 +02:00
Brett Jephson c08d05ade5 Fix select filters on table and cards blocks (#4608)
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 10:33:02 +00:00
Peter White b9453a92f8 Fix preview auth redirects dropping content paths (#4602) 2026-09-11 08:42:28 +02:00
Peter White 2c4d40ad97 Expose the site MCP tools through WebMCP in published docs (#4604) 2026-09-11 08:30:36 +02:00
Tomek 688515efcf Support fit-content width sizing for ContentKit buttons (#4605)
Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
2026-09-10 15:50:37 +02:00
Tomek 931cbe717e Restore Edit on Git page actions (#4597)
Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
Co-authored-by: Viktor Renkema <49148610+viktorrenkema@users.noreply.github.com>
Co-authored-by: conico974 <nicodorseuil@yahoo.fr>
2026-09-10 12:37:37 +02:00
Tomek 3ef1802e7e Add close button for modals in published sites (#4600)
Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
2026-09-09 12:23:17 +02:00
Greg Bergé 8a0e0df84e Fix search section links not scrolling to the target section (#4598)
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-09 11:40:58 +02:00
Peter White a9041a309a Fix fallback URL cleanup after successful page navigation (#4599) 2026-09-09 11:22:09 +02:00
conico974 625c108196 Add isRevalidationRequest function to handle specific requests (#4596) 2026-09-08 14:18:32 +02:00
Viktor Renkema 8e87856501 Fix page not found in preview links for sites with a custom homepage (#4594) 2026-09-08 11:27:07 +00:00
Tomek 9b822abbb6 Include page descriptions in markdown output (#4595)
Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
2026-09-08 12:38:54 +02:00
Peter White 81dba6455b Resolve stable refs in HTML blocks of published markdown pages (#4592) 2026-09-08 09:45:14 +02:00
Johan Preynat 1faa57b812 Keep revision search results in preview (#4582) 2026-09-07 19:46:57 +02:00
Tomek 40150f0a6c Serve markdown with text/plain content-type for ChatGPT (#4591)
Co-authored-by: Claude Haiku 4.5 <noreply@anthropic.com>
2026-09-07 17:13:19 +02:00
Brett Jephson bf29570bd5 RND-12706: measuring tabs fix (#4588)
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 15:40:43 +01:00
Peter White e8e979b6c0 Serve permanent site redirects (#4586) 2026-09-07 16:07:40 +02:00
156 changed files with 3799 additions and 559 deletions
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Add `leaveAgentFeedback` and `leaveUserFeedback` assistant tools, reporting documentation findings to the site's team through the same path as the MCP `sendFeedback` tool, and record an `agent_feedback` insights event on both surfaces.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Include published page descriptions in the page's Markdown output.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Fix select filters not working on table and cards blocks.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Fix ContentKit buttons to size to their content instead of stretching to the full container width.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Automatically resolve GitHub and GitLab page links to matching pages in the same published site, including cross-space links imported before their target page was available.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Give the prompt block a default "Copy prompt" action alongside "Open in Claude", "Open in Codex" and "Open in Cursor", and remember the visitor's last pick across every prompt block.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Hide heading and expandable anchor links on pages whose layout disables anchors (landing pages).
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Hide the Intercom launcher while the Assistant panel is open, so it no longer overlaps the message box.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Serve Markdown responses to ChatGPT with a `text/plain` Content-Type for compatibility.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Preserve the full site preview path and query parameters when redirecting users to log in.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Fix pages resolving to "not found" when a root URL lookup resolves to a custom homepage, by no longer using the homepage pathname as a prefix for the requested page path.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Keep current-space search results inside revision previews.
@@ -0,0 +1,7 @@
---
"gitbook": patch
---
Fix analytics and adaptive content silently breaking on sites served from a different host than the one configured (apex vs www, domain alias, CDN). The insights and visitor-claims endpoints are now requested relative to the page's own origin instead of the configured host, which a prerendered page cannot know.
Keep the traffic of GitBook's own preview deployments out of the sites' analytics, now that those requests reach the events endpoint.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Resolve stable page, space and file refs in images, definitions and HTML blocks of published markdown pages, instead of leaking internal `/pages/{id}`, `/spaces/{id}` and `/files/{id}` URLs.
@@ -0,0 +1,5 @@
---
"@gitbook/react-contentkit": patch
---
Show a close button on ContentKit modals rendered on published sites.
@@ -0,0 +1,7 @@
---
"@gitbook/react-contentkit": patch
---
Let ContentKit webframes dispatch the built-in `@ui.*` actions. Actions posted from a webframe were forwarded to the integration as a plain re-render instead of being handled, so `@ui.modal.open`, `@ui.modal.close` and `@ui.url.open` did nothing — most visibly, an integration could not close a modal from inside its own webframe.
Keep `null` values and class instances such as `Date` intact when resolving dynamic bindings in an action, instead of throwing or flattening them to `{}`.
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Fix section links in search results opening the page without scrolling to the section.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Fix keyboard focus getting trapped inside the header search popover, allowing Tab/Shift+Tab to exit it as expected.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Use cached Git metadata (via @gitbook/api 0.201.0's `cachedMetadata` param) when rendering Edit on Git actions.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Fix the tabs "more" dropdown showing when no tab is overflowing, and stop a tab click re-rendering every tab group on the page.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Let a tab keep its content selection across a rename, by honouring an explicit slug set on the tab instead of always deriving one from its title.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Remove the fallback query parameter after successful page navigation without adding a browser history entry.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Restore Edit on Git page actions for Git-synced pages.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Expose the site's MCP tools to browser agents through WebMCP when the MCP page action is enabled.
@@ -69,6 +69,7 @@ runs:
GITBOOK_RUNTIME: cloudflare
GITBOOK_BLOCK_SEARCH_INDEXATION: ${{ inputs.environment == 'preview' && 'true' || '' }}
GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE: ${{ inputs.environment == 'preview' && 'true' || '' }}
GITBOOK_DISABLE_INSIGHTS: ${{ inputs.environment == 'preview' && 'true' || '' }}
shell: bash
- name: Upload the DO worker
@@ -75,6 +75,7 @@ runs:
echo "GITBOOK_RUNTIME=vercel" >> .vercel/.env.${{ inputs.environment }}.local
echo "GITBOOK_BLOCK_SEARCH_INDEXATION=true" >> .vercel/.env.${{ inputs.environment }}.local
echo "GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE=true" >> .vercel/.env.${{ inputs.environment }}.local
echo "GITBOOK_DISABLE_INSIGHTS=true" >> .vercel/.env.${{ inputs.environment }}.local
echo "--- .vercel/.env.${{ inputs.environment }}.local after inject ---"
cat .vercel/.env.${{ inputs.environment }}.local
- name: Build Project Artifacts
+22
View File
@@ -0,0 +1,22 @@
{
"display_information": {
"name": "PR Status",
"description": "Updates PR status reactions in engineering"
},
"features": {
"bot_user": {
"display_name": "PR Status",
"always_online": false
}
},
"oauth_config": {
"scopes": {
"bot": ["channels:history", "reactions:read", "reactions:write"]
}
},
"settings": {
"org_deploy_enabled": false,
"socket_mode_enabled": false,
"token_rotation_enabled": false
}
}
+88
View File
@@ -0,0 +1,88 @@
# Slack PR reactions
[DataDog/slapr](https://github.com/DataDog/slapr) updates reactions on existing PR-link messages in [#engineering](https://gitbook.slack.com/archives/C01NXGWJELS). It runs in GitHub Actions. It does not post messages, approve or merge PRs, or change branch protection.
## Rollout and ownership
Owner: Peter White.
The rollout targets `GitbookIO/gitbook` (GBO), `GitbookIO/gitbook-x` (GBX), and `GitbookIO/integrations`. Each repository contains `.github/workflows/slapr.yml` and this runbook.
| Configuration | Value |
| --- | --- |
| Channel | `#engineering`, `C01NXGWJELS` |
| App manifest | `.github/slapr-app-manifest.json` |
| Slack app ID | `A0C2AGLAD0T` |
| Bot user ID | `U0C2AGP16R1`, repository variable `SLAPR_BOT_USER_ID` |
| Bot token | Repository Actions secret `SLAPR_SLACK_BOT_TOKEN` |
| Action | `DataDog/slapr@1c074e1dfd433f91a679d5113f7f8b956b65d973` |
| Approval threshold | Stock default, one approval |
| Events | `pull_request_review: submitted`, `pull_request: closed` |
## Install and configure
1. In [Slack app management](https://api.slack.com/apps), create the **PR Status** app from `.github/slapr-app-manifest.json` in the GitBook workspace. Obtain workspace approval if required, then install it. The bot requests Slapr's documented `channels:history`, `reactions:read`, and `reactions:write` scopes. `#engineering` is public, so `groups:history` is unnecessary. No review map is configured, so `channels:read` is unnecessary.
2. Invite **PR Status** only to `#engineering`. Keep it dedicated to Slapr: stock Slapr removes obsolete reactions belonging to this bot on a matched message. It leaves other users' reactions alone.
3. Record the app ID and bot user ID above. The bot profile's member ID or Slack `auth.test` response's `user_id` is the required bot user ID, not the app ID or bot ID.
4. Store the bot OAuth token as `SLAPR_SLACK_BOT_TOKEN` in each of the three repositories' Actions secrets. Use the GitHub secret UI or `gh secret set SLAPR_SLACK_BOT_TOKEN --repo GitbookIO/<repository>` and its hidden prompt. Never paste the token into a command argument, chat, workflow, or committed file. Alternatively, an organization secret must use selected-repository visibility limited to these three repositories.
5. Set Actions variable `SLAPR_BOT_USER_ID` in each repository to that bot's user ID. The token and user ID must belong to the same installation. Use `gh variable set SLAPR_BOT_USER_ID --repo GitbookIO/<repository> --body '<user-id>'` or the GitHub UI.
6. Merge the workflows through normal review, then run the live checks below. Repository maintainers handle reviews and merges; Slapr has only read access to GitHub contents and pull requests.
GBX runs this workflow on `blacksmith-2vcpu-ubuntu-2404`. GBO and integrations use `ubuntu-latest`, matching their existing workflows.
The workflow hardcodes the engineering channel and does not check out PR code. It uses the stock event triggers and leaves the approval threshold unset. There are no listeners, schedules, review maps, custom discovery, or additional services.
## Reactions
Slapr's status selection stays unchanged. Missing custom emoji names are mapped through the action's supported inputs to existing equivalents. Workspace lookup on 2026-09-17 confirmed `pr-approved` and `merged`; the other mappings are standard Slack emojis.
| Stock status | Reaction |
| --- | --- |
| Review started | `:eyes:` |
| Partially approved | `:next_track_button:` |
| Approved | `:pr-approved:` |
| Changes requested | `:construction:` |
| Merged | `:merged:` |
| Closed without merging | `:no_entry_sign:` |
| Comment-only review | `:speech_balloon:` |
The partially-approved reaction is configured but cannot occur with the default threshold of one approval. It becomes relevant only if that threshold is raised.
On approval, expect review-started and approved reactions. On merge, stock Slapr removes review-started and adds merged; it can retain approved alongside merged. Approval and merging have distinct reactions. Other stock review-state behavior is accepted.
## Live acceptance test
For each repository after credentials are configured and the workflow is on the default branch:
1. Open a fresh same-repository test PR through normal review. Post its full `https://github.com/GitbookIO/<repository>/pull/<number>` link as a new top-level message in `#engineering` before the review event.
2. Have another contributor approve it. Open the **Slack PR reactions** Actions run and verify that the matched message has the bot's `pr-approved` reaction.
3. Have an authorized maintainer merge it. Verify the closed-event run succeeds and the same message has the bot's `merged` reaction. No new Slack status message should appear.
4. Record the PR URL, Slack message permalink, approval/merge workflow run URLs, date, and result below. A green workflow alone does not prove the message was found or reacted to.
| Repository | PR and Slack message | Approval run/result | Merge run/result |
| --- | --- | --- | --- |
| GitbookIO/gitbook | Pending | Not tested | Not tested |
| GitbookIO/gitbook-x | Pending | Not tested | Not tested |
| GitbookIO/integrations | Pending | Not tested | Not tested |
Only the first matching message in Slapr's recent-history response is updated. Older messages, thread replies, duplicate posts, fork PRs, and links posted after the event are outside this rollout's acceptance criteria. Slapr does not paginate history or reconcile missed events.
## Troubleshoot and disable
- No workflow run: confirm the workflow is merged, Actions permits the pinned action, and the event was a submitted review or PR closure. These are the only configured triggers.
- `No message found requesting review`: confirm the full PR link was posted as a recent top-level message in `#engineering` before the event. This is a successful no-op in stock Slapr.
- `not_in_channel` or `channel_not_found`: check the app installation, channel ID, and bot membership in `#engineering`.
- `missing_scope`: compare the installed bot scopes with the manifest and reinstall after changes.
- `invalid_auth` or `account_inactive`: replace the repository secrets with the current bot token. If the bot identity changed, update `SLAPR_BOT_USER_ID` too.
- `invalid_name`: check the emoji mappings still exist. If a custom emoji was removed, map that input to another existing emoji, keeping approval and merged distinct.
- Old reactions remain or removal fails: confirm `SLAPR_BOT_USER_ID` is the member ID for the token's bot.
- GitHub permission errors: keep `contents: read` and `pull-requests: read`; do not introduce a PAT, write permissions, or `pull_request_target` to cover forks. Fork and Dependabot secret restrictions are accepted limitations.
- Rate limits or transient API failures: inspect the Actions log and retry the failed run after the limit resets. There is no scheduled reconciliation.
Disable one repository with `gh workflow disable slapr.yml --repo GitbookIO/<repository>`, or disable **Slack PR reactions** in its Actions UI. Repeat for all three to stop the integration. Revoke the Slack app token to stop its access immediately, remove its repository secrets, and remove the bot from `#engineering` when retiring it. Existing reactions remain.
## Pin review
On 2026-09-17, the pinned action definition, Dockerfile, entry point, dependency declarations, GitHub reads, Slack history lookup and reaction writes were inspected. Without `review-map`, the action targets only the supplied channel. It reads PR/review state and adds/removes reactions; it does not post Slack messages or write to GitHub.
The action SHA pins Slapr's source. Its upstream Dockerfile still uses the mutable `python:3.14` image and installs dependencies, including `pyyaml>=5.0`, at build time. This rollout keeps stock Slapr unchanged. Review upstream source and dependency changes before updating the SHA in all three repositories.
+30
View File
@@ -0,0 +1,30 @@
name: Slack PR reactions
on:
pull_request_review:
types: [submitted]
pull_request:
types: [closed]
permissions:
contents: read
pull-requests: read
jobs:
run_slapr:
runs-on: ubuntu-latest
steps:
- name: Update PR reactions in engineering
uses: DataDog/slapr@1c074e1dfd433f91a679d5113f7f8b956b65d973
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
slack-api-token: ${{ secrets.SLAPR_SLACK_BOT_TOKEN }}
slack-channel-id: C01NXGWJELS
bot-user-id: ${{ vars.SLAPR_BOT_USER_ID }}
emoji-review-started: eyes
emoji-partially-approved: next_track_button
emoji-approved: pr-approved
emoji-changes-requested: construction
emoji-merged: merged
emoji-closed: no_entry_sign
emoji-commented: speech_balloon
+3
View File
@@ -29,3 +29,6 @@ yarn-error.log*
# Bun pack artifacts
packages/*/*.tgz
# Playwright MCP artifacts
.playwright-mcp/
+3 -2
View File
@@ -275,6 +275,7 @@
},
"devDependencies": {
"@types/react": "catalog:",
"bun-types": "catalog:",
"react": "catalog:",
"tsdown": "catalog:",
"typescript": "catalog:",
@@ -354,7 +355,7 @@
},
"catalog": {
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.199.0",
"@gitbook/api": "0.202.0",
"@scalar/api-client-react": "^1.3.46",
"@tsconfig/node20": "^20.1.6",
"@tsconfig/strictest": "^2.0.6",
@@ -726,7 +727,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.199.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-yLxkSTXlGk7jbtThV2vpnTfqZTq6yLgMJt6jhDGqOmP0LsYAVYYtg8NPf2tXp37aF46m3Z0D908wfSQyu374cg=="],
"@gitbook/api": ["@gitbook/api@0.202.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-qhrjEQbNNmCljR0AgP79+BsVh9yelh9TIBg9X3TyYx5a3lJwDiT3sw1ND9DFQSxGHp8hH5w+20KJHn/IDpTbaw=="],
"@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.199.0",
"@gitbook/api": "0.202.0",
"@scalar/api-client-react": "^1.3.46",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
+131 -6
View File
@@ -10,6 +10,7 @@ import {
CustomizationDepth,
CustomizationHeaderPreset,
CustomizationIconsStyle,
CustomizationPageActionType,
CustomizationSidebarListStyle,
SiteSocialAccountPlatform,
} from '@gitbook/api';
@@ -158,7 +159,7 @@ const searchTestCases: Test[] = [
},
},
{
name: 'Search - Keyboard focus stays within search',
name: 'Search - Keyboard focus exits to the next page control',
url: getCustomizationURL({
ai: {
mode: CustomizationAIMode.Search,
@@ -179,13 +180,16 @@ const searchTestCases: Test[] = [
)
.filter({ visible: true })
.last();
const nextPageControl = page.getByTestId('table-of-contents').getByRole('link').first();
await expect(finalPopupControl).toBeVisible();
await expect(nextPageControl).toBeVisible();
await finalPopupControl.focus();
await page.keyboard.press('Tab');
await expect(searchInput).toBeFocused();
await expect(searchPopup).toBeHidden();
await expect(nextPageControl).toBeFocused();
await page.keyboard.press('Shift+Tab');
await expect(finalPopupControl).toBeFocused();
await expect(searchInput).toBeFocused();
},
},
{
@@ -245,6 +249,43 @@ const searchTestCases: Test[] = [
await expect(page.getByTestId('search-results')).toBeVisible();
},
},
{
// RND-12844: the popover's focus manager re-focused the closing popup and
// scrolled the page back to the top right after landing on the section.
name: 'Search - Section result scrolls to the section',
url: getCustomizationURL({
ai: {
mode: CustomizationAIMode.None,
},
}),
screenshot: false,
run: async (page) => {
await waitForCookiesDialog(page);
const searchInput = page.getByTestId('search-input');
await searchInput.focus();
// Type like a visitor: `fill()` doesn't trigger the remote search.
await searchInput.pressSequentially('tasks');
const sectionResult = page.locator(
'[data-testid="search-page-result"][href$="/blocks/lists#tasks"]'
);
// Section results come from the remote index, which can be slow to answer.
await expect(sectionResult).toBeVisible({ timeout: 30_000 });
await sectionResult.click();
await page.waitForURL(/\/blocks\/lists#tasks$/);
// The regression scrolled back to the top shortly after landing, so let
// that happen before asserting.
await page.waitForTimeout(1000);
// The heading is parked under the header, within its scroll margin.
const top = await page
.locator('#tasks')
.evaluate((heading) => heading.getBoundingClientRect().top);
expect(top).toBeGreaterThanOrEqual(0);
expect(top).toBeLessThanOrEqual(150);
},
},
{
name: 'Ask - AI Mode: Assistant - Complete flow',
url: getCustomizationURL({
@@ -513,6 +554,24 @@ const testCases: TestsCase[] = [
name: 'GitBook Site (Navigation when switching variant)',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/',
tests: [
{
name: 'Strip fallback after loading a page without adding history',
url: 'api-multi-versions/reference/api-reference/pets',
screenshot: false,
run: async (page) => {
await waitForHydration(page);
const previousURL = page.url();
const targetURL = new URL(previousURL);
targetURL.searchParams.set('fallback', 'true');
targetURL.searchParams.set('ref', 'variant');
targetURL.hash = 'pets';
await page.goto(targetURL.toString());
targetURL.searchParams.delete('fallback');
await expect(page).toHaveURL(targetURL.toString());
await page.goBack();
await expect(page).toHaveURL(previousURL);
},
},
{
name: 'Keep navigation path/route when switching variant (Public)',
url: 'api-multi-versions/reference/api-reference/pets',
@@ -535,8 +594,11 @@ const testCases: TestsCase[] = [
.click();
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL((url) =>
url.pathname.includes('api-multi-versions/2.0/reference/api-reference/pets')
await page.waitForURL(
(url) =>
url.pathname.includes(
'api-multi-versions/2.0/reference/api-reference/pets'
) && !url.searchParams.has('fallback')
);
},
},
@@ -1572,6 +1634,70 @@ const testCases: TestsCase[] = [
},
],
},
{
name: 'Edit on Git page actions',
contentBaseURL: 'https://gitbook-open-e2e-sites.gitbook.io/yjs/',
tests: [
{
name: 'With Edit on Git as the default action',
url: getCustomizationURL({
pageActions: {
items: [CustomizationPageActionType.Git],
},
}),
run: async (page) => {
await waitForHydration(page);
await expect(
page.getByRole('link', { name: 'Edit', exact: true })
).toHaveAttribute(
'href',
'https://github.com/taranvohra/yjs-docs/tree/main/README.md'
);
},
screenshot: false,
},
{
name: 'With Edit on Git in the dropdown',
url: getCustomizationURL({
pageActions: {
items: [
CustomizationPageActionType.Markdown,
CustomizationPageActionType.Git,
],
},
}),
run: async (page) => {
await waitForHydration(page);
await page.getByRole('button', { name: 'More' }).click();
await expect(page.getByRole('menu')).toBeVisible();
await expect(
page.getByRole('menuitem', { name: 'Edit on GitHub' })
).toHaveAttribute(
'href',
'https://github.com/taranvohra/yjs-docs/tree/main/README.md'
);
},
screenshot: false,
},
{
name: 'Without Edit on Git',
url: getCustomizationURL({
pageActions: {
items: [CustomizationPageActionType.Markdown],
},
}),
run: async (page) => {
await waitForHydration(page);
await page.getByRole('button', { name: 'More' }).click();
await expect(page.getByRole('menu')).toBeVisible();
await expect(
page.getByRole('menuitem', { name: 'Edit on GitHub' })
).toHaveCount(0);
},
screenshot: false,
},
],
},
{
name: 'Page actions',
contentBaseURL: 'https://gitbook.gitbook.io/test-gitbook-open/',
@@ -1624,7 +1750,6 @@ const testCases: TestsCase[] = [
{
name: 'Without previewed ads',
url: 'text-page?ads_preview=1',
run: waitForCookiesDialog,
},
],
},
+178
View File
@@ -0,0 +1,178 @@
import { type Page, expect, test } from '@playwright/test';
// Import the specific module (not the package barrel) so this stays free of the `@/` path alias,
// which Playwright's loader doesn't resolve — same reason as `select.spec.ts`.
import { resolveOverflowingItems } from '../src/components/hooks/listOverflow';
/**
* Behaviour tests for the tab bar's overflow rule (`useListOverflow`), which decides which tabs move
* into the "more" dropdown. Rects are measured in a real browser so the geometry is genuine — the
* layout below mirrors the tab bar in `DynamicTabs`: a non-wrapping flex row of `shrink-0` items,
* clipped by `overflow: hidden`, measured with the dropdown rendered ahead of the tabs.
*
* The regression these guard is a dropdown appearing when nothing actually overflowed: measuring
* with the dropdown present consumes `MENU` pixels, so a bar whose tabs total just under the
* container would hand its last tab to a menu it never needed.
*/
/** Width of the ellipsis button, matching the `px-3.5` + `size-4` icon of the real one. */
const MENU = 44;
interface Row {
/** Container width in px. */
container: number;
/** Tab widths in px, in order. */
tabs: number[];
/** Whether the dropdown is reserving space ahead of the tabs, as during a measure pass. */
withMenu?: boolean;
/** Hide an ancestor, so the row measures with no box at all. */
hidden?: boolean;
}
/**
* Lay the row out in the browser and run the real rule over the rects it produces.
* Returns the ids reported as overflowing, or `null` when the measurement carried no information.
*/
async function measure(page: Page, row: Row): Promise<string[] | null> {
const { container, tabs, withMenu = true, hidden = false } = row;
const items = tabs
.map((w, i) => `<div class="item" id="tab-${i}" style="width:${w}px">${i}</div>`)
.join('');
const menu = withMenu ? `<div class="item" style="width:${MENU}px">…</div>` : '';
await page.setContent(
`<!doctype html><html><head><style>
* { box-sizing: border-box; }
body { margin: 0; }
.pane { ${hidden ? 'display: none;' : ''} }
.bar {
width: ${container}px;
display: inline-flex;
overflow: hidden;
}
.bar::after { content: ""; flex: 1; }
.item { flex-shrink: 0; max-width: 100%; }
</style></head><body>
<div class="pane"><div class="bar" id="bar">${menu}${items}</div></div>
</body></html>`
);
const measured = await page.evaluate(() => {
const bar = document.getElementById('bar');
if (!bar) {
throw new Error('missing bar');
}
const rect = bar.getBoundingClientRect();
return {
container: { left: rect.left, right: rect.right, width: rect.width },
items: [...bar.querySelectorAll<HTMLElement>('.item[id]')].map((el) => {
const r = el.getBoundingClientRect();
return { id: el.id, rect: { left: r.left, right: r.right } };
}),
};
});
const result = resolveOverflowingItems(measured.container, measured.items);
return result ? [...result].sort() : null;
}
test.describe('tab overflow rule', () => {
test('reports nothing when every tab fits with room to spare', async ({ page }) => {
// 3 x 100 = 300 of 600, so even with the menu reserved there is slack.
expect(await measure(page, { container: 600, tabs: [100, 100, 100] })).toEqual([]);
});
test('reports nothing when the tabs fit exactly', async ({ page }) => {
expect(await measure(page, { container: 300, tabs: [100, 100, 100] })).toEqual([]);
});
test('reports nothing when only the reserved menu made the row overflow', async ({ page }) => {
// The regression: tabs total 300 and the container is 320, so they fit — but measuring
// reserves 44 for the menu, which used to push the last tab out and show a needless
// dropdown. Every width in `container - MENU < 300 <= container` must stay empty.
for (const container of [300, 305, 320, 330, 343]) {
expect(
await measure(page, { container, tabs: [100, 100, 100] }),
`container ${container}px`
).toEqual([]);
}
});
test('reports the tabs that genuinely do not fit alongside the menu', async ({ page }) => {
// 300 of tabs into 290: the row really does overflow, so the menu is warranted and the
// remaining tabs must fit beside it (100 + 100 + 44 = 244 <= 290).
expect(await measure(page, { container: 290, tabs: [100, 100, 100] })).toEqual(['tab-2']);
});
test('gives up as many tabs as the width demands', async ({ page }) => {
expect(await measure(page, { container: 190, tabs: [100, 100, 100] })).toEqual([
'tab-1',
'tab-2',
]);
expect(await measure(page, { container: 150, tabs: [100, 100, 100] })).toEqual([
'tab-1',
'tab-2',
]);
});
test('moves every tab into the menu once not even the first fits beside it', async ({
page,
}) => {
// 100 + 44 > 120, so no tab can share the row with the menu. Everything goes in, leaving a
// bar that is only the menu — deliberately, since the menu is then the sole route to any
// tab. Forcing the first tab to stay would push the menu past the clipped edge and strand
// the rest.
expect(await measure(page, { container: 120, tabs: [100, 100, 100] })).toEqual([
'tab-0',
'tab-1',
'tab-2',
]);
});
test('keeps a single tab that fills the bar rather than hiding it behind a menu', async ({
page,
}) => {
// `max-width: 100%` truncates it to the container, so it fits — a lone tab should never be
// the only thing in the dropdown.
expect(await measure(page, { container: 200, tabs: [400] })).toEqual([]);
});
test('cuts a nested bar earlier, since its pane padding narrows it', async ({ page }) => {
// A nested tab bar sits inside a `p-4` pane, so it has 32px less to work with. At 330 the
// outer bar keeps all three tabs; the nested one at 330 - 32 cannot.
expect(await measure(page, { container: 330, tabs: [100, 100, 100] })).toEqual([]);
expect(await measure(page, { container: 330 - 32, tabs: [100, 100, 100] })).toEqual([
'tab-2',
]);
});
test('progressively fills the menu as a long list is squeezed', async ({ page }) => {
const tabs = Array.from({ length: 12 }, () => 100);
let previous = -1;
for (const container of [1300, 1200, 1000, 800, 600, 400, 200]) {
const overflowing = await measure(page, { container, tabs });
expect(overflowing, `container ${container}px`).not.toBeNull();
const hidden = overflowing?.length ?? 0;
// Never loses a tab, and never un-hides one as the space shrinks.
expect(hidden, `container ${container}px`).toBeGreaterThanOrEqual(previous);
expect(hidden, `container ${container}px`).toBeLessThanOrEqual(tabs.length);
previous = hidden;
}
// Widest fits everything; at 200 only the first tab still fits beside the menu.
expect(await measure(page, { container: 1300, tabs })).toEqual([]);
expect((await measure(page, { container: 200, tabs }))?.length).toBe(11);
});
test('reports nothing measurable while an ancestor is hidden', async ({ page }) => {
// A bar behind an inactive tab has no box, so every rect is zero. That says nothing about
// what fits, and must not be mistaken for "everything overflows".
expect(
await measure(page, { container: 200, tabs: [100, 100, 100], hidden: true })
).toBeNull();
});
test('reports nothing measurable for an empty list', async ({ page }) => {
expect(await measure(page, { container: 600, tabs: [] })).toBeNull();
});
});
+5 -1
View File
@@ -465,7 +465,11 @@ export function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettin
socialAccounts: [],
};
const encoded = rison.encode_object(deepMerge(DEFAULT_CUSTOMIZATION, partial));
const encoded = rison.encode_object(
deepMerge(DEFAULT_CUSTOMIZATION, partial, {
arrayMerge: (_target, source) => source,
})
);
const searchParams = new URLSearchParams();
searchParams.set('customization', encoded);
+1
View File
@@ -94,6 +94,7 @@ const nextConfig = {
GITBOOK_RUNTIME: process.env.GITBOOK_RUNTIME,
GITBOOK_BLOCK_SEARCH_INDEXATION: process.env.GITBOOK_BLOCK_SEARCH_INDEXATION,
GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE: process.env.GITBOOK_ALLOW_CUSTOMIZATION_OVERRIDE,
GITBOOK_DISABLE_INSIGHTS: process.env.GITBOOK_DISABLE_INSIGHTS,
// Next.js envs
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
+1 -1
View File
@@ -132,7 +132,7 @@
"dev:cf:middleware": "wrangler dev --port 8771 --inspector-port 9230 --env dev --config ./openNext/customWorkers/middlewareWrangler.jsonc",
"dev:cf:server": "wrangler dev --port 8772 --env dev --config ./openNext/customWorkers/defaultWrangler.jsonc",
"profile:cf:memory": "bun run build:cloudflare && bun ./scripts/profile-opennext-memory.ts",
"e2e": "playwright test e2e/internal.spec.ts e2e/cookie-banner.spec.ts e2e/pdf.spec.ts e2e/select.spec.ts --project=chromium",
"e2e": "playwright test e2e/internal.spec.ts e2e/cookie-banner.spec.ts e2e/pdf.spec.ts e2e/select.spec.ts e2e/tabs-overflow.spec.ts --project=chromium",
"e2e-customers": "playwright test e2e/customers.spec.ts --project=chromium",
"e2e-style-perf": "playwright test e2e/style-perf.spec.ts --project=chromium --reporter=list",
"unit": "bun run generate:assets && bun test {src,packages} --preload ./tests/preload-bun.ts",
@@ -2,10 +2,21 @@ import { createMcpHandler } from 'mcp-handler';
import type { NextRequest } from 'next/server';
import { z } from 'zod';
import { CustomizationPageActionType, SiteInsightsDisplayContext } from '@gitbook/api';
import {
AgentFeedbackSource,
CustomizationPageActionType,
SiteInsightsDisplayContext,
} from '@gitbook/api';
import { type RouteLayoutParams, getDynamicSiteContext } from '@/app/utils';
import { isAIEnabled } from '@/components/utils/isAIChatEnabled';
import {
AGENT_FEEDBACK_GOAL_MAX_LENGTH,
AGENT_FEEDBACK_MAX_LENGTH,
agentFeedbackDescriptions,
parseAgentFeedbackPageURL,
} from '@/lib/agentFeedback';
import { submitAgentFeedback } from '@/lib/agentFeedback/server';
import { renderAskSourcesMarkdown, streamSiteAskAnswer } from '@/lib/ask';
import { getExposableError, throwIfDataError } from '@/lib/data';
import { fromPageMarkdown, getMarkdownForPageInSpace, toPageMarkdown } from '@/lib/markdownPage';
@@ -353,26 +364,14 @@ export async function handleMcpRequest(
content: z
.string()
.min(1)
.max(2048)
.describe(
'Explain the issue in full, as if writing to a documentation maintainer who never saw this conversation. Describe what is wrong, where on the page it appears (quote the exact sentence or section title when possible), what the user was trying to do, and, when relevant, what the correct or expected information should be. Write a few clear, specific sentences in English. Never include personal or confidential information from the conversation. Up to 2048 characters.'
),
.max(AGENT_FEEDBACK_MAX_LENGTH)
.describe(agentFeedbackDescriptions.finding),
pageUrl: z
.string()
.describe(
`The full URL of the page the issue is about (e.g. ${siteUrl}/getting-started), so the finding is linked to the exact page.`
)
.describe(agentFeedbackDescriptions.pageURL(siteUrl))
.transform((value, ctx) => {
const candidate = URL.canParse(value)
? new URL(value)
: URL.canParse(value, siteUrl)
? new URL(value, siteUrl)
: null;
if (
!candidate ||
(candidate.protocol !== 'https:' && candidate.protocol !== 'http:')
) {
const url = parseAgentFeedbackPageURL(value, siteUrl);
if (!url) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `"${value}" is not a valid URL on this site. Expected a full URL like ${siteUrl}/getting-started`,
@@ -380,14 +379,13 @@ export async function handleMcpRequest(
return z.NEVER;
}
return candidate.toString();
return url;
}),
goal: z
.string()
.max(AGENT_FEEDBACK_GOAL_MAX_LENGTH)
.optional()
.describe(
'The broader end goal you were ultimately trying to accomplish (as/on behalf of the user) when you hit this issue. Gives the team the context you were working towards. Optional.'
),
.describe(agentFeedbackDescriptions.goal),
},
{
title: 'Send feedback',
@@ -398,66 +396,36 @@ export async function handleMcpRequest(
},
async ({ content, pageUrl, goal }) => {
try {
const match = findSiteSpaceByUrl(context.structure, pageUrl);
if (!match) {
const result = await submitAgentFeedback(context, {
feedback: content,
goal,
page: pageUrl,
source: AgentFeedbackSource.Mcp,
});
if (!result.submitted) {
return {
content: [{ type: 'text', text: `Page not found: "${pageUrl}"` }],
content: [{ type: 'text', text: result.error }],
isError: true,
};
}
const revision = await throwIfDataError(
dataFetcher.getRevision({
spaceId: match.siteSpace.space.id,
revisionId: match.siteSpace.space.revision,
})
);
const resolved = resolveSiteSpacePagePath(
match.siteSpace,
revision.pages,
match.pagePath
);
if (!resolved) {
return {
content: [{ type: 'text', text: `Page not found: "${pageUrl}"` }],
isError: true,
};
}
const trimmedGoal = goal?.trim() || undefined;
//!! DISABLED FOR NOW: We'll add this back in when we have a way to track agent feedback.
// trackMcpEvent({
// organizationId: context.organizationId,
// siteId: site.id,
// events: [
// {
// type: 'agent_feedback',
// feedback: { content, category },
// location: {
// displayContext: SiteInsightsDisplayContext.Mcp,
// page: resolved.page.id,
// space: match.siteSpace.space.id,
// revision: match.siteSpace.space.revision,
// },
// },
// ],
// request,
// });
const apiClient = await dataFetcher.api();
await apiClient.orgs.submitSiteAgentFeedback(
context.organizationId,
site.id,
{
feedback: content,
url: pageUrl,
spaceId: match.siteSpace.space.id,
pageId: resolved.page.id,
...(trimmedGoal ? { goal: trimmedGoal } : {}),
}
);
trackMcpEvent({
organizationId: context.organizationId,
siteId: site.id,
events: [
{
type: 'agent_feedback',
location: {
displayContext: SiteInsightsDisplayContext.Mcp,
page: result.page.pageId,
space: result.page.spaceId,
revision: result.page.revisionId,
},
},
],
request,
});
return {
content: [{ type: 'text', text: 'Feedback recorded. Thank you.' }],
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'bun:test';
import type { SearchPageResult, SearchSpaceResult, SiteSpace } from '@gitbook/api';
import type {
RevisionPage,
RevisionPageDocument,
SearchPageResult,
SearchSpaceResult,
SiteSpace,
} from '@gitbook/api';
import { orderSearchResultGroups } from './orderSearchResults';
import { createLinker } from '@/lib/links';
@@ -16,6 +22,13 @@ const linker = createLinker({
spaceBasePath: '/',
});
const revisionLinker = createLinker({
protocol: 'https:',
host: 'docs.runway.team',
siteBasePath: '/handbook/',
spaceBasePath: '/handbook/api/~/revisions/revision_preview/',
});
const spaceItem: SearchSpaceResult = {
type: 'space',
id: 'space_runway',
@@ -63,6 +76,33 @@ function transformPage(pageItem: SearchPageResult, asEmbeddable = false) {
pageItem,
spaceItem,
siteSpace,
})!;
}
function createRevisionPage(id: string, path: string): RevisionPageDocument {
return {
id,
type: 'document',
path,
pages: [],
} as RevisionPageDocument;
}
function createRevisionPages(pagePath: string): RevisionPage[] {
return [
createRevisionPage('page_home', 'home'),
createRevisionPage('page_api_reference', pagePath),
];
}
function transformRevisionPage(pageItem: SearchPageResult, revisionPages: RevisionPage[]) {
return transformSitePageResult({
asEmbeddable: false,
linker: revisionLinker,
pageItem,
spaceItem,
siteSpace,
revisionPages,
});
}
@@ -83,12 +123,92 @@ describe('transformSitePageResult', () => {
expect(transformPage(createPageResult({ path: destination }), true).href).toBe(destination);
});
it('resolves a relative page path through the published site URL', () => {
it('keeps published search results on their published destination', () => {
const result = transformPage(createPageResult({ path: 'guides/getting-started' }));
expect(result.href).toBe('/guides/getting-started');
});
it('keeps a current-space page result inside the revision being previewed', () => {
const result = transformRevisionPage(
createPageResult({ path: 'guides/getting-started' }),
createRevisionPages('guides/getting-started')
);
expect(result?.href).toBe(
'/handbook/api/~/revisions/revision_preview/guides/getting-started'
);
});
it('uses the current revision path when a page moved after the indexed revision', () => {
const result = transformRevisionPage(
createPageResult({ path: 'guides/getting-started' }),
createRevisionPages('start/quickstart')
);
expect(result?.href).toBe('/handbook/api/~/revisions/revision_preview/start/quickstart');
});
it('keeps a section result and its anchor inside the current revision', () => {
const result = transformRevisionPage(
createPageResult({
path: 'guides/getting-started',
sections: [
{
id: 'section_authentication',
title: 'Authentication',
body: 'Synthetic section excerpt',
path: 'guides/getting-started#authentication',
score: 10,
resultType: 'section',
urls: {
app: 'https://app.gitbook.com/o/example/s/example',
},
},
],
}),
createRevisionPages('guides/getting-started')
);
expect(result?.bestSection?.href).toBe(
'/handbook/api/~/revisions/revision_preview/guides/getting-started#authentication'
);
});
it('falls back to the revision page root when a section anchor cannot be safely retained', () => {
const result = transformRevisionPage(
createPageResult({
path: 'guides/getting-started',
sections: [
{
id: 'section_authentication',
title: 'Authentication',
body: 'Synthetic section excerpt',
path: 'another-page#authentication',
score: 10,
resultType: 'section',
urls: {
app: 'https://app.gitbook.com/o/example/s/example',
},
},
],
}),
createRevisionPages('start/quickstart')
);
expect(result?.bestSection?.href).toBe(
'/handbook/api/~/revisions/revision_preview/start/quickstart'
);
});
it('excludes a main-index result that does not exist in the current revision', () => {
const result = transformRevisionPage(createPageResult({ path: 'guides/getting-started' }), [
createRevisionPage('page_home', 'home'),
]);
expect(result).toBeNull();
});
it('keeps embeddable GitBook page links in the embeddable route', () => {
const result = transformPage(createPageResult({ path: 'guides/getting-started' }), true);
@@ -126,7 +246,33 @@ describe('transformSitePageResult', () => {
spaceItem,
});
expect(result.href).toBe('/guides/getting-started');
expect(result?.href).toBe('/guides/getting-started');
});
it('keeps cross-space results on their published destination during a revision preview', () => {
const otherSpaceItem = { ...spaceItem, id: 'space_sdk', title: 'SDK' };
const otherSiteSpace = {
...siteSpace,
id: 'site_space_sdk',
path: 'sdk',
space: {
...siteSpace.space,
id: otherSpaceItem.id,
title: otherSpaceItem.title,
},
urls: {
published: 'https://docs.runway.team/handbook/sdk/',
},
} as SiteSpace;
const result = transformSitePageResult({
asEmbeddable: false,
linker: revisionLinker,
pageItem: createPageResult({ path: 'guides/getting-started' }),
spaceItem: otherSpaceItem,
siteSpace: otherSiteSpace,
});
expect(result?.href).toBe('/handbook/sdk/guides/getting-started');
});
it('preserves ranks, scores, and result ordering', () => {
@@ -9,7 +9,7 @@ import { throwIfDataError } from '@/lib/data';
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
import { transformSitePageResult } from '@/lib/search';
import { getServerActionBaseContext } from '@/lib/server-actions';
import { findSiteSpaceBy } from '@/lib/sites';
import { findSiteSpaceBy, getLinkerForSiteSpace } from '@/lib/sites';
export async function POST(request: NextRequest) {
const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest;
@@ -22,7 +22,7 @@ export async function POST(request: NextRequest) {
return NextResponse.json([]);
}
const [searchResults, { structure }] = await Promise.all([
const [searchResults, { structure }, revision] = await Promise.all([
throwIfDataError(
context.dataFetcher.searchSiteContent({
organizationId: siteURLData.organization,
@@ -38,8 +38,24 @@ export async function POST(request: NextRequest) {
siteShareKey: siteURLData.shareKey,
})
),
siteURLData.revision
? throwIfDataError(
context.dataFetcher.getRevision({
spaceId: siteURLData.space,
revisionId: siteURLData.revision,
})
)
: Promise.resolve(undefined),
]);
const currentSiteSpace = revision
? findSiteSpaceBy(structure, (siteSpace) => siteSpace.id === siteURLData.siteSpace)
: null;
const revisionLinker =
revision && currentSiteSpace
? getLinkerForSiteSpace(context.linker, currentSiteSpace.siteSpace, revision.pages)
: context.linker;
const results = orderSearchResultGroups<OrderedComputedResult>(
searchResults.map((resultItem) => {
if (resultItem.type === 'record') {
@@ -55,25 +71,31 @@ export async function POST(request: NextRequest) {
return { type: 'context' as const, results: [result] };
}
const found = findSiteSpaceBy(
structure,
(siteSpace) => siteSpace.space.id === resultItem.id
);
const isCurrentRevisionSpace = Boolean(revision && resultItem.id === siteURLData.space);
const found =
isCurrentRevisionSpace && currentSiteSpace
? currentSiteSpace
: findSiteSpaceBy(
structure,
(siteSpace) => siteSpace.space.id === resultItem.id
);
return {
type: 'pages' as const,
results: resultItem.pages.map((pageItem) => ({
rank: pageItem.rank,
result: transformSitePageResult({
results: resultItem.pages.flatMap((pageItem) => {
const result = transformSitePageResult({
asEmbeddable: Boolean(asEmbeddable),
linker: context.linker,
linker: isCurrentRevisionSpace ? revisionLinker : context.linker,
pageItem,
spaceItem: resultItem,
siteSpace: found?.siteSpace,
siteSection: found?.siteSection ?? undefined,
siteSectionGroup: found?.siteSectionGroup ?? undefined,
}),
})),
revisionPages: isCurrentRevisionSpace ? revision?.pages : undefined,
});
return result ? [{ rank: pageItem.rank, result }] : [];
}),
};
})
);
+2
View File
@@ -6,6 +6,7 @@ import {
GITBOOK_API_URL,
GITBOOK_APP_URL,
GITBOOK_ASSETS_URL,
GITBOOK_DISABLE_INSIGHTS,
GITBOOK_DISABLE_TRACKING,
GITBOOK_FONTS_URL,
GITBOOK_ICONS_URL,
@@ -35,6 +36,7 @@ export async function GET(_req: NextRequest) {
GITBOOK_INTEGRATIONS_HOST,
GITBOOK_INTEGRATIONS_CONTENT_HOST,
GITBOOK_DISABLE_TRACKING,
GITBOOK_DISABLE_INSIGHTS,
// Secret envs
GITBOOK_SECRET: !!GITBOOK_SECRET,
@@ -0,0 +1,45 @@
import { afterEach, describe, expect, it } from 'bun:test';
import { setIntercomLauncherHidden } from './intercom';
const originalWindow = globalThis.window;
afterEach(() => {
if (originalWindow === undefined) {
delete (globalThis as { window?: Window }).window;
} else {
globalThis.window = originalWindow;
}
});
function installIntercom(intercom: Window['Intercom']): void {
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: { Intercom: intercom },
writable: true,
});
}
describe('setIntercomLauncherHidden', () => {
it('hides the Intercom launcher', () => {
const calls: unknown[][] = [];
installIntercom((...args) => calls.push(args));
setIntercomLauncherHidden(true);
expect(calls).toEqual([['update', { hide_default_launcher: true }]]);
});
it('shows the Intercom launcher', () => {
const calls: unknown[][] = [];
installIntercom((...args) => calls.push(args));
setIntercomLauncherHidden(false);
expect(calls).toEqual([['update', { hide_default_launcher: false }]]);
});
it('does nothing when Intercom is unavailable', () => {
expect(() => setIntercomLauncherHidden(true)).not.toThrow();
});
});
@@ -0,0 +1,16 @@
declare global {
interface Window {
Intercom?: (command: string, options?: Record<string, unknown>) => void;
}
}
/**
* Hide or show Intercom's default launcher when it is available on the host page.
*/
export function setIntercomLauncherHidden(hidden: boolean): void {
if (typeof window === 'undefined' || typeof window.Intercom !== 'function') {
return;
}
window.Intercom('update', { hide_default_launcher: hidden });
}
@@ -0,0 +1,33 @@
'use server';
import { AgentFeedbackSource } from '@gitbook/api';
import type { AgentFeedbackResult } from '@/lib/agentFeedback';
import { submitAgentFeedback } from '@/lib/agentFeedback/server';
import { fetchServerActionSiteContext, getServerActionBaseContext } from '@/lib/server-actions';
import { traceErrorOnly } from '@/lib/tracing';
/**
* Record a finding about the site's content, submitted by the assistant while helping a reader.
*/
export async function submitAssistantFeedbackToTeam(input: {
feedback: string;
goal?: string;
/** Page the finding is about, as a URL on the site or a `/spaces/…/pages/…` ref. */
page: string;
asEmbeddable?: boolean;
}): Promise<AgentFeedbackResult> {
return traceErrorOnly('AI.submitAssistantFeedbackToTeam', async () => {
const baseContext = await getServerActionBaseContext({
isEmbeddable: input.asEmbeddable,
});
const context = await fetchServerActionSiteContext(baseContext);
return submitAgentFeedback(context, {
feedback: input.feedback,
goal: input.goal,
page: input.page,
source: AgentFeedbackSource.Assistant,
});
});
}
@@ -1,3 +1,4 @@
export * from './types';
export * from './chat';
export * from './feedback';
export * from './navigate';
@@ -1,7 +1,7 @@
'use server';
import { toInSiteHref } from '../navigation';
import { resolveContentRef, resolveStringContentRef } from '@/lib/references';
import { resolveContentRef, resolveStringContentRef, toContentRefPath } from '@/lib/references';
import { fetchServerActionSiteContext, getServerActionBaseContext } from '@/lib/server-actions';
import { traceErrorOnly } from '@/lib/tracing';
@@ -21,15 +21,7 @@ export async function resolveAINavigationLink(
const baseContext = await getServerActionBaseContext();
const context = await fetchServerActionSiteContext(baseContext);
// The content-ref scheme operates on the path portion of the URL. Strip any origin so an
// absolute URL (e.g. `https://docs.example.com/spaces/.../pages/...`) is handled too.
let path = url;
if (URL.canParse(url)) {
const parsed = new URL(url);
path = `${parsed.pathname}${parsed.search}${parsed.hash}`;
}
const contentRef = resolveStringContentRef(path);
const contentRef = resolveStringContentRef(toContentRefPath(url));
if (contentRef) {
const resolved = await resolveContentRef(contentRef, context);
if (!resolved) {
@@ -18,10 +18,12 @@ 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, streamAIChatResponse } from './server-actions';
import { getTools } from './tools';
import { useAIMessageContextRef } from './useAIMessageContext';
import { useLeaveAgentFeedbackTool, useLeaveUserFeedbackTool } from './useLeaveFeedbackTools';
import { useNavigateToPageTool } from './useNavigateToPageTool';
import {
type ResponseToRate,
@@ -240,7 +242,6 @@ export function AIChatProvider(props: {
const setSearchStateInURL = useSetSearchState();
const { siteSpaceId } = useCurrentContent();
const language = useLanguage();
const displayContext = renderMessageOptions?.asEmbeddable
? SiteInsightsDisplayContext.Embed
: SiteInsightsDisplayContext.Site;
@@ -256,6 +257,10 @@ export function AIChatProvider(props: {
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);
// 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.
@@ -265,22 +270,41 @@ export function AIChatProvider(props: {
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 page-feedback tool is gated on the site's "Was this helpful?" setting.
// 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];
const tools = [navigateToPageTool, submitAssistantFeedbackTool, leaveAgentFeedbackTool];
if (withPageFeedback) {
tools.push(submitPageFeedbackTool);
tools.push(submitPageFeedbackTool, leaveUserFeedbackTool);
}
return tools;
}, [navigateToPageTool, submitAssistantFeedbackTool, submitPageFeedbackTool, withPageFeedback]);
}, [
navigateToPageTool,
submitAssistantFeedbackTool,
leaveAgentFeedbackTool,
leaveUserFeedbackTool,
submitPageFeedbackTool,
withPageFeedback,
]);
// Event listeners storage
const eventsRef = React.useRef<Map<AIChatEvent['type'], AIChatEventListener[]>>(new Map());
// Open AI chat and sync with search state
const onOpen = React.useCallback(() => {
setIntercomLauncherHidden(true);
const { initialQuery } = globalState.getState();
globalState.setState((state) => ({ ...state, opened: true }));
@@ -297,6 +321,8 @@ export function AIChatProvider(props: {
// Close AI chat and clear ask parameter
const onClose = React.useCallback(() => {
setIntercomLauncherHidden(false);
globalState.setState((state) => ({ ...state, opened: false }));
// Clear ask parameter but keep other search state
@@ -711,6 +737,7 @@ export function AIChatProvider(props: {
// Clear the conversation and reset ask parameter
const onClear = React.useCallback(() => {
responseToRateRef.current = { responseId: null, query: null };
reportedAgentFeedbackRef.current = false;
globalState.setState((state) => ({
opened: state.opened,
responding: false,
@@ -0,0 +1,205 @@
'use client';
import * as React from 'react';
import { z } from 'zod';
import { zodToJsonSchema } from 'zod-to-json-schema';
import type { AIToolDefinition, SiteInsightsDisplayContext } from '@gitbook/api';
import type { GitBookIntegrationTool } from '@gitbook/browser-types';
import { type PagePointer, useCurrentPage } from '../hooks';
import { type InsightsEventPageContext, useTrackEvent } from '../Insights';
import { submitAssistantFeedbackToTeam } from './server-actions';
import { useLanguage } from '@/intl/client';
import { tString } from '@/intl/translate';
import {
AGENT_FEEDBACK_GOAL_MAX_LENGTH,
AGENT_FEEDBACK_MAX_LENGTH,
agentFeedbackDescriptions,
formatAgentFeedbackPageRef,
} from '@/lib/agentFeedback';
const feedbackInput = z.string().min(1).max(AGENT_FEEDBACK_MAX_LENGTH);
const pageInput = z.string().optional().describe(agentFeedbackDescriptions.pageReference);
const LeaveAgentFeedbackInputSchema = z.object({
feedback: feedbackInput.describe(agentFeedbackDescriptions.finding),
goal: z
.string()
.max(AGENT_FEEDBACK_GOAL_MAX_LENGTH)
.optional()
.describe(agentFeedbackDescriptions.goal),
page: pageInput,
});
const LeaveUserFeedbackInputSchema = z.object({
feedback: feedbackInput.describe(
"The user's feedback about the content, copied verbatim. Never rephrase, summarise, correct, translate or add to their words. Quote only what they said about the documentation, and leave out anything personal or confidential."
),
page: pageInput,
});
type LeaveFeedbackToolOptions = {
/** Whether the assistant runs in the embeddable, which resolves its own site context. */
asEmbeddable?: boolean;
/** Display context recorded with the feedback event (e.g. `site` vs. `embed`). */
displayContext: SiteInsightsDisplayContext;
};
/** The assistant's own finding, so it submits without confirmation, capped at one per chat. */
export function useLeaveAgentFeedbackTool(
options: LeaveFeedbackToolOptions & {
/** Whether a finding was already reported in this conversation, reset when it is cleared. */
reportedRef: React.RefObject<boolean>;
}
): GitBookIntegrationTool {
const { asEmbeddable, displayContext, reportedRef } = options;
const language = useLanguage();
const currentPage = useCurrentPage();
const trackEvent = useTrackEvent();
// The tool object is memoized once, so read the latest values from a ref at call time.
const ref = React.useRef({
language,
currentPage,
asEmbeddable,
displayContext,
trackEvent,
reportedRef,
});
React.useEffect(() => {
ref.current = {
language,
currentPage,
asEmbeddable,
displayContext,
trackEvent,
reportedRef,
};
});
return React.useMemo<GitBookIntegrationTool>(
() => ({
name: 'leaveAgentFeedback',
description:
'Leave feedback as you, the GitBook Assistant, on ways this question could have been answered more easily through content changes or reorganization — a missing explanation, an outdated or contradictory passage, or an answer you had to piece together from several pages. Use it when answering was hard, or when you could not answer at all, so the team can close the gap. Write it for a documentation maintainer who never saw this conversation, and send at most one per conversation. This carries your own observation: use `leaveUserFeedback` to relay what the user said, and `submitPageFeedback` to record their rating of a page. Do not use it to confirm that a page is accurate.',
inputSchema: zodToJsonSchema(
LeaveAgentFeedbackInputSchema as any
) as AIToolDefinition['inputSchema'],
execute: async (input) => {
const { reportedRef, ...tracking } = ref.current;
const { feedback, goal, page } = LeaveAgentFeedbackInputSchema.parse(input);
if (reportedRef.current) {
throw new Error(
'A finding was already reported in this conversation. Do not report another one.'
);
}
await submitFeedback({ feedback, goal, page, ...tracking });
reportedRef.current = true;
return {
output: { submitted: true },
summary: {
icon: 'comment-check',
text: tString(tracking.language, 'ai_chat_tools_shared_feedback_with_team'),
},
};
},
}),
// Rebuild when the locale changes so the summary (read at memo time, not from the ref)
// stays translated.
[language]
);
}
/** Speaks for the reader, so it confirms first, showing the exact text about to be sent. */
export function useLeaveUserFeedbackTool(
options: LeaveFeedbackToolOptions
): GitBookIntegrationTool {
const { asEmbeddable, displayContext } = options;
const language = useLanguage();
const currentPage = useCurrentPage();
const trackEvent = useTrackEvent();
// The tool object is memoized once, so read the latest values from a ref at call time.
const ref = React.useRef({ language, currentPage, asEmbeddable, displayContext, trackEvent });
React.useEffect(() => {
ref.current = { language, currentPage, asEmbeddable, displayContext, trackEvent };
});
return React.useMemo<GitBookIntegrationTool>(
() => ({
name: 'leaveUserFeedback',
description:
"Leave feedback on behalf of the user about the documentation, so the team can act on it. Use it when the user reports that something in the content is wrong, missing, outdated or confusing, or asks you to pass a message to the documentation team. Do not modify their feedback in any way: copy their own words. The user will be asked to confirm before it is sent. This carries the user's words: use `leaveAgentFeedback` for your own findings about the content, and `submitPageFeedback` to record their rating of a page.",
confirmation: (input) => {
const parsed = LeaveUserFeedbackInputSchema.safeParse(input);
const feedback = parsed.success ? parsed.data.feedback.trim() : undefined;
return {
icon: 'paper-plane',
label: tString(language, 'ai_chat_tools_submit_feedback'),
context: feedback ? `"${feedback}"` : undefined,
};
},
inputSchema: zodToJsonSchema(
LeaveUserFeedbackInputSchema as any
) as AIToolDefinition['inputSchema'],
execute: async (input) => {
const tracking = ref.current;
const { feedback, page } = LeaveUserFeedbackInputSchema.parse(input);
await submitFeedback({ feedback, page, ...tracking });
return {
output: { submitted: true },
summary: {
icon: 'comment-check',
text: tString(tracking.language, 'ai_chat_tools_submitted_feedback'),
},
};
},
}),
// Rebuild when the locale changes so the confirmation label (read at memo time, not from
// the ref) stays translated.
[language]
);
}
async function submitFeedback(input: {
feedback: string;
goal?: string;
page?: string;
currentPage: PagePointer | null;
asEmbeddable?: boolean;
displayContext: SiteInsightsDisplayContext;
trackEvent: ReturnType<typeof useTrackEvent>;
}): Promise<void> {
const page =
input.page?.trim() ||
(input.currentPage ? formatAgentFeedbackPageRef(input.currentPage) : null);
if (!page) {
throw new Error('No documentation page is currently open to leave feedback about.');
}
const result = await submitAssistantFeedbackToTeam({
feedback: input.feedback,
goal: input.goal,
page,
asEmbeddable: input.asEmbeddable,
});
if (!result.submitted) {
throw new Error(result.error);
}
// Attribute to the page the reader is on, since the insights location only lets us override
// the page — its space and revision come from the ambient context.
const pageContext: InsightsEventPageContext = {
pageId: input.currentPage?.pageId ?? null,
displayContext: input.displayContext,
};
input.trackEvent({ type: 'agent_feedback' }, pageContext, { immediate: true });
}
@@ -80,7 +80,7 @@ export function useSubmitPageFeedbackTool(options: {
() => ({
name: 'submitPageFeedback',
description:
"Submit the feedback on behalf of the user about the documentation page they are currently viewing. Use this when the user is indicating a sentiment about the page, particularly a negative one, or pointing to incorrect or incoherent information on a page. Proactively suggest to submit feedback for the user to help alleviate frustration or indicate a content gap they've encountered. The user will be asked to confirm before the feedback is recorded. Provide a rating and, when the user gave one, a comment in their own words.",
"Submit the feedback on behalf of the user about the documentation page they are currently viewing. Use this when the user is indicating a sentiment about the page, particularly a negative one, or pointing to incorrect or incoherent information on a page. Proactively suggest to submit feedback for the user to help alleviate frustration or indicate a content gap they've encountered. The user will be asked to confirm before the feedback is recorded. Provide a rating and, when the user gave one, a comment in their own words. This records their rating of the page — use `leaveUserFeedback` to pass a report of their own about the content on to the documentation team.",
confirmation: (input) => {
const parsed = SubmitPageFeedbackInputSchema.safeParse(input);
const comment = parsed.success ? parsed.data.comment?.trim() : undefined;
@@ -3,6 +3,7 @@ import { Icon } from '@gitbook/icons';
import type { BlockProps } from '../Block';
import { Blocks } from '../Blocks';
import { shouldShowHashLinks } from '../HashLinkButton';
import { Inlines } from '../Inlines';
import { Details } from './Details';
import { ToggleChevron } from '@/components/primitives';
@@ -31,6 +32,8 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
? await getSpaceLanguage(context.contentContext)
: defaultLanguage;
const showHashLink = shouldShowHashLinks(context);
return (
<Details
id={id}
@@ -41,7 +44,8 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
className={tcls(
'cursor-pointer',
'px-4',
'pr-10',
// Reserve room for the anchor icon pinned to the right edge
showHashLink && 'pr-10',
'py-4',
'relative',
'list-none',
@@ -71,32 +75,34 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
context={context}
ancestorInlines={[]}
/>
<a
href={`#${id}`}
aria-label={tString(language, 'direct_link_to_heading')}
className={tcls(
'absolute',
'top-2',
'bottom-2',
'right-4',
'flex',
'items-center',
'dark:shadow-none',
'dark:ring-0'
)}
>
<Icon
icon="hashtag"
{showHashLink ? (
<a
href={`#${id}`}
aria-label={tString(language, 'direct_link_to_heading')}
className={tcls(
'inline-block',
'size-3',
'transition-colors',
'text-transparent',
'group-hover/expandable:text-tint-subtle',
'contrast-more:group-hover/expandable:text-tint-strong'
'absolute',
'top-2',
'bottom-2',
'right-4',
'flex',
'items-center',
'dark:shadow-none',
'dark:ring-0'
)}
/>
</a>
>
<Icon
icon="hashtag"
className={tcls(
'inline-block',
'size-3',
'transition-colors',
'text-transparent',
'group-hover/expandable:text-tint-subtle',
'contrast-more:group-hover/expandable:text-tint-strong'
)}
/>
</a>
) : null}
</summary>
<Blocks
nodes={body.nodes}
@@ -2,9 +2,22 @@ import type { DocumentBlockHeading, DocumentBlockTabs } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { Link } from '../primitives';
import type { DocumentContext } from './DocumentView';
import { getBlockTextStyle } from './spacing';
import { type ClassValue, tcls } from '@/lib/tailwind';
/**
* Whether blocks should render a visible anchor link icon.
* Only the page body carries a page; search answers, AI chat and PDF export keep anchors.
*/
export function shouldShowHashLinks(context: DocumentContext): boolean {
const contentContext = context.contentContext;
if (!contentContext || !('page' in contentContext)) {
return true;
}
return contentContext.page.layout.anchors !== false;
}
/**
* A hash icon which adds the block or active block item's ID in the URL hash.
* The button needs to be wrapped in a container with `hashLinkButtonWrapperStyles`.
@@ -1,7 +1,7 @@
import type { DocumentBlockHeading } from '@gitbook/api';
import type { BlockProps } from './Block';
import { HashLinkButton, hashLinkButtonWrapperStyles } from './HashLinkButton';
import { HashLinkButton, hashLinkButtonWrapperStyles, shouldShowHashLinks } from './HashLinkButton';
import { HeadingRevealWrapper } from './HeadingRevealWrapper';
import { Inlines } from './Inlines';
import { getBlockTextStyle } from './spacing';
@@ -24,6 +24,8 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
? await getSpaceLanguage(context.contentContext)
: defaultLanguage;
const showHashLink = shouldShowHashLinks(context);
return (
<HeadingRevealWrapper
as={Tag}
@@ -34,7 +36,8 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
'font-heading',
'pdf-heading',
'block',
'pr-6',
// Reserve room for the absolutely positioned anchor icon on coarse pointers
showHashLink && 'pr-6',
'pointer-fine:flex',
'pointer-fine:items-baseline',
'pointer-fine:pr-0',
@@ -63,20 +66,22 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
<Inlines {...rest} context={context} nodes={block.nodes} ancestorInlines={[]} />
</span>
<HashLinkButton
id={id}
block={block}
className={tcls(
'absolute',
block.type === 'heading-1'
? '[transform:translateY(0.125em)]'
: '[transform:translateY(0.17em)]',
'pointer-fine:-ml-6 pointer-fine:relative pointer-fine:order-first pointer-fine:self-center pointer-fine:pr-2 pointer-fine:[transform:none]',
'pointer-fine:[.flip-heading-hash_&]:order-last pointer-fine:[.flip-heading-hash_&]:ml-1 pointer-fine:[.flip-heading-hash_&]:pl-2'
)}
iconClassName={tcls('size-4')}
label={tString(language, 'direct_link_to_heading')}
/>
{showHashLink ? (
<HashLinkButton
id={id}
block={block}
className={tcls(
'absolute',
block.type === 'heading-1'
? '[transform:translateY(0.125em)]'
: '[transform:translateY(0.17em)]',
'pointer-fine:-ml-6 pointer-fine:relative pointer-fine:order-first pointer-fine:self-center pointer-fine:pr-2 pointer-fine:[transform:none]',
'pointer-fine:[.flip-heading-hash_&]:order-last pointer-fine:[.flip-heading-hash_&]:ml-1 pointer-fine:[.flip-heading-hash_&]:pl-2'
)}
iconClassName={tcls('size-4')}
label={tString(language, 'direct_link_to_heading')}
/>
) : null}
</HeadingRevealWrapper>
);
}
@@ -52,8 +52,8 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
const anchorElement = (
<InlineLinkAnchor
href={resolved.href}
contentRef={inline.data.ref}
isExternal={inline.data.ref.kind === 'url'}
contentRef={resolved.resolvedRef ?? inline.data.ref}
isExternal={(resolved.resolvedRef ?? inline.data.ref).kind === 'url'}
>
{inlinesElement}
</InlineLinkAnchor>
@@ -121,7 +121,7 @@ function InlineLinkTooltipWrapper(props: {
let breadcrumbs = resolved.ancestors ?? [];
const isMailto = resolved.href.startsWith('mailto:');
const isExternal = inline.data.ref.kind === 'url';
const isExternal = (resolved.resolvedRef ?? inline.data.ref).kind === 'url';
const isSamePage = inline.data.ref.kind === 'anchor' && inline.data.ref.page === undefined;
if (isMailto) {
@@ -95,7 +95,7 @@
/** Buttons */
.contentkit-button {
@apply text-sm px-3 h-8 text-center inline-block py-1.5 rounded-md straight-corners:rounded-none place-self-start ring-1 ring-tint hover:ring-tint-hover shadow-sm shadow-tint dark:shadow-tint-1 hover:shadow-md active:shadow-none contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12 hover:scale-105 active:scale-100 transition-all grow-0 shrink-0 truncate w-full;
@apply text-sm px-3 h-8 text-center inline-block py-1.5 rounded-md straight-corners:rounded-none ring-1 ring-tint hover:ring-tint-hover shadow-sm shadow-tint dark:shadow-tint-1 hover:shadow-md active:shadow-none contrast-more:ring-tint-12 contrast-more:hover:ring-2 contrast-more:hover:ring-tint-12 hover:scale-105 active:scale-100 transition-all truncate;
}
.contentkit-button-style-primary {
@@ -130,15 +130,38 @@
.contentkit-modal-header {
@apply flex flex-col gap-2 px-4 py-2;
}
.contentkit-modal-header-with-close {
@apply flex-row items-start gap-4 px-4 pb-0 pt-4;
}
.contentkit-modal-header-content {
@apply min-w-0 flex-1;
}
.contentkit-modal-title {
@apply text-2xl font-medium text-tint-strong;
}
.contentkit-modal-header-with-close .contentkit-modal-subtitle {
@apply break-words text-sm text-tint;
}
.contentkit-modal-header-with-close .contentkit-modal-title {
@apply break-words;
}
.contentkit-modal-body {
@apply px-4 py-4;
}
.contentkit-modal-footer {
@apply flex justify-end gap-2 px-4 pb-4;
}
.contentkit-modal-close {
@apply flex size-8 shrink-0 items-center justify-center rounded-full text-tint transition-colors hover:bg-tint-hover hover:text-tint-strong focus-visible:outline-2 focus-visible:outline-primary;
}
.contentkit-modal-close-icon {
@apply size-4;
}
.contentkit-modal-header + .contentkit-modal-body {
@apply pt-0;
}
@@ -208,9 +231,6 @@
.contentkit-modal-confirm .contentkit-modal-footer {
@apply flex gap-2 justify-end;
}
.contentkit-button-confirm {
@apply w-auto flex-grow-0 flex-shrink-0;
}
.contentkit-button-style-danger {
@apply bg-danger text-danger hover:bg-danger-hover hover:text-danger-strong contrast-more:bg-tint-subtle;
}
@@ -0,0 +1,156 @@
'use client';
import React from 'react';
import { Icon } from '@gitbook/icons';
import { type PromptActionId, setPromptAction, usePromptAction } from './promptAction';
import {
Button,
ButtonGroup,
DropdownMenu,
DropdownMenuItem,
ToggleChevron,
} from '@/components/primitives';
import { tString, useLanguage } from '@/intl/client';
import { AI_AGENTS, getAIAgent } from '@/lib/ai-agents';
import { tcls } from '@/lib/tailwind';
/** How long the copy button shows its confirmation. */
const COPIED_MESSAGE_DURATION = 1000;
/**
* Actions of a prompt block: copying the prompt, or handing it to a coding agent. The visitor's
* last pick becomes the main button, here and in every other prompt block they come across.
*/
export function PromptActions(props: { prompt: string; openInAIProviders: boolean }) {
const { prompt, openInAIProviders } = props;
const language = useLanguage();
const selectedAction = usePromptAction();
const [copied, setCopied] = React.useState(false);
React.useEffect(() => {
if (!copied) {
return;
}
const timeout = setTimeout(() => {
setCopied(false);
}, COPIED_MESSAGE_DURATION);
return () => {
clearTimeout(timeout);
};
}, [copied]);
const copyPrompt = () => {
navigator.clipboard.writeText(prompt);
setCopied(true);
};
// The pick follows the visitor from site to site, so fall back to copying wherever the agent
// actions are turned off — and with nothing to hand over, an agent link would open an agent on
// an empty prompt.
const action: PromptActionId = openInAIProviders && prompt ? selectedAction : 'copy';
const agent = action === 'copy' ? null : getAIAgent(action);
const mainButton = agent ? (
<Button
variant="secondary"
size="xsmall"
icon={agent.icon}
label={tString(language, 'open_in', agent.label)}
href={agent.getURL(prompt)}
// The OS picks the deep link up and the page stays put, where `_blank` would strand the
// visitor on a tab that never loads anything.
target="_self"
/>
) : (
<Button
variant="secondary"
size="xsmall"
icon={copied ? 'check' : 'copy'}
label={copied ? tString(language, 'code_copied') : tString(language, 'prompt_copy')}
disabled={!prompt}
onClick={copyPrompt}
/>
);
return (
// Lifted above the header's overlay button, which otherwise swallows the clicks.
<div className="relative z-20 flex shrink-0 items-center gap-2">
{openInAIProviders ? (
<ButtonGroup>
{mainButton}
<DropdownMenu
align="end"
className="!min-w-48 max-w-max"
button={
<Button
label={tString(language, 'more')}
size="xsmall"
variant="secondary"
truncate={false}
disabled={!prompt}
>
<span className="flex items-center gap-1.5">
<AgentIconStack />
<ToggleChevron className="size-text-sm" />
</span>
</Button>
}
>
<DropdownMenuItem
active={action === 'copy'}
leadingIcon="copy"
onClick={() => {
setPromptAction('copy');
copyPrompt();
}}
>
{tString(language, 'prompt_copy')}
</DropdownMenuItem>
{AI_AGENTS.map((item) => (
<DropdownMenuItem
key={item.id}
active={action === item.id}
leadingIcon={item.icon}
href={item.getURL(prompt)}
target="_self"
onClick={() => setPromptAction(item.id)}
>
{tString(language, 'open_in', item.label)}
</DropdownMenuItem>
))}
</DropdownMenu>
</ButtonGroup>
) : (
mainButton
)}
</div>
);
}
/**
* The agents on offer, overlapped into a stack, so the menu advertises what it holds without
* spelling out three names next to a button that already has one.
*/
function AgentIconStack() {
return (
<span className="flex items-center">
{AI_AGENTS.map((agent, index) => (
<span
key={agent.id}
className={tcls(
'flex size-4 shrink-0 items-center justify-center rounded-full border border-tint bg-tint-base',
// Each chip's border cuts into the one behind it, so the marks stay legible
// however tightly they are stacked.
index > 0 && '-ms-1.5'
)}
>
<Icon icon={agent.icon} className="size-2.5" />
</span>
))}
</span>
);
}
@@ -5,14 +5,11 @@ import React from 'react';
import type { DocumentBlockPrompt } from '@gitbook/api';
import { Icon, type IconName } from '@gitbook/icons';
import { Button, DropdownMenu, DropdownMenuItem, ToggleChevron } from '@/components/primitives';
import { getURLForLLM } from '@/components/utils';
import { PromptActions } from './PromptActions';
import { ToggleChevron } from '@/components/primitives';
import { tString, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
const OPEN_IN_AI_PROVIDERS = ['claude', 'chatgpt', 'cursor'] as const;
type AIProviders = (typeof OPEN_IN_AI_PROVIDERS)[number];
type PromptClientProps = DocumentBlockPrompt['data'] & {
contentIcon: IconName | null;
prompt: string;
@@ -88,106 +85,3 @@ export function PromptClient(props: PromptClientProps) {
</div>
);
}
function PromptActions(props: { prompt: string; openInAIProviders: boolean }) {
const { prompt, openInAIProviders } = props;
return (
<div className="relative z-20 flex shrink-0 items-center gap-2">
<CopyPromptButton prompt={prompt} />
{openInAIProviders ? <OpenPromptDropdown prompt={prompt} /> : null}
</div>
);
}
// time in milliseconds to show the "Copied" message after copying a prompt
const COPIED_MESSAGE_DURATION = 1000;
function CopyPromptButton(props: { prompt: string }) {
const { prompt } = props;
const language = useLanguage();
const [copied, setCopied] = React.useState(false);
React.useEffect(() => {
if (!copied) {
return;
}
const timeout = setTimeout(() => {
setCopied(false);
}, COPIED_MESSAGE_DURATION);
return () => {
clearTimeout(timeout);
};
}, [copied]);
return (
<Button
variant="primary"
size="xsmall"
label={copied ? tString(language, 'code_copied') : tString(language, 'prompt_copy')}
disabled={!prompt}
onClick={() => {
navigator.clipboard.writeText(prompt);
setCopied(true);
}}
/>
);
}
function OpenPromptDropdown(props: { prompt: string }) {
const { prompt } = props;
const language = useLanguage();
return (
<DropdownMenu
align="end"
className="!min-w-48 max-w-max"
button={
<Button
label={tString(language, 'open_in_ai')}
trailing={<ToggleChevron className="size-text-sm" />}
size="xsmall"
variant="secondary"
className="max-sm:hidden"
disabled={!prompt}
/>
}
>
{OPEN_IN_AI_PROVIDERS.map((provider) => {
const definition = getPromptOpenActionDefinition(provider);
return (
<DropdownMenuItem
key={provider}
href={getURLForLLM(provider, prompt)}
target="_blank"
leadingIcon={definition.icon}
>
{tString(language, 'open_in', definition.label)}
</DropdownMenuItem>
);
})}
</DropdownMenu>
);
}
function getPromptOpenActionDefinition(action: AIProviders): { icon: IconName; label: string } {
switch (action) {
case 'cursor':
return {
icon: 'cursor',
label: 'Cursor',
};
case 'claude':
return {
icon: 'claude',
label: 'Claude',
};
case 'chatgpt':
return {
icon: 'chatgpt',
label: 'ChatGPT',
};
}
}
@@ -0,0 +1,95 @@
'use client';
import React from 'react';
import { type AIAgentId, isAIAgentId } from '@/lib/ai-agents';
import { getLocalStorageItem, setLocalStorageItem } from '@/lib/browser';
/**
* What a prompt block does when its main button is pressed: copy the prompt, or hand it to one of
* the coding agents.
*/
export type PromptActionId = 'copy' | AIAgentId;
/**
* Not namespaced per site: a visitor who works in Cursor works in Cursor everywhere, so the pick
* follows them across sites the same way the `select` store's slugs do.
*/
const STORAGE_KEY = '@gitbook/prompt-action';
const DEFAULT_ACTION: PromptActionId = 'copy';
let state: PromptActionId = DEFAULT_ACTION;
let loaded = false;
const listeners = new Set<() => void>();
function isPromptActionId(value: unknown): value is PromptActionId {
return value === 'copy' || isAIAgentId(value);
}
function read(): PromptActionId {
const stored = getLocalStorageItem<unknown>(STORAGE_KEY, DEFAULT_ACTION);
return isPromptActionId(stored) ? stored : DEFAULT_ACTION;
}
function emitChange() {
for (const listener of listeners) {
listener();
}
}
/**
* Adopt what's in storage, once per page load. Deferred to the first subscription rather than run at
* module scope so the first client render still matches the server's, and the stored pick only
* lands once React is listening.
*/
function load() {
if (loaded || typeof window === 'undefined') {
return;
}
loaded = true;
state = read();
// Another tab picking an action updates this one too.
window.addEventListener('storage', (event) => {
if (event.key !== null && event.key !== STORAGE_KEY) {
return;
}
state = read();
emitChange();
});
}
function subscribe(listener: () => void) {
load();
listeners.add(listener);
// Storage was only read just now, so nudge the subscriber to re-read the snapshot.
listener();
return () => {
listeners.delete(listener);
};
}
/**
* Remember the action the visitor picked, for every prompt block on the page and the next one.
*/
export function setPromptAction(action: PromptActionId) {
load();
if (state === action) {
return;
}
state = action;
setLocalStorageItem(STORAGE_KEY, action);
emitChange();
}
/**
* The action the visitor last picked, defaulting to copying the prompt.
*/
export function usePromptAction(): PromptActionId {
return React.useSyncExternalStore(
subscribe,
() => state,
() => DEFAULT_ACTION
);
}
@@ -226,11 +226,10 @@ function SelectFilterDropdown(props: { column: TableSelectColumn }) {
key={option.value}
active={selected}
leadingIcon={selected ? 'check' : undefined}
onSelect={(event) => {
// Keep the menu open so several options can be toggled at once.
event.preventDefault();
toggleOption(column.id, option.value);
}}
// `closeOnClick={false}` keeps the menu open so several options can be
// toggled at once.
closeOnClick={false}
onClick={() => toggleOption(column.id, option.value)}
>
{option.label || option.value}
</DropdownMenuItem>
@@ -5,7 +5,12 @@ import { validateIconName } from '@gitbook/icons/icons';
import type { BlockProps } from '../Block';
import { Blocks } from '../Blocks';
import { DynamicTabs } from './DynamicTabs';
import { generateSelectCSS, selectSetClassName, slugifySelectValue } from '@/lib/select';
import {
generateSelectCSS,
resolveSelectSlug,
selectSetClassName,
slugifySelectValue,
} from '@/lib/select';
import { tcls } from '@/lib/tailwind';
export function Tabs(props: BlockProps<DocumentBlockTabs>) {
@@ -26,6 +31,7 @@ export function Tabs(props: BlockProps<DocumentBlockTabs>) {
return {
id: tab.meta?.id ?? tab.key,
title: tab.data.title ?? '',
slug: tab.data.slug,
icon,
body: (
<Blocks
@@ -94,19 +100,20 @@ function SelectGroupStyle({ slugs }: { slugs: string[] }) {
}
/**
* Derive a `select` slug for each tab from its title. Untitled tabs fall back to their (stable) id
* so they stay selectable.
* Resolve a `select` slug for each tab: its explicit slug when set, else one derived from its title.
* Untitled tabs fall back to their (stable) id so they stay selectable.
*
* Same-named tabs deliberately share a slug — selecting one syncs every tab of that name, here and
* on other pages, which is the whole point of name-based selection. We don't disambiguate duplicates
* with a positional suffix: that would desync the duplicate and make a stored selection retarget
* whenever tabs are renamed or reordered.
* whenever tabs are renamed or reordered. An explicit slug is the way out for a tab that needs to
* keep its identity across a rename.
*/
function withSelectSlugs<T extends { id: string; title: string }>(
function withSelectSlugs<T extends { id: string; title: string; slug?: string }>(
items: T[]
): (T & { slug: string })[] {
return items.map((item) => ({
...item,
slug: slugifySelectValue(item.title) || slugifySelectValue(item.id) || item.id,
slug: resolveSelectSlug(item) || slugifySelectValue(item.id) || item.id,
}));
}
@@ -16,18 +16,10 @@ import { SearchInput } from './SearchInput';
import { SearchLiveResultsAnnouncer } from './SearchLiveResultsAnnouncer';
import { SearchScopeControl } from './SearchScopeControl';
import { useSearchController } from './useSearchController';
import { useSearchPopupFocusTrap } from './useSearchPopupFocusTrap';
import { t, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
const SEARCH_POPUP_FOCUSABLE_SELECTOR = [
'a[href]:not([aria-disabled="true"])',
'button:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
const SearchFrame = dynamic(() => import('./SearchFrame').then((mod) => mod.SearchFrame), {
ssr: false,
});
@@ -144,54 +136,7 @@ export function SearchContainer({
? Boolean(state?.open || state?.query || wasSearchOpened)
: Boolean(state?.query || withAI);
React.useEffect(() => {
if (
usesSideSheet ||
!isSearchOpen ||
!shouldShowSearchFrame ||
!searchInputRef.current ||
!searchPopup
) {
return;
}
const searchInput = searchInputRef.current.querySelector<HTMLElement>(
'[data-testid="search-input"]'
);
if (!searchInput) {
return;
}
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Tab') {
return;
}
const popupControls = Array.from(
searchPopup.querySelectorAll<HTMLElement>(SEARCH_POPUP_FOCUSABLE_SELECTOR)
).filter((element) => element.getClientRects().length > 0);
const focusableElements = [searchInput, ...popupControls];
const currentIndex = focusableElements.indexOf(document.activeElement as HTMLElement);
const nextIndex =
currentIndex === -1
? event.shiftKey
? focusableElements.length - 1
: 0
: event.shiftKey
? currentIndex - 1
: currentIndex + 1;
const wrappedIndex = (nextIndex + focusableElements.length) % focusableElements.length;
event.preventDefault();
focusableElements[wrappedIndex]?.focus();
};
document.addEventListener('keydown', handleKeyDown, true);
return () => {
document.removeEventListener('keydown', handleKeyDown, true);
};
}, [isSearchOpen, searchPopup, shouldShowSearchFrame, usesSideSheet]);
useSearchPopupFocusTrap({ close, searchInputRef, searchPopup, usesSideSheet });
const scopeControlNode =
searchProps.withVariants || searchProps.withSections ? (
@@ -5,6 +5,7 @@ import { motion } from 'framer-motion';
import React from 'react';
import { Button, SkeletonParagraph, SkeletonSmall } from '../primitives';
import { isExternalLink } from '../utils/link';
import { addRecentSearchQuery } from './recent-queries';
import { SearchPageResultItem } from './SearchPageResultItem';
import { SearchQuestionResultItem } from './SearchQuestionResultItem';
@@ -218,6 +219,16 @@ export const SearchResults = React.forwardRef(function SearchResults(
addRecentSearchQuery(siteSpaceId, query, 'search');
}
// The popover's focus manager re-focuses the popup when the focused
// result is torn down during close (base-ui `restoreFocus`), and that
// focus() scrolls the popup — anchored at the top of the page — into
// view, undoing the scroll to the section the result linked to.
// A click that opens elsewhere leaves the search open, and keyboard
// users should keep their place in it.
if (navigatesCurrentWindow(event)) {
event.currentTarget.blur();
}
onResultSelect?.();
};
const resultItemProps = {
@@ -385,3 +396,19 @@ const SearchResultsSkeleton = (props: { items: number }) => {
</>
);
};
/**
* Whether clicking a result navigates the current window, and so closes the search — as opposed
* to opening a new tab or window (modifier keys, `target="_blank"`, or an external destination,
* which an embed opens in a new tab).
*/
function navigatesCurrentWindow(event: React.MouseEvent<HTMLAnchorElement>) {
const link = event.currentTarget;
return (
!event.ctrlKey &&
!event.metaKey &&
!event.shiftKey &&
link.target !== '_blank' &&
!isExternalLink(link.href, window.location.origin)
);
}
@@ -0,0 +1,115 @@
import React from 'react';
const SEARCH_POPUP_FOCUSABLE_SELECTOR = [
'a[href]:not([aria-disabled="true"])',
'button:not([disabled])',
'input:not([disabled])',
'select:not([disabled])',
'textarea:not([disabled])',
'[tabindex]:not([tabindex="-1"])',
].join(',');
/**
* Traps Tab/Shift+Tab within the search input and its popup while it's open, and hands focus
* off to the adjacent page element once the trap's boundary is reached.
*/
export function useSearchPopupFocusTrap({
close,
searchInputRef,
searchPopup,
usesSideSheet,
}: {
close: () => void;
searchInputRef: React.RefObject<HTMLDivElement | null>;
searchPopup: HTMLDivElement | null;
usesSideSheet: boolean;
}) {
React.useEffect(() => {
if (usesSideSheet || !searchInputRef.current || !searchPopup) {
return;
}
const searchInput = searchInputRef.current.querySelector<HTMLElement>(
'[data-testid="search-input"]'
);
if (!searchInput) {
return;
}
// Finds the next (or previous) focusable element in real document order,
// skipping the popup's own content as well as Base UI's internal focus-guard
// sentinels — both live in a portal, so their DOM position doesn't match their
// visual position after the search input, and would otherwise re-trap focus.
const findAdjacentPageElement = (direction: 'next' | 'previous') => {
const step = direction === 'next' ? 1 : -1;
const pageFocusable = Array.from(
document.querySelectorAll<HTMLElement>(SEARCH_POPUP_FOCUSABLE_SELECTOR)
).filter(
(element) =>
element.getClientRects().length > 0 &&
!element.closest('[data-base-ui-portal], [data-base-ui-focus-guard]')
);
return pageFocusable[pageFocusable.indexOf(searchInput) + step];
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== 'Tab') {
return;
}
const activeElement = document.activeElement as HTMLElement | null;
// Whether or not the popover ever visibly opened, Base UI still keeps a pair
// of hidden, tabbable focus-guard nodes mounted in its portal — reachable by
// Tab regardless of open state, and otherwise a dead end.
const isOnOwnFocusGuard = Boolean(
activeElement?.hasAttribute('data-base-ui-focus-guard') &&
searchPopup.closest('[data-base-ui-portal]')?.contains(activeElement)
);
const popupControls = Array.from(
searchPopup.querySelectorAll<HTMLElement>(SEARCH_POPUP_FOCUSABLE_SELECTOR)
).filter((element) => element.getClientRects().length > 0);
const focusableElements = [searchInput, ...popupControls];
const currentIndex = focusableElements.indexOf(activeElement as HTMLElement);
if (currentIndex === -1 && !isOnOwnFocusGuard) {
// Focus isn't within the search widget — leave native Tab handling alone.
return;
}
if (event.shiftKey && currentIndex === 0) {
// Search input is a regular DOM node, so the browser's native Shift+Tab
// already moves focus to whatever precedes it once we close the popover.
close();
return;
}
if (event.shiftKey && (isOnOwnFocusGuard || currentIndex === -1)) {
event.preventDefault();
close();
findAdjacentPageElement('previous')?.focus();
return;
}
if (
!event.shiftKey &&
(isOnOwnFocusGuard || currentIndex === focusableElements.length - 1)
) {
event.preventDefault();
close();
findAdjacentPageElement('next')?.focus();
return;
}
const nextIndex = event.shiftKey ? currentIndex - 1 : currentIndex + 1;
event.preventDefault();
focusableElements[nextIndex]?.focus();
};
document.addEventListener('keydown', handleKeyDown, true);
return () => {
document.removeEventListener('keydown', handleKeyDown, true);
};
}, [close, searchPopup, usesSideSheet]);
}
@@ -5,18 +5,13 @@ import { useCallback, useSyncExternalStore } from 'react';
import { selectStore } from '@/lib/select';
/**
* Subscribe to the site-wide `select` state. Returns the current recency list plus the setters.
* Consumers that only need "which of my options is active" should prefer {@link useResolvedSlug}.
* Setters for the site-wide `select` state. Deliberately does not subscribe: the store notifies on
* every activation anywhere on the page, so returning the recency list here would re-render every
* block that only ever wanted to *write* a selection. To read one, use {@link useResolvedSlug},
* which re-renders a block only when its own resolved option changes.
*/
export function useSelect() {
const slugs = useSyncExternalStore(
selectStore.subscribe,
selectStore.getState,
selectStore.getState
).slugs;
return {
slugs,
activate: selectStore.activate,
deactivate: selectStore.deactivate,
};
@@ -3,7 +3,7 @@ import Script from 'next/script';
import React from 'react';
import * as ReactDOM from 'react-dom';
import { CustomizationDefaultThemeMode } from '@gitbook/api';
import { CustomizationDefaultThemeMode, CustomizationPageActionType } from '@gitbook/api';
import { AIContextProvider } from '../AI';
import { RocketLoaderDetector } from './RocketLoaderDetector';
@@ -12,6 +12,7 @@ import { AdminToolbar } from '@/components/AdminToolbar';
import { CookiesToast } from '@/components/Cookies';
import { LoadIntegrations } from '@/components/Integrations';
import { SpaceLayout } from '@/components/SpaceLayout';
import { WebMCP } from '@/components/WebMCP/WebMCP';
import type { VisitorAuthClaims } from '@/lib/adaptive';
import { buildVersion } from '@/lib/build';
import type { GitBookSiteContext } from '@/lib/context';
@@ -117,6 +118,9 @@ export async function SiteLayout(props: {
</AIContextProvider>
<LoadIntegrations />
{customization.pageActions.items.includes(CustomizationPageActionType.Mcp) ? (
<WebMCP mcpURL={context.linker.toPathInSite('~gitbook/mcp')} />
) : null}
{scripts.map(({ script }) =>
isDeferrableScript(script) ? (
<Script key={script} src={script} strategy="lazyOnload" />
@@ -1,6 +1,6 @@
'use client';
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import { usePathname, useSearchParams } from 'next/navigation';
import React from 'react';
import type { PageMetaLinks } from './SitePage';
@@ -33,7 +33,6 @@ export function PageClientLayout({ pageMetaLinks }: { pageMetaLinks: PageMetaLin
* so we need to remove the fallback parameter.
*/
function useStripFallbackQueryParam() {
const router = useRouter();
const pathname = usePathname();
const searchParams = useSearchParams();
@@ -41,9 +40,14 @@ function useStripFallbackQueryParam() {
if (searchParams?.has('fallback')) {
const params = new URLSearchParams(searchParams.toString());
params.delete('fallback');
router.push(`${pathname}?${params.toString()}${window.location.hash ?? ''}`);
const query = params.toString();
window.history.replaceState(
null,
'',
`${pathname}${query ? `?${query}` : ''}${window.location.hash}`
);
}
}, [router, pathname, searchParams]);
}, [pathname, searchParams]);
}
/**
@@ -0,0 +1,94 @@
import { describe, expect, it, mock } from 'bun:test';
import { CustomizationPageActionType, type RevisionPageDocument } from '@gitbook/api';
import type { GitBookSiteContext } from '@/lib/context';
mock.module('server-only', () => ({}));
const { fetchPageData } = await import('./fetch');
const page = {
id: 'page-1',
title: 'Introduction',
kind: 'sheet',
type: 'document',
path: 'readme',
slug: 'readme',
pages: [],
} as RevisionPageDocument;
const git = {
oid: 'abc123',
path: 'README.md',
};
function createContext(options: { gitEnabled: boolean; gitSync?: boolean }) {
const getRevisionPageByPath = mock(async () => ({
data: {
...page,
git,
},
}));
const context = {
revision: { pages: [page] },
revisionId: 'revision-1',
customization: {
pageActions: {
items: options.gitEnabled ? [CustomizationPageActionType.Git] : [],
},
},
space: {
id: 'space-1',
gitSync:
options.gitSync === false
? undefined
: {
url: 'https://github.com/gitbook/example/tree/main',
},
},
dataFetcher: { getRevisionPageByPath },
} as unknown as GitBookSiteContext;
return { context, getRevisionPageByPath };
}
describe('fetchPageData', () => {
it('fetches the Git metadata for an enabled Edit on Git action', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: true });
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).toHaveBeenCalledWith({
spaceId: 'space-1',
revisionId: 'revision-1',
path: 'readme',
metadata: true,
cachedMetadata: true,
});
expect(result.pageTarget?.page.git).toEqual(git);
expect(result.context.page?.git).toEqual(git);
});
it('does not fetch Git metadata when the action is disabled', async () => {
const { context, getRevisionPageByPath } = createContext({ gitEnabled: false });
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result.pageTarget?.page.git).toBeUndefined();
});
it('does not fetch Git metadata without Git Sync', async () => {
const { context, getRevisionPageByPath } = createContext({
gitEnabled: true,
gitSync: false,
});
const result = await fetchPageData(context, { pageId: page.id });
expect(getRevisionPageByPath).not.toHaveBeenCalled();
expect(result.pageTarget?.page.git).toBeUndefined();
});
});
@@ -1,6 +1,7 @@
import { redirect } from 'next/navigation';
import { permanentRedirect, redirect } from 'next/navigation';
import {
CustomizationPageActionType,
SITE_REDIRECT_SOURCE_PATH_MAX_LENGTH,
SITE_REDIRECT_SOURCE_PATH_PATTERN,
} from '@gitbook/api';
@@ -26,7 +27,34 @@ export type PageParams = PagePathParams | PageIdParams;
* Optimized to fetch in parallel as much as possible.
*/
export async function fetchPageData(context: GitBookSiteContext, params: PageParams) {
const pageTarget = await resolvePage(context, params);
let pageTarget = await resolvePage(context, params);
// Revision trees omit metadata for cache efficiency, so load it only when this action needs the Git path.
if (
pageTarget &&
!pageTarget.page.git &&
context.space.gitSync?.url &&
context.customization.pageActions.items.includes(CustomizationPageActionType.Git)
) {
const response = await context.dataFetcher.getRevisionPageByPath({
spaceId: context.space.id,
revisionId: context.revisionId,
path: pageTarget.page.path,
metadata: true,
cachedMetadata: true,
});
const pageWithMetadata = response.data;
if (pageWithMetadata?.type === 'document' && pageWithMetadata.git) {
pageTarget = {
...pageTarget,
page: {
...pageTarget.page,
git: pageWithMetadata.git,
},
};
}
}
return {
context: {
@@ -89,7 +117,21 @@ async function resolvePage(context: GitBookSiteContext, params: PagePathParams |
})
));
if (resolvedSiteRedirect) {
return redirect(linker.toLinkForContent(resolvedSiteRedirect.target));
const destination = linker.toLinkForContent(resolvedSiteRedirect.target);
const isPublicLiveContext =
!shareKey &&
!context.changeRequest &&
!context.preview &&
context.revisionId === context.space.revision &&
!context.isLoggedInVisitor;
if (
resolvedSiteRedirect.redirect?.permanent &&
!resolvedSiteRedirect.redirect.draft &&
isPublicLiveContext
) {
return permanentRedirect(destination);
}
return redirect(destination);
}
}
@@ -58,15 +58,15 @@ export function SpaceLayoutServerContext(props: SpaceLayoutProps) {
? context.linker.toPathInSite('~gitbook/auth/login')
: null;
const eventUrl = new URL(
context.linker.toAbsoluteURL(context.linker.toPathInSite('/~gitbook/__evt'))
);
eventUrl.searchParams.set('o', context.organizationId);
eventUrl.searchParams.set('s', context.site.id);
// Kept relative: a prerendered page has no request to read the host from, so an absolute URL
// pins the configured host and turns these fetches cross-origin when it differs (apex vs www).
const eventParams = new URLSearchParams({
o: context.organizationId,
s: context.site.id,
});
const eventUrl = `${context.linker.toPathInSite('/~gitbook/__evt')}?${eventParams}`;
const getVisitorClaimsUrl = context.linker.toAbsoluteURL(
context.linker.toPathInSite('/~gitbook/visitor')
);
const getVisitorClaimsUrl = context.linker.toPathInSite('/~gitbook/visitor');
return (
<SpaceLayoutContextProvider
@@ -92,7 +92,7 @@ export function SpaceLayoutServerContext(props: SpaceLayoutProps) {
appURL={GITBOOK_APP_URL}
visitorCookieTrackingEnabled={customization.insights?.trackingCookie}
>
<InsightsProvider enabled={withTracking} eventUrl={eventUrl.toString()}>
<InsightsProvider enabled={withTracking} eventUrl={eventUrl}>
<AIChatProvider
renderMessageOptions={aiChatRenderMessageOptions}
withPageFeedback={customization.feedback.enabled}
@@ -0,0 +1,81 @@
'use client';
import * as React from 'react';
// Subset of the WebMCP `ModelContext` interface (https://webmachinelearning.github.io/webmcp/).
type ModelContext = {
registerTool: (
tool: {
name: string;
description: string;
inputSchema?: object;
execute: (input: object, options?: { signal?: AbortSignal }) => Promise<unknown>;
},
options?: { signal?: AbortSignal }
) => Promise<void>;
};
/**
* Expose the site's MCP tools (`~gitbook/mcp`) to browser agents through WebMCP, so anything
* added to the server is automatically available to them. Renders nothing.
*/
export function WebMCP(props: { mcpURL: string }) {
const { mcpURL } = props;
React.useEffect(() => {
const modelContext = (document as { modelContext?: ModelContext }).modelContext;
if (!modelContext) {
return;
}
// Aborting unregisters the tools and discards a load still in flight.
const controller = new AbortController();
const { signal } = controller;
(async () => {
// The MCP SDK is imported lazily: only agentic browsers pay for it.
const [{ Client }, { StreamableHTTPClientTransport }] = await Promise.all([
import('@modelcontextprotocol/sdk/client/index.js'),
import('@modelcontextprotocol/sdk/client/streamableHttp.js'),
]);
// Tagged so WebMCP calls are distinguishable in insights (the request URL is tracked).
const url = new URL(mcpURL, window.location.href);
url.searchParams.set('client', 'webmcp');
const client = new Client({ name: 'gitbook-webmcp', version: '1.0.0' });
await client.connect(new StreamableHTTPClientTransport(url));
const { tools } = await client.listTools();
if (signal.aborted) {
return;
}
for (const tool of tools) {
// Answer synthesis takes 20-30s and browser agents abort tool calls around 30s.
if (tool.name === 'askQuestion') {
continue;
}
await modelContext.registerTool(
{
name: tool.name,
description: tool.description ?? tool.name,
inputSchema: tool.inputSchema,
// The MCP result (`content` blocks, plus `isError` on failure) is passed through.
execute: (input, options) =>
client.callTool(
{ name: tool.name, arguments: input as Record<string, unknown> },
undefined,
{ signal: options?.signal }
),
},
{ signal }
);
}
})().catch((error) => {
// oxlint-disable-next-line no-console
console.warn('WebMCP: could not expose the site MCP tools', error);
});
return () => controller.abort();
}, [mcpURL]);
return null;
}
@@ -0,0 +1,53 @@
/**
* Geometry rule behind {@link useListOverflow}, kept free of React so it can be tested directly
* against rects measured in a real browser.
*/
export interface MeasuredRect {
left: number;
right: number;
}
export interface MeasuredItem {
id: string;
rect: MeasuredRect;
}
/** Sub-pixel tolerance, so a row that fits exactly isn't reported as overflowing. */
const EPSILON = 1;
/**
* Decide which items don't fit the container.
*
* Items are expected to be measured with the overflow affordance (a "more" menu, say) already
* rendered *ahead* of them, which is what lets a single measurement answer both questions: the space
* before the first item is the width that affordance is reserving, so subtracting it gives the
* position each item would have without it. The list only has to make room for the affordance if it
* overflows without one — otherwise a row that fits on its own would give up its last item to a menu
* it never needed.
*
* Returns `null` when the measurement carries no information — an empty list, or a container with no
* width because an ancestor is hidden (a pane behind an inactive tab). Callers should keep their
* previous result and re-measure once it is visible.
*/
export function resolveOverflowingItems(
container: MeasuredRect & { width: number },
items: MeasuredItem[]
): Set<string> | null {
if (container.width <= 0 || items.length === 0) {
return null;
}
const reserved = Math.min(...items.map((item) => item.rect.left)) - container.left;
const fitsUnaided = items.every(
(item) => item.rect.right - reserved <= container.right + EPSILON
);
if (fitsUnaided) {
return new Set();
}
return new Set(
items.filter((item) => item.rect.right > container.right + EPSILON).map((item) => item.id)
);
}
@@ -1,6 +1,8 @@
'use client';
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { resolveOverflowingItems } from './listOverflow';
interface OverflowState {
/**
* Ref for the container element.
@@ -24,12 +26,23 @@ interface OverflowState {
* Detects which items are overflowing in a horizontal list.
* The items must have unique IDs set on their elements.
*
* In the measuring phase indicated by `isMeasuring`, all items must be rendered.
* In the measuring phase indicated by `isMeasuring`, all items must be rendered. Whatever the list
* 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.
*/
export function useListOverflow(): OverflowState {
const containerRef = useRef<HTMLDivElement>(null);
const [overflowing, setOverflowing] = useState<Set<string>>(new Set());
const [isMeasuring, setIsMeasuring] = useState(false);
// Measuring is a request/completed pair of counters rather than a boolean, because a boolean
// reset can be swallowed: the observer re-arms measuring from a rAF, and when that lands in the
// same batch as the measure effect's reset the net value is unchanged, so React bails out and the
// effect — keyed on that value — never runs again, leaving the list stuck measuring with its
// "more" menu permanently on show. Counters only increase, so a request can't cancel a
// completion; it just queues another pass.
const [measureRequest, setMeasureRequest] = useState(0);
const [measureCompleted, setMeasureCompleted] = useState(0);
const isMeasuring = measureRequest !== measureCompleted;
const itemRefs = useRef(new Map<string, HTMLElement>());
const rafRef = useRef(0);
@@ -43,19 +56,19 @@ export function useListOverflow(): OverflowState {
};
}, []);
const requestMeasure = useCallback(() => setMeasureRequest((request) => request + 1), []);
// Measure on mount and when container size changes
useEffect(() => {
if (!containerRef.current) {
return;
}
setIsMeasuring(true);
requestMeasure();
const ro = new ResizeObserver(() => {
cancelAnimationFrame(rafRef.current);
rafRef.current = requestAnimationFrame(() => {
setIsMeasuring(true);
});
rafRef.current = requestAnimationFrame(requestMeasure);
});
ro.observe(containerRef.current);
@@ -64,7 +77,7 @@ export function useListOverflow(): OverflowState {
ro.disconnect();
cancelAnimationFrame(rafRef.current);
};
}, []);
}, [requestMeasure]);
// Measure which items are overflowing
useLayoutEffect(() => {
@@ -72,29 +85,32 @@ export function useListOverflow(): OverflowState {
return;
}
const containerRect = containerRef.current.getBoundingClientRect();
const newOverflowing = new Set<string>();
const newOverflowing = resolveOverflowingItems(
containerRef.current.getBoundingClientRect(),
Array.from(itemRefs.current, ([id, element]) => ({
id,
rect: element.getBoundingClientRect(),
}))
);
itemRefs.current.forEach((el, id) => {
const elRect = el.getBoundingClientRect();
if (elRect.right > containerRect.right + 1) {
newOverflowing.add(id);
}
});
setOverflowing((previous) => {
if (previous.size !== newOverflowing.size) {
return newOverflowing;
}
for (const id of previous) {
if (!newOverflowing.has(id)) {
// `null` means the measurement said nothing (hidden ancestor, or no items) — keep what we
// had and wait for the observer to fire once it is visible.
if (newOverflowing) {
setOverflowing((previous) => {
if (previous.size !== newOverflowing.size) {
return newOverflowing;
}
}
return previous;
});
setIsMeasuring(false);
}, [isMeasuring]);
for (const id of previous) {
if (!newOverflowing.has(id)) {
return newOverflowing;
}
}
return previous;
});
}
setMeasureCompleted(measureRequest);
}, [isMeasuring, measureRequest]);
return { containerRef, itemRef, overflowing, isMeasuring };
}
@@ -3,15 +3,13 @@ import assertNever from 'assert-never';
/**
* Returns the URL to open the page in a LLM with a pre-filled prompt.
*/
export function getURLForLLM(provider: 'chatgpt' | 'claude' | 'cursor', prompt: string) {
export function getURLForLLM(provider: 'chatgpt' | 'claude', prompt: string) {
const encodedPrompt = encodeURIComponent(prompt);
switch (provider) {
case 'chatgpt':
return `https://chat.openai.com/?q=${encodedPrompt}`;
case 'claude':
return `https://claude.ai/new?q=${encodedPrompt}`;
case 'cursor':
return `https://cursor.com/link/prompt?text=${encodedPrompt}`;
default:
assertNever(provider);
}
@@ -148,6 +148,7 @@ export const ar: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'إرسال الملاحظات',
ai_chat_tools_submit_assistant_feedback: 'قيّم رسالة المساعد السابقة بأنها ${1}',
ai_chat_tools_submitted_feedback: 'تم إرسال ملاحظاتك',
ai_chat_tools_shared_feedback_with_team: 'تم إرسال الملاحظات إلى فريق التوثيق',
ai_chat_tools_mcp_tool: 'تم استدعاء ${1}',
ai_chat_ask: 'اسأل ${1}',
ai_chat_ask_about: 'اسأل ${1} عن ${2}',
@@ -152,6 +152,8 @@ export const bg: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Изпращане на обратна връзка',
ai_chat_tools_submit_assistant_feedback: 'Оценете предишното съобщение на асистента като ${1}',
ai_chat_tools_submitted_feedback: 'Обратната връзка е изпратена',
ai_chat_tools_shared_feedback_with_team:
'Обратната връзка е изпратена на екипа по документацията',
ai_chat_tools_mcp_tool: 'Извика ${1}',
ai_chat_ask: 'Попитайте ${1}',
ai_chat_ask_about: 'Попитайте ${1} за ${2}',
@@ -150,6 +150,7 @@ export const cs: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Odeslat zpětnou vazbu',
ai_chat_tools_submit_assistant_feedback: 'Ohodnotit předchozí zprávu asistenta jako ${1}',
ai_chat_tools_submitted_feedback: 'Zpětná vazba odeslána',
ai_chat_tools_shared_feedback_with_team: 'Zpětná vazba odeslána týmu dokumentace',
ai_chat_tools_mcp_tool: 'Zavolal ${1}',
ai_chat_ask: 'Zeptat se ${1}',
ai_chat_ask_about: 'Zeptat se ${1} na ${2}',
@@ -149,6 +149,7 @@ export const da: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Send feedback',
ai_chat_tools_submit_assistant_feedback: 'Bedøm assistentens forrige besked som ${1}',
ai_chat_tools_submitted_feedback: 'Feedback sendt',
ai_chat_tools_shared_feedback_with_team: 'Feedback sendt til dokumentationsteamet',
ai_chat_tools_mcp_tool: 'Kaldte ${1}',
ai_chat_ask: 'Spørg ${1}',
ai_chat_ask_about: 'Spørg ${1} om ${2}',
@@ -156,6 +156,7 @@ export const de: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Feedback senden',
ai_chat_tools_submit_assistant_feedback: 'Vorherige Assistenten-Nachricht als ${1} bewerten',
ai_chat_tools_submitted_feedback: 'Feedback gesendet',
ai_chat_tools_shared_feedback_with_team: 'Feedback an das Dokumentationsteam gesendet',
ai_chat_tools_mcp_tool: '${1} aufgerufen',
ai_chat_ask: '${1} fragen',
ai_chat_ask_about: '${1} zu ${2} befragen',
@@ -155,6 +155,7 @@ export const el: TranslationLanguage = {
ai_chat_tools_submit_assistant_feedback:
'Αξιολόγηση του προηγούμενου μηνύματος του Βοηθού ως ${1}',
ai_chat_tools_submitted_feedback: 'Τα σχόλια υποβλήθηκαν',
ai_chat_tools_shared_feedback_with_team: 'Τα σχόλια στάλθηκαν στην ομάδα τεκμηρίωσης',
ai_chat_tools_mcp_tool: 'Κλήθηκε ${1}',
ai_chat_ask: 'Ρωτήστε ${1}',
ai_chat_ask_about: 'Ρωτήστε ${1} για ${2}',
@@ -147,6 +147,7 @@ export const en = {
ai_chat_tools_submit_feedback: 'Submit feedback',
ai_chat_tools_submit_assistant_feedback: "Rate the Assistant's previous message as ${1}",
ai_chat_tools_submitted_feedback: 'Submitted your feedback',
ai_chat_tools_shared_feedback_with_team: 'Shared feedback with the docs team',
ai_chat_tools_mcp_tool: 'Called ${1}',
ai_chat_ask: 'Ask ${1}',
ai_chat_ask_about: 'Ask ${1} about ${2}',
@@ -154,6 +154,7 @@ export const es: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Enviar comentarios',
ai_chat_tools_submit_assistant_feedback: 'Valorar el mensaje anterior del asistente como ${1}',
ai_chat_tools_submitted_feedback: 'Comentarios enviados',
ai_chat_tools_shared_feedback_with_team: 'Comentarios enviados al equipo de documentación',
ai_chat_tools_mcp_tool: 'Llamó a ${1}',
ai_chat_ask: 'Preguntar a ${1}',
ai_chat_ask_about: 'Preguntar a ${1} sobre ${2}',
@@ -149,6 +149,7 @@ export const et: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Saada tagasiside',
ai_chat_tools_submit_assistant_feedback: 'Hinda assistendi eelmist sõnumit kui ${1}',
ai_chat_tools_submitted_feedback: 'Tagasiside saadetud',
ai_chat_tools_shared_feedback_with_team: 'Tagasiside saadetud dokumentatsioonimeeskonnale',
ai_chat_tools_mcp_tool: 'Kutsus ${1}',
ai_chat_ask: 'Küsi ${1}',
ai_chat_ask_about: 'Küsi ${1}: ${2}',
@@ -151,6 +151,7 @@ export const fi: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Lähetä palaute',
ai_chat_tools_submit_assistant_feedback: 'Arvioi avustajan edellinen viesti: ${1}',
ai_chat_tools_submitted_feedback: 'Palaute lähetetty',
ai_chat_tools_shared_feedback_with_team: 'Palaute lähetetty dokumentaatiotiimille',
ai_chat_tools_mcp_tool: 'Kutsuttiin ${1}',
ai_chat_ask: 'Kysy ${1}',
ai_chat_ask_about: 'Kysy ${1}: ${2}',
@@ -151,6 +151,7 @@ export const fr: TranslationLanguage = {
ai_chat_tools_submit_assistant_feedback:
"Évaluer le message précédent de l'assistant comme ${1}",
ai_chat_tools_submitted_feedback: 'Merci pour votre retour',
ai_chat_tools_shared_feedback_with_team: "Retour envoyé à l'équipe de documentation",
ai_chat_tools_mcp_tool: 'A appelé ${1}',
ai_chat_ask: 'Demander à ${1}',
ai_chat_ask_about: 'Demander à ${1} à propos de ${2}',
@@ -147,6 +147,7 @@ export const he: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'שליחת משוב',
ai_chat_tools_submit_assistant_feedback: 'דרג את ההודעה הקודמת של העוזר בתור ${1}',
ai_chat_tools_submitted_feedback: 'המשוב נשלח',
ai_chat_tools_shared_feedback_with_team: 'המשוב נשלח לצוות התיעוד',
ai_chat_tools_mcp_tool: 'קרא ל-${1}',
ai_chat_ask: 'שאל את ${1}',
ai_chat_ask_about: 'שאל את ${1} על ${2}',
@@ -148,6 +148,7 @@ export const hi: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'प्रतिक्रिया सबमिट करें',
ai_chat_tools_submit_assistant_feedback: 'सहायक के पिछले संदेश को ${1} के रूप में रेट करें',
ai_chat_tools_submitted_feedback: 'आपकी प्रतिक्रिया सबमिट कर दी गई',
ai_chat_tools_shared_feedback_with_team: 'दस्तावेज़ीकरण टीम को प्रतिक्रिया भेजी गई',
ai_chat_tools_mcp_tool: '${1} को कॉल किया',
ai_chat_ask: '${1} से पूछें',
ai_chat_ask_about: '${1} से ${2} के बारे में पूछें',
@@ -150,6 +150,7 @@ export const hr: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Pošalji povratne informacije',
ai_chat_tools_submit_assistant_feedback: 'Ocijenite prethodnu poruku asistenta kao ${1}',
ai_chat_tools_submitted_feedback: 'Povratne informacije poslane',
ai_chat_tools_shared_feedback_with_team: 'Povratne informacije poslane timu za dokumentaciju',
ai_chat_tools_mcp_tool: 'Pozvao ${1}',
ai_chat_ask: 'Pitaj ${1}',
ai_chat_ask_about: 'Pitaj ${1} o ${2}',
@@ -151,6 +151,7 @@ export const hu: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Visszajelzés küldése',
ai_chat_tools_submit_assistant_feedback: 'Az asszisztens előző üzenetének értékelése: ${1}',
ai_chat_tools_submitted_feedback: 'Visszajelzés elküldve',
ai_chat_tools_shared_feedback_with_team: 'Visszajelzés elküldve a dokumentációs csapatnak',
ai_chat_tools_mcp_tool: '${1} meghívva',
ai_chat_ask: '${1} kérdezése',
ai_chat_ask_about: '${1} megkérdezése ${2} témában',
@@ -149,6 +149,7 @@ export const id: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Kirim masukan',
ai_chat_tools_submit_assistant_feedback: 'Nilai pesan sebelumnya dari Asisten sebagai ${1}',
ai_chat_tools_submitted_feedback: 'Masukan terkirim',
ai_chat_tools_shared_feedback_with_team: 'Masukan dikirim ke tim dokumentasi',
ai_chat_tools_mcp_tool: 'Memanggil ${1}',
ai_chat_ask: 'Tanya ${1}',
ai_chat_ask_about: 'Tanya ${1} tentang ${2}',
@@ -154,6 +154,7 @@ export const it: TranslationLanguage = {
ai_chat_tools_submit_assistant_feedback:
"Valuta il messaggio precedente dell'assistente come ${1}",
ai_chat_tools_submitted_feedback: 'Feedback inviato',
ai_chat_tools_shared_feedback_with_team: 'Feedback inviato al team di documentazione',
ai_chat_tools_mcp_tool: 'Ha chiamato ${1}',
ai_chat_ask: 'Chiedi a ${1}',
ai_chat_ask_about: 'Chiedi a ${1} riguardo a ${2}',
@@ -150,6 +150,7 @@ export const ja: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'フィードバックを送信',
ai_chat_tools_submit_assistant_feedback: 'アシスタントの前のメッセージを${1}と評価する',
ai_chat_tools_submitted_feedback: 'フィードバックを送信しました',
ai_chat_tools_shared_feedback_with_team: 'ドキュメントチームにフィードバックを送信しました',
ai_chat_tools_mcp_tool: '${1} を呼び出しました',
ai_chat_ask: '${1} に質問する',
ai_chat_ask_about: '${1}に${2}について質問する',
@@ -149,6 +149,7 @@ export const ko: TranslationLanguage = {
ai_chat_tools_submit_feedback: '피드백 제출',
ai_chat_tools_submit_assistant_feedback: '어시스턴트의 이전 메시지를 ${1}(으)로 평가하기',
ai_chat_tools_submitted_feedback: '피드백을 제출했습니다',
ai_chat_tools_shared_feedback_with_team: '문서 팀에 피드백을 보냈습니다',
ai_chat_tools_mcp_tool: '${1} 호출함',
ai_chat_ask: '${1}에게 질문',
ai_chat_ask_about: '${1}에게 ${2}에 대해 질문',
@@ -150,6 +150,7 @@ export const lt: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Siųsti atsiliepimą',
ai_chat_tools_submit_assistant_feedback: 'Įvertinkite ankstesnę asistento žinutę kaip ${1}',
ai_chat_tools_submitted_feedback: 'Atsiliepimas išsiųstas',
ai_chat_tools_shared_feedback_with_team: 'Atsiliepimas išsiųstas dokumentacijos komandai',
ai_chat_tools_mcp_tool: 'Iškviesta ${1}',
ai_chat_ask: 'Klausti ${1}',
ai_chat_ask_about: 'Klausti ${1} apie ${2}',
@@ -148,6 +148,7 @@ export const lv: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Nosūtīt atsauksmi',
ai_chat_tools_submit_assistant_feedback: 'Novērtējiet asistenta iepriekšējo ziņojumu kā ${1}',
ai_chat_tools_submitted_feedback: 'Atsauksme nosūtīta',
ai_chat_tools_shared_feedback_with_team: 'Atsauksme nosūtīta dokumentācijas komandai',
ai_chat_tools_mcp_tool: 'Izsauca ${1}',
ai_chat_ask: 'Jautāt ${1}',
ai_chat_ask_about: 'Jautāt ${1} par ${2}',
@@ -150,6 +150,7 @@ export const ms: TranslationLanguage = {
ai_chat_tools_submit_assistant_feedback:
'Nilai mesej sebelumnya daripada Pembantu sebagai ${1}',
ai_chat_tools_submitted_feedback: 'Maklum balas dihantar',
ai_chat_tools_shared_feedback_with_team: 'Maklum balas dihantar kepada pasukan dokumentasi',
ai_chat_tools_mcp_tool: 'Memanggil ${1}',
ai_chat_ask: 'Tanya ${1}',
ai_chat_ask_about: 'Tanya ${1} tentang ${2}',
@@ -152,6 +152,7 @@ export const nl: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Feedback verzenden',
ai_chat_tools_submit_assistant_feedback: 'Vorig bericht van de assistent beoordelen als ${1}',
ai_chat_tools_submitted_feedback: 'Feedback verzonden',
ai_chat_tools_shared_feedback_with_team: 'Feedback naar het documentatieteam gestuurd',
ai_chat_tools_mcp_tool: '${1} aangeroepen',
ai_chat_ask: 'Vraag het aan ${1}',
ai_chat_ask_about: 'Stel ${1} een vraag over ${2}',
@@ -151,6 +151,7 @@ export const no: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Send tilbakemelding',
ai_chat_tools_submit_assistant_feedback: 'Vurder assistentens forrige melding som ${1}',
ai_chat_tools_submitted_feedback: 'Tilbakemelding sendt',
ai_chat_tools_shared_feedback_with_team: 'Tilbakemelding sendt til dokumentasjonsteamet',
ai_chat_tools_mcp_tool: 'Kalte ${1}',
ai_chat_ask: 'Spør ${1}',
ai_chat_ask_about: 'Spør ${1} om ${2}',
@@ -150,6 +150,7 @@ export const pl: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Wyślij opinię',
ai_chat_tools_submit_assistant_feedback: 'Oceń poprzednią wiadomość asystenta jako ${1}',
ai_chat_tools_submitted_feedback: 'Przesłano opinię',
ai_chat_tools_shared_feedback_with_team: 'Opinia przesłana zespołowi dokumentacji',
ai_chat_tools_mcp_tool: 'Wywołano ${1}',
ai_chat_ask: 'Zapytaj ${1}',
ai_chat_ask_about: 'Zapytaj ${1} o ${2}',
@@ -154,6 +154,7 @@ export const pt_br: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Enviar feedback',
ai_chat_tools_submit_assistant_feedback: 'Avalie a mensagem anterior do assistente como ${1}',
ai_chat_tools_submitted_feedback: 'Feedback enviado',
ai_chat_tools_shared_feedback_with_team: 'Feedback enviado à equipe de documentação',
ai_chat_tools_mcp_tool: 'Chamou ${1}',
ai_chat_ask: 'Perguntar a ${1}',
ai_chat_ask_about: 'Perguntar a ${1} sobre ${2}',
@@ -151,6 +151,7 @@ export const pt: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Enviar feedback',
ai_chat_tools_submit_assistant_feedback: 'Avaliar a mensagem anterior do assistente como ${1}',
ai_chat_tools_submitted_feedback: 'Feedback enviado',
ai_chat_tools_shared_feedback_with_team: 'Feedback enviado à equipa de documentação',
ai_chat_tools_mcp_tool: 'Chamou ${1}',
ai_chat_ask: 'Perguntar a ${1}',
ai_chat_ask_about: 'Perguntar a ${1} sobre ${2}',
@@ -153,6 +153,7 @@ export const ro: TranslationLanguage = {
ai_chat_tools_submit_feedback: 'Trimite feedback',
ai_chat_tools_submit_assistant_feedback: 'Evaluează mesajul anterior al Asistentului ca ${1}',
ai_chat_tools_submitted_feedback: 'Feedback trimis',
ai_chat_tools_shared_feedback_with_team: 'Feedback trimis echipei de documentație',
ai_chat_tools_mcp_tool: 'A apelat ${1}',
ai_chat_ask: 'Întreabă ${1}',
ai_chat_ask_about: 'Întreabă ${1} despre ${2}',

Some files were not shown because too many files have changed in this diff Show More