Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
opt(web): low hanging optimizations for page load time (#1168)
teo91028482c11d
diff --git a/js/app/bun.lock b/js/app/bun.lockindex 6c018808f5..5eec5d5e99 100644--- a/js/app/bun.lock+++ b/js/app/bun.lock@@ -20,6 +20,7 @@"@corvu/resizable": "^0.2.5","@corvu/tooltip": "^0.2.2","@floating-ui/dom": "^1.7.4",+ "@fontsource-variable/inter": "^5.2.8","@inkibra/tauri-plugins": "git+https://github.com/seanaye/tauri-plugins.git#0c932ffd3202145b40645246d87a38deb72ba09c","@kobalte/core": "^0.13.11","@leeoniya/ufuzzy": "^1.0.19",@@ -665,6 +666,8 @@"@floating-ui/utils": ["@floating-ui/[email protected]", "", {}, "sha512-aGTxbpbg8/b5JfU1HXSrbH3wXZuLPJcNEcZQFMxLs3oSzgtVu6nFPkbbGGUvBcUjKV2YyB9Wxxabo+HEH9tcRQ=="],+ "@fontsource-variable/inter": ["@fontsource-variable/[email protected]", "", {}, "sha512-kOfP2D+ykbcX/P3IFnokOhVRNoTozo5/JxhAIVYLpea/UBmCQ/YWPBfWIDuBImXX/15KH+eKh4xpEUyS2sQQGQ=="],+"@gerrit0/mini-shiki": ["@gerrit0/[email protected]", "", { "dependencies": { "@shikijs/engine-oniguruma": "^3.13.0", "@shikijs/langs": "^3.13.0", "@shikijs/themes": "^3.13.0", "@shikijs/types": "^3.13.0", "@shikijs/vscode-textmate": "^10.0.2" } }, "sha512-mCrNvZNYNrwKer5PWLF6cOc0OEe2eKzgy976x+IT2tynwJYl+7UpHTSeXQJGijgTcoOf+f359L946unWlYRnsg=="],"@google-cloud/common": ["@google-cloud/[email protected]", "", { "dependencies": { "@google-cloud/projectify": "^4.0.0", "@google-cloud/promisify": "^4.0.0", "arrify": "^2.0.1", "duplexify": "^4.1.1", "extend": "^3.0.2", "google-auth-library": "^9.0.0", "html-entities": "^2.5.2", "retry-request": "^7.0.0", "teeny-request": "^9.0.0" } }, "sha512-V7bmBKYQyu0eVG2BFejuUjlBt+zrya6vtsKdY+JxMM/dNntPF41vZ9+LhOshEUH01zOHEqBSvI7Dad7ZS6aUeA=="],diff --git a/js/app/package.json b/js/app/package.jsonindex 04d4130869..923868f19c 100644--- a/js/app/package.json+++ b/js/app/package.json@@ -36,6 +36,7 @@"@corvu/resizable": "^0.2.5","@corvu/tooltip": "^0.2.2","@floating-ui/dom": "^1.7.4",+ "@fontsource-variable/inter": "^5.2.8","@inkibra/tauri-plugins": "git+https://github.com/seanaye/tauri-plugins.git#0c932ffd3202145b40645246d87a38deb72ba09c","@kobalte/core": "^0.13.11","@leeoniya/ufuzzy": "^1.0.19",diff --git a/js/app/packages/app/component/auth/Login.tsx b/js/app/packages/app/component/auth/Login.tsxindex b9cdfe8cc7..ad153155c1 100644--- a/js/app/packages/app/component/auth/Login.tsx+++ b/js/app/packages/app/component/auth/Login.tsx@@ -9,18 +9,22 @@ import { Navigate, useLocation, useSearchParams } from '@solidjs/router';import {createEffect,createSignal,+ lazy,Match,onCleanup,Show,+ Suspense,Switch,} from 'solid-js';import { updateCookie } from '@core/util/cookies';import { EmailForm } from './EmailForm';import { LoginOptions } from './LoginOptions';import { identifyUser, Stage } from './Shared';-import ThreeWireframe from './ThreeWireframe';import { VerifyForm } from './VerifyForm';+// Lazy load ThreeWireframe to keep three.js out of main bundle+const ThreeWireframe = lazy(() => import('./ThreeWireframe'));+export function Login() {const [stage, setStage] = createSignal(Stage.None);const location = useLocation<RedirectLocation>();@@ -94,7 +98,18 @@ export function Login() {<div class="grid w-full h-[100dvh] items-center justify-center font-mono text-[15px]"><div class="grid w-min bg-[var(--color-surface)]"><div class="border border-dashed border-[var(--color-ink)] box-border w-[350px]">- <ThreeWireframe src="m" scale={9.5} clockwise={false} />+ <Suspense+ fallback={+ <div+ style={{+ width: 'min(350px, 100%)',+ 'aspect-ratio': '1 / 1',+ }}+ />+ }+ >+ <ThreeWireframe src="m" scale={9.5} clockwise={false} />+ </Suspense></div><Switch><Match when={stage() === Stage.None}>diff --git a/js/app/packages/app/component/auth/ThreeWireframe.tsx b/js/app/packages/app/component/auth/ThreeWireframe.tsxindex b50388c80a..3b527c13be 100644--- a/js/app/packages/app/component/auth/ThreeWireframe.tsx+++ b/js/app/packages/app/component/auth/ThreeWireframe.tsx@@ -1,4 +1,10 @@-import { createEffect, createSignal, onCleanup, onMount } from 'solid-js';+import {+ createEffect,+ createMemo,+ createSignal,+ onCleanup,+ onMount,+} from 'solid-js';import * as THREE from 'three';import isWebGL2Available from 'three/addons/capabilities/WebGL.js';import { OrbitControls } from 'three/addons/controls/OrbitControls.js';@@ -6,9 +12,9 @@ import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';import { createThemeEffect } from '../../../block-theme/signals/themeReactive';import modelM from './model-m.glb?inline';import {- colorAccent,- colorBase,- colorContrast,+ colorAccentRgb,+ colorBaseRgb,+ colorContrastRgb,pixelation,rafSpeed,setColor,@@ -43,6 +49,40 @@ export default function ThreeWireframe(props: ThreeWireframeProps) {let onPointerMove: (event: PointerEvent) => void;let pointerRelease: () => void;+ // Convert RGB tuples to THREE.Color objects+ const colorContrast = createMemo(() => {+ const rgb = colorContrastRgb();+ if (!rgb) return undefined;+ return new THREE.Color().setRGB(+ rgb[0],+ rgb[1],+ rgb[2],+ THREE.SRGBColorSpace+ );+ });++ const colorAccent = createMemo(() => {+ const rgb = colorAccentRgb();+ if (!rgb) return undefined;+ return new THREE.Color().setRGB(+ rgb[0],+ rgb[1],+ rgb[2],+ THREE.SRGBColorSpace+ );+ });++ const colorBase = createMemo(() => {+ const rgb = colorBaseRgb();+ if (!rgb) return undefined;+ return new THREE.Color().setRGB(+ rgb[0],+ rgb[1],+ rgb[2],+ THREE.SRGBColorSpace+ );+ });+onMount(async () => {if (!isWebGL2Available) {return;@@ -154,12 +194,16 @@ export default function ThreeWireframe(props: ThreeWireframeProps) {const distanceToPointer = pointerWorldPosition.distanceTo(vertex);const normalizedDistance = Math.min(distanceToPointer / maxDistance, 1);- const mixedColor = new THREE.Color().lerpColors(- colorAccent()!,- colorContrast()!,- normalizedDistance- );- colors.setXYZ(i, mixedColor.r, mixedColor.g, mixedColor.b);+ const accent = colorAccent();+ const contrast = colorContrast();+ if (accent && contrast) {+ const mixedColor = new THREE.Color().lerpColors(+ accent,+ contrast,+ normalizedDistance+ );+ colors.setXYZ(i, mixedColor.r, mixedColor.g, mixedColor.b);+ }}colors.needsUpdate = true;}@@ -192,7 +236,10 @@ export default function ThreeWireframe(props: ThreeWireframeProps) {: Math.exp(speed() * rafSpeed * 0.5);});createEffect(() => {- scene.fog = new THREE.Fog(colorBase()!, 8, 13);+ const base = colorBase();+ if (base) {+ scene.fog = new THREE.Fog(base, 8, 13);+ }});createEffect(() => {renderer.setPixelRatio(Math.pow(pixelation(), 6));diff --git a/js/app/packages/app/component/auth/store.ts b/js/app/packages/app/component/auth/store.tsindex a7d51ee863..a8e4ca6e93 100644--- a/js/app/packages/app/component/auth/store.ts+++ b/js/app/packages/app/component/auth/store.ts@@ -1,10 +1,16 @@import { createSignal } from 'solid-js';-import * as THREE from 'three';import { themeReactive } from '../../../block-theme/signals/themeReactive';-export const [colorContrast, setColorContrast] = createSignal<THREE.Color>();-export const [colorAccent, setColorAccent] = createSignal<THREE.Color>();-export const [colorBase, setColorBase] = createSignal<THREE.Color>();+// RGB values as tuples - THREE.Color creation moved to ThreeWireframe for lazy loading+export const [colorContrastRgb, setColorContrastRgb] = createSignal<+ [number, number, number] | undefined+>();+export const [colorAccentRgb, setColorAccentRgb] = createSignal<+ [number, number, number] | undefined+>();+export const [colorBaseRgb, setColorBaseRgb] = createSignal<+ [number, number, number] | undefined+>();export const rafSpeed = navigator.vendor?.includes('Apple') ? 2 : 1;export const [currentTheme, setCurrentTheme] = createSignal();export const [pixelation, setPixelation] = createSignal(1);@@ -30,30 +36,9 @@ export interface ThemeValues {export function setColor() {const currentTheme = getCurrentTheme();- setColorContrast(- new THREE.Color().setRGB(- currentTheme.contrast[0],- currentTheme.contrast[1],- currentTheme.contrast[2],- THREE.SRGBColorSpace- )- );- setColorBase(- new THREE.Color().setRGB(- currentTheme.surface[0],- currentTheme.surface[1],- currentTheme.surface[2],- THREE.SRGBColorSpace- )- );- setColorAccent(- new THREE.Color().setRGB(- currentTheme.accent[0],- currentTheme.accent[1],- currentTheme.accent[2],- THREE.SRGBColorSpace- )- );+ setColorContrastRgb(currentTheme.contrast);+ setColorBaseRgb(currentTheme.surface);+ setColorAccentRgb(currentTheme.accent);}export function oklchToRgb(diff --git a/js/app/packages/app/index.html b/js/app/packages/app/index.htmlindex 0649e36728..c70ddc9b64 100644--- a/js/app/packages/app/index.html+++ b/js/app/packages/app/index.html@@ -25,13 +25,6 @@user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/--><link rel="manifest" href="/manifest.json" />-- <link rel="preconnect" href="https://fonts.googleapis.com" />- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />- <link- href="https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,100..900;1,100..900&display=swap"- rel="stylesheet"- /></head><body>diff --git a/js/app/packages/app/index.tsx b/js/app/packages/app/index.tsxindex add2813f2c..d9297da470 100644--- a/js/app/packages/app/index.tsx+++ b/js/app/packages/app/index.tsx@@ -1,4 +1,5 @@import './index.css';+import '@fontsource-variable/inter';// SolidDevtools retains disposed memos, causes memory leak// import 'solid-devtools';@@ -7,7 +8,6 @@ import { initializeLexical } from '@core/component/LexicalMarkdown/init';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { getPlatform, isTauri } from '@core/util/platform';import { platformFetch } from '@core/util/platformFetch';-import * as Observability from '@observability';import { ErrorBoundary, render } from 'solid-js/web';import { FatalError } from './component/FatalError';import { Root } from './component/Root';@@ -84,14 +84,26 @@ const renderApp = () => {function main() {console.log('App Version ', import.meta.env.__APP_VERSION__);- Observability.init(import.meta.env.__APP_VERSION__);- // during `vite dev` (but not dev builds), don't inject analytics garbage+ // during `vite dev` (but not dev builds), don't inject analytics/observabilityif (!import.meta.hot) {- analytics.init({- appVersion: import.meta.env.__APP_VERSION__,- segmentWriteKey: import.meta.env.VITE_SEGMENT_WRITE_KEY,- mode: import.meta.env.MODE,+ const scheduleIdleTask =+ window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1));++ // Lazy load and init observability (Datadog) to reduce initial bundle+ scheduleIdleTask(() => {+ import('@observability').then((Observability) => {+ Observability.init(import.meta.env.__APP_VERSION__);+ });+ });++ // Defer analytics initialization to avoid blocking initial render+ scheduleIdleTask(() => {+ analytics.init({+ appVersion: import.meta.env.__APP_VERSION__,+ segmentWriteKey: import.meta.env.VITE_SEGMENT_WRITE_KEY,+ mode: import.meta.env.MODE,+ });});// this event is emitted when dynamically loading a module failsdiff --git a/js/app/packages/app/vite.base.ts b/js/app/packages/app/vite.base.tsindex a35e149427..e8f2ce18c5 100644--- a/js/app/packages/app/vite.base.ts+++ b/js/app/packages/app/vite.base.ts@@ -85,11 +85,21 @@ export const createAppViteConfig = ({entryFileNames: `assets/[name].js`,chunkFileNames: `assets/[name].js`,assetFileNames: `assets/[name].[ext]`,+ manualChunks: {+ three: ['three'],+ katex: ['katex'],+ pdfjs: ['pdfjs-dist'],+ },}: {format: 'es',chunkFileNames: '[name]-[hash].js',entryFileNames: '[name]-[hash].js',+ manualChunks: {+ three: ['three'],+ katex: ['katex'],+ pdfjs: ['pdfjs-dist'],+ },},},assetsInlineLimit: (filePath) => {diff --git a/js/app/packages/core/component/LexicalMarkdown/component/decorator/Equation.tsx b/js/app/packages/core/component/LexicalMarkdown/component/decorator/Equation.tsxindex db1b2f2958..61d070a71b 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/decorator/Equation.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/decorator/Equation.tsx@@ -1,10 +1,23 @@-import katex from 'katex';-import 'katex/dist/katex.min.css';import type { NodeKey } from 'lexical';-import { createEffect, createSignal, useContext } from 'solid-js';+import { createEffect, createSignal, onMount, useContext } from 'solid-js';import { LexicalWrapperContext } from '../../context/LexicalWrapperContext';import { TRY_UPDATE_EQUATION_COMMAND } from '../../plugins';+// Lazy load katex - will be loaded on first render+let katexModule: typeof import('katex') | null = null;+let katexLoaded = false;++async function loadKatex() {+ if (katexLoaded) return katexModule;+ const [mod] = await Promise.all([+ import('katex'),+ import('katex/dist/katex.min.css'),+ ]);+ katexModule = mod;+ katexLoaded = true;+ return mod;+}+export function Equation(props: {equation: string;inline: boolean;@@ -13,6 +26,7 @@ export function Equation(props: {const [katexElementRef, setKatexElementRef] = createSignal<HTMLElement | undefined>(undefined);+ const [isKatexReady, setIsKatexReady] = createSignal(katexLoaded);const lexicalWrapper = useContext(LexicalWrapperContext);const selection = () => lexicalWrapper?.selection;@@ -23,11 +37,19 @@ export function Equation(props: {return sel.type === 'node' && sel.nodeKeys.has(props.key ?? '');};+ onMount(async () => {+ if (!katexLoaded) {+ await loadKatex();+ setIsKatexReady(true);+ }+ });+createEffect(() => {const katexElement = katexElementRef();+ const ready = isKatexReady();- if (katexElement) {- katex.render(props.equation, katexElement, {+ if (katexElement && ready && katexModule) {+ katexModule.default.render(props.equation, katexElement, {displayMode: !props.inline,errorColor: '#cc0000',output: 'html',diff --git a/js/app/packages/service-clients/service-sync/client.ts b/js/app/packages/service-clients/service-sync/client.tsindex 68a79d795a..5a5bb453fb 100644--- a/js/app/packages/service-clients/service-sync/client.ts+++ b/js/app/packages/service-clients/service-sync/client.ts@@ -24,11 +24,26 @@ const SYNC_ORIGIN =? 'https://dev.macro.com': 'https://macro.com';-const WAKEUP_TTL = 55 * 1000; // 55 seconds - cloudflare ttl is 60+const WAKEUP_TTL = 55 * 1000;+const WAKEUP_DEBOUNCE_MS = 200;-const pendingWakeups = new Map<string, ReturnType<typeof setTimeout>>();+const pendingWakeups = new Map<+ string,+ { debounceTimer: ReturnType<typeof setTimeout>; idleTaskId?: number }+>();const recentWakeups = new Map<string, number>();+const scheduleIdleTask =+ typeof window !== 'undefined' && window.requestIdleCallback+ ? (cb: () => void) => window.requestIdleCallback(cb)+ : (cb: () => void) => window.setTimeout(cb, 0) as unknown as number;++const cancelIdleTask =+ typeof window !== 'undefined' && window.cancelIdleCallback+ ? (id: number) => window.cancelIdleCallback(id)+ : (id: number) =>+ window.clearTimeout(id as unknown as ReturnType<typeof setTimeout>);+export function syncFetch(url: string,init?: SafeFetchInit@@ -65,45 +80,53 @@ export const syncServiceClient = {method: 'GET',});},- async safeWakeup(id: string, delay: number = 200) {+ safeWakeup(id: string) {const lastWakeup = recentWakeups.get(id);if (lastWakeup && Date.now() - lastWakeup < WAKEUP_TTL) {return;}- const existingTimeout = pendingWakeups.get(id);- if (existingTimeout) {- // let the first timeout handle it.+ const existing = pendingWakeups.get(id);+ if (existing) {return;}- const timeout = setTimeout(async () => {- try {- await syncFetch(`/document/${id}/wakeup`, {- method: 'GET',- });- recentWakeups.set(id, Date.now());-- // prune- const now = Date.now();- for (const [key, timestamp] of recentWakeups.entries()) {- if (now - timestamp >= WAKEUP_TTL) {- recentWakeups.delete(key);+ const debounceTimer = setTimeout(() => {+ const pending = pendingWakeups.get(id);+ if (!pending) return;++ const idleTaskId = scheduleIdleTask(async () => {+ try {+ await syncFetch(`/document/${id}/wakeup`, {+ method: 'GET',+ });+ recentWakeups.set(id, Date.now());++ const now = Date.now();+ for (const [key, timestamp] of recentWakeups.entries()) {+ if (now - timestamp >= WAKEUP_TTL) {+ recentWakeups.delete(key);+ }}+ } catch (error) {+ console.error(`Failed to wakeup document ${id}:`, error);+ } finally {+ pendingWakeups.delete(id);}- } catch (error) {- console.error(`Failed to wakeup document ${id}:`, error);- } finally {- pendingWakeups.delete(id);- }- }, delay);+ });++ pendingWakeups.set(id, { debounceTimer, idleTaskId });+ }, WAKEUP_DEBOUNCE_MS);- pendingWakeups.set(id, timeout);+ pendingWakeups.set(id, { debounceTimer });},cancelWakeup(id: string) {- const timeout = pendingWakeups.get(id);- if (timeout) {- clearTimeout(timeout);+ const pending = pendingWakeups.get(id);+ if (pending) {+ clearTimeout(pending.debounceTimer);+ if (pending.idleTaskId !== undefined) {+ cancelIdleTask(pending.idleTaskId);+ }pendingWakeups.delete(id);}},