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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/pages.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ jobs:
- run: pnpm build
- name: Check the service worker is in the build
run: test -f dist/sw.js && grep -q "Cross-Origin-Embedder-Policy" dist/sw.js
- name: Check the build id is in index.html and version.json
run: grep -q "\"build\":\"$(grep -o 'narrata-build" content="[0-9a-f]*' dist/index.html | cut -d'"' -f3)\"" dist/version.json
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v4
with:
Expand Down
47 changes: 47 additions & 0 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# On a version tag (v0.2.0), builds the extension and attaches it to the GitHub release as
# narrata-extension-<version>.zip, so people can install or update it without building it.
# The version lives in package.json; the build copies it into the manifest, and the tag must match.
name: Release

on:
push:
tags: ['v*']

permissions:
contents: write

jobs:
extension:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: pnpm/action-setup@v4
- uses: actions/setup-node@v5
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- name: Check the tag matches package.json
run: |
version=$(node -p "require('./package.json').version")
if [ "v$version" != "$GITHUB_REF_NAME" ]; then
echo "Tag $GITHUB_REF_NAME does not match package.json version $version"
exit 1
fi
echo "VERSION=$version" >> "$GITHUB_ENV"
- run: pnpm test
- run: pnpm build:ext
- run: pnpm audit:licenses
- name: Zip the extension
run: |
test "$(node -p "require('./dist-ext/manifest.json').version")" = "$VERSION"
(cd dist-ext && zip -qr "../narrata-extension-$VERSION.zip" .)
- name: Attach it to the release
env:
GH_TOKEN: ${{ github.token }}
run: |
if gh release view "$GITHUB_REF_NAME" > /dev/null 2>&1; then
gh release upload "$GITHUB_REF_NAME" "narrata-extension-$VERSION.zip" --clobber
else
gh release create "$GITHUB_REF_NAME" "narrata-extension-$VERSION.zip" --title "$GITHUB_REF_NAME" --generate-notes
fi
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ public/pdfjs
dist-ext
dist-ext-test
.e2e-profile*
.e2e-update-site
narrata-e2e-*.json
__pycache__
.bench-profile
Expand Down
29 changes: 20 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@

**Web app:** open [kernel-hunter.github.io/narrata](https://kernel-hunter.github.io/narrata/). Pick a voice, then try the sample, open a file or paste text. Nothing to install, though the browser can install it as an app.

**Chrome extension:** not in the Chrome Web Store yet. [Load it from the source](#chrome-extension) in a few steps.
**Chrome extension:** not in the Chrome Web Store yet. [Download it from the releases and load it](#chrome-extension) in a few steps.

<details>
<summary>Run it from the source</summary>
Expand Down Expand Up @@ -97,20 +97,29 @@ Most other Piper voices are fine-tuned from the "lessac" voice, whose recordings

## Privacy

Everything runs in your browser. The app downloads the voice you choose from Hugging Face the first time (and the other voice only if you pick it later). Apart from that it makes no network requests of its own: no analytics, no server, no account. Your documents, reading positions and settings stay in the browser's storage (IndexedDB, local storage and the Origin Private File System) and are never uploaded. Clearing the site data in your browser, or **Remove voice data** under More, About and storage, deletes them.
Everything runs in your browser. The app downloads the voice you choose from Hugging Face the first time (and the other voice only if you pick it later). While it is open, it also checks the site it was loaded from for a newer version (a small `version.json` file), and offers to reload when there is one. Apart from that it makes no network requests of its own: no analytics, no server, no account. Your documents, reading positions and settings stay in the browser's storage (IndexedDB, local storage and the Origin Private File System) and are never uploaded. Clearing the site data in your browser, or **Remove voice data** under More, About and storage, deletes them.

## Chrome extension

The extension reads web pages where they are, highlights the word being spoken on the page and tints the sentence. It uses the same voices as the web app, running inside the extension.

![Reading an article with the extension: the current word and sentence are highlighted on the page, with the floating player in the corner](docs/screenshots/ext-reading.png)

It is not in the Chrome Web Store yet. To install it from the source:
It is not in the Chrome Web Store yet. To install it:

1. Install [Node.js](https://nodejs.org/) 22 or newer and [pnpm](https://pnpm.io/installation).
2. Run `pnpm install` and then `pnpm build:ext` in this folder.
3. Open `chrome://extensions`, turn on **Developer mode**, click **Load unpacked** and pick the `dist-ext` folder.
4. On an article, click the Narrata button and choose **Read this page**, or press Alt+Shift+R. The first time, the player asks which voice to download.
1. Download `narrata-extension-<version>.zip` from the [latest release](https://github.com/Kernel-Hunter/narrata/releases/latest) and unzip it into a folder you will keep.
2. Open `chrome://extensions`, turn on **Developer mode**, click **Load unpacked** and pick that folder.
3. On an article, click the Narrata button and choose **Read this page**, or press Alt+Shift+R. The first time, the player asks which voice to download.

To build it yourself instead, install [Node.js](https://nodejs.org/) 22 or newer and [pnpm](https://pnpm.io/installation), run `pnpm install` and then `pnpm build:ext` in this folder, and load the `dist-ext` folder.

**Updating.** Chrome does not update extensions loaded this way. When a new version is out, the Narrata popup says so. To update:

1. Download the new zip from the release page.
2. Unzip it and copy its files over your Narrata folder.
3. In `chrome://extensions`, click the reload button on Narrata.

Keep the same folder. Chrome ties an unpacked extension to its folder, so loading a different one, or removing the extension, starts over without your settings and the downloaded voice.

What it does:

Expand All @@ -128,7 +137,7 @@ What it does:
| `storage` | Remember your speed, voice and model choice. |
| `contextMenus` | The right-click entries. |

There are no host permissions. The extension's content security policy allows network connections only to Hugging Face, for the voice download.
There are no host permissions. The extension's content security policy allows network connections only to Hugging Face, for the voice download, and to `api.github.com`, where the popup checks for a newer release at most once a day. The request sends nothing about what you read.

## Browser support

Expand Down Expand Up @@ -205,10 +214,12 @@ pnpm build:ext:test # extension with test hooks
pnpm audit:licenses # fails on GPL, LGPL or AGPL
```

`pnpm build:ext:test` builds the extension with hooks for automated checks, in `dist-ext-test/`. `pnpm audit:licenses` checks the licences of everything the builds contain.
`pnpm build:ext:test` builds the extension with hooks for automated checks, in `dist-ext-test/`. `node tests/e2e/verify-update.mjs` checks the web app's update notice against a local copy served the way GitHub Pages serves it, and `node tests/e2e/verify-ext-update.mjs` checks the one in the extension popup. `pnpm audit:licenses` checks the licences of everything the builds contain.

The production build uses relative paths, so `dist/` can be served from any path, such as `https://<user>.github.io/narrata/`. `.github/workflows/pages.yml` builds it and deploys it to GitHub Pages; `.github/workflows/ci.yml` runs the tests, type check, both builds and the licence audit on every push and pull request.

The version lives in `package.json`; `pnpm build:ext` copies it into the extension manifest. To publish the extension, bump it, then push a matching tag (`v0.2.0`): `.github/workflows/release.yml` builds the extension and attaches `narrata-extension-<version>.zip` to the GitHub release.

The G2P data in `src/engine/g2p/data/` is generated by the scripts in `scripts/g2p/`; each one explains its inputs at the top. `pnpm dev` and `pnpm build` copy the ONNX Runtime and pdf.js runtime files into `public/`, so the app never loads code from a CDN.

<details>
Expand Down
2 changes: 1 addition & 1 deletion extension/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,6 @@
"cross_origin_embedder_policy": { "value": "require-corp" },
"cross_origin_opener_policy": { "value": "same-origin" },
"content_security_policy": {
"extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; connect-src 'self' https://huggingface.co https://*.huggingface.co https://*.hf.co; default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; media-src 'self' blob:; worker-src 'self'"
"extension_pages": "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'; connect-src 'self' https://huggingface.co https://*.huggingface.co https://*.hf.co https://api.github.com; default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; media-src 'self' blob:; worker-src 'self'"
}
}
7 changes: 6 additions & 1 deletion extension/popup.html
Original file line number Diff line number Diff line change
Expand Up @@ -50,10 +50,15 @@
a { color: inherit; }
.links { display: grid; gap: 6px; }
footer { padding: 12px 16px 14px; color: var(--muted); font-size: 12px; }
#update { background: var(--surface); }
#update h2 { color: var(--ink); font-size: 13px; text-transform: none; letter-spacing: 0; }
#update ol { margin: 0 0 12px; padding-left: 18px; }
#update li { margin: 2px 0; }
</style>
</head>
<body>
<header><span id="logo"></span><h1>Narrata</h1></header>
<section id="update" hidden></section>
<section>
<h2>This page</h2>
<div id="page"><p class="muted">Checking…</p></div>
Expand All @@ -70,7 +75,7 @@ <h2>Shortcuts</h2>
<section class="links">
<a id="webapp" target="_blank" rel="noopener" href="#">PDFs, EPUBs and files: open them in the Narrata web app</a>
</section>
<footer>Private: the voice runs on this computer. The only network request Narrata makes is the one-time voice download from Hugging Face. Nothing you read leaves your browser.</footer>
<footer>Private: the voice runs on this computer. Narrata connects to Hugging Face to download the voice, once, and to GitHub once a day to check for a new version. Nothing you read leaves your browser.</footer>
<script type="module" src="./src/popup.ts"></script>
</body>
</html>
25 changes: 24 additions & 1 deletion extension/src/popup.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
// Toolbar popup: what is happening on this page, the voice download, shortcuts and privacy.
// Toolbar popup: a new version if there is one, what is happening on this page, the voice
// download, shortcuts and privacy.

import type { EngineInfo } from '../../src/engine/client';
import { downloadSize } from '../../src/engine/model-store';
import { icons, logo } from '../../src/ui/icons';
import { choiceHtml, isFirstRun } from './choice';
import { WEB_APP_URL } from './config';
import { type PopupEvent, type PopupRequest, type PopupStatus, envelope, isEnvelope } from './protocol';
import { type Release, availableUpdate } from './update';

const $ = <T extends HTMLElement = HTMLElement>(sel: string) => document.querySelector(sel) as T;
const mb = (n: number) => `${Math.round(n / 1e6)} MB`;
Expand Down Expand Up @@ -106,6 +108,26 @@ async function refresh() {
void renderEngine(s.engine);
}

/** The extension cannot update itself when loaded unpacked, so say how. */
function renderUpdate(release: Release) {
const box = $('#update');
const zip = `narrata-extension-${release.version}.zip`;
box.innerHTML = `<h2>Update available: v${release.version}</h2>
<ol><li>Download <strong>${zip}</strong> from the release page.</li><li>Unzip it and copy the files over your Narrata folder. Keep the same folder, so the voice stays downloaded.</li><li>In <a href="#" id="extensions-link">chrome://extensions</a>, click the reload button on Narrata.</li></ol>
<a class="btn" id="release-link" target="_blank" rel="noopener">${icons.download}<span>Open the release page</span></a>`;
$('#release-link').setAttribute('href', release.url);
$('#extensions-link').onclick = (e) => {
e.preventDefault();
void chrome.tabs.create({ url: 'chrome://extensions' });
};
box.hidden = false;
}

async function checkForUpdate() {
const release = await availableUpdate(chrome.runtime.getManifest().version, chrome.storage.local).catch(() => null);
if (release) renderUpdate(release);
}

async function shortcuts() {
const list = await chrome.commands.getAll();
const names: Record<string, string> = { 'read-page': 'Read this page', 'read-selection': 'Read selection', 'toggle-reading': 'Play or pause' };
Expand Down Expand Up @@ -136,6 +158,7 @@ async function init() {
const forced = Number(new URLSearchParams(location.search).get('tab'));
const [tab] = forced ? [] : await chrome.tabs.query({ active: true, currentWindow: true });
tabId = forced || (tab?.id ?? -1);
void checkForUpdate();
await Promise.all([refresh(), shortcuts()]);
setInterval(refresh, 1500);
}
Expand Down
77 changes: 77 additions & 0 deletions extension/src/update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
// Unpacked extensions cannot update themselves. The popup asks GitHub for the latest release, at
// most once a day (the answer is kept in chrome.storage), and offers it when it is newer than the
// version that is running. The request sends nothing about what they read.

export const RELEASES_API = 'https://api.github.com/repos/Kernel-Hunter/narrata/releases/latest';
const RELEASES_PAGE = 'https://github.com/Kernel-Hunter/narrata/releases/';
const KEY = 'update';
const DAY_MS = 24 * 60 * 60 * 1000;

export interface Release {
/** Without the leading v, as in the manifest. */
version: string;
/** The release page on GitHub. */
url: string;
}

interface Cached {
checkedAt: number;
latest: Release | null;
}

/** The part of chrome.storage.local this needs, so tests can pass a stand-in. */
export interface UpdateStorage {
get(key: string): Promise<Record<string, unknown>>;
set(items: Record<string, unknown>): Promise<void>;
}

const parts = (v: string) => v.replace(/^v/i, '').split('.').map((n) => Number.parseInt(n, 10) || 0);

/** True when `candidate` is a later version than `current` ("0.10.0" is later than "0.9.2"). */
export function isNewer(candidate: string, current: string): boolean {
const a = parts(candidate);
const b = parts(current);
for (let i = 0; i < Math.max(a.length, b.length); i++) {
const d = (a[i] ?? 0) - (b[i] ?? 0);
if (d !== 0) return d > 0;
}
return false;
}

/** The release in a GitHub API answer, or null if it is not a usable published release. */
export function parseRelease(data: unknown): Release | null {
if (!data || typeof data !== 'object') return null;
const r = data as { tag_name?: unknown; html_url?: unknown; draft?: unknown; prerelease?: unknown };
if (r.draft || r.prerelease || typeof r.tag_name !== 'string' || typeof r.html_url !== 'string') return null;
const version = r.tag_name.replace(/^v/i, '');
if (!/^\d+(\.\d+){0,3}$/.test(version)) return null;
// Only ever link to this repository's releases.
if (!r.html_url.startsWith(RELEASES_PAGE)) return null;
return { version, url: r.html_url };
}

/**
* The latest release, from storage if GitHub was asked less than a day ago. A failed request
* counts as a check too, so an unreachable GitHub is not asked on every popup.
*/
export async function latestRelease(storage: UpdateStorage, now = Date.now(), fetcher: typeof fetch = fetch): Promise<Release | null> {
const stored: Record<string, unknown> = await storage.get(KEY).catch(() => ({}));
const cached = stored[KEY] as Cached | undefined;
if (cached && typeof cached.checkedAt === 'number' && now - cached.checkedAt < DAY_MS && now >= cached.checkedAt) return cached.latest;
let latest: Release | null = cached?.latest ?? null;
try {
const res = await fetcher(RELEASES_API, { headers: { Accept: 'application/vnd.github+json' }, credentials: 'omit', cache: 'no-store' });
if (res.ok) latest = parseRelease(await res.json());
else if (res.status === 404) latest = null; // no release published yet
} catch {
// Offline: keep what was known.
}
await storage.set({ [KEY]: { checkedAt: now, latest } satisfies Cached }).catch(() => {});
return latest;
}

/** The release to offer, or null when the running version is the latest. */
export async function availableUpdate(current: string, storage: UpdateStorage, now = Date.now(), fetcher: typeof fetch = fetch): Promise<Release | null> {
const latest = await latestRelease(storage, now, fetcher);
return latest && isNewer(latest.version, current) ? latest : null;
}
15 changes: 14 additions & 1 deletion src/main.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import './styles/app.css';
import { onIsolationReady, registerServiceWorker, reloadForIsolation } from './pwa/register';
import { reloadForUpdate, watchForUpdates } from './pwa/update';
import { App } from './ui/app';
import { toast } from './ui/overlay';
import { notice, toast } from './ui/overlay';

const root = document.getElementById('app')!;

Expand All @@ -12,6 +13,18 @@ async function boot() {
const app = new App(root);
// The first install took very long and the app started single-threaded: offer the reload.
onIsolationReady(() => toast('Narrata is ready to use all processor cores.', { action: 'Reload', onAction: reloadForIsolation, ms: 60_000 }));
// A newer version was deployed while this page was open. Reload only when asked, so playback
// is never cut off; the document and the reading position are saved first.
watchForUpdates(() =>
notice('Narrata was updated. Reload to get the new version.', {
action: 'Reload',
className: 'update-notice',
onAction: async () => {
if (!(await app.prepareReload())) return false;
await reloadForUpdate();
},
}),
);
// Files opened with the installed app ("Open with Narrata").
const lq = (window as unknown as { launchQueue?: { setConsumer(cb: (p: { files: FileSystemFileHandle[] }) => void): void } }).launchQueue;
lq?.setConsumer(async (params) => {
Expand Down
3 changes: 3 additions & 0 deletions src/pwa/sw.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ const abs = (p) => new URL(p, self.registration.scope).href;
const revByUrl = new Map(Object.entries(REVS).map(([p, r]) => [abs(p), r]));
const assetsPrefix = abs('./assets/');
const appUrls = new Set([abs('./'), abs('./index.html')]);
const versionUrl = abs('./version.json');
/** URL without query or fragment, the key files are cached under. */
const keyOf = (url) => {
const u = new URL(url);
Expand Down Expand Up @@ -211,5 +212,7 @@ self.addEventListener('fetch', (event) => {
const url = new URL(req.url);
if (url.origin !== self.location.origin) return;
if (req.cache === 'only-if-cached' && req.mode !== 'same-origin') return;
// The page checks this file for a newer deploy, so it always comes from the network.
if (keyOf(req.url) === versionUrl) return;
event.respondWith(req.mode === 'navigate' ? navigate(req) : asset(req, event));
});
Loading
Loading