perf: paint a snapshot of the last home in place of the boot splash (#12158)

* perf: paint home from a per-user persisted cache while it refreshes

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: keep a cached first page from offering load more after a failed refresh

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: drop expired cache entries from disk when hydrating

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf: render home as the last confirmed user while whoami is in flight

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf: hydrate the home cache at boot; file answers only under their session

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf: paint home's cached data in its first frame from a synchronous snapshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: show nothing rather than 'Loading user...' while rendering as the remembered user

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: bind the cache identity to the session that confirmed the tab's user

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: record the session confirmation before setting the user, so the cache hydrates

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* chore: cache immutable chunks on the cloudflare pages previews

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf: keep the cache snapshot's small entries when a large one exceeds its cap

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* perf: paint a snapshot of the last home in place of the boot splash

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: clean the home snapshot when painted and cache favorites for its hand-over

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: make home's first live frame match its boot snapshot

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix: save the home snapshot with its boot stylesheets and through keyboard reloads

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-11-03 03:53:05 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 116c90280e
commit 0ac2b61034
11 changed files with 711 additions and 10 deletions
+145 -2
View File
@@ -7,7 +7,15 @@
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#fbfbfd" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#3b4252" />
<meta name="mobile-web-app-capable" content="yes" />
<style type="text/css">
<style type="text/css" data-wm-shell>
html[data-wm-home-snapshot] #svelte-global-loader {
display: none;
}
#wm-home-snapshot * {
animation: none !important;
transition: none !important;
}
.st2 {
fill: #bcd4fc;
}
@@ -197,9 +205,95 @@
})()
</script>
%sveltekit.head%
<script id="wm-home-snapshot-head">
// A reload of Home paints the last rendered Home (homeSnapshot.ts) in place of the splash
// while the app boots. Bound like the optimistic render (lastSession.ts): only under the
// session hint it was saved with, else it is dropped, so the next person on a shared
// browser never sees it; only for the workspace this load opens, at the width and theme
// it was rendered at. Its stylesheets are content-hashed files of the build it was saved
// by, hence the build check; they are written by the parser so they block the first
// paint as the build's own would, and one failing to load drops the snapshot.
;(function () {
var KEY = 'wm-home-snapshot'
var s
function drop() {
window.__wmHomeSnapshot = undefined
document.documentElement.removeAttribute('data-wm-home-snapshot')
var shot = document.getElementById('wm-home-snapshot')
if (shot) shot.remove()
try {
localStorage.removeItem(KEY)
} catch (_) {}
}
// Every other page, the public apps included, pays nothing for it.
if (location.pathname !== '/' || window.parent !== window) return
try {
var raw = localStorage.getItem(KEY)
if (!raw) return
s = JSON.parse(raw)
var hint
document.cookie.split(/;\s*/).forEach(function (c) {
var eq = c.indexOf('=')
if (eq > 0 && c.slice(0, eq) === s.cookie) hint = c.slice(eq + 1)
})
var age = Date.now() - s.savedAt
if (
s.format !== 1 ||
s.build !== '%sveltekit.version%' ||
!hint ||
hint !== s.hint ||
!(age >= 0 && age < 7 * 24 * 3600 * 1000)
)
return drop()
var params = new URLSearchParams(location.search)
var other = false
params.forEach(function (_, k) {
if (k !== 'workspace') other = true
})
// The workspace the app opens, as stores.ts and the (logged) layout pick it.
var ws = params.get('workspace')
if (ws === null) ws = sessionStorage.getItem('workspace')
if (ws === null) ws = localStorage.getItem('workspace')
var mode = localStorage.getItem('dark-mode')
var dark =
mode !== null ? mode === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches
if (other || ws !== s.workspace || innerWidth !== s.width || dark !== s.dark) return
} catch (_) {
return
}
var html = document.documentElement
html.setAttribute('data-wm-home-snapshot', '')
;['dark', 'github-dark'].forEach(function (c) {
html.classList.toggle(c, (' ' + s.htmlClass + ' ').indexOf(' ' + c + ' ') !== -1)
})
document.addEventListener(
'error',
function (e) {
var t = e.target
if (t && t.tagName === 'LINK' && t.hasAttribute('data-wm-home-snapshot')) drop()
},
true
)
var links = ''
s.stylesheets.forEach(function (href) {
links +=
'<link rel="stylesheet" data-wm-home-snapshot href="' +
String(href).replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;') +
'">'
})
document.write(links)
s.styles.forEach(function (css) {
var style = document.createElement('style')
style.setAttribute('data-wm-home-snapshot', '')
style.textContent = css
document.head.appendChild(style)
})
window.__wmHomeSnapshot = s
})()
</script>
</head>
<body data-sveltekit-preload-code="viewport" class="outline-none focus:outline-none">
<div style="display: contents">
<div id="wm-app" style="display: contents">
<div id="svelte-global-loader">
<div id="mainbg" style="position: absolute; bottom: 0; left: 0; width: 100%; height: 100vh">
</div>
@@ -259,6 +353,55 @@
</div>
</div>
</div>
<script id="wm-home-snapshot-body">
// The snapshot the head script accepted. Not interactive: its content is inert, and the
// cover above it takes the pointer until the live Home replaces it (homeSnapshot.ts).
// A boot that never gets there gives the splash back.
;(function () {
var s = window.__wmHomeSnapshot
if (!s) return
try {
var shot = document.createElement('div')
shot.id = 'wm-home-snapshot'
shot.setAttribute('aria-hidden', 'true')
shot.style.cssText =
'position:fixed;inset:0;z-index:2147483647;overflow:hidden;cursor:progress'
shot.style.background = s.background
var parsed = new DOMParser().parseFromString(s.html, 'application/xhtml+xml')
if (parsed.getElementsByTagName('parsererror').length) {
document.documentElement.removeAttribute('data-wm-home-snapshot')
try {
localStorage.removeItem('wm-home-snapshot')
} catch (_) {}
return
}
// Cleaned again here, not only when saved: anything that can write this origin's
// storage once could otherwise plant markup that runs on every load of Home.
var executable =
/^(script|iframe|frame|object|embed|link|meta|base|form|animate|set|animatemotion|animatetransform)$/i
Array.prototype.forEach.call(parsed.querySelectorAll('*'), function (el) {
if (executable.test(el.localName)) return el.remove()
Array.prototype.slice.call(el.attributes).forEach(function (a) {
var v = a.value.replace(/[\u0000-\u0020]/g, '')
if (/^on/i.test(a.name) || /^(javascript|vbscript):/i.test(v))
el.removeAttribute(a.name)
})
})
var content = document.importNode(parsed.documentElement, true)
content.setAttribute('inert', '')
content.style.height = '100%'
shot.appendChild(content)
var loader = document.getElementById('svelte-global-loader')
loader.parentNode.insertBefore(shot, loader.nextSibling)
setTimeout(function () {
shot.remove()
document.documentElement.removeAttribute('data-wm-home-snapshot')
}, 15000)
} catch (_) {
document.documentElement.removeAttribute('data-wm-home-snapshot')
}
})()
</script>
%sveltekit.body%
</div>
</body>
@@ -18,7 +18,16 @@ not this component) — so the lead can run the whole line.
import MeltButton from '$lib/components/meltComponents/MeltButton.svelte'
import WorkspacePickerBody from '$lib/components/sidebar/WorkspacePickerBody.svelte'
import BreadcrumbNavPicker from './BreadcrumbNavPicker.svelte'
import { userWorkspaces, workspaceStore, workspaceColor, superadmin } from '$lib/stores'
import {
userWorkspaces,
usersWorkspaceStore,
workspaceStore,
workspaceColor,
superadmin,
type UserWorkspace
} from '$lib/stores'
import { persistedValue } from '$lib/persistedResource.svelte'
import { readSessionHint } from '$lib/lastSession'
import { findWorkspaceRoot } from '$lib/utils/workspaceHierarchy'
import { useForkableWorkspaces } from '$lib/utils/useForkableWorkspaces.svelte'
import { twMerge } from 'tailwind-merge'
@@ -113,12 +122,26 @@ not this component) — so the lead can run the whole line.
copiedReset = setTimeout(() => (pathCopied = false), 1500)
}
const family = $derived(findWorkspaceRoot(scopeId, $userWorkspaces ?? []))
// Named from the list last loaded until the session's own loads (persistedCache), so a reload
// draws the workspace's name and colour in its first frame, as the snapshot of Home painted
// before boot does (homeSnapshot.ts). Only what the band shows reads it.
const workspacesCache = persistedValue<UserWorkspace[]>('nav_workspaces', 1)
const workspaces = $derived(
$usersWorkspaceStore || !scopeId
? $userWorkspaces
: (workspacesCache.peek({ workspace: scopeId }) ?? $userWorkspaces)
)
$effect(() => {
if ($usersWorkspaceStore && scopeId)
workspacesCache.save({ workspace: scopeId }, $userWorkspaces, readSessionHint())
})
const family = $derived(findWorkspaceRoot(scopeId, workspaces ?? []))
const discColor = $derived(family?.color ?? $workspaceColor ?? 'rgb(var(--color-surface-sunken))')
const glyphColor = $derived(getContrastTextColor(discColor))
const forkable = useForkableWorkspaces({
workspaces: () => $userWorkspaces,
workspaces: () => workspaces,
currentWorkspaceId: () => scopeId,
isSuperadmin: () => !!$superadmin
})
@@ -137,7 +160,7 @@ not this component) — so the lead can run the whole line.
// is standing in is answered the same way whichever one it is.
/** Whether this family has a dev workspace anywhere under it. */
const familyHasDev = $derived.by(() => {
const all = $userWorkspaces ?? []
const all = workspaces ?? []
const root = family?.id
return (
!!root && all.some((w) => w.is_dev_workspace && findWorkspaceRoot(w.id, all)?.id === root)
@@ -323,8 +323,11 @@ The row's height matches the sidebar's own header row, so the two read as one ba
<!-- `actionsFill`: the actions are a surface rather than a row, so they take the rest of the
bar and run to its right edge, and they stretch its full height because that surface
sits on the bottom edge. -->
<!-- `data-wm-snapshot-hidden`: a mount always starts unmeasured, so Home's snapshot draws
this box hidden too (homeSnapshot.ts). -->
<div
{@attach measureActions(fold, actionsEpoch, actionsVersion)}
data-wm-snapshot-hidden
class={twMerge(
'flex',
// pl-4: the gap between the breadcrumb and the filling surface is bare bar, so it
@@ -65,7 +65,7 @@
</script>
<div class="w-full {showComposer ? 'mt-2' : 'mb-1'}">
<div class="relative group/composer">
<div class="relative group/composer" data-wm-snapshot-slot>
{#if showComposer}
<!-- The block is a session's chat, so it waits for the sessions it might reuse. Keyed on
the workspace family, not the workspace: another family needs its own draft, but a
@@ -78,6 +78,10 @@
onSettled={(height) => rememberComposerHeight($workspaceStore ?? undefined, height)}
/>
{/key}
<!-- What a reload draws here until the starter's code loads, kept for the snapshot of
Home painted before boot (homeSnapshot.ts), which shows it in the starter's place
so the hand-over to the live page changes nothing. -->
<div hidden data-wm-snapshot-stand-in>{@render placeholder()}</div>
{:else}
{@render placeholder()}
{/if}
+238
View File
@@ -0,0 +1,238 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { version } from '$app/environment'
import type { UserExt } from '$lib/stores'
import { forgetLastSession, rememberUser } from './lastSession'
import {
HOME_SNAPSHOT_KEY,
noteClientNavigation,
releaseHomeSnapshot,
saveHomeSnapshot,
watchHomeForSnapshot,
type HomeSnapshot
} from './homeSnapshot'
import appHtml from '../app.html?raw'
// The rules are `app.html`'s: run its own scripts against what `saveHomeSnapshot` writes.
function inlineScript(id: string): string {
const m = new RegExp(`<script id="${id}">([\\s\\S]*?)</script>`).exec(appHtml)
if (!m) throw new Error(`no script #${id} in app.html`)
return m[1].replace('%sveltekit.version%', version)
}
// Node's own experimental `localStorage` global shadows jsdom's, and is unset without a file.
function memoryStorage(): Storage {
const m = new Map<string, string>()
return {
getItem: (k) => m.get(k) ?? null,
setItem: (k, v) => void m.set(k, String(v)),
removeItem: (k) => void m.delete(k),
clear: () => m.clear(),
key: (i) => [...m.keys()][i] ?? null,
get length() {
return m.size
}
}
}
for (const name of ['localStorage', 'sessionStorage'] as const)
Object.defineProperty(globalThis, name, { value: memoryStorage(), configurable: true })
const headScript = inlineScript('wm-home-snapshot-head')
const bodyScript = inlineScript('wm-home-snapshot-body')
const user = { email: 'a@x.dev', username: 'a', workspace_id: 'demo' } as unknown as UserExt
const setHint = (v: string | undefined) => {
for (const c of document.cookie.split(/;\s*/)) {
const name = c.split('=')[0]
if (name) document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT`
}
if (v) document.cookie = `${__WM_SESSION_HINT__}=${v}`
}
function renderHome() {
document.documentElement.removeAttribute('data-wm-home-snapshot')
document.head.innerHTML = '<link rel="stylesheet" href="/_app/immutable/assets/app.css">'
document.body.innerHTML = `<div id="wm-app"><div id="svelte-global-loader"></div><div id="content">
<a href="/scripts/get/f/a">f/a</a><a href="javascript:alert(1)" onclick="alert(1)">x</a>
<input value="typed"><textarea>draft</textarea><div contenteditable>draft</div>
<div role="menu">menu</div><svg><g id="g1"></g><foreignObject><span class="icon">i</span></foreignObject></svg></div></div>`
}
/** Runs app.html's scripts as a load of `url` would; what it painted, if anything. */
function boot(url: string): { painted: HTMLElement | null; written: string } {
history.replaceState(null, '', url)
;(window as any).__wmHomeSnapshot = undefined
document.documentElement.removeAttribute('data-wm-home-snapshot')
document.head.innerHTML = ''
document.body.innerHTML = '<div id="wm-app"><div id="svelte-global-loader"></div></div>'
let written = ''
document.write = (s: string) => {
written += s
document.head.insertAdjacentHTML('beforeend', s)
}
new Function(headScript)()
new Function(bodyScript)()
return { painted: document.getElementById('wm-home-snapshot'), written }
}
function stored(): HomeSnapshot | null {
const raw = localStorage.getItem(HOME_SNAPSHOT_KEY)
return raw ? JSON.parse(raw) : null
}
beforeEach(() => {
localStorage.clear()
sessionStorage.clear()
forgetLastSession()
window.matchMedia = vi.fn(() => ({ matches: false })) as any
history.replaceState(null, '', '/?workspace=demo')
setHint('h1')
rememberUser(user, 'h1')
renderHome()
})
describe('home snapshot', () => {
it('paints what was saved, without values, handlers or anything open', () => {
saveHomeSnapshot('demo', 'demo')
const { painted, written } = boot('/?workspace=demo')
expect(painted).not.toBeNull()
expect(written).toContain('href="/_app/immutable/assets/app.css"')
const html = painted!.innerHTML
expect(html).toContain('f/a')
expect(html).not.toMatch(/typed|draft|menu|onclick|javascript:|id="content"/)
expect(html).toContain('id="g1"')
// The workspace disc draws its icon in a foreignObject.
expect(html).toContain('class="icon"')
})
it('hands over to the live page, which keeps the stylesheets', () => {
saveHomeSnapshot('demo', 'demo')
boot('/?workspace=demo')
releaseHomeSnapshot()
expect(document.getElementById('wm-home-snapshot')).toBeNull()
expect(document.documentElement.isConnected).toBe(true)
expect(document.documentElement.hasAttribute('data-wm-home-snapshot')).toBe(false)
expect(document.getElementById('svelte-global-loader')).not.toBeNull()
expect(document.querySelector('link[href="/_app/immutable/assets/app.css"]')).not.toBeNull()
})
it('shows what a part draws while the app boots, in its place', () => {
document
.getElementById('content')!
.insertAdjacentHTML(
'beforeend',
'<div data-wm-snapshot-slot><p>starter</p><div hidden data-wm-snapshot-stand-in><p>skeleton</p></div></div>' +
'<div data-wm-snapshot-hidden><button>CLI</button></div>'
)
saveHomeSnapshot('demo', 'demo')
const html = boot('/?workspace=demo').painted!.innerHTML
expect(html).toContain('skeleton')
expect(html).not.toMatch(/starter|\shidden=/)
expect(html).toMatch(/visibility: hidden;"[^>]*><button>CLI/)
})
it('keeps a tree the HTML parser would restructure', () => {
// An anchor in an anchor can only be built through the DOM; parsed as HTML it splits.
const outer = document.createElement('a')
outer.href = '/outer'
outer.appendChild(document.createElement('span')).appendChild(document.createElement('a'))
const row = document.createElement('div')
row.className = 'row'
row.append(outer, Object.assign(document.createElement('div'), { className: 'after' }))
document.getElementById('content')!.appendChild(row)
saveHomeSnapshot('demo', 'demo')
const { painted } = boot('/?workspace=demo')
expect(painted!.querySelector('.row > .after')).not.toBeNull()
expect(painted!.querySelector('.row > a span a')).not.toBeNull()
})
it('paints no script planted in the stored snapshot', () => {
saveHomeSnapshot('demo', 'demo')
const html =
'<div xmlns="http://www.w3.org/1999/xhtml"><img src="x" onerror="alert(1)"/>' +
'<script>alert(1)</script><iframe srcdoc="x"></iframe>' +
'<a href=" javascript:alert(1)">a</a><svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)">' +
'<set attributeName="href" to="javascript:alert(1)"/></svg><p>kept</p></div>'
localStorage.setItem(HOME_SNAPSHOT_KEY, JSON.stringify({ ...stored(), html }))
const painted = boot('/?workspace=demo').painted!.innerHTML
expect(painted).toContain('kept')
expect(painted).not.toMatch(/onerror|onload|<script|<iframe|<set|javascript:/)
})
it('shows nothing under another session and drops the snapshot', () => {
saveHomeSnapshot('demo', 'demo')
setHint('h2')
expect(boot('/?workspace=demo').painted).toBeNull()
expect(stored()).toBeNull()
})
it('shows nothing once the session hint is gone and drops the snapshot', () => {
saveHomeSnapshot('demo', 'demo')
setHint(undefined)
expect(boot('/').painted).toBeNull()
expect(stored()).toBeNull()
})
it('shows nothing for another workspace, page or search, and keeps the snapshot', () => {
saveHomeSnapshot('demo', 'demo')
expect(boot('/?workspace=other').painted).toBeNull()
expect(boot('/runs?workspace=demo').painted).toBeNull()
expect(boot('/?workspace=demo&search=a').painted).toBeNull()
localStorage.setItem('workspace', 'other')
expect(boot('/').painted).toBeNull()
localStorage.setItem('workspace', 'demo')
expect(boot('/').painted).not.toBeNull()
expect(stored()).not.toBeNull()
})
it('drops a snapshot of another format, another build, or too old', () => {
for (const change of [
{ format: 999 },
{ build: 'another-build' },
{ savedAt: Date.now() - 8 * 24 * 3600 * 1000 }
]) {
saveHomeSnapshot('demo', 'demo')
localStorage.setItem(HOME_SNAPSHOT_KEY, JSON.stringify({ ...stored(), ...change }))
expect(boot('/?workspace=demo').painted).toBeNull()
expect(stored()).toBeNull()
}
})
it('saves as Home is left unless something on it was pressed, with its mount-time styles', () => {
const current = () => ({ workspace: 'demo', userWorkspace: 'demo' })
const leave = () => window.dispatchEvent(new Event('pagehide'))
const press = (init: KeyboardEventInit) =>
document.dispatchEvent(new KeyboardEvent('keydown', init))
let stop = watchHomeForSnapshot(current)
document.head.insertAdjacentHTML('beforeend', '<link rel="stylesheet" href="/later.css">')
press({ key: 'r', ctrlKey: true })
press({ key: 'F5' })
leave()
stop()
expect(stored()?.stylesheets).toEqual(['/_app/immutable/assets/app.css'])
localStorage.clear()
stop = watchHomeForSnapshot(current)
press({ key: 'Enter' })
leave()
stop()
expect(stored()).toBeNull()
// Last: the flag lasts for the document.
noteClientNavigation()
stop = watchHomeForSnapshot(current)
leave()
stop()
expect(stored()).toBeNull()
})
it('saves nothing for a session this tab has not confirmed, or without a hint', () => {
// Another tab logged in: this tab's user is not the session's.
setHint('h2')
saveHomeSnapshot('demo', 'demo')
expect(stored()).toBeNull()
setHint(undefined)
rememberUser(user, undefined)
saveHomeSnapshot('demo', 'demo')
expect(stored()).toBeNull()
})
})
+237
View File
@@ -0,0 +1,237 @@
import { version } from '$app/environment'
import { readSessionHint, sessionStillConfirmed } from '$lib/lastSession'
// The markup of the last rendered Home, painted by `app.html` in place of its loading splash
// while the app boots, and replaced by the live page when it mounts. `app.html` reads it before
// any module loads, so the rules it applies live there, in the script that paints it; this side
// writes what that script checks. Same binding as the optimistic render (`lastSession.ts`): a
// snapshot is shown only under the session hint it was saved with, so the next person on a
// shared browser never sees the previous one's Home.
export const HOME_SNAPSHOT_KEY = 'wm-home-snapshot'
/** Bumped when what the snapshot holds changes shape; `app.html` checks the same number. */
export const HOME_SNAPSHOT_FORMAT = 1
const MAX_HTML_CHARS = 512 * 1024
const MAX_INLINE_STYLE_CHARS = 64 * 1024
export interface HomeSnapshot {
format: number
/** The build it was rendered by: its stylesheets are content-hashed and go with it. */
build: string
/** The session-hint cookie's name, which the dev proxy renames per backend. */
cookie: string
hint: string
workspace: string
width: number
dark: boolean
htmlClass: string
background: string
stylesheets: string[]
styles: string[]
html: string
savedAt: number
}
/** Everything a live Home holds that the snapshot must not: values typed, and anything open. */
const DROPPED = [
'script',
'noscript',
'template',
'iframe',
'frame',
'object',
'embed',
'canvas',
'video',
'audio',
'link',
'dialog',
'[popover]',
'[role="dialog"]',
'[role="alertdialog"]',
'[role="menu"]',
'[role="listbox"]',
'[role="tooltip"]',
'._toastContainer',
'#svelte-announcer',
'#svelte-global-loader',
'#wm-home-snapshot'
].join(',')
const SVG_NS = 'http://www.w3.org/2000/svg'
/**
* The app's markup without what could carry a value or act, as XML: the live tree nests what the
* HTML parser would restructure (an anchor inside an anchor), and XML parses back as it was.
*/
function snapshotMarkup(root: Element): string {
const clone = document.createElement('div')
clone.append(...Array.from(root.childNodes, (n) => n.cloneNode(true)))
// A part the live page draws differently while it boots carries what it draws then, and the
// snapshot shows that instead, so the live page's first frame matches it.
clone.querySelectorAll('[data-wm-snapshot-slot]').forEach((slot) => {
const standIn = slot.querySelector(':scope > [data-wm-snapshot-stand-in]')
if (standIn) slot.replaceChildren(...Array.from(standIn.childNodes))
})
clone
.querySelectorAll<HTMLElement>('[data-wm-snapshot-hidden]')
.forEach((el) => (el.style.visibility = 'hidden'))
clone.querySelectorAll(DROPPED).forEach((el) => el.remove())
clone.querySelectorAll('*').forEach((el) => {
for (const { name, value } of Array.from(el.attributes)) {
if (
name.startsWith('on') ||
// The live page owns these ids while both are in the document.
(name === 'id' && el.namespaceURI !== SVG_NS) ||
(/^(href|src|xlink:href|action|formaction)$/.test(name) && /^\s*javascript:/i.test(value))
)
el.removeAttribute(name)
}
if (el instanceof HTMLInputElement) el.removeAttribute('value')
else if (el instanceof HTMLTextAreaElement) el.textContent = ''
else if (el.hasAttribute('contenteditable')) el.replaceChildren()
})
return new XMLSerializer().serializeToString(clone)
}
function linkedStylesheets(): string[] {
return Array.from(document.querySelectorAll<HTMLLinkElement>('link[rel="stylesheet"]'))
.map((l) => l.getAttribute('href') ?? '')
.filter(Boolean)
}
// SvelteKit keeps every visited route's stylesheets linked, so the stylesheets a Home reached in
// the app sees are not the ones a reload of it needs.
let navigatedInApp = false
/** Called by the root layout before every client-side navigation. */
export function noteClientNavigation(): void {
navigatedInApp = true
}
/** Only the plain Home URL: a search or another tab renders something else. */
function isPlainHomeUrl(url: URL): boolean {
let other = false
url.searchParams.forEach((_, k) => (other ||= k !== 'workspace'))
return url.pathname === '/' && !other
}
/**
* Saves what Home shows now for `workspace`, if the session it was rendered for is still the
* browser's. Anything that cannot be painted faithfully on the next load clears the previous
* snapshot instead of keeping one that no longer matches.
*/
export function saveHomeSnapshot(
workspace: string,
userWorkspace: string | undefined,
stylesheets: string[] = linkedStylesheets()
): void {
try {
const hint = readSessionHint()
if (
!hint ||
!sessionStillConfirmed() ||
userWorkspace !== workspace ||
window.parent !== window ||
!isPlainHomeUrl(new URL(location.href)) ||
homeSnapshotShown()
)
return
const app = document.getElementById('wm-app')
if (!app) return
const styles = Array.from(document.head.querySelectorAll('style'))
.filter((s) => !s.hasAttribute('data-wm-shell') && !s.hasAttribute('data-wm-home-snapshot'))
.map((s) => s.textContent ?? '')
const html = snapshotMarkup(app)
// Unbundled dev styles arrive as megabytes of inline <style>: no snapshot there.
if (
html.length > MAX_HTML_CHARS ||
styles.reduce((n, s) => n + s.length, 0) > MAX_INLINE_STYLE_CHARS
) {
clearHomeSnapshot()
return
}
const snapshot: HomeSnapshot = {
format: HOME_SNAPSHOT_FORMAT,
build: version,
cookie: __WM_SESSION_HINT__,
hint,
workspace,
width: window.innerWidth,
dark: document.documentElement.classList.contains('dark'),
htmlClass: document.documentElement.className,
// The cover is opaque so the app mounting under it never shows through.
background: getComputedStyle(document.documentElement).backgroundColor,
stylesheets,
styles,
html,
savedAt: Date.now()
}
localStorage.setItem(HOME_SNAPSHOT_KEY, JSON.stringify(snapshot))
} catch {
clearHomeSnapshot()
}
}
/**
* Saves Home while it is mounted: once its fresh data has had time to land, and again as the
* page is left or hidden. Only while nothing has been pressed on it since it mounted: a reload
* renders Home with folders collapsed and the composer closed, and a snapshot of another state
* would jump at the hand-over. Only for a Home the document loaded on, with the stylesheets linked
* as it mounted: what a reload's first frame has. Returns the cleanup.
*/
export function watchHomeForSnapshot(
current: () => { workspace: string | undefined; userWorkspace: string | undefined }
): () => void {
if (navigatedInApp) return () => {}
const stylesheets = linkedStylesheets()
let touched = false
const touch = () => (touched = true)
// A shortcut or a modifier changes nothing on Home, and a keyboard reload or an alt-tab would
// otherwise cancel the save it leads to.
const touchKey = (e: KeyboardEvent) => {
if (!e.ctrlKey && !e.metaKey && !e.altKey && !/^(F\d+|Control|Meta|Alt|Shift|Tab)$/.test(e.key))
touched = true
}
const save = () => {
const { workspace, userWorkspace } = current()
if (!touched && workspace) saveHomeSnapshot(workspace, userWorkspace, stylesheets)
}
const onHidden = () => {
if (document.visibilityState === 'hidden') save()
}
const settled = setTimeout(save, 2000)
document.addEventListener('pointerdown', touch, true)
document.addEventListener('keydown', touchKey, true)
document.addEventListener('visibilitychange', onHidden)
window.addEventListener('pagehide', save)
return () => {
clearTimeout(settled)
document.removeEventListener('pointerdown', touch, true)
document.removeEventListener('keydown', touchKey, true)
document.removeEventListener('visibilitychange', onHidden)
window.removeEventListener('pagehide', save)
}
}
export function clearHomeSnapshot(): void {
try {
localStorage.removeItem(HOME_SNAPSHOT_KEY)
} catch {}
}
/** Whether `app.html` painted a snapshot that the live page has not replaced yet. */
export function homeSnapshotShown(): boolean {
return typeof document !== 'undefined' && !!document.getElementById('wm-home-snapshot')
}
/**
* Replaces the snapshot with the live page. Called as the live page mounts, before the browser
* can paint it, so the two never share a frame.
*/
export function releaseHomeSnapshot(): void {
document.getElementById('wm-home-snapshot')?.remove()
// Its stylesheet links stay: they are the app's own now, since the build's preload helper
// does not add a stylesheet the document already links.
document.querySelectorAll('style[data-wm-home-snapshot]').forEach((el) => el.remove())
document.documentElement.removeAttribute('data-wm-home-snapshot')
}
+8
View File
@@ -31,6 +31,14 @@ describe('clearUser', () => {
expect(localStorage.getItem('dark-mode')).toBe('true')
})
it("drops the Home snapshot app.html would paint", async () => {
localStorage.setItem('wm-home-snapshot', '{}')
await clearUser()
expect(localStorage.getItem('wm-home-snapshot')).toBeNull()
})
// Logging out while impersonating must not leave the impersonator's own token behind.
it('drops the impersonation token backup', async () => {
sessionStorage.setItem('pre_impersonation_token', 'a-token')
+2
View File
@@ -4,6 +4,7 @@ import { UserService } from '$lib/gen'
import { clearStores } from './storeUtils'
import { clearPersistedCache } from './persistedCache.svelte'
import { forgetLastSession } from './lastSession'
import { clearHomeSnapshot } from './homeSnapshot'
// Note: logout and logoutWithRedirect have been moved to logoutKit.ts
// as they depend on SvelteKit navigation
@@ -29,6 +30,7 @@ export async function clearUser() {
// Before clearStores: the cache is found by the email it clears.
await clearPersistedCache()
forgetLastSession()
clearHomeSnapshot()
noteSessionEmail(undefined)
accountSetup.reset()
clearStores()
@@ -139,6 +139,8 @@
import Modal2 from '$lib/components/common/modal/Modal2.svelte'
import CreateWorkspaceInner from '$lib/components/workspaceSettings/CreateWorkspaceInner.svelte'
import { recordForkParent, rememberForkParent } from '$lib/forkParentMemory'
import { homeSnapshotShown } from '$lib/homeSnapshot'
import { persistedValue } from '$lib/persistedResource.svelte'
interface Props {
children?: import('svelte').Snippet
}
@@ -610,8 +612,9 @@
}
// Set once the user docks or detaches, so the rail that mounts from then on skips its
// app-entry animation (`wm-sidebar-in`) and only plays `railMorph`.
let dockToggled = $state(false)
// app-entry animation (`wm-sidebar-in`) and only plays `railMorph`. Also set when the rail
// replaces the one in Home's snapshot (homeSnapshot.ts), which is already on screen.
let dockToggled = $state(homeSnapshotShown())
function setDetached(detached: boolean) {
dockToggled = true
menuOpen = false
@@ -680,6 +683,22 @@
((await SettingService.getGlobal({ key: 'disable_hub' })) as boolean) ?? false
}
// Home holds its Favorites and Recent shortcuts back until the favorites are in, so they are
// painted from the last answer as soon as the user is known: Home's first frame then has them,
// as the snapshot of it painted before boot (homeSnapshot.ts) does. Paths and summaries only.
const favoritesCache = persistedValue<typeof favoriteManager.current>('favorites', 1)
$effect(() => {
const workspace = $workspaceStore
if (!$userStore || !workspace) return
untrack(() => {
if (favoriteManager.loadedFor === workspace) return
const cached = favoritesCache.peek({ workspace })
if (!cached) return
favoriteManager.current = cached
favoriteManager.loadedFor = workspace
})
})
async function loadFavorites() {
const workspace = $workspaceStore ?? ''
try {
@@ -699,6 +718,7 @@
}
async function loadFavoritesFor(workspace: string) {
const sentWith = readSessionHint()
const [scripts, flows, apps, agents, assets] = await Promise.all([
ScriptService.listScripts({
workspace,
@@ -744,6 +764,7 @@
kind: 'asset' as const
}))
]
favoritesCache.save({ workspace }, favoriteManager.current, sentWith)
}
async function loadUsedTriggerKinds() {
@@ -49,6 +49,7 @@
import HomeAIChat from '$lib/components/home/HomeAIChat.svelte'
import { isGlobalAiEnabled } from '$lib/components/copilot/chat/global/gate'
import { onDestroy, onMount, untrack } from 'svelte'
import { homeSnapshotShown, releaseHomeSnapshot, watchHomeForSnapshot } from '$lib/homeSnapshot'
import OperatorTour from '$lib/components/tutorials/OperatorTour.svelte'
import {
hasSeenOperatorTour,
@@ -163,6 +164,16 @@
})
})
// Replacing the snapshot `app.html` painted, the page is already on screen: no arrival to play.
const fromSnapshot = homeSnapshotShown()
onMount(() => {
releaseHomeSnapshot()
return watchHomeForSnapshot(() => ({
workspace: $workspaceStore,
userWorkspace: $userStore?.workspace_id
}))
})
let operatorTour: OperatorTour | undefined = $state(undefined)
// Delayed so the tabs the first steps point at exist. `runTutorial` refuses while a tour is
@@ -351,7 +362,9 @@
<div
bind:this={pageEl}
class="wm-page-in group/home flex flex-col w-full h-full overflow-y-auto items-center"
class="{fromSnapshot
? ''
: 'wm-page-in'} group/home flex flex-col w-full h-full overflow-y-auto items-center"
style="scrollbar-gutter: stable both-edges;"
style:--home-pinned="{pinnedHeight}px"
>
+9
View File
@@ -13,6 +13,8 @@
import { page } from '$app/state'
import { installDevPollingDormancy } from '$lib/utils/devPollingDormancy'
import { noteClientNavigation, releaseHomeSnapshot } from '$lib/homeSnapshot'
import { onNavigate } from '$app/navigation'
interface Props {
children?: import('svelte').Snippet
}
@@ -33,6 +35,13 @@
document.getElementById('svelte-global-loader')?.remove()
// Home replaces the snapshot `app.html` painted when it mounts; a load that lands elsewhere
// (a redirect to login, to the workspace picker) replaces it here.
$effect(() => {
if (page.route.id !== '/(root)/(logged)') releaseHomeSnapshot()
})
onNavigate(noteClientNavigation)
installDevPollingDormancy()
// Prevent scrolling over number inputs from changing their value