// Development-only harness: renders the real shell chrome (titlebar, dockview tabs, address bars, // menus, palette, pickers) in a plain browser (`vite dev`, then open `/?shell`) with native commands // mocked in memory and fake tabs, for visual review at any width. There are no tab webviews, so // each pane shows its placeholder. Not bundled into production (main.tsx imports it only in DEV). // // Query parameters: // tabs=N number of fake tabs in the first group (default 6) // split a second group on the right // pinned=N pin the first N tabs (default 2) // loading mark the second unpinned tab as loading // profiles=N number of accounts (1..4, default 3) // update=ready|installing|problem (check=ok: the app menu's "Check for updates" finds the app up to date; default: no answer) // open=palette|accounts|menu|drafts|media|newtab|empty // q=text palette query // deck=N Power User Mode: a deck of N columns (open=deck shows it, open=addcol its dialog) // unread with deck: fake unread counts on some columns // open=install a waybetter://install link arrives (kind=plugin|theme, src=; not `url=`, which vite reserves) // open=install-error a link that native code refused // open=appmenu the app menu ("Settings and more"); sub=language|theme|mode|workspaces|developer opens that submenu // safe=on safe mode for this run (the titlebar chip; the chrome drops its theme) // theme= the global theme; mode= the mode in use; changed: flags changed by hand (the Mode submenu asks) // open=workspaces the titlebar workspace menu (ws=N saved ones, wsactive=); open=wssave its save field // commands the focused X tab reports plugin commands (open=palette lists them under each plugin) // dev=on|errors, sync=newer developer mode / synced-settings chips (see settingsMocks.ts) import { bridge } from '../../bridge/index'; import { installPreviewMocks } from '../../../../../waybetter/packages/shell/src/frame/bridge.ts'; import type { Draft } from '../../core/types'; import { storeHandlers } from './storeMocks'; import { SAMPLE_COMMANDS, SAMPLE_PLUGIN_NAMES, settingsHandlers } from './settingsMocks'; type Handler = (args: Record) => unknown; const params = new URLSearchParams(location.search); const svg = (body: string, bg = 'none') => `data:image/svg+xml,${encodeURIComponent(`${body}`)}`; const X_ICON = svg('', '#000'); const GH_ICON = svg('', '#161b22'); const NEWS_ICON = svg('', '#b3261e'); // Accounts as native code reports them: two signed in, one signed out on X, one never signed in. const PROFILES = [ { id: 'default', name: 'Main', color: '#1d9bf0', account: { handle: 'CRTkafa', name: 'CRT kafa', signedIn: true } }, { id: 'pwork1', name: 'wayBetter for X', color: '#7856ff', account: { handle: 'playfishies', name: 'Fishies', signedIn: true } }, { id: 'pmemes1', name: 'Shitposts', color: '#f91880', account: { handle: 'oldshitposts', name: 'Shitposts', signedIn: false } }, { id: 'pnews01', name: 'New account', color: '#00ba7c' }, ].slice(0, Math.min(4, Math.max(1, Number(params.get('profiles') ?? 3)))); const state = { profiles: { profiles: PROFILES, active: 'default' }, tabProfiles: [] as string[], /** Last tabs_sync payload and column configs, for scripts (scripts/deck-check.mjs). */ sync: [] as unknown[], columns: {} as Record, zoom: {} as Record, navigations: 0, find: { count: 0, index: -1 }, safe: params.get('safe') === 'on', features: (params.has('changed') ? { hidePromotedPosts: true, hideViewCounts: true } : {}) as Record, modes: { mode: params.get('mode'), onboarded: !params.has('onboard'), existing: true } as { mode: string | null; onboarded: boolean; existing: boolean; preset?: Record | null }, theme: (params.get('theme') ? { preset: params.get('theme') } : null) as unknown, media: { folders: ['C:\\Users\\you\\Pictures\\Screenshots'], clipboardEnabled: true, clipboardMax: 30 }, }; const update = params.get('update'); const updateStatus = update === 'ready' ? { state: 'ready', version: '1.4.0', notes: '' } : update === 'installing' ? { state: 'installing', version: '1.4.0' } : update === 'problem' ? { state: 'problem', downloadUrl: 'https://twttr.crt.fyi/download' } : { state: 'idle' }; const tile = (hue: number) => svg(``, `hsl(${hue} 40% 20%)`); const handlers: Record = { // `slowipc=ms`: the first native answer arrives late, as it can on a real start. settings_get: () => new Promise(resolve => setTimeout(() => resolve({ homeUrl: 'https://x.com/home', restoreTabs: true, externalLinks: 'pane', siteLinks: 'same' }), Number(params.get('slowipc') ?? 0))), profiles_get: () => state.profiles, // Like native code (profiles.rs `removal`): a profile that still has a synced tab cannot be removed. profiles_set: ({ settings }) => { const next = settings as typeof state.profiles; const removed = state.profiles.profiles.filter(p => !next.profiles.some(n => n.id === p.id)).map(p => p.id); if (state.tabProfiles.some(profile => removed.includes(profile))) throw new Error("PROFILE: close this profile's tabs before removing it"); return (state.profiles = next); }, // `mode=`: the mode in use; `changed`: one flag changed by hand (the app menu's Mode submenu asks before replacing it). features_get: () => state.features, features_set: ({ features }) => { state.features = features as Record; return null; }, mode_get: () => state.modes, mode_set: ({ mode, onboarded, preset }) => (state.modes = { mode: (mode as string | null) ?? null, onboarded: !!onboarded, existing: true, preset: (preset as Record | undefined) ?? (mode === state.modes.mode ? state.modes.preset : null) }), // The global theme (the app menu's Theme submenu picks one; the chrome follows). theme_get: () => state.theme, theme_set: ({ theme }) => { state.theme = theme; return null; }, // Account and pane themes: none saved; `panetheme` sets one after the tabs exist. theme_scopes_get: () => ({ chrome: 'theme', profiles: {}, panes: {} }), theme_scopes_set: () => null, tabs_sync: ({ items }) => { state.sync = items as unknown[]; state.tabProfiles = (items as Array<{ profile: string }>).map(item => item.profile); return null; }, column_configure: ({ id, config }) => { if (config) state.columns[String(id)] = config; else delete state.columns[String(id)]; return null; }, tab_action: () => null, // Like native code (zoom.rs): clamped to 25%..500%, remembered per tab; without a factor it only reads. tab_zoom: ({ id, factor }) => { if (typeof factor === 'number') state.zoom[String(id)] = Math.round(Math.min(5, Math.max(0.25, factor)) * 100) / 100; return state.zoom[String(id)] ?? 1; }, // Find in page: the preview has no page to search, so it answers like an engine that counts // (a made-up total from the query's length) and moves the active match on next/previous. tab_find: ({ id, action, query }) => { const find = state.find; if (action === 'stop') { find.count = 0; find.index = -1; return null; } if (action === 'start') { find.count = String(query ?? '').toLowerCase() === 'zzz' ? 0 : (String(query ?? '').length * 5) % 23; find.index = find.count ? 0 : -1; } else if (find.count) find.index = (find.index + (action === 'next' ? 1 : -1) + find.count) % find.count; setTimeout(() => emit('tab-find', { id, count: find.count, index: find.index }), 30); return null; }, // Safe mode (`safe=on` starts in it): a flag for this run; switching it asks for every tab to be rebuilt. safe_mode_get: () => ({ active: state.safe }), safe_mode_set: ({ on }) => { state.safe = !!on; setTimeout(() => { emit('safe-mode', { active: state.safe }); emit('tabs-rebuild', null); }, 20); return { active: state.safe }; }, plugins_open_folder: () => null, 'plugin:app|version': () => '1.3.2', // Every navigation is counted (scripts check that the find bar's Enter never navigates). tab_navigate: () => { state.navigations += 1; return null; }, tab_insert_text: () => null, shell_focus: () => null, open_external_url: () => null, app_ready: () => updateStatus, update_status: () => updateStatus, // "Check for updates" in the app menu: answers after a moment. `check=ok` is up to date; by default the // server does not answer (the state the real app shows while the update feed is withheld). update_check: async () => { await new Promise(resolve => setTimeout(resolve, 1400)); if (updateStatus.state !== 'idle') return updateStatus; return params.get('check') === 'ok' ? { state: 'upToDate' } : { state: 'error', message: 'UPDATE: error sending request for url' }; }, apply_update: () => null, window_system_menu: () => null, media_get: () => state.media, gallery_list: () => Array.from({ length: 9 }, (_, i) => ({ path: `C:\\shots\\${i}.png`, name: `Screenshot ${i}.png`, folder: state.media.folders[0], modifiedMs: Date.now() - i * 3.6e6, size: 1000 })), gallery_thumb: ({ path }) => tile((String(path).length * 37 + Number(String(path).match(/\d+/)?.[0] ?? 0) * 40) % 360), clip_list: () => [ { id: 'c1', kind: 'text', text: 'https://github.com/tauri-apps/tauri/releases/tag/tauri-v2.9.0', hash: 'a', at: Date.now() - 60_000 }, { id: 'c2', kind: 'image', file: 'clip-1.png', hash: 'b', at: Date.now() - 20 * 60_000 }, { id: 'c3', kind: 'text', text: 'ship it. the draft vault never loses a word, even when X eats your composer.', hash: 'c', at: Date.now() - 3 * 3.6e6 }, ], clip_thumb: () => tile(200), 'plugin:window|is_maximized': () => false, 'plugin:window|minimize': () => null, 'plugin:window|toggle_maximize': () => null, 'plugin:window|close': () => null, 'plugin:window|start_resize_dragging': () => null, }; // Install screen and store (`open=install&kind=plugin|theme&src=…`, `open=install-error`). Object.assign(handlers, storeHandlers({ list: [] })); // Workspaces, backup/sync, developer mode, palette commands (settingsMocks.ts). Object.assign(handlers, settingsHandlers()); if (params.has('commands')) handlers.plugins_list = () => SAMPLE_PLUGIN_NAMES.map(plugin => ({ ...plugin, description: '', version: '', author: '', enabled: true, permissions: null })); // Native code answered from memory (the framework's preview mocks); `emit` delivers a native event. const { emit } = installPreviewMocks(handlers, { name: 'shell preview' }); // Scripts (scripts/shell-links-check.mjs) drive native events through this. (window as unknown as { __btEmit: typeof emit }).__btEmit = emit; (window as unknown as { __btHarness: unknown }).__btHarness = { state }; const now = Date.now(); const draft = (id: string, title: string, text: string, contextUrl = '', minutes = 5): Draft => ({ id, accountId: 'unassigned-x', kind: 'post', title, text, contextUrl, revision: 1, status: 'active', createdAt: new Date(now - minutes * 60_000).toISOString(), updatedAt: new Date(now - minutes * 60_000).toISOString(), source: 'capture', } as Draft); Object.assign(bridge, { listDrafts: async () => [ draft('d1', 'Launch thread', 'wayBetter for X is out: a tiny tabbed shell around the real X, with a draft vault that never loses a word.', 'https://x.com/home', 3), draft('d2', '', 'hot take: every desktop app should have a command palette. ctrl+k or bust', '', 40), draft('d3', 'Reply to Tauri team', 'Thanks for 2.9! The child webview APIs made the tab strip possible.', 'https://x.com/TauriApps/status/1', 180), ], }); const TABS: Array<{ url: string; title: string; favicon?: string }> = [ { url: 'https://x.com/home', title: 'Home / X', favicon: X_ICON }, { url: 'https://x.com/notifications', title: 'Notifications / X', favicon: X_ICON }, { url: 'https://x.com/TauriApps/status/1839201', title: 'Tauri on X: "Tauri 2.9 is out with child webviews"', favicon: X_ICON }, { url: 'https://x.com/search?q=from%3Atauriapps%20since%3A2026-09-01&f=live', title: 'from:tauriapps since:2026-09-01 - Search / X', favicon: X_ICON }, { url: 'https://github.com/tauri-apps/tauri', title: 'tauri-apps/tauri: Build smaller, faster, and more secure desktop apps', favicon: GH_ICON }, { url: 'https://x.com/i/bookmarks', title: 'Bookmarks / X', favicon: X_ICON }, { url: 'https://news.ycombinator.com/item?id=41', title: 'Show HN: wayBetter for X', favicon: NEWS_ICON }, { url: 'https://x.com/elonmusk', title: 'Elon Musk (@elonmusk) / X', favicon: X_ICON }, { url: 'http://example.com/', title: 'Example Domain' }, { url: 'https://x.com/explore', title: 'Explore / X', favicon: X_ICON }, ]; const DECK_SOURCES = [ { kind: 'home' }, { kind: 'notifications' }, { kind: 'mentions' }, { kind: 'search', value: 'from:playfishies filter:media' }, { kind: 'user', value: 'playfishies' }, { kind: 'list', value: '1234567890' }, { kind: 'bookmarks' }, { kind: 'following' }, ]; export async function mountShellHarness(root: HTMLElement) { // `keeplayout`: a reload test; the saved layout stays and no fake tabs are added. if (!params.has('keeplayout')) try { localStorage.removeItem('bt.shell.layout.v1'); } catch { /* Preview only. */ } try { localStorage.removeItem('bt.shell.decks.v1'); localStorage.removeItem('bt.shell.deck-settings.v1'); const deckCount = Number(params.get('deck') ?? -1); if (deckCount >= 0) { const columns = Array.from({ length: deckCount }, (_, i) => ({ id: `col${i}`, tabId: `k${i}`, profile: PROFILES[i % 2 === 0 ? 0 : Math.min(1, PROFILES.length - 1)]!.id, source: DECK_SOURCES[i % DECK_SOURCES.length], width: 360, flags: {}, filters: { terms: i === 1 ? ['giveaway'] : [], hideReplies: false, hideReposts: false, mediaOnly: false }, })); localStorage.setItem('bt.shell.decks.v1', JSON.stringify([{ id: 'deck1', name: 'Launch day', columns }])); } } catch { /* Preview only. */ } // X's site sets the shell frame up (after the mocks above, so it sees a native API). const [{ createRoot }, { Shell }, store] = await Promise.all([ import('react-dom/client'), import('../site'), import('../../../../../waybetter/packages/shell/src/frame/state.ts'), ]); createRoot(root).render(); // Layout snapshot for scripts: groups left to right with their tab ids, and the active tab. (window as unknown as { __btShellLayout: () => unknown }).__btShellLayout = () => { const api = store.shell.api; if (!api) return null; const groups = api.groups.map(group => ({ id: group.id, left: Math.round(group.element.getBoundingClientRect().left), top: Math.round(group.element.getBoundingClientRect().top), tabs: group.panels.map(panel => panel.id), urls: group.panels.map(panel => (panel.params as { url?: string } | undefined)?.url ?? ''), active: group.activePanel?.id ?? null })); return { groups: groups.sort((a, b) => a.left - b.left || a.top - b.top), active: api.activePanel?.id ?? null }; }; const open = params.get('open'); const api = await new Promise>(resolve => { const poll = () => (store.shell.api && store.shell.api.panels.length ? resolve(store.shell.api) : setTimeout(poll, 30)); poll(); }); const first = api.panels[0]!; if (open === 'empty') { api.clear(); return; } // The workspace opened on start is the layout: no fake tabs on top. if (params.has('wsdefault') || params.has('keeplayout')) return; const count = Math.max(1, Number(params.get('tabs') ?? 6)); const pinned = Number(params.get('pinned') ?? 2); const profiles = state.profiles.profiles; first.api.close(); for (let i = 0; i < count; i++) { const tab = TABS[i % TABS.length]!; api.addPanel({ id: `tab${i}`, component: 'web', title: tab.title, params: { kind: 'web', url: tab.url, title: tab.title, favicon: tab.favicon, pinned: i < pinned || undefined, profile: profiles[i % profiles.length]!.id, loading: params.has('loading') && i === pinned + 1 ? true : undefined, }, position: api.groups.length ? { referenceGroup: api.groups[0]!, direction: 'within' } : undefined, inactive: i !== Math.min(count - 1, pinned + 2), }); } if (params.has('split')) { api.addPanel({ id: 'right0', component: 'web', title: 'Messages / X', params: { kind: 'web', url: 'https://x.com/messages', title: 'Messages / X', favicon: X_ICON, profile: 'default' }, position: { referencePanel: 'tab0', direction: 'right' } }); api.addPanel({ id: 'right1', component: 'web', title: 'Lists / X', params: { kind: 'web', url: 'https://x.com/i/lists', title: 'Lists / X', favicon: X_ICON, profile: profiles[1]?.id ?? 'default' }, position: { referencePanel: 'right0', direction: 'within' }, inactive: true }); } // `panetheme=` (with `split`): the right pane gets its own theme once it exists (scopes name open tabs only). if (params.has('split') && params.get('panetheme')) { const { setScopes } = await import('../themes'); await setScopes({ chrome: 'theme', profiles: {}, panes: { right0: params.get('panetheme')! } }); } store.shell.closed.push( { url: 'https://x.com/TauriApps', profile: 'default', title: 'Tauri (@TauriApps) / X' }, { url: 'https://github.com/features/copilot', profile: 'default', title: 'GitHub Copilot' }, { url: 'https://x.com/i/lists/1234', profile: profiles[1]?.id, title: 'Rust people / X' }, ); await new Promise(resolve => setTimeout(resolve, 150)); if (params.has('commands')) emit('tab-commands', { id: api.activePanel?.id ?? 'tab0', commands: SAMPLE_COMMANDS }); const key = (init: KeyboardEventInit) => window.dispatchEvent(new KeyboardEvent('keydown', { bubbles: true, ...init })); if (open === 'palette') { key({ key: 'k', ctrlKey: true }); const q = params.get('q'); if (q) setTimeout(() => { const input = document.querySelector('.bt-palette-input'); if (!input) return; Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, q); input.dispatchEvent(new Event('input', { bubbles: true })); }, 50); } if (open === 'accounts') document.querySelector('.bt-profile-switcher')?.click(); // The app menu (open=appmenu; sub=language|theme|mode|workspaces|developer opens that submenu). if (open === 'appmenu') window.dispatchEvent(new CustomEvent('bt-app-menu', { detail: { keyboard: true, submenu: params.get('sub') ?? undefined } })); if (open === 'workspaces') document.querySelector('.bt-ws-button')?.click(); if (open === 'wssave') window.dispatchEvent(new CustomEvent('bt-workspace-menu', { detail: 'save' })); if (open === 'newtab') key({ key: 't', ctrlKey: true }); if (open === 'menu') { const tab = document.querySelectorAll('.bt-tab')[3] ?? document.querySelector('.bt-tab'); const rect = tab?.getBoundingClientRect(); tab?.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: (rect?.left ?? 0) + 30, clientY: (rect?.bottom ?? 0) - 4 })); } if (open === 'drafts') { emit('drafts-picker', { from: api.activePanel?.id ?? 'tab0', kind: 'post', contextUrl: 'https://x.com/home', x: 320, y: 220 }); } if (open === 'media') key({ key: 'G', ctrlKey: true, shiftKey: true }); if (open === 'deck' || open === 'addcol') { window.dispatchEvent(new CustomEvent('bt-deck-open', { detail: 'deck1' })); await new Promise(resolve => setTimeout(resolve, 120)); if (params.has('unread')) { emit('tab-state', { id: 'k0', unread: 12 }); emit('tab-state', { id: 'k1', unread: 3, loading: true }); emit('tab-state', { id: 'k2', unread: 1200 }); } if (open === 'addcol') document.querySelector('.bt-deck-action')?.click(); } if (open === 'install') { const kind = params.get('kind') ?? 'plugin'; const url = params.get('src') ?? (kind === 'theme' ? 'https://waybetter.fyi/store/themes/nord.json' : 'https://waybetter.fyi/store/plugins/bt-reply-guard.plugin.js'); emit('install-link', { link: { kind, url } }); } if (open === 'install-error') emit('install-link', { error: 'LINK: only https links on waybetter.fyi, cdn1.crt.fyi, git.crt.fyi (git.crt.fyi: raw files) can be installed' }); }