You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hugegraph.apache.org by ji...@apache.org on 2026/10/02 11:00:15 UTC
(hugegraph-doc) branch master updated: feat: improve Ask AI consent and community entry (#505)
This is an automated email from the ASF dual-hosted git repository.
imbajin pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hugegraph-doc.git
The following commit(s) were added to refs/heads/master by this push:
new 3e8d3e33a feat: improve Ask AI consent and community entry (#505)
3e8d3e33a is described below
commit 3e8d3e33a4e98dd9d2f713ba9ed8ac1fc15ccc7a
Author: imbajin <ji...@apache.org>
AuthorDate: Fri Oct 2 19:00:11 2026 +0800
feat: improve Ask AI consent and community entry (#505)
---
assets/js/kapa-adapter.js | 121 +++++++++++--
assets/scss/_styles_project.scss | 28 ++-
data/ai/questions.yaml | 81 +++++++++
i18n/en.yaml | 9 +-
i18n/zh-CN.yaml | 9 +-
layouts/_partials/footer.html | 3 +
layouts/_partials/hooks/body-end.html | 20 ++-
scripts/kapa-rollout.md | 17 +-
scripts/oink-upgrade.md | 2 +-
tests/e2e/ai.spec.js | 302 +++++++++++++++++++++++++++++++-
tests/e2e/platform.spec.js | 3 +-
tests/ui-ai/kapa-adapter.test.cjs | 314 +++++++++++++++++++++++++++++++++-
12 files changed, 855 insertions(+), 54 deletions(-)
diff --git a/assets/js/kapa-adapter.js b/assets/js/kapa-adapter.js
index 0cda8dd6f..9c903e644 100644
--- a/assets/js/kapa-adapter.js
+++ b/assets/js/kapa-adapter.js
@@ -64,6 +64,18 @@
return queue;
}
+ function pickExampleQuestions(questions, random) {
+ var choices = Array.from(new Set(questions || []));
+ random = random || Math.random;
+ for (var i = choices.length - 1; i > 0; i--) {
+ var j = Math.floor(random() * (i + 1));
+ var value = choices[i];
+ choices[i] = choices[j];
+ choices[j] = value;
+ }
+ return choices.slice(0, 3);
+ }
+
function scriptAttributes(config) {
return {
'data-website-id': config.websiteId,
@@ -104,14 +116,58 @@
'data-exit-feedback-enabled': 'false',
'data-user-satisfaction-feedback-enabled': 'false',
'data-bot-protection-mechanism': 'hcaptcha',
+ 'data-example-questions': (config.exampleQuestions || []).join(','),
+ 'data-example-questions-col-span': '12',
+ 'data-answer-cta-button-enabled': 'true',
+ 'data-answer-cta-button-text': config.labels.community,
+ 'data-answer-cta-button-link': config.communityURL,
+ 'data-answer-cta-button-background-color': 'transparent',
+ 'data-answer-cta-button-border': 'none',
+ 'data-answer-cta-button-font-weight': '400',
+ 'data-answer-cta-button-font-size': '.8rem',
};
}
function createController(windowObject, documentObject, config) {
var state = 'idle';
- var consented = false;
+ var widgetConfig = Object.assign({}, config, {
+ exampleQuestions: pickExampleQuestions(config.exampleQuestions),
+ });
+ var consentKey = 'hg-ai-consent:v2:' + config.websiteId;
+ var choice = null;
+ try {
+ choice = windowObject.localStorage.getItem(consentKey);
+ } catch (_) {
+ // Storage may be disabled; consent still works for this page only.
+ }
+ var consented = choice === 'granted';
+ var grantPersisted = consented;
+ var dismissed = choice === 'dismissed';
+ windowObject.addEventListener('storage', function (event) {
+ if (event.key !== consentKey && event.key !== null) return;
+ if ((consented && event.newValue !== 'granted') ||
+ (!consented && (event.newValue === 'granted' ||
+ (event.newValue === 'dismissed' && choice !== 'dismissed')))) {
+ // Synchronize other tabs' choices without loading the vendor on startup.
+ windowObject.location.reload();
+ }
+ });
var pending = null;
var consent = documentObject.querySelector('[data-hg-ai-consent]');
+ var launcher = documentObject.querySelector('.hg-ask-ai-launcher');
+ if (consent) consent.hidden = consented || dismissed;
+ function renderLauncher(hidden) {
+ if (!launcher) return;
+ launcher.hidden = hidden;
+ if (consented) launcher.setAttribute('aria-haspopup', 'dialog');
+ else launcher.removeAttribute('aria-haspopup');
+ }
+ renderLauncher(!consented && !dismissed);
+
+ function dismissConsent() {
+ if (consent) consent.hidden = true;
+ renderLauncher(false);
+ }
var attempt = 0;
var timer = 0;
var lastTrigger = null;
@@ -119,6 +175,23 @@
var activeQueue = null;
var operation = null;
var status = documentObject.querySelector('[data-hg-ai-status]');
+ var revoke = documentObject.querySelector('[data-hg-ai-revoke]');
+ if (revoke) {
+ revoke.hidden = !consented;
+ revoke.addEventListener('click', function () {
+ if (!consented) return;
+ if (grantPersisted) {
+ try {
+ windowObject.localStorage.removeItem(consentKey);
+ } catch (_) {
+ renderState(state, config.labels.revokeError);
+ return;
+ }
+ }
+ // Navigation terminates the vendor's loaded state and pending callbacks.
+ windowObject.location.reload();
+ });
+ }
function renderState(next, message) {
state = next;
@@ -158,6 +231,7 @@
discardAttempt(attempt);
renderState('error', config.labels.error);
settle(new Error(config.labels.error));
+ restoreFocus();
}
}
@@ -192,6 +266,7 @@
discardAttempt(serial);
renderState('error', config.labels.error);
settle(new Error(config.labels.error));
+ restoreFocus();
}
function ready(serial, query, submit) {
@@ -215,7 +290,7 @@
BUNDLE_URL + (retrying ? '?hg-retry=' + encodeURIComponent(serial) : '');
script.dataset.hgKapaWidget = '';
script.dataset.hgKapaAttempt = String(serial);
- var attrs = scriptAttributes(config);
+ var attrs = scriptAttributes(widgetConfig);
Object.keys(attrs).forEach(function (name) {
script.setAttribute(name, attrs[name]);
});
@@ -260,9 +335,18 @@
}
function cancelConsent() {
+ if (!consented) {
+ try {
+ windowObject.localStorage.setItem(consentKey, 'dismissed');
+ choice = 'dismissed';
+ } catch (_) {
+ // Without storage the dismissal applies only to this page.
+ }
+ }
pending = null;
renderState('idle', '');
- if (consent && consent.open) consent.close();
+ dismissConsent();
+ if (!lastTrigger) lastTrigger = launcher;
restoreFocus();
settle();
}
@@ -280,13 +364,13 @@
if (state === 'loading') discardAttempt(attempt);
attempt += 1;
pending = null;
- if (consent && consent.open) consent.close();
+ dismissConsent();
renderState('idle', '');
settle();
};
context.signal.addEventListener('abort', operation.abort, { once: true });
});
- // Transfer focus before opening a dialog; OINK keeps cancellation alive
+ // Transfer focus to the inline notice; OINK keeps cancellation alive
// until this promise settles, including when search is opened again.
if (!context.handoff()) {
settle();
@@ -298,19 +382,21 @@
return completion;
}
// Fail closed if the local consent panel is unavailable.
- if (!consent || typeof consent.showModal !== 'function') {
+ if (!consent) {
renderState('error', config.labels.error);
settle(new Error(config.labels.error));
return completion;
}
pending = { query: trimmedQuery(query), submit: submit };
renderState('consent', '');
- consent.showModal();
+ renderLauncher(true);
+ consent.hidden = false;
+ consent.querySelector('[data-hg-ai-continue]').focus();
return completion;
}
if (consent) {
- // Keep the underlying search palette from consuming modal keyboard events.
+ // Keep pending search handoff keyboard events within the consent notice.
consent.addEventListener('keydown', function (event) {
event.stopPropagation();
if (event.key === 'Escape') {
@@ -319,18 +405,22 @@
}
});
consent.querySelector('[data-hg-ai-continue]').addEventListener('click', function () {
- if (!pending) return;
- var request = pending;
+ if (consented || state === 'loading') return;
+ var request = pending || { query: '', submit: false };
+ if (!pending) lastTrigger = launcher;
pending = null;
consented = true;
- consent.close();
+ try {
+ windowObject.localStorage.setItem(consentKey, 'granted');
+ grantPersisted = true;
+ } catch (_) {
+ // Never bypass initial consent when persistence is unavailable.
+ }
+ if (revoke) revoke.hidden = false;
+ dismissConsent();
load(request.query, request.submit);
});
consent.querySelector('[data-hg-ai-cancel]').addEventListener('click', cancelConsent);
- consent.addEventListener('cancel', function (event) {
- event.preventDefault();
- cancelConsent();
- });
}
function restoreFocus() {
@@ -407,6 +497,7 @@
preinitialize: preinitialize,
readConfig: readConfig,
scriptAttributes: scriptAttributes,
+ pickExampleQuestions: pickExampleQuestions,
trimmedQuery: trimmedQuery,
};
global.HugeGraphKapa = api;
diff --git a/assets/scss/_styles_project.scss b/assets/scss/_styles_project.scss
index 29fbad69f..f22f015a6 100644
--- a/assets/scss/_styles_project.scss
+++ b/assets/scss/_styles_project.scss
@@ -533,6 +533,7 @@
}
.hg-ask-ai-launcher {
+ &[hidden] { display: none; }
position: fixed;
z-index: 1040;
inset-inline-end: unquote('max(1rem, env(safe-area-inset-right))');
@@ -864,23 +865,34 @@
}
-// Local disclosure renders before any third-party AI resource is requested.
+// The first-use notice stays beside the AI entry without blocking the page.
+.hg-ai-revoke {
+ font-size: inherit;
+ &[hidden] { display: none; }
+}
+
.hg-ai-consent {
+ position: fixed;
+ z-index: 1040;
+ inset-inline-end: unquote('max(1rem, env(safe-area-inset-right))');
+ inset-block-end: unquote('calc(max(1rem, env(safe-area-inset-bottom)) + 4rem)');
width: calc(100% - 2rem);
- max-width: 28rem;
- padding: 1.5rem;
+ max-width: 22rem;
+ padding: 1rem;
border: 1px solid var(--bs-border-color);
border-radius: .75rem;
background: var(--bs-body-bg);
color: var(--bs-body-color);
- box-shadow: 0 .75rem 3rem rgba(0, 0, 0, .2);
- &::backdrop { background: rgba(0, 0, 0, .4); }
- h2 { font-size: 1.25rem; }
+ box-shadow: 0 .25rem 1rem rgba(0, 0, 0, .12);
+ font-size: .85rem;
+
+ &[hidden] { display: none; }
+ p { margin-bottom: .6rem; }
.hg-ai-consent-actions {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
- gap: .75rem;
- margin-top: 1.25rem;
+ gap: .5rem;
+ .btn { font-size: inherit; }
}
}
diff --git a/data/ai/questions.yaml b/data/ai/questions.yaml
new file mode 100644
index 000000000..9f56a7c56
--- /dev/null
+++ b/data/ai/questions.yaml
@@ -0,0 +1,81 @@
+# Each entry has paired translations. Uniform sampling makes topic proportions follow pool sizes.
+
+# server: 16 questions
+- en: "What is HugeGraph useful for and how does it differ from a relational database?"
+ cn: "HugeGraph 适合哪些场景?与关系型数据库有什么区别?"
+- en: "How do I start HugeGraph Server?"
+ cn: "如何启动 HugeGraph Server?"
+- en: "What is the quickest way to start HugeGraph Server and its visualization UI?"
+ cn: "如何最快捷地启动 HugeGraph 服务和可视化界面?"
+- en: "How do I deploy HugeGraph Server with Docker?"
+ cn: "如何使用 Docker 部署 HugeGraph Server?"
+- en: "What environment and Java version do I need to install HugeGraph Server?"
+ cn: "安装 HugeGraph Server 需要什么环境和 Java 版本?"
+- en: "How do I choose between standalone and distributed HugeGraph deployment?"
+ cn: "HugeGraph 的单机模式和分布式模式应该如何选择?"
+- en: "How do I create a schema with vertex and edge labels in HugeGraph?"
+ cn: "如何在 HugeGraph 中创建图模型、顶点类型和边类型?"
+- en: "How do I add vertices and edges in HugeGraph?"
+ cn: "如何在 HugeGraph 中添加顶点和边?"
+- en: "How do I query neighboring vertices with Gremlin in HugeGraph?"
+ cn: "如何在 HugeGraph 中用 Gremlin 查询顶点的邻居?"
+- en: "How do I query multi-hop relationships and shortest paths in HugeGraph?"
+ cn: "如何在 HugeGraph 中查询多跳关系和最短路径?"
+- en: "How do I create indexes to speed up HugeGraph queries?"
+ cn: "如何在 HugeGraph 中创建索引来加快查询?"
+- en: "How do I access HugeGraph through its REST API?"
+ cn: "如何通过 REST API 操作 HugeGraph?"
+- en: "How do I enable user authentication and access control in HugeGraph?"
+ cn: "如何在 HugeGraph 中开启用户认证和权限控制?"
+- en: "How do I troubleshoot HugeGraph Server startup failures or connection problems?"
+ cn: "HugeGraph 服务启动失败或无法连接时如何排查?"
+- en: "How do I back up and restore HugeGraph data?"
+ cn: "如何备份和恢复 HugeGraph 数据?"
+- en: "How do I troubleshoot and optimize slow HugeGraph queries?"
+ cn: "HugeGraph 图查询很慢时应该如何排查和优化?"
+
+# ai: 10 questions
+- en: "How do I get HugeGraph-AI running quickly?"
+ cn: "如何快速启动 HugeGraph-AI?"
+- en: "How does GraphRAG in HugeGraph-AI differ from vector-based RAG?"
+ cn: "HugeGraph-AI 的 GraphRAG 与普通向量 RAG 有什么区别?"
+- en: "How do I build a knowledge graph from text or documents in HugeGraph-AI?"
+ cn: "如何在 HugeGraph-AI 中将文本或文档构建成知识图谱?"
+- en: "How do I extract entities and relationships from text in HugeGraph-AI?"
+ cn: "如何在 HugeGraph-AI 中从文本中提取实体和关系?"
+- en: "How do I configure LLM and embedding models for HugeGraph-AI?"
+ cn: "如何为 HugeGraph-AI 配置大模型和 Embedding 模型?"
+- en: "How do I connect local models through Ollama in HugeGraph-AI?"
+ cn: "如何在 HugeGraph-AI 中使用 Ollama 接入本地模型?"
+- en: "How do I answer questions using a knowledge graph in HugeGraph-AI?"
+ cn: "如何在 HugeGraph-AI 中基于知识图谱进行问答?"
+- en: "How do I generate Gremlin queries from natural language in HugeGraph-AI?"
+ cn: "如何在 HugeGraph-AI 中用自然语言生成 Gremlin 查询?"
+- en: "How do I access HugeGraph from Python?"
+ cn: "如何通过 Python 操作 HugeGraph?"
+- en: "How do I use HugeGraph-ML for node classification?"
+ cn: "如何使用 HugeGraph-ML 做节点分类?"
+
+# toolchain: 7 questions
+- en: "How do I import data into HugeGraph?"
+ cn: "如何将数据导入 HugeGraph?"
+- en: "How do I import CSV or JSON files into HugeGraph?"
+ cn: "如何将 CSV 或 JSON 文件导入 HugeGraph?"
+- en: "How do I import SQL database data into HugeGraph?"
+ cn: "如何将 SQL 数据库中的数据导入 HugeGraph?"
+- en: "How do I migrate Neo4j graph data to HugeGraph?"
+ cn: "如何将 Neo4j 的图数据迁移到 HugeGraph?"
+- en: "How do I connect Hubble to HugeGraph Server?"
+ cn: "如何让 Hubble 连接到 HugeGraph Server?"
+- en: "How do I view and query graph data in Hubble?"
+ cn: "如何在 Hubble 中查看和查询图数据?"
+- en: "How do I troubleshoot a failed data import into HugeGraph?"
+ cn: "向 HugeGraph 导入数据失败时应该如何排查?"
+
+# computing: 3 questions
+- en: "How do I choose between Vermeer and Computer for graph computing?"
+ cn: "图计算应该选择 Vermeer 还是 Computer?"
+- en: "How do I get started with graph computing in Vermeer?"
+ cn: "如何快速启动 Vermeer 进行图计算?"
+- en: "How do I run graph algorithms such as PageRank with HugeGraph Computing?"
+ cn: "如何使用 HugeGraph Computing 运行 PageRank 等图算法?"
diff --git a/i18n/en.yaml b/i18n/en.yaml
index ad2a00080..15ce3691b 100644
--- a/i18n/en.yaml
+++ b/i18n/en.yaml
@@ -20,7 +20,10 @@ download_component_computer: Computer
download_component_commons: Common
download_asf_note: Source archives are the official Apache Software Foundation releases; binary packages are convenience builds made from them. All files are served from ASF mirrors, with signatures and checksums hosted on downloads.apache.org. Source archives generated automatically by GitHub are not ASF releases.
-ui_ai_consent_description: "Continuing loads Kapa, a third-party service. Your question will be sent to Kapa to generate an answer."
-ui_ai_consent_continue: "Continue to Ask AI"
-ui_ai_consent_cancel: "Cancel"
+ui_ai_consent_description: "Agree to send your questions to the third-party Kapa service for AI answers based on the documentation."
+ui_ai_consent_continue: "Agree and open Ask AI"
+ui_ai_consent_cancel: "Not now"
ui_ai_privacy: "Privacy policy"
+ui_ai_revoke: "Withdraw AI consent"
+ui_ai_revoke_error: "AI consent could not be removed and remains active. Clear this site's browser data to withdraw consent."
+ui_ai_community: "Ask the community on GitHub"
diff --git a/i18n/zh-CN.yaml b/i18n/zh-CN.yaml
index a75023877..a194fb3f6 100644
--- a/i18n/zh-CN.yaml
+++ b/i18n/zh-CN.yaml
@@ -21,7 +21,10 @@ download_component_computer: Computer
download_component_commons: Common
download_asf_note: 源码归档是 Apache 软件基金会的正式发布物;二进制软件包是基于源码构建的便利用品。所有文件均通过 ASF 镜像分发,签名与校验和托管在 downloads.apache.org。GitHub 自动生成的源码归档不是 ASF 正式发布版本。
-ui_ai_consent_description: "继续后将加载第三方服务 Kapa,并将你的问题发送给 Kapa 生成回答。"
-ui_ai_consent_continue: "继续使用 Ask AI"
-ui_ai_consent_cancel: "取消"
+ui_ai_consent_description: "同意后将把你的问题发送给第三方 Kapa 服务,使用 AI 结合文档回答。"
+ui_ai_consent_continue: "同意并打开 Ask AI"
+ui_ai_consent_cancel: "暂不使用"
ui_ai_privacy: "隐私政策"
+ui_ai_revoke: "撤回 AI 授权"
+ui_ai_revoke_error: "未能撤回 AI 授权,授权仍有效。请清除此网站的浏览器数据以撤回授权。"
+ui_ai_community: "前往 GitHub 向社区提问"
diff --git a/layouts/_partials/footer.html b/layouts/_partials/footer.html
index 94fe3c0e3..83eff243f 100644
--- a/layouts/_partials/footer.html
+++ b/layouts/_partials/footer.html
@@ -34,6 +34,9 @@
<div class="hg-asf-footer__legal">
<p>Copyright © {{ now.Year }} The Apache Software Foundation, Licensed under the <a href="https://www.apache.org/licenses/LICENSE-2.0" target="_blank" rel="noopener noreferrer">Apache License Version 2.0</a></p>
<p>Apache, the names of Apache projects, and the feather logo are either registered trademarks or trademarks of the Apache Software Foundation in the United States and/or other countries.</p>
+ {{- if (partial "ai/config.html" .).enabled }}
+ <button type="button" class="btn btn-link hg-ai-revoke p-0" data-hg-ai-revoke hidden>{{ T "ui_ai_revoke" }}</button>
+ {{- end }}
</div>
</div>
</div>
diff --git a/layouts/_partials/hooks/body-end.html b/layouts/_partials/hooks/body-end.html
index 06d57502b..d30e99e60 100644
--- a/layouts/_partials/hooks/body-end.html
+++ b/layouts/_partials/hooks/body-end.html
@@ -25,7 +25,13 @@
"description" (T "ui_ask_ai_description")
"latest" (T "ui_ask_ai_latest")
"error" (T "ui_ai_error")
+ "revokeError" (T "ui_ai_revoke_error")
+ "community" (T "ui_ai_community")
-}}
+ {{- $questions := slice -}}
+ {{- range hugo.Data.ai.questions -}}
+ {{- $questions = $questions | append (index . $lang) -}}
+ {{- end -}}
{{- $clientConfig := dict
"websiteId" $ai.websiteID
"sourceGroupId" $sourceGroup
@@ -33,23 +39,25 @@
"themeColor" $themeColor
"historical" $historical
"labels" $labels
+ "exampleQuestions" $questions
+ "communityURL" "https://github.com/apache/hugegraph/discussions"
-}}
<script type="application/json" id="hg-ai-config">{{ $clientConfig | jsonify | safeJS }}</script>
<button type="button" class="hg-ask-ai-launcher d-print-none" data-hg-ask-ai
- data-hg-ai-submit="false" aria-haspopup="dialog"{{ if $historical }} aria-label="{{ index $labels "ask" }} — {{ index $labels "latest" }}"{{ end }}>
+ data-hg-ai-submit="false" hidden aria-haspopup="dialog"{{ if $historical }} aria-label="{{ index $labels "ask" }} — {{ index $labels "latest" }}"{{ end }}>
<i class="fa-solid fa-wand-magic-sparkles" aria-hidden="true"></i>
<span>{{ index $labels "ask" }}</span>
</button>
-<dialog class="hg-ai-consent" data-hg-ai-consent aria-labelledby="hg-ai-consent-title" aria-describedby="hg-ai-disclosure">
- <h2 id="hg-ai-consent-title">{{ index $labels "ask" }}</h2>
+<section class="hg-ai-consent d-print-none" data-hg-ai-consent hidden aria-labelledby="hg-ai-consent-title" aria-describedby="hg-ai-disclosure">
+ <h2 class="visually-hidden" id="hg-ai-consent-title">{{ index $labels "ask" }}</h2>
<p id="hg-ai-disclosure">{{ T "ui_ai_consent_description" }}</p>
{{ if $historical }}<p>{{ index $labels "latest" }}.</p>{{ end }}
<p><a href="https://www.kapa.ai/content/privacy-policy" target="_blank" rel="noopener noreferrer">{{ T "ui_ai_privacy" }}</a></p>
<div class="hg-ai-consent-actions">
- <button type="button" class="btn btn-secondary" data-hg-ai-cancel autofocus>{{ T "ui_ai_consent_cancel" }}</button>
- <button type="button" class="btn btn-primary" data-hg-ai-continue>{{ T "ui_ai_consent_continue" }}</button>
+ <button type="button" class="btn btn-secondary" data-hg-ai-cancel>{{ T "ui_ai_consent_cancel" }}</button>
+ <button type="button" class="btn btn-primary" data-hg-ai-continue aria-haspopup="dialog" aria-describedby="hg-ai-disclosure">{{ T "ui_ai_consent_continue" }}</button>
</div>
-</dialog>
+</section>
<div class="hg-ai-status visually-hidden" role="status" aria-live="polite" data-hg-ai-status></div>
{{- $adapter := resources.Get "js/kapa-adapter.js" -}}
{{- if hugo.IsProduction }}{{ $adapter = $adapter | minify | fingerprint }}{{ end }}
diff --git a/scripts/kapa-rollout.md b/scripts/kapa-rollout.md
index 13090fc4d..45ee34d7a 100644
--- a/scripts/kapa-rollout.md
+++ b/scripts/kapa-rollout.md
@@ -36,10 +36,21 @@ HTML 抓取分别从 `/docs/` 与 `/cn/docs/` 开始,用锚定到站点和语
记录实际抓取站点和候选 SHA;引用会指向抓取站点,staging 来源不能直接当作生产引用配置。
[ASF FAQ](https://privacy.apache.org/faq/committers.html#can-i-use-kapaai-on-our-website-answer-machine)
-确认 Kapa 已签署 DPA,并要求在加载前征得用户同意。本站先展示本地授权弹窗,
+确认 Kapa 已签署 DPA,并要求在加载前征得用户同意。本站在首次入口展示本地非模态授权说明,
用户同意后才加载第三方脚本;`data-consent-required=false` 用于避免 widget 再次弹窗,
不表示跳过本站授权。保留禁用分析 cookie、指纹及反馈的现有配置。
+首次入口显示本地非模态说明;用户点击“同意并打开 Ask AI”后,授权保存在当前浏览器中,
+并由同源中英文及历史页面复用。清除网站数据或授权版本变化后会重新询问。
+即使已同意,页面加载也不会请求 Kapa;再次点击 Ask AI 时才加载服务。
+“暂不使用”也会在浏览器中记住,后续页面只显示入口;主动点击入口才再次显示授权说明。
+授权后可通过页脚的“撤回 AI 授权”清除授权并重新加载页面,卸载已加载的第三方资源。
+授权说明与撤回入口在 HTML 中默认隐藏,由本地适配器初始化后显示,避免闪现及失效按钮。
+存储不可用时仅对当前页面有效。不迁移此前仅限会话的授权,以免延长用户原先同意的范围。
+Widget 从 `data/ai/questions.yaml` 的 36 组中英文常见问题中随机抽取 3 条,当前页面内保持不变,回答后显示低调的 GitHub Discussions 求助链接;
+问题池按 Server 16、AI 10、Toolchain 7、Computing 3 分配,每条等概率抽取,因此展示比重由各类题数决定。
+点击社区链接不会自动提交问题或转交会话。
+
[ASF CSP 文档](https://infra.apache.org/tools/csp.html) 要求新增域名有 VP Data Privacy
批准依据。核对 Kapa 及其 hCaptcha 依赖的具体域名和许可范围,再修改产物根目录的
`.htaccess`,并在注释中注明依据。不要手改后会被构建覆盖的产物,也不要添加未经核对的通配域名。
@@ -49,7 +60,7 @@ Kapa 服务获准使用不等于任意附带服务或域名都获准。
## 当前启用变更
#496 已按维护者要求纳入 `enabled=true` 和既有 staging 验证过的 Kapa/hCaptcha CSP。
-这使合入后的正式站具备技术加载条件;修改 PR 不会立即发布正式站。本站授权弹窗仍保留,
+这使合入后的正式站具备技术加载条件;修改 PR 不会立即发布正式站。本站首次授权说明仍保留,
第三方资源只在用户同意后加载。CSP 注释记录既有部署依据,不宣称已找到独立批准记录。
用于正式站的 HTML 来源应直接抓取 `https://hugegraph.apache.org/docs/` 与
`https://hugegraph.apache.org/cn/docs/`,使回答引用保持在正式域名。切换来源前核对
@@ -89,7 +100,7 @@ Kapa 服务获准使用不等于任意附带服务或域名都获准。
| 场景 | 必须观察到的结果 |
| --- | --- |
| AI 关闭 | 页面、搜索及导航不发送任何第三方 AI 请求 |
-| AI 开启但尚未同意 | 页面加载、输入搜索、打开授权弹窗及取消均无 Kapa/hCaptcha 请求;不能仅检查 cookie |
+| AI 开启但尚未同意 | 页面加载、输入搜索、显示首次授权说明及暂不使用均无 Kapa/hCaptcha 请求;不能仅检查 cookie |
| 同意并提问 | bundle 只在同意后加载,真实请求与回答成功;响应头和控制台没有阻止该流程的 CSP 错误 |
| 中英文 | 英文使用 `.en` group、中文使用 `.cn` group;回答引用来自对应语言的最新文档,不混入历史语料 |
| 继承与引用 | EN/CN 不再继承旧 Global/父组来源;用各语言真实问题检查返回引用,确认 Legacy 内容未泄漏到回答 |
diff --git a/scripts/oink-upgrade.md b/scripts/oink-upgrade.md
index d69ebab11..ee16a4166 100644
--- a/scripts/oink-upgrade.md
+++ b/scripts/oink-upgrade.md
@@ -84,7 +84,7 @@ git diff -- go.mod go.sum layouts assets scripts .github/workflows/hugo.yml
| Version/language navigation and historical shell | `layouts/`, `scripts/versioning.py` | All-version aggregate, versioning and platform browser tests |
| Browser language default and manual preference | `assets/js/language-preference.js`, `hooks/head-end.html` | Homepage, explicit links, storage, palette and keyboard browser tests |
| Sidebar expansion memory | `assets/js/hugegraph-shell.js` | Public OinkSidebar API, storage/focus/keyboard browser tests |
-| Authorized Ask AI | `assets/js/kapa-adapter.js` | Public search-tail API, adapter tests and AI browser contracts |
+| Authorized Ask AI, remembered consent/dismissal, withdrawal and community entry | `assets/js/kapa-adapter.js`, `layouts/_partials/hooks/body-end.html`, `layouts/_partials/footer.html` | Public search-tail API, adapter tests and AI browser contracts |
| Brand and layout | `assets/scss/`, `data/`, `i18n/` | Bilingual desktop/mobile, dark/light and print captures |
`scripts/oink-overrides.json` records upstream hashes, not copies of upstream
diff --git a/tests/e2e/ai.spec.js b/tests/e2e/ai.spec.js
index 754f53e08..82555b08d 100644
--- a/tests/e2e/ai.spec.js
+++ b/tests/e2e/ai.spec.js
@@ -32,7 +32,8 @@ for (const [locale, route, source, language] of [
document.documentElement.setAttribute("data-bs-theme", "dark")
);
const launcher = page.locator(".hg-ask-ai-launcher");
- await expect(launcher).toBeVisible();
+ await expect(launcher).toBeHidden();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
await page.locator("[data-td-shell-search-open]").first().click();
const input = page.locator(".td-shell-search__input");
@@ -55,6 +56,20 @@ for (const [locale, route, source, language] of [
]);
const script = page.locator("script[data-hg-kapa-widget]");
await expect(script).toHaveAttribute("data-language", language);
+ const config = await page.locator("#hg-ai-config").evaluate(node => JSON.parse(node.textContent));
+ expect(config.exampleQuestions).toHaveLength(36);
+ const displayed = (await script.getAttribute("data-example-questions")).split(",");
+ expect(displayed).toHaveLength(3);
+ expect(new Set(displayed).size).toBe(3);
+ expect(displayed.every(question => config.exampleQuestions.includes(question))).toBe(true);
+ await expect(script).not.toHaveAttribute("data-chat-disclaimer");
+ await expect(script).toHaveAttribute("data-answer-cta-button-enabled", "true");
+ await expect(script).toHaveAttribute("data-answer-cta-button-text", config.labels.community);
+ await expect(script).toHaveAttribute("data-answer-cta-button-link", "https://github.com/apache/hugegraph/discussions");
+ expect(await script.evaluate(node => Array.from(node.attributes).some(attr =>
+ /handoff|email/.test(attr.name)))).toBe(false);
+ await expect(script).toHaveAttribute("data-user-analytics-cookie-enabled", "false");
+ await expect(script).toHaveAttribute("data-user-analytics-fingerprint-enabled", "false");
await expect(script).toHaveAttribute("data-source-group-ids-include", source);
await expect(script).toHaveAttribute("data-project-color", "#532fc9");
await expect(script).toHaveAttribute("data-project-color-dark", "#a693e3");
@@ -77,7 +92,6 @@ test("AI consent cancel and Escape keep native search local", async ({ page }) =
});
await page.goto(AI_ORIGIN + "/docs/");
const launcher = page.locator(".hg-ask-ai-launcher");
- await launcher.click();
const consent = page.locator("[data-hg-ai-consent]");
await expect(consent).toBeVisible();
await consent.locator("[data-hg-ai-cancel]").click();
@@ -103,13 +117,13 @@ test("AI 500 remains non-blocking and retry issues one fresh request", async ({
});
await page.goto(AI_ORIGIN + "/docs/");
const launcher = page.locator(".hg-ask-ai-launcher");
- await launcher.dblclick();
await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
expect(attempts).toBe(0);
await page.locator("[data-hg-ai-consent] [data-hg-ai-continue]").click();
await expect.poll(() => attempts).toBe(1);
await expect(launcher).toHaveAttribute("data-hg-ai-state", "error");
await expect(launcher).toHaveAttribute("title", /unavailable/i);
+ await expect(launcher).toBeFocused();
await launcher.click();
await expect.poll(() => attempts).toBe(2);
await expect(launcher).toHaveAttribute("data-hg-ai-state", "ready");
@@ -135,7 +149,6 @@ test("AI pending timeout discards stale state and retry waits for a fresh bundle
});
await page.goto(AI_ORIGIN + "/docs/");
const launcher = page.locator(".hg-ask-ai-launcher");
- await launcher.click();
await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
expect(attempts).toBe(0);
await page.locator("[data-hg-ai-consent] [data-hg-ai-continue]").click();
@@ -172,6 +185,7 @@ test("native AI row supports keyboard selection, IME, and consent focus handoff"
await route.fulfill({ status: 200, contentType: "text/javascript", body: mockBundle });
});
await page.goto(AI_ORIGIN + "/docs/");
+ await page.locator("[data-hg-ai-cancel]").click();
await page.locator("[data-td-shell-search-open]").first().click();
const input = page.locator(".td-shell-search__input");
await input.fill("server");
@@ -224,3 +238,283 @@ test("reopening native search cancels a pending AI handoff", async ({ page }) =>
expect(await page.evaluate(() => (window.__kapaCalls || []).filter(([method]) => method === "open"))).toEqual([]);
await expect(input).toBeFocused();
});
+
+
+test("persistent consent survives language navigation, reload and a fresh tab without loading AI", async ({ page }) => {
+ const requests = [];
+ await page.route("https://widget.kapa.ai/kapa-widget.bundle.js*", async route => {
+ requests.push(route.request().url());
+ await route.fulfill({ status: 200, contentType: "text/javascript", body: mockBundle });
+ });
+ await page.goto(AI_ORIGIN + "/docs/");
+ await expect(page.locator("[data-hg-ai-revoke]")).toBeHidden();
+ await expect(page.locator(".hg-ask-ai-launcher")).toBeHidden();
+ await page.locator("[data-hg-ai-continue]").click();
+ await expect.poll(() => requests.length).toBe(1);
+
+ await page.goto(AI_ORIGIN + "/cn/docs/");
+ expect(requests).toHaveLength(1);
+ await expect(page.locator("script[data-hg-kapa-widget]")).toHaveCount(0);
+ await page.locator(".hg-ask-ai-launcher").click();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeHidden();
+ await expect.poll(() => requests.length).toBe(2);
+ await expect(page.locator("script[data-hg-kapa-widget]")).toHaveAttribute("data-language", "zh");
+
+ await page.reload();
+ await expect(page.locator("script[data-hg-kapa-widget]")).toHaveCount(0);
+ expect(requests).toHaveLength(2);
+ await page.locator(".hg-ask-ai-launcher").click();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeHidden();
+ await expect.poll(() => requests.length).toBe(3);
+ const fresh = await page.context().newPage();
+ await fresh.route("https://widget.kapa.ai/kapa-widget.bundle.js*", async route => {
+ requests.push(route.request().url());
+ await route.fulfill({ status: 200, contentType: "text/javascript", body: mockBundle });
+ });
+ await fresh.goto(AI_ORIGIN + "/docs/");
+ await expect(fresh.locator("[data-hg-ai-consent]")).toBeHidden();
+ await expect(fresh.locator(".hg-ask-ai-launcher")).toBeVisible();
+ await expect(fresh.locator("script[data-hg-kapa-widget]")).toHaveCount(0);
+ expect(requests).toHaveLength(3);
+ await fresh.close();
+});
+
+test("blocked local storage requires fresh consent after navigation", async ({ page }) => {
+ const requests = [];
+ await page.addInitScript(() => {
+ Object.defineProperty(window, "localStorage", {
+ get() { throw new DOMException("Storage disabled", "SecurityError"); },
+ });
+ });
+ await page.route("https://widget.kapa.ai/kapa-widget.bundle.js*", async route => {
+ requests.push(route.request().url());
+ await route.fulfill({ status: 200, contentType: "text/javascript", body: mockBundle });
+ });
+ await page.goto(AI_ORIGIN + "/docs/");
+ await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
+ await page.locator("[data-hg-ai-cancel]").click();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeHidden();
+ await page.reload();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
+ expect(requests).toHaveLength(0);
+ await page.locator("[data-hg-ai-continue]").click();
+ await expect.poll(() => requests.length).toBe(1);
+ await page.goto(AI_ORIGIN + "/cn/docs/");
+ await expect(page.locator("script[data-hg-kapa-widget]")).toHaveCount(0);
+ await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
+ expect(requests).toHaveLength(1);
+});
+
+
+test("inline disclosure is nonmodal and first agreement opens AI with one click", async ({ page }) => {
+ const requests = [];
+ await page.route("https://widget.kapa.ai/kapa-widget.bundle.js*", async route => {
+ requests.push(route.request().url());
+ await route.fulfill({ status: 200, contentType: "text/javascript", body: mockBundle });
+ });
+ await page.goto(AI_ORIGIN + "/docs/");
+ const notice = page.locator("[data-hg-ai-consent]");
+ await expect(notice).toBeVisible();
+ expect(await notice.evaluate(node => node.tagName)).toBe("SECTION");
+ await expect(notice).not.toHaveAttribute("aria-modal", "true");
+ await expect(page.locator("dialog[data-hg-ai-consent]")).toHaveCount(0);
+ await expect(page.locator(".hg-ask-ai-launcher")).toBeHidden();
+ // Reading and native search remain interactive before making any AI choice.
+ await page.locator("[data-td-shell-search-open]").first().click();
+ await expect(page.locator(".td-shell-search__input")).toBeFocused();
+ await page.locator(".td-shell-search__input").press("Escape");
+ expect(requests).toHaveLength(0);
+ await notice.locator("[data-hg-ai-continue]").click();
+ await expect.poll(() => requests.length).toBe(1);
+ await expect(notice).toBeHidden();
+ await expect(page.locator(".hg-ask-ai-launcher")).toBeVisible();
+ await expect.poll(() => page.evaluate(() => window.__kapaCalls || [])).toContainEqual([
+ "open", { mode: "ai", query: "", submit: false }
+ ]);
+});
+
+
+for (const dismiss of ["button", "escape"]) {
+ test(`dismissal via ${dismiss} survives navigation and a fresh tab without granting AI`, async ({ page }) => {
+ const requests = [];
+ await page.context().route("https://widget.kapa.ai/kapa-widget.bundle.js*", async route => {
+ requests.push(route.request().url());
+ await route.fulfill({ status: 200, contentType: "text/javascript", body: mockBundle });
+ });
+ await page.goto(AI_ORIGIN + "/docs/");
+ if (dismiss === "button") await page.locator("[data-hg-ai-cancel]").click();
+ else await page.locator("[data-hg-ai-continue]").press("Escape");
+ await page.goto(AI_ORIGIN + "/cn/docs/");
+ await expect(page.locator("[data-hg-ai-consent]")).toBeHidden();
+ await expect(page.locator(".hg-ask-ai-launcher")).toBeVisible();
+ await expect(page.locator("[data-hg-ai-revoke]")).toBeHidden();
+ await page.reload();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeHidden();
+ const fresh = await page.context().newPage();
+ await fresh.goto(AI_ORIGIN + "/docs/");
+ await expect(fresh.locator("[data-hg-ai-consent]")).toBeHidden();
+ await fresh.locator(".hg-ask-ai-launcher").click();
+ await expect(fresh.locator("[data-hg-ai-consent]")).toBeVisible();
+ await expect(fresh.locator("[data-hg-ai-continue]")).toBeFocused();
+ expect(requests).toHaveLength(0);
+ await fresh.close();
+ await page.locator("[data-td-shell-search-open]").first().click();
+ await page.locator(".td-shell-search__input").fill("zzzxqnonexistentzzzxq");
+ await page.getByRole("option").filter({ hasText: /Ask AI|询问 AI|问 AI/ }).click();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
+ expect(requests).toHaveLength(0);
+ });
+}
+
+for (const loaded of [false, true]) {
+ test(`revocation resets grant and vendor state (${loaded ? "after" : "before"} loading)`, async ({ page }) => {
+ const requests = [];
+ await page.route("https://widget.kapa.ai/kapa-widget.bundle.js*", async route => {
+ requests.push(route.request().url());
+ await route.fulfill({ status: 200, contentType: "text/javascript", body: mockBundle });
+ });
+ await page.goto(AI_ORIGIN + "/docs/");
+ await page.evaluate(() => {
+ const config = JSON.parse(document.querySelector("#hg-ai-config").textContent);
+ localStorage.setItem('hg-ai-consent:v2:' + config.websiteId, 'granted');
+ localStorage.setItem('unrelated', 'preserve');
+ });
+ await page.reload();
+ await expect(page.locator("[data-hg-ai-revoke]")).toBeVisible();
+ expect(requests).toHaveLength(0);
+ if (loaded) {
+ await page.locator(".hg-ask-ai-launcher").click();
+ await expect.poll(() => requests.length).toBe(1);
+ await expect(page.locator(".hg-ask-ai-launcher")).toHaveAttribute("data-hg-ai-state", "ready");
+ }
+ await page.locator("[data-hg-ai-revoke]").click();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
+ await expect(page.locator(".hg-ask-ai-launcher")).toBeHidden();
+ await expect(page.locator("[data-hg-ai-revoke]")).toBeHidden();
+ await expect(page.locator("script[data-hg-kapa-widget]")).toHaveCount(0);
+ expect(await page.evaluate(() => window.__kapaCalls)).toBeUndefined();
+ expect(await page.evaluate(() => localStorage.getItem('unrelated'))).toBe('preserve');
+ expect(requests).toHaveLength(loaded ? 1 : 0);
+ });
+}
+
+test("blocked adapter leaves consent and launcher hidden and native search usable", async ({ page }) => {
+ const requests = [];
+ await page.route("**/js/kapa-adapter*.js", route => route.abort());
+ await page.route("https://widget.kapa.ai/kapa-widget.bundle.js*", route => {
+ requests.push(route.request().url());
+ return route.abort();
+ });
+ await page.goto(AI_ORIGIN + "/docs/");
+ await expect(page.locator("[data-hg-ai-consent]")).toBeHidden();
+ await expect(page.locator(".hg-ask-ai-launcher")).toBeHidden();
+ await expect(page.locator("[data-hg-ai-revoke]")).toBeHidden();
+ await page.locator("[data-td-shell-search-open]").first().click();
+ await expect(page.locator(".td-shell-search__input")).toBeFocused();
+ expect(requests).toHaveLength(0);
+});
+
+
+test("failed persistent grant removal announces error without pretending to revoke", async ({ page }) => {
+ await page.goto(AI_ORIGIN + "/docs/");
+ await page.evaluate(() => {
+ const config = JSON.parse(document.querySelector("#hg-ai-config").textContent);
+ localStorage.setItem('hg-ai-consent:v2:' + config.websiteId, 'granted');
+ });
+ await page.reload();
+ await page.evaluate(() => {
+ Storage.prototype.removeItem = function () { throw new DOMException('blocked', 'SecurityError'); };
+ });
+ await page.locator("[data-hg-ai-revoke]").click();
+ const revokeError = await page.locator("#hg-ai-config").evaluate(node =>
+ JSON.parse(node.textContent).labels.revokeError);
+ await expect(page.locator("[data-hg-ai-status]")).toHaveText(revokeError);
+ await expect(page.locator("[data-hg-ai-revoke]")).toBeVisible();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeHidden();
+ expect(await page.evaluate(() => {
+ const config = JSON.parse(document.querySelector("#hg-ai-config").textContent);
+ return localStorage.getItem('hg-ai-consent:v2:' + config.websiteId);
+ })).toBe('granted');
+});
+
+
+for (const loaded of [false, true]) {
+ test(`revocation synchronizes sibling tabs (${loaded ? "loaded vendor" : "before loading"})`, async ({ page }) => {
+ const requests = [];
+ const fulfillBundle = async route => {
+ requests.push(route.request().url());
+ await route.fulfill({ status: 200, contentType: "text/javascript", body: mockBundle });
+ };
+ await page.route("https://widget.kapa.ai/kapa-widget.bundle.js*", fulfillBundle);
+ await page.context().route("https://widget.kapa.ai/kapa-widget.bundle.js*", fulfillBundle);
+ await page.goto(AI_ORIGIN + "/docs/");
+ await page.evaluate(() => {
+ const config = JSON.parse(document.querySelector("#hg-ai-config").textContent);
+ localStorage.setItem('hg-ai-consent:v2:' + config.websiteId, 'granted');
+ });
+ await page.reload();
+ const sibling = await page.context().newPage();
+ await sibling.goto(AI_ORIGIN + "/cn/docs/");
+ await expect(sibling.locator("[data-hg-ai-consent]")).toBeHidden();
+ if (loaded) {
+ await page.locator(".hg-ask-ai-launcher").click();
+ await sibling.locator(".hg-ask-ai-launcher").click();
+ await expect.poll(() => requests.length).toBe(2);
+ await expect(sibling.locator(".hg-ask-ai-launcher")).toHaveAttribute("data-hg-ai-state", "ready");
+ }
+ await page.locator("[data-hg-ai-revoke]").click();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
+ await expect(sibling.locator("[data-hg-ai-consent]")).toBeVisible();
+ await expect(sibling.locator("script[data-hg-kapa-widget]")).toHaveCount(0);
+ expect(await sibling.evaluate(() => window.__kapaCalls)).toBeUndefined();
+ expect(requests).toHaveLength(loaded ? 2 : 0);
+ await sibling.close();
+ });
+}
+
+
+test("grant synchronizes stale disclosure tabs without autoloading AI", async ({ page }) => {
+ const requests = [];
+ const fulfillBundle = async route => {
+ requests.push(route.request().url());
+ await route.fulfill({ status: 200, contentType: "text/javascript", body: mockBundle });
+ };
+ await page.route("https://widget.kapa.ai/kapa-widget.bundle.js*", fulfillBundle);
+ await page.context().route("https://widget.kapa.ai/kapa-widget.bundle.js*", fulfillBundle);
+ await page.goto(AI_ORIGIN + "/docs/");
+ const sibling = await page.context().newPage();
+ await sibling.goto(AI_ORIGIN + "/cn/docs/");
+ await expect(sibling.locator("[data-hg-ai-consent]")).toBeVisible();
+ await page.locator("[data-hg-ai-continue]").click();
+ await expect.poll(() => requests.length).toBe(1);
+ await expect(sibling.locator("[data-hg-ai-consent]")).toBeHidden();
+ await expect(sibling.locator(".hg-ask-ai-launcher")).toBeVisible();
+ await expect(sibling.locator("[data-hg-ai-revoke]")).toBeVisible();
+ await expect(sibling.locator("script[data-hg-kapa-widget]")).toHaveCount(0);
+ expect(requests).toHaveLength(1);
+ await sibling.close();
+});
+
+
+test("blocked storage page-only consent can be revoked after loading AI", async ({ page }) => {
+ const requests = [];
+ await page.addInitScript(() => {
+ Object.defineProperty(window, "localStorage", {
+ get() { throw new DOMException("Storage disabled", "SecurityError"); },
+ });
+ });
+ await page.route("https://widget.kapa.ai/kapa-widget.bundle.js*", async route => {
+ requests.push(route.request().url());
+ await route.fulfill({ status: 200, contentType: "text/javascript", body: mockBundle });
+ });
+ await page.goto(AI_ORIGIN + "/docs/");
+ await page.locator("[data-hg-ai-continue]").click();
+ await expect.poll(() => requests.length).toBe(1);
+ await expect(page.locator(".hg-ask-ai-launcher")).toHaveAttribute("data-hg-ai-state", "ready");
+ await page.locator("[data-hg-ai-revoke]").click();
+ await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
+ await expect(page.locator("[data-hg-ai-revoke]")).toBeHidden();
+ await expect(page.locator("script[data-hg-kapa-widget]")).toHaveCount(0);
+ expect(await page.evaluate(() => window.__kapaCalls)).toBeUndefined();
+ expect(requests).toHaveLength(1);
+});
diff --git a/tests/e2e/platform.spec.js b/tests/e2e/platform.spec.js
index 89bb4df7d..3af698353 100644
--- a/tests/e2e/platform.spec.js
+++ b/tests/e2e/platform.spec.js
@@ -214,8 +214,7 @@ test("enabled AI makes no third-party request before consent", async ({ page })
expect(kapaRequests).toEqual([]);
await page.locator(".td-shell-search__input").press("Escape");
const launcher = page.locator("[data-hg-ask-ai]").first();
- await expect(launcher).toBeVisible();
- await launcher.click();
+ await expect(launcher).toBeHidden();
await expect(page.locator("[data-hg-ai-consent]")).toBeVisible();
await page.locator("[data-hg-ai-cancel]").click();
await expect(page.locator("[data-hg-ai-consent]")).not.toBeVisible();
diff --git a/tests/ui-ai/kapa-adapter.test.cjs b/tests/ui-ai/kapa-adapter.test.cjs
index dd373f3a8..17710744d 100644
--- a/tests/ui-ai/kapa-adapter.test.cjs
+++ b/tests/ui-ai/kapa-adapter.test.cjs
@@ -3,7 +3,7 @@ const test = require('node:test');
const adapter = require('../../assets/js/kapa-adapter.js');
-function harness() {
+function harness(storage = new Map()) {
const calls = [];
const timers = new Map();
const scripts = [];
@@ -11,6 +11,7 @@ function harness() {
let renderCallbacks = [];
const trigger = {
dataset: {},
+ hidden: true,
disabled: false,
attrs: {},
setAttribute(name, value) { this.attrs[name] = value; },
@@ -22,12 +23,11 @@ function harness() {
classList: { toggle() {} },
};
const consentListeners = new Map();
- const continueButton = { addEventListener(name, callback) { consentListeners.set(`continue:${name}`, callback); } };
+ const continueButton = { focus() { this.focused = true; }, addEventListener(name, callback) { consentListeners.set(`continue:${name}`, callback); } };
const cancelButton = { addEventListener(name, callback) { consentListeners.set(`cancel:${name}`, callback); } };
+ const revoke = { hidden: true, addEventListener(name, cb) { consentListeners.set(`revoke:${name}`, cb); } };
const consent = {
- open: false,
- showModal() { this.open = true; },
- close() { this.open = false; },
+ hidden: false,
addEventListener(name, callback) { consentListeners.set(`dialog:${name}`, callback); },
querySelector(selector) {
if (selector === '[data-hg-ai-continue]') return continueButton;
@@ -40,6 +40,8 @@ function harness() {
querySelector(selector) {
if (selector === '[data-hg-ai-status]') return status;
if (selector === '[data-hg-ai-consent]') return consent;
+ if (selector === '[data-hg-ai-revoke]') return revoke;
+ if (selector === '.hg-ask-ai-launcher') return trigger;
if (selector === 'script[data-hg-kapa-widget]') {
return scripts.find((script) => !script.removed) || null;
}
@@ -69,7 +71,15 @@ function harness() {
appendChild(script) { script.appended = true; },
},
};
+ const windowListeners = new Map();
const windowObject = {
+ addEventListener(name, cb) { windowListeners.set(name, cb); },
+ location: { reload() { windowObject.reloaded = true; } },
+ localStorage: {
+ getItem(key) { return storage.get(key) || null; },
+ setItem(key, value) { storage.set(key, value); },
+ removeItem(key) { storage.delete(key); },
+ },
setKapaImplementation() {
this.Kapa = function (method, value) {
calls.push([method, value]);
@@ -92,10 +102,19 @@ function harness() {
sourceGroupId: 'source-en',
locale: 'en',
themeColor: '#123456',
- labels: { error: 'unavailable' },
+ exampleQuestions: ['How do I start HugeGraph?', 'How do I import data?'],
+ communityURL: 'https://github.com/apache/hugegraph/discussions',
+ labels: { error: 'unavailable', revokeError: 'Unable to revoke. AI consent remains enabled.', community: 'Ask the community' },
};
return {
calls,
+ status,
+ revoke,
+ revokeConsent() { consentListeners.get('revoke:click')(); },
+ storageEvent(event) { windowListeners.get('storage')(event); },
+ consent,
+ continueButton,
+ storage,
config,
documentObject,
fireRender(index = renderCallbacks.length - 1) { renderCallbacks[index](); },
@@ -103,7 +122,6 @@ function harness() {
continueConsent() { consentListeners.get('continue:click')(); },
cancelConsent() { consentListeners.get('cancel:click')(); },
escapeConsent() { consentListeners.get('dialog:keydown')({ key: 'Escape', preventDefault() {}, stopPropagation() {} }); },
- nativeCancel() { consentListeners.get('dialog:cancel')({ preventDefault() {} }); },
installBundle() {
const queued =
windowObject.Kapa && Array.isArray(windowObject.Kapa.q)
@@ -129,7 +147,17 @@ test('uses one fixed bundle and explicit privacy-safe widget settings', () => {
sourceGroupId: 'source-cn',
locale: 'zh',
themeColor: '#123456',
+ exampleQuestions: ['如何启动 HugeGraph?', '如何导入数据?'],
+ labels: { community: '向社区求助' },
+ communityURL: 'https://github.com/apache/hugegraph/discussions',
});
+ assert.equal(attrs['data-example-questions'], '如何启动 HugeGraph?,如何导入数据?');
+ assert.equal(attrs['data-example-questions-col-span'], '12');
+ assert.equal(attrs['data-answer-cta-button-enabled'], 'true');
+ assert.equal(attrs['data-answer-cta-button-text'], '向社区求助');
+ assert.equal(attrs['data-answer-cta-button-link'], 'https://github.com/apache/hugegraph/discussions');
+ assert.equal(attrs['data-chat-disclaimer'], undefined);
+ assert.equal(Object.keys(attrs).some(name => /handoff|email/.test(name)), false);
assert.equal(attrs['data-render-on-load'], 'false');
assert.equal(attrs['data-project-logo'], '/img/logo.svg');
assert.ok(Number(attrs['data-modal-z-index']) > 1040, 'modal must cover the site launcher');
@@ -219,8 +247,8 @@ test('launcher opens a blank session without auto-submit', () => {
]);
});
-test('cancel, Escape, and native cancel keep Kapa unloaded and restore focus', () => {
- for (const close of ['cancelConsent', 'escapeConsent', 'nativeCancel']) {
+test('cancel and Escape keep Kapa unloaded and restore focus', () => {
+ for (const close of ['cancelConsent', 'escapeConsent']) {
const h = harness();
const controller = adapter.createController(h.windowObject, h.documentObject, h.config);
controller.activate('private question', true, h.trigger);
@@ -464,3 +492,271 @@ test('stale activation refreshes the palette query and cancellation context', ()
assert.equal(h.scripts.length, 0);
}
});
+
+
+test('persistent consent survives language navigation but never loads before activation', () => {
+ const first = harness();
+ const controller = adapter.createController(first.windowObject, first.documentObject, first.config);
+ controller.activate('', false, first.trigger);
+ first.continueConsent();
+ const next = harness(first.storage);
+ next.config.locale = 'zh';
+ next.config.sourceGroupId = 'source-cn';
+ next.config.labels.community = '向社区求助';
+ const nextController = adapter.createController(next.windowObject, next.documentObject, next.config);
+ assert.equal(nextController.getState(), 'idle');
+ assert.equal(next.scripts.length, 0);
+ nextController.activate('', false, next.trigger);
+ assert.equal(nextController.getState(), 'loading');
+ assert.equal(next.scripts[0].attrs['data-source-group-ids-include'], 'source-cn');
+ assert.equal(next.scripts[0].attrs['data-answer-cta-button-text'], '向社区求助');
+
+});
+
+test('consent is scoped to website id and rejects obsolete or malformed grants', () => {
+ for (const entries of [
+ [['hg-ai-consent:v2:other', 'granted']],
+ [['hg-ai-consent:v0:website', 'granted']],
+ [['hg-ai-consent:v1:website', 'granted']],
+ [['hg-ai-consent:v2:website', 'true']],
+ ]) {
+ const h = harness(new Map(entries));
+ const controller = adapter.createController(h.windowObject, h.documentObject, h.config);
+ controller.activate('', false, h.trigger);
+ assert.equal(controller.getState(), 'consent');
+ assert.equal(h.scripts.length, 0);
+ }
+});
+
+test('unavailable local storage leaves consent explicit and usable for this page', () => {
+ for (const failure of ['property', 'methods']) {
+ const h = harness();
+ if (failure === 'property') Object.defineProperty(h.windowObject, 'localStorage', {
+ get() { throw new Error('blocked'); },
+ });
+ else h.windowObject.localStorage = {
+ getItem() { throw new Error('blocked'); },
+ setItem() { throw new Error('blocked'); },
+ removeItem() { throw new Error('blocked'); },
+ };
+ const controller = adapter.createController(h.windowObject, h.documentObject, h.config);
+ controller.activate('', false, h.trigger);
+ assert.equal(controller.getState(), 'consent');
+ assert.equal(h.scripts.length, 0);
+ h.continueConsent();
+ assert.equal(controller.getState(), 'loading');
+ assert.equal(h.storage.size, 0);
+ }
+});
+
+
+test('random examples select three distinct pool entries without mutating the pool', () => {
+ const pool = ['one', 'two', 'three', 'four', 'five'];
+ assert.deepEqual(adapter.pickExampleQuestions(pool, () => 0.999), ['one', 'two', 'three']);
+ assert.deepEqual(adapter.pickExampleQuestions(pool, () => 0), ['two', 'three', 'four']);
+ assert.deepEqual(pool, ['one', 'two', 'three', 'four', 'five']);
+ assert.deepEqual(adapter.pickExampleQuestions(['one', 'one', 'two'], () => 0.999), ['one', 'two']);
+ assert.deepEqual(adapter.pickExampleQuestions([], () => 0), []);
+});
+
+test('a page retains its sampled examples when the widget load is retried', () => {
+ const h = harness();
+ h.config.exampleQuestions = ['one', 'two', 'three', 'four', 'five'];
+ const controller = adapter.createController(h.windowObject, h.documentObject, h.config);
+ controller.activate('', false, h.trigger);
+ h.continueConsent();
+ const selected = h.scripts[0].attrs['data-example-questions'].split(',');
+ assert.equal(selected.length, 3);
+ assert.equal(new Set(selected).size, 3);
+ assert.ok(selected.every(question => h.config.exampleQuestions.includes(question)));
+ h.fireTimeout();
+ controller.activate('', false, h.trigger);
+ assert.equal(h.scripts[1].attrs['data-example-questions'], selected.join(','));
+});
+
+
+test('inline consent opens AI in one click and restores the launcher on widget close', () => {
+ const h = harness();
+ adapter.createController(h.windowObject, h.documentObject, h.config);
+ assert.equal(h.consent.hidden, false);
+ assert.equal(h.trigger.hidden, true);
+ assert.equal(h.scripts.length, 0);
+ h.continueConsent();
+ assert.equal(h.consent.hidden, true);
+ assert.equal(h.trigger.hidden, false);
+ assert.equal(h.trigger.attrs['aria-haspopup'], 'dialog');
+ assert.equal(h.storage.get('hg-ai-consent:v2:website'), 'granted');
+ h.scripts[0].fire('load');
+ h.fireRender();
+ assert.deepEqual(h.calls.at(-1), ['open', { mode: 'ai', query: '', submit: false }]);
+ h.calls.find(([method]) => method === 'onModalClose')[1]();
+ assert.equal(h.trigger.focused, true);
+ h.continueConsent();
+ assert.equal(h.scripts.length, 1);
+});
+
+test('initial inline dismissal remembers no-grant choice and pending activation focuses agreement', () => {
+ const h = harness();
+ const controller = adapter.createController(h.windowObject, h.documentObject, h.config);
+ h.cancelConsent();
+ assert.equal(h.trigger.hidden, false);
+ assert.equal(h.trigger.focused, true);
+ assert.equal(h.trigger.attrs['aria-haspopup'], undefined);
+ assert.equal(h.consent.hidden, true);
+ assert.equal(h.storage.get('hg-ai-consent:v2:website'), 'dismissed');
+ assert.equal(h.scripts.length, 0);
+ controller.activate(' import data ', true, h.trigger);
+ assert.equal(h.consent.hidden, false);
+ assert.equal(h.continueButton.focused, true);
+ assert.equal(h.trigger.hidden, true);
+ h.continueConsent();
+ h.scripts[0].fire('load');
+ h.fireRender();
+ assert.deepEqual(h.calls.at(-1), ['open', { mode: 'ai', query: 'import data', submit: true }]);
+});
+
+
+test('remembered dismissal stays local and explicit reopening still requires consent', () => {
+ for (const dismiss of ['cancelConsent', 'escapeConsent']) {
+ const first = harness();
+ adapter.createController(first.windowObject, first.documentObject, first.config);
+ first[dismiss]();
+ const next = harness(first.storage);
+ next.config.locale = 'zh';
+ const controller = adapter.createController(next.windowObject, next.documentObject, next.config);
+ assert.equal(next.consent.hidden, true);
+ assert.equal(next.trigger.hidden, false);
+ assert.equal(next.trigger.attrs['aria-haspopup'], undefined);
+ assert.equal(next.revoke.hidden, true);
+ assert.equal(next.scripts.length, 0);
+ controller.activate('private query', true, next.trigger);
+ assert.equal(controller.getState(), 'consent');
+ assert.equal(next.consent.hidden, false);
+ assert.equal(next.trigger.hidden, true);
+ assert.equal(next.scripts.length, 0);
+ }
+});
+
+test('revocation clears only the grant and reloads whether vendor is loaded or not', () => {
+ for (const loaded of [false, true]) {
+ const storage = new Map([['hg-ai-consent:v2:website', 'granted'], ['unrelated', 'preserve']]);
+ const h = harness(storage);
+ const controller = adapter.createController(h.windowObject, h.documentObject, h.config);
+ assert.equal(h.revoke.hidden, false);
+ if (loaded) {
+ controller.activate('', false, h.trigger);
+ h.scripts[0].fire('load');
+ h.fireRender();
+ }
+ h.revokeConsent();
+ assert.equal(h.windowObject.reloaded, true);
+ assert.deepEqual(Array.from(storage), [['unrelated', 'preserve']]);
+ const fresh = harness(storage);
+ adapter.createController(fresh.windowObject, fresh.documentObject, fresh.config);
+ assert.equal(fresh.consent.hidden, false);
+ assert.equal(fresh.trigger.hidden, true);
+ assert.equal(fresh.revoke.hidden, true);
+ assert.equal(fresh.scripts.length, 0);
+ }
+});
+
+test('failed grant removal reports an error and keeps the active permission', () => {
+ const h = harness(new Map([['hg-ai-consent:v2:website', 'granted']]));
+ h.windowObject.localStorage.removeItem = () => { throw new Error('blocked'); };
+ const controller = adapter.createController(h.windowObject, h.documentObject, h.config);
+ h.revokeConsent();
+ assert.equal(h.windowObject.reloaded, undefined);
+ assert.equal(h.storage.get('hg-ai-consent:v2:website'), 'granted');
+ assert.equal(h.revoke.hidden, false);
+ assert.equal(h.status.textContent, 'Unable to revoke. AI consent remains enabled.');
+ controller.activate('', false, h.trigger);
+ assert.equal(controller.getState(), 'loading');
+});
+
+test('blocked storage keeps dismissal page-only and exposes fresh disclosure next visit', () => {
+ const h = harness();
+ h.windowObject.localStorage.setItem = () => { throw new Error('blocked'); };
+ adapter.createController(h.windowObject, h.documentObject, h.config);
+ h.cancelConsent();
+ assert.equal(h.consent.hidden, true);
+ assert.equal(h.storage.size, 0);
+ const fresh = harness(h.storage);
+ adapter.createController(fresh.windowObject, fresh.documentObject, fresh.config);
+ assert.equal(fresh.consent.hidden, false);
+ assert.equal(fresh.scripts.length, 0);
+});
+
+
+test('cross-tab removal or storage clear reloads consented tabs and ignores unrelated updates', () => {
+ for (const key of ['hg-ai-consent:v2:website', null]) {
+ const h = harness(new Map([['hg-ai-consent:v2:website', 'granted']]));
+ adapter.createController(h.windowObject, h.documentObject, h.config);
+ h.storageEvent({ key: 'unrelated', newValue: null });
+ assert.equal(h.windowObject.reloaded, undefined);
+ h.storageEvent({ key: 'hg-ai-consent:v2:website', newValue: 'granted' });
+ assert.equal(h.windowObject.reloaded, undefined);
+ h.storageEvent({ key, newValue: null });
+ assert.equal(h.windowObject.reloaded, true);
+ }
+ const h = harness();
+ adapter.createController(h.windowObject, h.documentObject, h.config);
+ h.storageEvent({ key: 'hg-ai-consent:v2:website', newValue: null });
+ assert.equal(h.windowObject.reloaded, undefined);
+});
+
+
+test('incoming permission synchronizes stale preconsent tabs without loading the vendor', () => {
+ for (const value of ['granted', 'dismissed']) {
+ const h = harness();
+ adapter.createController(h.windowObject, h.documentObject, h.config);
+ h.storageEvent({ key: 'hg-ai-consent:v2:website', newValue: value });
+ assert.equal(h.windowObject.reloaded, true);
+ assert.equal(h.scripts.length, 0);
+ }
+ const h = harness(new Map([['hg-ai-consent:v2:website', 'dismissed']]));
+ adapter.createController(h.windowObject, h.documentObject, h.config);
+ h.storageEvent({ key: 'hg-ai-consent:v2:website', newValue: 'dismissed' });
+ assert.equal(h.windowObject.reloaded, undefined);
+});
+
+test('load and vendor open failures return keyboard focus from hidden agreement to launcher', () => {
+ for (const failure of ['bundle', 'open']) {
+ const h = harness();
+ adapter.createController(h.windowObject, h.documentObject, h.config);
+ h.continueConsent();
+ assert.equal(h.consent.hidden, true);
+ if (failure === 'bundle') h.scripts[0].fire('error');
+ else {
+ const implementation = h.windowObject.Kapa;
+ h.windowObject.Kapa = (method, value) => {
+ if (method === 'open') throw new Error('vendor');
+ return implementation(method, value);
+ };
+ h.scripts[0].fire('load');
+ h.fireRender();
+ }
+ assert.equal(h.trigger.focused, true);
+ assert.equal(h.trigger.disabled, false);
+ }
+});
+
+
+test('page-only permission can be revoked when storage is wholly blocked', () => {
+ const h = harness();
+ Object.defineProperty(h.windowObject, 'localStorage', {
+ get() { throw new Error('blocked'); },
+ });
+ adapter.createController(h.windowObject, h.documentObject, h.config);
+ h.continueConsent();
+ h.scripts[0].fire('load');
+ h.fireRender();
+ assert.equal(h.revoke.hidden, false);
+ h.revokeConsent();
+ assert.equal(h.windowObject.reloaded, true);
+ assert.equal(h.status.textContent, '');
+ assert.equal(h.storage.size, 0);
+ const fresh = harness(h.storage);
+ adapter.createController(fresh.windowObject, fresh.documentObject, fresh.config);
+ assert.equal(fresh.consent.hidden, false);
+ assert.equal(fresh.scripts.length, 0);
+});