diff --git a/packages/runtime/src/featureModules.ts b/packages/runtime/src/featureModules.ts index 11f7b00..0987a5c 100644 --- a/packages/runtime/src/featureModules.ts +++ b/packages/runtime/src/featureModules.ts @@ -21,7 +21,7 @@ // (`selectors["."]`) or switch a feature off (`flags[""] = false`). import { isHeavyPath, observeSelector, watchDom, type DomWatch, type DomWatchHandle, type DomWindow } from './domHub.ts'; -import { areaFlag, type AreaSpec, type FeatureSpec, type FeatureTable, type Flags } from './featureTable.ts'; +import { HEALTH_COMMAND, areaFlag, healthKeywords, type AreaSpec, type FeatureSpec, type FeatureTable, type Flags } from './featureTable.ts'; import { formatMessage, type Params } from './i18n.ts'; import type { CommandDefinition } from './commands.ts'; import type { PluginI18n } from './pluginI18n.ts'; @@ -194,6 +194,7 @@ export function createFeatureRegistry(options: FeatureR const modules = new Map>(); const running = new Map>(); const areaScopes = new Map(); + const healthScopes = new Map(); const strikes = new Map(); const paused = new Map(); const waiting = new Map(); @@ -437,6 +438,18 @@ export function createFeatureRegistry(options: FeatureR scope.dispose(); areaScopes.delete(area.id); } + // A paused feature that would run (its flag and area are on) is named in the palette: the + // entry opens the notes, and the panel reads it for the feature's row (featureTable `pausedFeatures`). + const ids = [...paused.keys()].filter(id => specs.get(id)!.area === area.id && flags[id] === true).join(' '); + const shown = healthScopes.get(area.id); + if (shown && shown.ids !== ids) { shown.scope.dispose(); healthScopes.delete(area.id); } + if (ids && !healthScopes.has(area.id)) { + const created = api.commands.withOwner(area.owner, () => api.scope()); + healthScopes.set(area.id, { scope: created, ids }); + try { + created.commands.register({ id: HEALTH_COMMAND, title: text('kit.feature.pausedList', { area: area.name }), keywords: healthKeywords(ids.split(' ')), run: () => { openSettings(area.id); } }); + } catch (error) { console.error(`[${label}] ${area.name} health command failed`, error); } + } } } @@ -484,6 +497,8 @@ export function createFeatureRegistry(options: FeatureR for (const id of [...running.keys()]) stop(id); for (const scope of areaScopes.values()) scope.dispose(); areaScopes.clear(); + for (const shown of healthScopes.values()) shown.scope.dispose(); + healthScopes.clear(); modules.clear(); }, }; diff --git a/packages/runtime/src/featureTable.ts b/packages/runtime/src/featureTable.ts index ee3eae6..c6875aa 100644 --- a/packages/runtime/src/featureTable.ts +++ b/packages/runtime/src/featureTable.ts @@ -173,6 +173,29 @@ export function switchMode(table: FeatureTable, flags: Readonly, from: st return next; } +/** + * Feature health, as the panel learns it. A feature that paused itself (featureModules.ts: its + * selector probes failed) is named by its area's `health` palette command in the page: the entry + * opens the notes there, and its keywords carry the paused flags. The panel reads the focused + * tab's command list (it already has it for the palette), so no new report crosses to the host. + */ +export const HEALTH_COMMAND = 'health'; +const HEALTH_WORD = 'paused'; + +/** The keywords of an area's health command: the paused flags of that area. */ +export const healthKeywords = (ids: readonly string[]) => [HEALTH_WORD, ...ids].join(' '); + +/** The flags of `table` a tab's reported commands say are paused (unknown words are ignored). */ +export function pausedFeatures(table: FeatureTable, commands: ReadonlyArray<{ id: string; keywords?: string }> | null | undefined): Set { + const paused = new Set(); + for (const area of table.areas) { + const words = commands?.find(command => command.id === `${area.owner}:${HEALTH_COMMAND}`)?.keywords?.split(' ') ?? []; + if (words[0] !== HEALTH_WORD) continue; + for (const feature of table.features) if (feature.area === area.id && words.includes(feature.id)) paused.add(feature.id); + } + return paused; +} + /** The old plugin files the table's features replace, for the app's native migration list. */ export function supersededFiles(table: FeatureTable): { file: string; flag: string }[] { return table.features.filter(feature => feature.supersedes && feature.backing !== 'plugin').map(feature => ({ file: feature.supersedes!, flag: feature.id })); diff --git a/packages/runtime/src/ui.ts b/packages/runtime/src/ui.ts index a95dfd9..9ce2160 100644 --- a/packages/runtime/src/ui.ts +++ b/packages/runtime/src/ui.ts @@ -155,6 +155,7 @@ export const KIT_MESSAGES = { 'kit.save': 'Save', 'kit.feature.paused': '{feature} ({area}) is paused: this page changed.', 'kit.feature.pausedOne': 'A feature of {area} is paused: this page changed.', + 'kit.feature.pausedList': 'Paused features of {area}', 'kit.feature.needsEnglish': '{feature} needs the site in English.', 'kit.feature.settings': '{name} settings', } as const; diff --git a/packages/runtime/tests/features.test.ts b/packages/runtime/tests/features.test.ts index d167d66..1fc5d76 100644 --- a/packages/runtime/tests/features.test.ts +++ b/packages/runtime/tests/features.test.ts @@ -6,7 +6,7 @@ import test from 'node:test'; import { observeSelector, type DomWindow } from '../src/domHub.ts'; import { AREA_COMMAND_BUDGET, PROBE_STRIKES, createFeatureRegistry, type FeatureModule, type HotfixData } from '../src/featureModules.ts'; import { - areaFlag, effectiveFlags, manualChanges, modeFlags, normalizeFlags, sparseFlags, supersededFiles, switchMode, tableDefaults, validateTable, + areaFlag, effectiveFlags, manualChanges, modeFlags, normalizeFlags, pausedFeatures, sparseFlags, supersededFiles, switchMode, tableDefaults, validateTable, type FeatureTable, } from '../src/featureTable.ts'; import { createCorePluginApi, type CorePluginApi, type PluginApiSite } from '../src/pluginApi.ts'; @@ -369,8 +369,19 @@ test(`registry: a probe that matches nothing ${PROBE_STRIKES} visits in a row pa assert.deepEqual(registry.active(), ['navigation.keys'], 'the feature paused itself; the rest of the area runs'); assert.deepEqual(registry.health(), [{ id: 'hideTrends', area: 'navigation', state: 'paused', probes: ['module'] }]); assert.match(String(warnings[0]), /\[Demo\] hideTrends paused: nothing matches module/); + // The area says so in the palette; the panel reads which features from the same entry. + const health = env.api.commands.list().filter(command => command.id.endsWith(':health')); + assert.deepEqual(health, [{ id: 'wb-navigation-plus.plugin.js:health', title: 'Paused features of Navigation+', keywords: 'paused hideTrends' }]); + assert.deepEqual([...pausedFeatures(TABLE, env.api.commands.list())], ['hideTrends']); + assert.deepEqual([...pausedFeatures(TABLE, [{ id: 'wb-navigation-plus.plugin.js:health', keywords: 'paused hideAds nope navigation.keys' }])], ['navigation.keys'], 'only flags of that area'); + assert.deepEqual([...pausedFeatures(TABLE, [{ id: 'other.plugin.js:health', keywords: 'paused hideTrends' }]), ...pausedFeatures(TABLE, null)], []); registry.setFlags({ hideTrends: true, 'navigation.keys': true }); assert.deepEqual(registry.active(), ['navigation.keys'], 'paused for the session'); + // Turned off by its owner: nothing to report about it any more. + registry.setFlags({ 'navigation.keys': true }); + assert.deepEqual(env.api.commands.list(), []); + registry.setFlags({ hideTrends: true, 'navigation.keys': true }); + assert.equal(env.api.commands.list().length, 1); assert.equal(timers.pending(), 0, 'no timer left behind'); registry.dispose(); diff --git a/packages/shell/src/frame/pluginCommandStore.ts b/packages/shell/src/frame/pluginCommandStore.ts index 2d5f9f6..3c6a90e 100644 --- a/packages/shell/src/frame/pluginCommandStore.ts +++ b/packages/shell/src/frame/pluginCommandStore.ts @@ -9,6 +9,9 @@ import { isWeb, shell } from './state.ts'; type Reported = { id: string; title: string; keywords: string }; +/** Dispatched on `window` when a tab's reported commands changed. */ +export const COMMANDS_CHANGED = 'wb-tab-commands'; + const byTab = new Map(); let names: Record = {}; /** Owners that are not plugin files: an app's area plugins, by the owner id their commands carry. */ @@ -26,6 +29,8 @@ export function installPluginCommands(): () => void { if (!payload || typeof payload.id !== 'string') return; if (Array.isArray(payload.commands) && payload.commands.length) byTab.set(payload.id, payload.commands); else byTab.delete(payload.id); + // The panel's area cards show what a tab says about its features (a paused one). + window.dispatchEvent(new CustomEvent(COMMANDS_CHANGED)); }); void refreshPluginNames(); return () => { void off.then(dispose => dispose(), () => {}); }; diff --git a/packages/shell/src/panel/PluginFeatures.tsx b/packages/shell/src/panel/PluginFeatures.tsx index b811976..553f5af 100644 --- a/packages/shell/src/panel/PluginFeatures.tsx +++ b/packages/shell/src/panel/PluginFeatures.tsx @@ -4,11 +4,11 @@ // mode, owned by no plugin. Flags are the host's (`features_get/set`, stored sparsely); a feature // that is still an old plugin file is switched with `plugin_set_enabled`. import { useEffect, useRef, useState } from 'react'; -import { areaFlag, normalizeFlags, sparseFlags, type FeatureTable, type Flags } from '../../../runtime/src/featureTable.ts'; +import { areaFlag, normalizeFlags, pausedFeatures, sparseFlags, type FeatureTable, type Flags } from '../../../runtime/src/featureTable.ts'; import { invoke } from '../frame/bridge.ts'; import { useT } from '../frame/hooks.ts'; import { tx } from '../frame/i18n.ts'; -import { focusedCommands, runPluginCommand } from '../frame/pluginCommandStore.ts'; +import { COMMANDS_CHANGED, focusedCommands, runPluginCommand } from '../frame/pluginCommandStore.ts'; import { hasFeature } from '../frame/site.ts'; import { Badge, Button, Row, Section, Toggle, matchesQuery, useSettingsQuery } from './controls.tsx'; import { areaCards, fixRows, rowKeywords, type AreaCard, type FeatureRow, type PluginFileState } from './featureModel.ts'; @@ -63,6 +63,21 @@ function usePluginFiles(): [PluginFileState[], (list: PluginFileState[]) => void return [plugins, setPlugins]; } +/** The flags the focused site tab says paused themselves (its area's `health` palette entry). */ +function usePaused(table: FeatureTable): Set { + const [paused, setPaused] = useState(() => pausedFeatures(table, focusedCommands()?.items)); + useEffect(() => { + const read = () => setPaused(before => { + const next = pausedFeatures(table, focusedCommands()?.items); + return next.size === before.size && [...next].every(id => before.has(id)) ? before : next; + }); + read(); + window.addEventListener(COMMANDS_CHANGED, read); + return () => window.removeEventListener(COMMANDS_CHANGED, read); + }, [table]); + return paused; +} + /** The area cards and the Fixes list. Renders nothing for an app without a feature table. */ export function AreaPlugins({ notify }: { notify: Notify }) { const table = featureTable(); @@ -76,9 +91,10 @@ function AreaPluginsOf({ table, notify }: { table: FeatureTable; notify: Notify const [plugins, setPlugins] = usePluginFiles(); const [open, setOpen] = useState>({}); const [asking, setAsking] = useState(null); + const paused = usePaused(table); if (!flags) return null; - const cards = areaCards(table, flags, plugins); + const cards = areaCards(table, flags, plugins, paused); const fixes = fixRows(table, flags, panelSite().features?.elsewhere); const words = (row: FeatureRow) => ({ label: tx(row.label, undefined, row.spec.id), description: tx(row.description, undefined, '') }); const shown = (row: FeatureRow, card?: AreaCard) => !query || matchesQuery(query, words(row).label, words(row).description, rowKeywords(row, card?.area)); @@ -111,12 +127,14 @@ function AreaPluginsOf({ table, notify }: { table: FeatureTable; notify: Notify const locked = row.missing || (!!card && !card.enabled && row.kind === 'flag'); return {text.description} + {row.paused && {t('wb.features.paused')}} {copy && !row.on && {t('wb.features.ownCopy', { name: copy.name ?? copy.file })}} {asking === row.spec.id && copy && {t('wb.features.ownCopyAsk', { name: copy.name ?? copy.file })} }} badge={<> + {row.paused && {t('wb.features.pausedBadge')}} {row.isDefault && {t('wb.features.default')}} {card && row.spec.backing === 'app' && {t('wb.features.inApp')}} {row.kind === 'plugin' && {row.missing ? t('wb.features.missing') : t('wb.features.pluginFile')}} @@ -139,6 +157,7 @@ function AreaPluginsOf({ table, notify }: { table: FeatureTable; notify: Notify {card.enabled ? tx(card.area.description, undefined, '') : t('wb.features.off')}{card.total === 0 && ` ${t('wb.features.soon')}`} {card.total > 0 && } + {card.paused > 0 && {t('wb.features.pausedBadge')}} {card.settings && hasFeature('pluginCommands') && } void choose({ [areaFlag(card.area.id)]: next })}/> diff --git a/packages/shell/src/panel/featureModel.ts b/packages/shell/src/panel/featureModel.ts index dbf5bc1..f9a2009 100644 --- a/packages/shell/src/panel/featureModel.ts +++ b/packages/shell/src/panel/featureModel.ts @@ -26,6 +26,8 @@ export type FeatureRow = { ownCopy: PluginFileState | null; /** On unless the owner turned it off. */ isDefault: boolean; + /** On, but it paused itself in the focused site tab (the page changed under it). */ + paused: boolean; /** Catalog keys. */ label: string; description: string; @@ -42,9 +44,11 @@ export type AreaCard = { total: number; /** A feature with settings of its own is running: the card offers "Settings". */ settings: boolean; + /** How many of its features paused themselves in the focused site tab. */ + paused: number; }; -function rowOf(spec: FeatureSpec, flags: Readonly, plugins: ReadonlyArray): FeatureRow { +function rowOf(spec: FeatureSpec, flags: Readonly, plugins: ReadonlyArray, paused?: ReadonlySet): FeatureRow { const words = featureWords(spec); const file = spec.backing === 'plugin' ? plugins.find(plugin => plugin.file === spec.file) : undefined; const ownCopy = spec.backing !== 'plugin' && spec.supersedes ? plugins.find(plugin => plugin.file === spec.supersedes) ?? null : null; @@ -55,27 +59,32 @@ function rowOf(spec: FeatureSpec, flags: Readonly, plugins: ReadonlyArray missing: spec.backing === 'plugin' && !file, ownCopy, isDefault: spec.default, + paused: spec.backing !== 'plugin' && flags[spec.id] === true && !!paused?.has(spec.id), label: words.label, description: words.description, }; } -/** One card per area, in table order; rows keep the table's order inside their group. */ -export function areaCards(table: FeatureTable, flags: Readonly, plugins: ReadonlyArray): AreaCard[] { +/** + * One card per area, in table order; rows keep the table's order inside their group. `paused`: + * the flags the focused site tab reported as paused (runtime featureTable `pausedFeatures`). + */ +export function areaCards(table: FeatureTable, flags: Readonly, plugins: ReadonlyArray, paused?: ReadonlySet): AreaCard[] { return table.areas.map(area => { - const rows = areaFeatures(table, area.id).map(spec => rowOf(spec, flags, plugins)); + const enabled = flags[areaFlag(area.id)] !== false; + const rows = areaFeatures(table, area.id).map(spec => rowOf(spec, flags, plugins, enabled ? paused : undefined)); const groups: AreaCard['groups'] = []; for (const row of rows) { const id = row.spec.group ?? ''; const group = groups.find(item => item.id === id) ?? groups[groups.push({ id, rows: [] }) - 1]!; group.rows.push(row); } - const enabled = flags[areaFlag(area.id)] !== false; return { area, enabled, groups, rows, on: rows.filter(row => row.on).length, total: rows.length, settings: enabled && rows.some(row => row.spec.settings && row.on), + paused: rows.filter(row => row.paused).length, }; }); } diff --git a/packages/shell/src/panel/panelMessages.ts b/packages/shell/src/panel/panelMessages.ts index dbde832..6b78592 100644 --- a/packages/shell/src/panel/panelMessages.ts +++ b/packages/shell/src/panel/panelMessages.ts @@ -292,6 +292,8 @@ export const PANEL_MESSAGES = { 'wb.features.off': 'Off. Its features are paused; your choices are kept.', 'wb.features.ownCopy': 'You have your own copy of {name}, so the built-in feature is off.', 'wb.features.ownCopyAsk': 'Your own copy of {name} is on. Turn it off and use the built-in one?', + 'wb.features.paused': 'Paused in the open {site} tab: the page changed under it. Everything else keeps working; an update brings it back.', + 'wb.features.pausedBadge': 'paused', 'wb.features.pluginFile': 'plugin file', 'wb.features.settingsNoTab': 'Open a {site} tab first, then choose Settings again.', 'wb.features.soon': 'Its features arrive in a later update.', diff --git a/packages/shell/tests/panel.test.ts b/packages/shell/tests/panel.test.ts index 958cfc0..a2955ea 100644 --- a/packages/shell/tests/panel.test.ts +++ b/packages/shell/tests/panel.test.ts @@ -218,6 +218,12 @@ test('area cards: a feature is its flag or, until it is ported, its plugin file; assert.equal(own.rows[1]!.on, false, 'never both: the built-in feature stays off while their copy is on'); assert.match(rowKeywords(own.rows[1]!, own.area), /Focus Mode.*wb-focus-mode\.plugin\.js.*Navigation\+/, 'the search finds a feature by its old plugin name'); assert.deepEqual(fixRows(FEATURE_TABLE, flags, ['logo']).map(row => row.spec.id), ['fixScroll'], 'core flags, minus what has a control elsewhere'); + // A feature that paused itself in the focused tab: its row and its card say so, only while it would run. + const paused = new Set(['navigation.focusMode', 'hideTrends']); + const noted = areaCards(FEATURE_TABLE, flags, plugins, paused)[0]!; + assert.deepEqual([noted.paused, noted.rows.map(row => row.paused)], [1, [false, true]], 'the one that is off is not "paused"'); + assert.equal(navigation!.paused, 0); + assert.equal(areaCards(FEATURE_TABLE, { ...flags, 'area.navigation': false }, plugins, paused)[0]!.paused, 0, 'an area that is off runs nothing'); }); test('modes: a mode replaces the owner\'s changes or keeps them, old plugin files included', () => { diff --git a/packages/waybetter/locales/en.json b/packages/waybetter/locales/en.json index 268372a..8801dec 100644 --- a/packages/waybetter/locales/en.json +++ b/packages/waybetter/locales/en.json @@ -17,6 +17,7 @@ "kit.save": "Save", "kit.feature.paused": "{feature} ({area}) is paused: this page changed.", "kit.feature.pausedOne": "A feature of {area} is paused: this page changed.", + "kit.feature.pausedList": "Paused features of {area}", "kit.feature.needsEnglish": "{feature} needs the site in English.", "kit.feature.settings": "{name} settings", "wb.account.notSignedIn": "Not signed in yet", @@ -1105,6 +1106,8 @@ "wb.features.off": "Off. Its features are paused; your choices are kept.", "wb.features.ownCopy": "You have your own copy of {name}, so the built-in feature is off.", "wb.features.ownCopyAsk": "Your own copy of {name} is on. Turn it off and use the built-in one?", + "wb.features.paused": "Paused in the open {site} tab: the page changed under it. Everything else keeps working; an update brings it back.", + "wb.features.pausedBadge": "paused", "wb.features.pluginFile": "plugin file", "wb.features.settingsNoTab": "Open a {site} tab first, then choose Settings again.", "wb.features.useBuiltIn": "Use the built-in one",