diff --git a/apps/workbench/README.md b/apps/workbench/README.md index 117f9692bc..6666ae3519 100644 --- a/apps/workbench/README.md +++ b/apps/workbench/README.md @@ -208,6 +208,8 @@ npm test -w @calli/e2e -- --test-concurrency=1 test/smoke.spec.mjs ### 安装为桌面应用 -在 Chrome 中打开 LooChat 后,可通过浏览器菜单将它安装为应用。安装名称为 LooChat,图标使用蓝白配色的大小钳小螃蟹。 +在 macOS 或 Windows 的 Chrome 中打开 LoopX,浏览器允许安装时,侧栏底部会出现「安装 LoopX」。点击「安装」后,在 Chrome 弹窗中确认;网页不能跳过这次确认。安装后可从 Spotlight 或开始菜单打开独立窗口。 + +选择「以后再说」或取消安装后,7 天内不再主动提示;「配置 → 安装 LoopX」仍可手动进入。没有快捷安装按钮时,该页面会显示浏览器菜单安装说明。请使用 HTTPS(本机 localhost 也可);受管理的浏览器可能禁用安装。独立窗口仍需连接原来的 Workbench 服务,不提供离线 Agent 执行。 如果此前安装的应用仍显示 Limi、AgentHub 或旧图标,先尝试关闭所有应用窗口后重新打开,并接受 Chrome 提供的名称或图标更新。如果仍未更新,可卸载旧应用后从当前网页重新安装;卸载时不要勾选清除网站数据,以保留本机登录和偏好。 diff --git a/apps/workbench/packages/e2e/test/pwa-install.spec.mjs b/apps/workbench/packages/e2e/test/pwa-install.spec.mjs new file mode 100644 index 0000000000..b4bad5a1c2 --- /dev/null +++ b/apps/workbench/packages/e2e/test/pwa-install.spec.mjs @@ -0,0 +1,85 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { startDaemon, launchBrowser, openUi, api } from '../harness.mjs'; + +// Real packaged UI/backend; only browser-owned consent events are simulated. This does not +// certify OS installation on macOS or Windows. Screenshots contain synthetic conversations. +const shots = new URL('../../../../../output/playwright/pwa-install/', import.meta.url).pathname; +async function offer(page, outcome = 'dismissed', fail = false) { + await page.evaluate(({ outcome, fail }) => { + const event = new Event('beforeinstallprompt', { cancelable: true }); + event.prompt = () => { + window.installCalls = (window.installCalls ?? 0) + 1; + window.installClickedWithActivation = navigator.userActivation.isActive; + return fail ? Promise.reject(new Error('simulated browser refusal')) : Promise.resolve(); + }; + event.userChoice = Promise.resolve({ outcome }); + window.dispatchEvent(event); + }, { outcome, fail }); +} + +test('install entrypoints preserve consent, suppression, recovery and populated layouts', { timeout: 120000 }, async () => { + mkdirSync(shots, { recursive: true }); + const daemon = await startDaemon(); + const browser = await launchBrowser(); + try { + for (let i = 0; i < 18; i++) await api(daemon, '/api/threads', { + method: 'POST', body: JSON.stringify({ agent: 'pi', cwd: daemon.workdir, title: `Workspace review ${i + 1} — long conversation title for layout verification` }), + }); + for (const mobile of [false, true]) for (const theme of ['light', 'dark']) { + const context = await browser.newContext({ viewport: mobile ? { width: 390, height: 844 } : { width: 1440, height: 1000 }, isMobile: mobile, hasTouch: mobile, colorScheme: theme }); + const page = await context.newPage(); page.setDefaultTimeout(10000); + const errors = []; page.on('pageerror', error => errors.push(error.message)); + try { + // A synthetic expiring credential exercises the other standing footer notice. + await page.route('**/api/auth/kind', route => route.fulfill({ json: { kind: 'link', linkId: 'layout-fixture', expiresAt: new Date(Date.now() + 3600000).toISOString() } })); + await openUi(page, daemon); + await page.addStyleTag({ content: '*,*::before,*::after{animation:none!important;transition:none!important}' }); + if (!mobile && theme === 'light') { + const cdp = await context.newCDPSession(page); + const manifest = await cdp.send('Page.getAppManifest'); + assert.deepEqual(manifest.errors, [], 'the served manifest parses without errors'); + assert.equal(JSON.parse(manifest.data).name, 'LoopX'); + assert.deepEqual((await cdp.send('Page.getInstallabilityErrors')).installabilityErrors, []); + await cdp.detach(); + } + if (mobile) await page.getByRole('button', { name: '打开对话列表', exact: true }).click(); + await page.screenshot({ path: join(shots, `before-${mobile ? 'phone' : 'desktop'}-${theme}.png`) }); + await offer(page); + const promo = page.locator('.pwa-install-promo'); + await promo.waitFor(); + await page.locator('.sidebar-scroll').evaluate(el => { el.scrollTop = el.scrollHeight; }); + const [list, card] = await Promise.all([page.locator('.sidebar-scroll').boundingBox(), promo.boundingBox()]); + assert.ok(list.y + list.height <= card.y + 1, 'installation does not cover the populated list'); + assert.ok(card.x >= 0 && card.x + card.width <= (mobile ? 390 : 1440), 'card fits viewport'); + const notice = await page.locator('.link-login-notice').boundingBox(); + assert.ok(card.y + card.height <= notice.y + 1, 'installation does not cover the expiring-login notice'); + await page.screenshot({ path: join(shots, `after-${mobile ? 'phone' : 'desktop'}-${theme}.png`) }); + await promo.getByRole('button', { name: '以后再说' }).click(); + await promo.waitFor({ state: 'detached' }); + await page.locator('.sidebar').getByRole('button', { name: '配置', exact: true }).click(); + await page.locator('.settings-nav').getByRole('button', { name: '安装 LoopX', exact: true }).click(); + const settings = page.getByRole('region', { name: '安装 LoopX', exact: true }); + await settings.getByRole('button', { name: '安装', exact: true }).click(); + assert.equal(await page.evaluate(() => window.installCalls), 1); + assert.equal(await page.evaluate(() => window.installClickedWithActivation), true); + await settings.getByText('浏览器尚未提供快捷安装。', { exact: false }).waitFor(); + await page.reload(); await settings.waitFor(); await offer(page); + assert.equal(await promo.count(), 0, 'dismissal survives reload and renewed offers'); + await offer(page, 'dismissed', true); + await settings.getByRole('button', { name: '安装', exact: true }).click(); + await settings.getByRole('alert').waitFor(); + await page.screenshot({ path: join(shots, `recovery-${mobile ? 'phone' : 'desktop'}-${theme}.png`) }); + await offer(page, 'accepted'); + await settings.getByRole('button', { name: '安装', exact: true }).click(); + await settings.getByRole('status').filter({ hasText: '已接受安装' }).waitFor(); + await page.evaluate(() => window.dispatchEvent(new Event('appinstalled'))); + await settings.getByRole('status').filter({ hasText: '已安装' }).waitFor(); + assert.equal(await settings.getByRole('button', { name: '安装', exact: true }).count(), 0); + assert.deepEqual(errors, []); + } finally { await context.close(); } + } + } finally { await browser.close(); await daemon.stop(); } +}); diff --git a/apps/workbench/packages/web/public/manifest.webmanifest b/apps/workbench/packages/web/public/manifest.webmanifest index bebbeee3ae..c1c3c5c703 100644 --- a/apps/workbench/packages/web/public/manifest.webmanifest +++ b/apps/workbench/packages/web/public/manifest.webmanifest @@ -11,6 +11,18 @@ "background_color": "#f8f6f1", "theme_color": "#f8f6f1", "icons": [ + { + "src": "/pwa/icon-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "any" + }, + { + "src": "/pwa/icon-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "any" + }, { "src": "/loochat-icon.png?v=crab-1", "sizes": "1024x1024", diff --git a/apps/workbench/packages/web/public/pwa/icon-192.png b/apps/workbench/packages/web/public/pwa/icon-192.png new file mode 100644 index 0000000000..ed9957d940 Binary files /dev/null and b/apps/workbench/packages/web/public/pwa/icon-192.png differ diff --git a/apps/workbench/packages/web/public/pwa/icon-512.png b/apps/workbench/packages/web/public/pwa/icon-512.png new file mode 100644 index 0000000000..26cc2db73c Binary files /dev/null and b/apps/workbench/packages/web/public/pwa/icon-512.png differ diff --git a/apps/workbench/packages/web/src/App.tsx b/apps/workbench/packages/web/src/App.tsx index ef022d1912..f41b92a972 100644 --- a/apps/workbench/packages/web/src/App.tsx +++ b/apps/workbench/packages/web/src/App.tsx @@ -94,6 +94,7 @@ import { SchedulesPage } from './components/SchedulesPage'; import { GoalWorkPage, GOAL_TABS, type GoalTab } from './components/GoalWorkPage'; import { GoalsPage, type GoalsFilter } from './components/GoalsPage'; import { AccessSettings } from './components/AccessSettings'; +import { PwaInstallPromotion, PwaInstallSettings } from './components/PwaInstall'; import { LinkLoginNotice, useAuthKind } from './components/LinkLoginNotice'; import { StewardActions, StewardPage } from './components/StewardPage'; import { SidebarGoals, useLoopxStatus } from './components/SidebarGoals'; @@ -133,7 +134,7 @@ import { ConnectDialog, DemoBar } from './components/ConnectDialog'; import { DemoApi, DemoError } from './demo/DemoApi'; import { EMPTY_MODEL_PREFERENCE, type DraftModelPreference } from '../../daemon/src/model-preferences'; import { QUICK_SWITCH_HIDDEN_KEY, clampQuickSwitchBottom, savedQuickSwitchBottom, saveQuickSwitchBottom } from './quick-switch'; -import { IconCheck, IconBell, AgentMark, IconActivity, IconAgents, IconArchive, IconArrowLeft, IconArrowDown, IconBack, IconClose, IconEdit, IconFolder, IconGauge, IconGlobe, IconList, IconMenu, IconSettings, IconMore, IconOverview, IconPalette, IconPlus, IconPuzzle, IconServer, IconShield, IconSidebar, IconSignIn, IconSignOut, IconSparkle, IconTerminal, IconTrace, IconLanguage, IconWaveform, IconSideChat } from './components/icons'; +import { IconDownload, IconCheck, IconBell, AgentMark, IconActivity, IconAgents, IconArchive, IconArrowLeft, IconArrowDown, IconBack, IconClose, IconEdit, IconFolder, IconGauge, IconGlobe, IconList, IconMenu, IconSettings, IconMore, IconOverview, IconPalette, IconPlus, IconPuzzle, IconServer, IconShield, IconSidebar, IconSignIn, IconSignOut, IconSparkle, IconTerminal, IconTrace, IconLanguage, IconWaveform, IconSideChat } from './components/icons'; import { StatReadings } from './components/SessionStats'; import { ThreadTracePanel } from './components/TracePanel'; import { chooseLocale, locale, LOCALES, localeChoice, t } from './i18n'; @@ -2829,6 +2830,7 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } { label: t('settings.preferences'), entries: [ ...(!demo ? [{ id: 'general', label: t('general.title'), icon: IconSettings, render: () => { setStartupSettings(value); setExternalNonce(n => n + 1); }} onClose={closeSettings} /> }] : []), { id: 'appearance', label: t('appearance.title'), icon: IconPalette, render: () => }, + ...(!showcase ? [{ id: 'install', label: t('pwa.title'), icon: IconDownload, render: () => }] : []), { id: 'language', label: t('locale.menu'), icon: IconLanguage, render: () =>
{[{ id: 'system' as const, name: t('locale.system') }, ...LOCALES].map(l => )}
}, @@ -3020,7 +3022,10 @@ function Hub({ token, onToken, connect, hostId = null, onHost, start, showcase } schedulesActive={onSchedules} extensionNav={extensionNav} notice={demo && compact ? showcase ? showcase.notice(selectedId, extWant) : : undefined} - footerNotice={authKind?.kind === 'link' && !showcase ? openSettings('access')} /> : undefined} + footerNotice={!showcase ? <> + openSettings('install')} /> + {authKind?.kind === 'link' && openSettings('access')} />} + : undefined} /> {!compact && !sidebarHidden && ( diff --git a/apps/workbench/packages/web/src/components/PwaInstall.tsx b/apps/workbench/packages/web/src/components/PwaInstall.tsx new file mode 100644 index 0000000000..6e0bdaa1a4 --- /dev/null +++ b/apps/workbench/packages/web/src/components/PwaInstall.tsx @@ -0,0 +1,48 @@ +import { useSyncExternalStore } from 'react'; +import { createPwaInstall } from '../pwa-install'; +import { t } from '../i18n'; +import { SettingsSection } from './PageNavigation'; +import { IconDownload } from './icons'; + +// Capture eligibility before React mounts, and share one single-use offer across both entrypoints. +const install = typeof window !== 'undefined' && typeof window.matchMedia === 'function' ? createPwaInstall(window) : null; +if (import.meta.hot) import.meta.hot.dispose(() => install?.dispose()); +const empty = { available: false, installed: false, busy: false, accepted: false, failed: false, dismissedUntil: 0 }; +const snapshot = () => install?.getSnapshot() ?? empty; +const subscribe = (listener: () => void) => install?.subscribe(listener) ?? (() => {}); +const useInstall = () => useSyncExternalStore(subscribe, snapshot); + +export function PwaInstallPromotion({ onHelp }: { onHelp: () => void }) { + const state = useInstall(); + if (state.installed || state.dismissedUntil > Date.now() || (!state.available && !state.busy && !state.failed)) return null; + return
+ {t('pwa.title')} +

{t('pwa.hint')}

+ {state.failed &&

{t('pwa.failed')}

} +
+ {state.failed + ? + : } + +
+
; +} + +export function PwaInstallSettings() { + const state = useInstall(); + const secure = typeof window !== 'undefined' && window.isSecureContext; + return + {state.installed ?

{t('pwa.installed')}

: <> + {state.failed &&

{t('pwa.failed')}

} + {state.accepted &&

{t('pwa.accepted')}

} + {state.available || state.busy + ? + : !state.accepted &&

{t(secure ? 'pwa.unavailable' : 'pwa.insecure')}

} +
+ {t('pwa.help')} +

{t('pwa.chrome')}

+

{t('pwa.launch')}

+
+ } +
; +} diff --git a/apps/workbench/packages/web/src/i18n/locales/en.ts b/apps/workbench/packages/web/src/i18n/locales/en.ts index 7156c9c75e..87d7cc3f0a 100644 --- a/apps/workbench/packages/web/src/i18n/locales/en.ts +++ b/apps/workbench/packages/web/src/i18n/locales/en.ts @@ -3,6 +3,20 @@ import type { Messages } from './zh'; const plural = (n: number, one: string, other: string) => `${n} ${n === 1 ? one : other}`; export const en: Messages = { + "pwa.title": "Install LoopX", + "pwa.hint": "Open in its own window, ready to launch from your computer.", + "pwa.install": "Install", + "pwa.later": "Not now", + "pwa.prompting": "Confirm in Chrome…", + "pwa.help": "Installation help", + "pwa.failed": "Installation could not start. Try the browser menu.", + "pwa.installed": "Installed. Open LoopX from your computer’s app list.", + "pwa.accepted": "Installation accepted. Waiting for Chrome to finish.", + "pwa.unavailable": "The browser has not offered quick installation. Try the Chrome menu; if already installed, open LoopX from your app list.", + "pwa.insecure": "Open this site over HTTPS or local localhost, then try installing again.", + "pwa.chrome": "In Chrome on macOS or Windows, use the address bar’s install icon, or find “Cast, save, and share” → “Install page as app” in the menu. Labels vary by Chrome version; managed browsers may disable installation.", + "pwa.launch": "After installing, find LoopX with Spotlight on Mac or the Windows Start menu. You can pin it to the Dock or taskbar yourself. Installation does not make the remote service available offline.", + "references.message": (value: string) => `Message · ${value}`, "references.messageHint": "A snapshot of this message for the agent to read as needed.", "messageActions.context": "Use as context", diff --git a/apps/workbench/packages/web/src/i18n/locales/ja.ts b/apps/workbench/packages/web/src/i18n/locales/ja.ts index 112ce07dfd..decb98df2a 100644 --- a/apps/workbench/packages/web/src/i18n/locales/ja.ts +++ b/apps/workbench/packages/web/src/i18n/locales/ja.ts @@ -1,6 +1,20 @@ import type { Messages } from './zh'; export const ja: Messages = { + "pwa.title": "LoopX をインストール", + "pwa.hint": "独立したウィンドウで開き、パソコンからすぐに起動できます。", + "pwa.install": "インストール", + "pwa.later": "後で", + "pwa.prompting": "Chrome で確認してください…", + "pwa.help": "インストール方法", + "pwa.failed": "インストールを開始できませんでした。ブラウザのメニューから再試行してください。", + "pwa.installed": "インストール済みです。パソコンのアプリ一覧から LoopX を開けます。", + "pwa.accepted": "インストールを承認しました。Chrome の処理をお待ちください。", + "pwa.unavailable": "ブラウザからインストールの案内がまだ届いていません。Chrome のメニューをお試しください。インストール済みならアプリ一覧から開けます。", + "pwa.insecure": "HTTPS またはローカルの localhost で開いてから、再度インストールしてください。", + "pwa.chrome": "macOS または Windows の Chrome で、アドレスバーのインストールアイコン、またはメニューの「キャスト、保存、共有」→「ページをアプリとしてインストール」を選びます。名称は Chrome のバージョンによって異なります。管理対象のブラウザではインストールが禁止されている場合があります。", + "pwa.launch": "インストール後は Mac の Spotlight または Windows のスタートメニューで LoopX を検索できます。Dock やタスクバーへの固定は手動で行えます。リモートサービスがオフラインで使えるようになるわけではありません。", + "references.message": (value: string) => `メッセージ · ${value}`, "references.messageHint": "このメッセージの本文を保存し、必要に応じてエージェントが読みます。", "messageActions.context": "コンテキストにする", diff --git a/apps/workbench/packages/web/src/i18n/locales/zh.ts b/apps/workbench/packages/web/src/i18n/locales/zh.ts index ea08558610..ac1b50a94f 100644 --- a/apps/workbench/packages/web/src/i18n/locales/zh.ts +++ b/apps/workbench/packages/web/src/i18n/locales/zh.ts @@ -3,6 +3,20 @@ * a key added here has to be added to them too. Messages with values are functions. */ export const zh = { + "pwa.title": "安装 LoopX", + "pwa.hint": "用独立窗口打开,随时从电脑启动。", + "pwa.install": "安装", + "pwa.later": "以后再说", + "pwa.prompting": "请在 Chrome 中确认…", + "pwa.help": "安装说明", + "pwa.failed": "安装未能启动,请通过浏览器菜单重试。", + "pwa.installed": "已安装,可从电脑的应用列表打开 LoopX。", + "pwa.accepted": "已接受安装,请等待 Chrome 完成。", + "pwa.unavailable": "浏览器尚未提供快捷安装。可以尝试从 Chrome 菜单安装;如果已安装,直接从应用列表打开。", + "pwa.insecure": "请通过 HTTPS 或本机 localhost 打开,再尝试安装。", + "pwa.chrome": "在 macOS 或 Windows 的 Chrome 中,点击地址栏的安装图标,或在菜单中找到「投放、保存和分享」→「将网页安装为应用」。菜单名称可能随 Chrome 版本变化;受管理的浏览器可能禁用安装。", + "pwa.launch": "安装后可在 Mac 的 Spotlight 或 Windows 开始菜单搜索 LoopX,也可以自行固定到 Dock 或任务栏。安装不会让远程服务离线可用。", + "references.message": (value: string) => `消息 · ${value}`, "references.messageHint": "保存这条消息的正文快照,供 agent 按需读取。", "messageActions.context": "作为上下文", diff --git a/apps/workbench/packages/web/src/pwa-install.ts b/apps/workbench/packages/web/src/pwa-install.ts new file mode 100644 index 0000000000..c63928e689 --- /dev/null +++ b/apps/workbench/packages/web/src/pwa-install.ts @@ -0,0 +1,86 @@ +/** The browser owns eligibility and consent; these are only the page's presentation states. */ +interface InstallPrompt extends Event { + prompt(): Promise; + userChoice: Promise<{ outcome: 'accepted' | 'dismissed' }>; +} + +const DISMISSED_KEY = 'loopx.install.dismissedUntil'; +const WEEK = 7 * 24 * 60 * 60 * 1000; + +export function createPwaInstall(browser: Window) { + const modes = ['standalone', 'window-controls-overlay'].map(mode => browser.matchMedia(`(display-mode: ${mode})`)); + const standalone = () => modes.some(mode => mode.matches); + const readDismissed = () => { + try { + const value = Number(browser.localStorage.getItem(DISMISSED_KEY)); + return Number.isFinite(value) ? value : 0; + } catch { return 0; } + }; + let prompt: InstallPrompt | null = null; + let observedInstall = false; + let state = { available: false, installed: standalone(), busy: false, accepted: false, failed: false, dismissedUntil: readDismissed() }; + const listeners = new Set<() => void>(); + const update = (patch: Partial) => { + state = { ...state, ...patch }; + listeners.forEach(listener => listener()); + }; + const dismiss = () => { + const dismissedUntil = Date.now() + WEEK; + try { browser.localStorage.setItem(DISMISSED_KEY, String(dismissedUntil)); } catch { /* Session-only when storage is unavailable. */ } + update({ dismissedUntil }); + }; + const onPrompt = (event: Event) => { + if (!browser.isSecureContext || standalone()) return; + event.preventDefault(); + prompt = event as InstallPrompt; + // A fresh browser offer also recovers from an uninstall in another window. + observedInstall = false; + update({ available: true, installed: false, accepted: false, failed: false }); + }; + const onInstalled = () => { + observedInstall = true; + prompt = null; + update({ installed: true, available: false, busy: false, accepted: false, failed: false }); + }; + const onMode = () => { + if (standalone()) prompt = null; + update({ installed: observedInstall || standalone(), available: prompt !== null }); + }; + const onStorage = (event: StorageEvent) => { + if (event.key === DISMISSED_KEY || event.key === null) update({ dismissedUntil: readDismissed() }); + }; + browser.addEventListener('beforeinstallprompt', onPrompt); + browser.addEventListener('appinstalled', onInstalled); + browser.addEventListener('storage', onStorage); + modes.forEach(mode => mode.addEventListener('change', onMode)); + return { + getSnapshot: () => state, + subscribe: (listener: () => void) => { listeners.add(listener); return () => { listeners.delete(listener); }; }, + dismiss, + async install() { + if (!prompt || state.busy || state.installed) return; + const offer = prompt; + prompt = null; // Each event is single-use, including failed or canceled prompts. + update({ available: false, busy: true, failed: false, accepted: false }); + try { + // Must run in the button's click handler, before any await loses user activation. + await offer.prompt(); + const choice = await offer.userChoice; + if (state.installed) return; // appinstalled may arrive before userChoice. + if (choice.outcome === 'dismissed') dismiss(); + update({ accepted: choice.outcome === 'accepted' }); + } catch { + if (!state.installed) update({ failed: true }); + } finally { + update({ busy: false }); + } + }, + dispose() { + browser.removeEventListener('beforeinstallprompt', onPrompt); + browser.removeEventListener('appinstalled', onInstalled); + browser.removeEventListener('storage', onStorage); + modes.forEach(mode => mode.removeEventListener('change', onMode)); + listeners.clear(); + }, + }; +} diff --git a/apps/workbench/packages/web/src/styles.css b/apps/workbench/packages/web/src/styles.css index fd67ab3fa1..e8266fe9f8 100644 --- a/apps/workbench/packages/web/src/styles.css +++ b/apps/workbench/packages/web/src/styles.css @@ -4507,6 +4507,32 @@ input.picker-search { margin-left: auto; } +/* Install offers reserve space instead of covering the last conversations or access notice. */ +.sidebar-inner:has(.pwa-install-promo) .sidebar-scroll { padding-bottom: 12px; } +.sidebar-float:has(.pwa-install-promo) { + position: static; + flex-shrink: 0; + flex-wrap: wrap; + gap: 8px; + padding-top: 8px; +} +.sidebar-float:has(.pwa-install-promo) .link-login-notice { position: static; width: 100%; } +.pwa-install-promo { + width: 100%; + padding: 12px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface); + font-size: 12px; + line-height: 1.5; +} +.pwa-install-promo strong { display: flex; align-items: center; gap: 8px; font-size: 13px; } +.pwa-install-promo p { color: var(--muted); margin: 6px 0 10px; } +.pwa-install-actions { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; } +.pwa-install-actions button { min-height: 32px; padding: 5px 10px; font-size: 12px; } +.pwa-install-help { margin-top: 20px; color: var(--muted); line-height: 1.7; } +.pwa-install-help summary { cursor: pointer; color: var(--text); } + /* ---------- Sidebar on a phone ---------- */ /* A page of its own, laid out for thumbs: large rows, round buttons, the one main action floating diff --git a/apps/workbench/packages/web/test/pwa-install.test.ts b/apps/workbench/packages/web/test/pwa-install.test.ts new file mode 100644 index 0000000000..cb4093a69b --- /dev/null +++ b/apps/workbench/packages/web/test/pwa-install.test.ts @@ -0,0 +1,125 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { createPwaInstall } from '../src/pwa-install'; + +function fixture({ secure = true, standalone = false, storageBlocked = false } = {}) { + const values = new Map(); + const modes = new Map(); + const browser = Object.assign(new EventTarget(), { + isSecureContext: secure, + matchMedia: (query: string) => { + if (!modes.has(query)) modes.set(query, Object.assign(new EventTarget(), { matches: standalone && query.includes(': standalone)') })); + return modes.get(query)!; + }, + localStorage: { + getItem: (key: string) => { if (storageBlocked) throw new Error('blocked'); return values.get(key) ?? null; }, + setItem: (key: string, value: string) => { if (storageBlocked) throw new Error('blocked'); values.set(key, value); }, + }, + }); + const store = createPwaInstall(browser as unknown as Window); + let calls = 0; + function offer(outcome: 'accepted' | 'dismissed' = 'dismissed', fail = false) { + const event = Object.assign(new Event('beforeinstallprompt', { cancelable: true }), { + prompt: () => { calls++; return fail ? Promise.reject(new Error('blocked')) : Promise.resolve(); }, + userChoice: Promise.resolve({ outcome }), + }); + browser.dispatchEvent(event); + return event; + } + return { browser, store, offer, modes, values, calls: () => calls }; +} + +test('eligibility comes from the browser; clicking consumes the event synchronously and only once', async () => { + const f = fixture(); + assert.equal(f.store.getSnapshot().available, false); + assert.equal(f.offer().defaultPrevented, true); + const installing = f.store.install(); + assert.equal(f.calls(), 1, 'native prompt is invoked within user activation'); + await f.store.install(); + await installing; + assert.equal(f.calls(), 1); + assert.equal(f.store.getSnapshot().installed, false); + assert.ok(f.store.getSnapshot().dismissedUntil > Date.now() + 6.9 * 86400000); + const reloaded = createPwaInstall(f.browser as unknown as Window); + assert.equal(reloaded.getSnapshot().dismissedUntil, f.store.getSnapshot().dismissedUntil); + reloaded.dispose(); f.store.dispose(); +}); + +test('not now suppresses promotion but keeps the explicit settings install usable', async () => { + const f = fixture(); f.offer('accepted'); f.store.dismiss(); + assert.equal(f.store.getSnapshot().available, true); + await f.store.install(); + assert.equal(f.store.getSnapshot().accepted, true); + assert.equal(f.store.getSnapshot().installed, false, 'consent alone is not installation success'); + f.browser.dispatchEvent(new Event('appinstalled')); + assert.equal(f.store.getSnapshot().installed, true); + assert.equal(f.store.getSnapshot().accepted, false); + f.store.dispose(); +}); + +test('an early success receipt is not overwritten by a later prompt result', async () => { + const f = fixture(); f.offer('accepted'); + const installing = f.store.install(); + f.browser.dispatchEvent(new Event('appinstalled')); + await installing; + assert.equal(f.store.getSnapshot().installed, true); + assert.equal(f.store.getSnapshot().accepted, false); + assert.equal(f.store.getSnapshot().busy, false); + f.store.dispose(); +}); + +test('a failed prompt is not reused and a fresh browser offer can recover', async () => { + const f = fixture(); f.offer('dismissed', true); await f.store.install(); + assert.equal(f.store.getSnapshot().failed, true); + await f.store.install(); assert.equal(f.calls(), 1); + f.offer('accepted'); assert.equal(f.store.getSnapshot().failed, false); + await f.store.install(); assert.equal(f.calls(), 2); + f.store.dispose(); +}); + +test('standalone and titlebar-overlay windows suppress installation, including a live mode switch', () => { + const f = fixture({ standalone: true }); f.offer(); + assert.equal(f.store.getSnapshot().installed, true); + assert.equal(f.store.getSnapshot().available, false); + const standalone = f.modes.get('(display-mode: standalone)')!; + standalone.matches = false; standalone.dispatchEvent(new Event('change')); + f.offer(); assert.equal(f.store.getSnapshot().available, true); + const overlay = f.modes.get('(display-mode: window-controls-overlay)')!; + overlay.matches = true; overlay.dispatchEvent(new Event('change')); + assert.equal(f.store.getSnapshot().installed, true); + assert.equal(f.store.getSnapshot().available, false); + f.store.dispose(); +}); + +test('unsafe origins cannot offer installation; blocked storage still allows session suppression', async () => { + const unsafe = fixture({ secure: false }); unsafe.offer(); + await unsafe.store.install(); assert.equal(unsafe.calls(), 0); unsafe.store.dispose(); + const f = fixture({ storageBlocked: true }); f.offer(); f.store.dismiss(); + assert.ok(f.store.getSnapshot().dismissedUntil > Date.now()); + await f.store.install(); assert.equal(f.calls(), 1); f.store.dispose(); +}); + +test('dismissal synchronizes across tabs, expired values do not suppress, disposal releases listeners', () => { + const f = fixture(); f.values.set('loopx.install.dismissedUntil', '1'); + f.browser.dispatchEvent(Object.assign(new Event('storage'), { key: 'loopx.install.dismissedUntil' })); + assert.equal(f.store.getSnapshot().dismissedUntil, 1); + f.values.set('loopx.install.dismissedUntil', 'NaN'); + f.browser.dispatchEvent(Object.assign(new Event('storage'), { key: null })); + assert.equal(f.store.getSnapshot().dismissedUntil, 0); + f.store.dispose(); f.offer(); assert.equal(f.store.getSnapshot().available, false); +}); + +test('install metadata retains stable app identity and supplies real 192/512 PNGs', () => { + const root = new URL('../public/', import.meta.url); + const manifest = JSON.parse(readFileSync(new URL('manifest.webmanifest', root), 'utf8')); + assert.equal(manifest.id, '/'); assert.equal(manifest.start_url, '/'); + assert.equal(manifest.display, 'standalone'); + for (const size of [192, 512]) { + const icon = manifest.icons.find((icon: { sizes: string }) => icon.sizes === `${size}x${size}`); + assert.ok(icon); + const png = readFileSync(new URL(icon.src.slice(1), root)); + assert.equal(png.subarray(1, 4).toString(), 'PNG'); + assert.equal(png.readUInt32BE(16), size); assert.equal(png.readUInt32BE(20), size); + } +});