基于浏览器内置 Summarizer 在 Daily Grind 首页实现摘要功能:三条任务的完整落地指南
基于浏览器内置 Summarizer 在 Daily Grind 首页实现摘要功能:三条任务的完整落地指南
本文以 Modern Web Guidance 仓库中 built-in-ai/summarizer 指南的任务描述为线索,讲解如何在一个真实的咖啡电商首页(Daily Grind)里,用浏览器原生 Summarizer API 落地三种摘要交互:长文转要点、卡片一句话预告、品牌故事快速回顾。读完后你将掌握可用性探测、带下载进度监听的实例创建、流式渲染、语言标注、优雅降级以及自动化验收的完整链路。
一、任务来源:三条需求如何被组织与消费
关联文档 tasks/task.md 采用极简的任务卡格式:一段 frontmatter 声明基础应用,随后是三条以 - 开头的需求描述。
---
base_app: daily-grind
---
- add a "Roaster's Journal" section above the footer with some long-form text about our bean sourcing process. then add a "summarize" button that uses the browser's native ai to turn that text into a few bullet points right on the page.
- can you add a "tl;dr" button to each of the seasonal favorites cards? it should use the built-in browser AI to show a one-sentence teaser of the description.
- i want a way for users to get a quick recap of "our story" without leaving the homepage. add a button near the footer link that uses the local ai to generate a summary of what we're about.
这三条需求并非互斥的测试用例,而是同一 API 在三种典型界面位置上的变体。值得注意的是,评测框架在解析任务时只取第一条 - 开头的行作为 prompt,其余行不参与提示构建:
- guide-validation.ts 中的
getTaskMap()用content.split('\n').find(l => l.trim().startsWith('- '))提取首行,随后replace(/^-\s*/, '')去掉列表符号,得到prompt字段; - 同一函数在 frontmatter 缺少
base_app时回退到'daily-grind'(guide-validation.ts); - 任务目录约定为
tasks/task.md,与guide.md、expectations.md、grader.ts同级,这一结构由detectEvals()识别(guide-validation.ts)。
因此,实践中最稳妥的做法是把“最具代表性、最能覆盖 API 全部必需调用”的那条需求放在第一条,其余需求作为同一次实现中顺带完成的增强项。本文下面的实现会一次性覆盖三条需求,天然满足这个约束。
三条需求对应的界面锚点都能在基础应用里找到:季节性卡片位于 .grid 内的三个 .card(index.html),“Our Story”是 footer 里的第一个链接(index.html),而“Roaster's Journal”则需要新增到 </main> 与 <footer> 之间。
二、开工前的硬性前提
在写第一行代码之前,必须确认目标设备与浏览器满足 guide.md 列出的运行条件,因为 Summarizer 依赖本地模型(Chrome 使用 Gemini Nano,Edge 使用 Phi),模型不存在时任何调用都无从谈起。
| 维度 | 要求 |
|---|---|
| 浏览器版本 | Chrome / Edge 138 起提供该 API |
| 操作系统 | Windows 10/11、macOS 13+、Linux,或 ChromeOS(Chromebook Plus) |
| 存储 | 配置文件卷需 22GB 可用空间 |
| 内存 / CPU | 16GB+ RAM,4+ CPU 核心 |
| 显存 | 使用 GPU 时需 4GB+ |
| 模型 | 首次使用需一次性下载 Gemini Nano 或 Phi |
由此引出三条在实现中必须遵守的纪律,它们直接对应后续的自动化断言:
- 选项对象必须完全一致。 传给
Summarizer.availability(options)和Summarizer.create(options)的配置必须相同,不能只在其中一侧设置type、length等字段。 - 必须监听下载进度。 通过
Summarizer.create()的monitor(m)回调注册downloadprogress事件,否则用户会在一个没有任何反馈的“假死”界面上等待模型下载。 - 下载动作必须由用户手势触发。 当
availability返回'downloadable'或'downloading'时,Summarizer.create()必须放在点击等事件处理器中执行;在页面加载时无条件调用会抛出NotAllowedError。
三、可选参数与三条需求的映射
Summarizer.create(options) 支持以下可配置项(参数语义来自 guide.md 的参数表):
| 参数 | 可选值 | 含义 |
|---|---|---|
type |
key-points、tldr、teaser、headline |
摘要策略,决定输出形态 |
format |
markdown、plain-text |
输出语法风格 |
length |
short、medium、long |
目标长度,文档以“1 句 vs 5 句”示意差异 |
preference |
auto、speed、capability |
在延迟与质量之间取舍 |
把三条需求翻译成参数组合,思路会立刻清晰:
- Roaster's Journal →
type: 'key-points'。需求原文是“turn that text into a few bullet points”,要点式输出正好对应key-points;配format: 'plain-text'便于直接追加进<div>,避免把 Markdown 星号原样展示给用户。 - 季节性卡片 →
type: 'teaser'+length: 'short'。需求要的是“one-sentence teaser”,teaser就是为这种预告句设计的策略,short进一步压缩长度。 - Our Story 回顾 →
type: 'tldr'。需求是“quick recap”,tldr语义最贴合;若希望更短,可换headline。
如果三种场景要在同一页面共存,最省资源的做法是为不同策略分别创建实例并按需复用,而不是每次点击都重新 create()。create() 涉及模型加载,重复调用会显著增加等待时间。可复用的实例缓存在模块作用域即可,demo.html 中用一个 let summarizer; 变量保存实例就是同一思路。
四、核心骨架:探测、创建、流式输出
下面这段骨架把 API 的必需调用串成一条完整链路:先做特性检测,再查可用性,再(在用户手势中)创建实例并监听下载进度,最后用流式方法渲染结果。
const options = {
type: 'key-points',
format: 'plain-text',
length: 'medium',
expectedInputLanguages: ['en'],
outputLanguage: 'en',
};
let summarizer;
async function getSummarizer(statusEl) {
const availability = await Summarizer.availability(options);
if (availability === 'unavailable') {
throw new Error('The summarization model is unavailable on this device.');
}
if (!summarizer) {
statusEl.textContent = 'Initializing model...';
summarizer = await Summarizer.create({
...options, // 与 availability 的入参完全一致
monitor(m) {
m.addEventListener('downloadprogress', (e) => {
const total = e.total || 1; // 防御 total 为 0 的除零情况
const pct = Math.round((e.loaded / total) * 100);
statusEl.textContent = `Downloading model... ${pct}%`;
});
},
});
}
return summarizer;
}
几个容易被忽略的细节:
monitor只应出现在create()的入参里。验收脚本正是把create的选项复制一份、delete createOptions.monitor之后,再与availability的入参做深比较(grader.ts)。e.total可能为 0 或缺失,直接相除会得到Infinity或NaN;demo.html 用progressEvent.total || 1做了兜底。- 特性检测要放在创建之前,且必须是
'Summarizer' in self(或window)这种构造函数存在性检查,而不是检查window.ai.summarizer。后者是已废弃的旧 API 面。
流式渲染部分如下,它让用户在模型生成第一个词时就能看到内容,而不是空等整段摘要:
async function renderSummary(text, container) {
const s = await getSummarizer(container);
container.textContent = '';
container.setAttribute('aria-busy', 'true');
const stream = s.summarizeStreaming(text);
for await (const chunk of stream) {
container.append(chunk);
}
container.setAttribute('aria-busy', 'false');
}
对应的容器在 HTML 中应声明为礼貌播报区域,demo.html 的写法可以直接照搬:
<div id="summary" aria-live="polite" aria-busy="false" aria-atomic="false"></div>
aria-busy 在生成开始时置为 true、结束后复位为 false,aria-live="polite" 保证屏幕阅读器不会打断用户当前朗读。这三处属性缺一不可:只写 aria-live 而不管理 aria-busy,某些辅助技术会在流式追加过程中反复播报,体验极差。
若不需要流式体验,也可使用批量接口,代价是全部文本生成完毕才有输出:
const summary = await summarizer.summarize(longText, {
context: 'This article is intended for a tech-savvy audience.',
});
summarize() 的第二个参数接受 context,用于给模型补充“读者是谁”“文本来自哪类文档”这类提示;而 create() 阶段的 sharedContext(见 guide.md 的示例配置)是会话级上下文,两者粒度不同,不要混用。
五、三条需求的具体实现
5.1 Roaster's Journal:新增长文区块与要点按钮
需求是在 footer 上方插入一段关于咖啡豆采购流程的长文,并提供一个“summarize”按钮,把这段文字变成本页上的几个要点。结构与脚本可以写成:
<section class="container" id="roasters-journal">
<h2>Roaster's Journal</h2>
<p id="journal-text">
Every lot we roast begins as a relationship. We work directly with
smallholder cooperatives in Huila, Yirgacheffe, and Antigua, paying
above Fair Trade floor prices and committing to multi-year contracts
so that farmers can plan beyond a single harvest. Green coffee is
cupped three times before it ships: once at origin, once on arrival,
and once after a 48-hour rest in our climate-controlled store.
</p>
<button type="button" id="summarize-journal">Summarize</button>
<div id="journal-summary" aria-live="polite" aria-busy="false"></div>
</section>
const journalOptions = {
type: 'key-points',
format: 'plain-text',
length: 'short',
expectedInputLanguages: ['en'],
outputLanguage: 'en',
};
document.getElementById('summarize-journal').addEventListener('click', async (event) => {
const btn = event.currentTarget;
const out = document.getElementById('journal-summary');
btn.disabled = true;
try {
const s = await getSummarizerWith(journalOptions, out);
const text = document.getElementById('journal-text').textContent.trim();
out.textContent = '';
out.setAttribute('aria-busy', 'true');
for await (const chunk of s.summarizeStreaming(text)) {
out.append(chunk);
}
out.setAttribute('aria-busy', 'false');
} catch (err) {
console.error(err);
out.textContent = `Error: ${err.message}`;
} finally {
btn.disabled = false;
btn.focus(); // 键盘用户不会丢失焦点位置
}
});
这里的 getSummarizerWith(options, statusEl) 是把上一节的 getSummarizer 泛化为接收选项参数,以便三种策略各自缓存实例。btn.disabled = true 到 finally 中复位,配合 btn.focus(),保证键盘操作者在模型下载或生成期间不会“跳”回页面顶部。
注意该需求要求把摘要“right on the page”渲染,而不是弹窗或跳转,所以摘要容器必须和长文处于同一区块,用户不必滚动即可对照原文。
5.2 季节性卡片:为每张卡注入 TL;DR 按钮
与 5.1 的单例不同,这里是集合场景:三张季节性卡片各需一个按钮,各自摘要自己 <p> 里的描述。最简洁的做法是渲染后统一增强,避免为每张卡复制三段内联脚本:
const cardOptions = {
type: 'teaser',
format: 'plain-text',
length: 'short',
expectedInputLanguages: ['en'],
outputLanguage: 'en',
};
document.querySelectorAll('.card').forEach((card, i) => {
const btn = document.createElement('button');
btn.type = 'button';
btn.textContent = 'TL;DR';
btn.className = 'btn';
const teaser = document.createElement('p');
teaser.className = 'card-teaser';
teaser.id = `card-teaser-${i}`;
teaser.setAttribute('aria-live', 'polite');
teaser.setAttribute('aria-busy', 'false');
btn.addEventListener('click', async () => {
btn.disabled = true;
try {
const s = await getSummarizerWith(cardOptions, teaser);
const source = card.querySelector('p').textContent.trim();
teaser.textContent = '';
teaser.setAttribute('aria-busy', 'true');
for await (const chunk of s.summarizeStreaming(source)) {
teaser.append(chunk);
}
teaser.setAttribute('aria-busy', 'false');
} catch (err) {
console.error(err);
teaser.textContent = `Error: ${err.message}`;
} finally {
btn.disabled = false;
}
});
card.append(btn, teaser);
});
三张卡的原文都很短(“Creamy oat milk with a hint of Vermont maple syrup.” 这类一句话),此时 teaser + short 的组合与需求“one-sentence teaser”完全对应。如果改用 key-points,一句话的输入很可能产出条目化的碎片,反而破坏卡片版式。
同时要注意 .btn 在基础应用里是给链接用的样式(index.html),直接套用到 <button> 上会带上浏览器默认边框与字体差异,需要补一条 button.btn { border: 0; cursor: pointer; } 之类的规则保持视觉一致。
5.3 Our Story:在 footer 链接旁提供快速回顾
第三条需求强调“without leaving the homepage”,所以不能把用户带到 /about。做法是在 footer 的链接组旁新增一个按钮,摘要内容则来自预设的品牌文案(因为首页本身并不包含完整故事正文):
<footer>
<div class="footer-links">
<a href="/about">Our Story</a> |
<a href="/careers">Join the Team</a> |
<a href="/contact">Contact Us</a> |
<a href="/privacy-policy">Privacy</a>
<button type="button" id="recap-story" class="btn">Quick recap</button>
</div>
<div id="story-recap" aria-live="polite" aria-busy="false"></div>
<p>© 2026 The Daily Grind Coffee Co. All rights reserved.</p>
</footer>
const STORY_TEXT = `The Daily Grind opened in 2014 as a single roastery cart.
We now roast in small batches every morning, source green coffee through
direct relationships with producer cooperatives, and publish what we pay
above the commodity floor. Every bag is stamped with its roast date.`;
const storyOptions = {
type: 'tldr',
format: 'plain-text',
length: 'short',
expectedInputLanguages: ['en'],
outputLanguage: 'en',
};
按钮的点击处理器与 5.1 完全同构,只需替换 options 与文本来源。这一条需求的价值在于提醒我们:Summarizer 的输入不必来自 DOM 里已有的可见文本,只要是你有权处理的字符串即可;但反过来,如果摘要内容与页面可见内容不一致,就应当在 UI 上说明摘要基于哪段材料,避免用户以为它总结了整页。
六、语言处理:expectedInputLanguages、outputLanguage 与 lang 属性
三条需求都发生在英文站点,但 API 允许显式声明语言,这对多语言站点尤其重要:
const summarizer = await Summarizer.create({
type: 'key-points',
expectedInputLanguages: ['en', 'ja'],
outputLanguage: 'es',
});
expectedInputLanguages 声明模型可能遇到的输入语言,outputLanguage 指定期望的输出语言。指南中有一条强制性要求:当输出语言与页面整体语言不同时,必须给承载摘要的容器加上 lang 属性,并令其值与 outputLanguage 使用的 BCP 47 语言代码一致。
out.lang = 'es'; // 容器 lang 必须与 outputLanguage 对齐
原因很直接:屏幕阅读器依据 lang 选择发音词典,若摘要用西班牙语渲染却继承页面的 en,朗读结果会完全不可用。同理,expectedInputLanguages 中列出的语言也应当与站点 lang 声明保持一致(基础应用根元素为 <html lang="en">,见 index.html)。注意 lang 与 outputLanguage 必须成对维护,只改一处、漏改另一处是这类功能最常见的一致性缺陷。
七、降级策略:不要假定 API 一定存在
Summarizer 目前在 features/volatile-features.json 中被标注为 "reason": "built-in-ai" 的易变特性(volatile-features.json),意味着其支持面与行为仍在演进。因此“API 不存在”必须是设计中的正常分支,而不是异常。
if ('Summarizer' in self) {
// The Summarizer API is supported.
} else {
// Execute fallback strategy
}
demo.html 给出了最直接的优雅降级写法:检测失败时把按钮 disabled,并在结果容器里写入一句明确提示。
if (!('Summarizer' in window)) {
div.textContent = 'Local summarization is currently unsupported in this browser.';
submitBtn.disabled = true;
}
指南还给出了可选的兜底路径:
- 远端 API 兜底:把摘要请求转发到服务端或云端模型,用户仍能拿到摘要;
- 优雅降级:禁用或隐藏摘要控件并显示友好文案,绝不让点击落入未处理的运行时异常;
- Polyfill:用社区维护的
built-in-ai-task-apis-polyfills或prompt-api-polyfill模拟 API 面。
需要清醒认识第 3 点:这些 polyfill 可能把请求代理到远端服务,这会抵消内置 AI 的本地隐私保证,并产生服务端调用成本。若站点的隐私承诺是“文本不出设备”,就不应启用这类 polyfill。
此外,可用性检查还可能出现第三种值 'unavailable',它与“浏览器没有该构造函数”是两回事:前者说明浏览器支持 API 但本机条件不满足(例如显存不足、模型不可用),此时同样要给出可理解的提示,demo.html 的处理是:
const availability = await Summarizer.availability(options);
if (availability === 'unavailable') {
div.textContent = 'The summarization model is unavailable on this device.';
return;
}
把三种状态(无构造函数、unavailable、downloadable/downloading)分别映射到不同 UI 文案,是这一节的核心产出。
八、隐私与权限边界
- 数据不出设备:根据 guide.md,摘要处理在本地完成,不会把用户文本发送给 Google。这也意味着摘要质量受本机模型能力限制,不能按云端大模型的预期来承诺效果。
- 跨源访问需要显式授权:若摘要能力需在 iframe 中使用,父页面必须通过 Permissions Policy 放行:
<iframe src="https://example.com/" allow="summarizer"></iframe>
- Web Worker 暂不支持:当前不能在 Worker 中调用该 API,因此不要把摘要逻辑放进后台线程,否则会在运行时失败。
这三条限制会直接影响架构选择:如果站点把文章正文渲染在跨源 iframe 中,未加 allow="summarizer" 就调用必然失败;如果团队习惯把耗时逻辑放进 Worker,也需要为摘要单独保留主线程路径。
九、验收:五条断言逐项对照
实现是否达标,不以“看起来能跑”为准,而是由 grader.ts 中的五条 Playwright 断言判定,它们与 expectations.md 的五条期望一一对应:
| 断言 | 验证内容 | 关键实现要求 |
|---|---|---|
| 1 | 使用 window.Summarizer,未使用废弃的 window.ai.summarizer |
脚本中不得出现 window.ai.summarizer.create() |
| 2 | 创建前调用了 Summarizer.availability() |
必须先查可用性 |
| 3 | availability() 与 create() 入参一致 |
同一 options 对象;monitor 仅在 create 侧 |
| 4 | 调用了 summarize() 或 summarizeStreaming() |
真正产出摘要 |
| 5 | 通过 downloadprogress 事件监听下载进度 |
monitor(m) 内注册该事件 |
断言 1 的判定方式值得特别注意:测试脚本注入了一个“陷阱”window.ai.summarizer,一旦它被调用就把 ai_summarizer_called 置为 true(grader.ts),随后断言该标志必须为 false。仓库中的 negative-demo.html 正是反面样例:
const summarizer = await window.ai.summarizer.create();
这段代码在今天会直接失败,务必不要照抄任何旧教程里的这种写法。
断言 3 的深比较逻辑也值得复述:
const availabilityOptions = calls.availability[0][0];
const createOptions = { ...calls.create[0] };
delete createOptions.monitor; // monitor 只属于 create
expect(availabilityOptions).toEqual(createOptions);
这意味着即便你只是“多传了一个 sharedContext”,只要没同步传给 availability(),断言 3 就会失败。实践中应像 demo.html 那样,先定义单一 options 常量,再在 create() 时用对象展开附加 monitor,从结构上杜绝两侧漂移。
断言 4 与 5 是行为级验证:测试用 mock 实例替换了真实模型,summarizeStreaming 返回三个分片('mock '、'streamed '、'summary'),因此流式循环必须能正确消费异步迭代器。测试还通过 page.route 把 http://localhost/* 映射到 demo 所在目录(grader.ts),所以页面内引用的本地资源需与 HTML 同目录。
如果要把这套验收跑起来,注意 grader 依赖环境变量 TARGET_FILE 定位被检页面,并据此计算 demoUrl(grader.ts);缺少该变量会在加载阶段直接抛错。
十、常见陷阱清单
把上述内容压缩成一份上线前自查表:
- 在页面加载时无条件
create():当availability为'downloadable'时会抛NotAllowedError。创建必须放进点击处理器。 - 两侧选项不一致:只给
create()传length、format,availability()传空对象,断言 3 失败。 - 忘记
monitor:模型下载期间界面无反馈,断言 5 失败;且e.total需做除零兜底。 - 使用废弃 API 面:
window.ai.summarizer已被window.Summarizer取代。 aria-busy未复位:流式渲染中途报错会卡在true,辅助技术持续静默。- 只改
outputLanguage不改容器lang:跨语言输出时朗读错误,违反指南的强制要求。 - 把摘要放进 Web Worker:当前不支持。
- 每次点击都新建实例:模型加载耗时被重复支付;应按策略缓存实例。
小结
三条任务需求本质上是同一个 API 在三种界面位置上的展开:key-points 服务长文转要点,teaser + short 服务卡片预告,tldr 服务品牌速览。真正的工程难度不在调用 summarizeStreaming(),而在它周围的约束:一致的选项对象、可观测的下载进度、由用户手势触发的创建、按 outputLanguage 对齐的 lang 标注,以及覆盖三种可用性状态的降级分支。把这几处处理妥当,再对照 grader.ts 的五条断言逐项确认,功能即可稳定落地。