mirror of
https://github.com/AutoMaker-Org/automaker.git
synced 2026-03-16 21:53:07 +00:00
* fix(copilot): correct tool.execution_complete event handling The CopilotProvider was using incorrect event type and data structure for tool execution completion events from the @github/copilot-sdk, causing tool call outputs to be empty. Changes: - Update event type from 'tool.execution_end' to 'tool.execution_complete' - Fix data structure to use nested result.content instead of flat result - Fix error structure to use error.message instead of flat error - Add success field to match SDK event structure - Add tests for empty and missing result handling This aligns with the official @github/copilot-sdk v0.1.16 types defined in session-events.d.ts. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * test(copilot): add edge case test for error with code field Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * refactor(copilot): improve error handling and code quality Code review improvements: - Extract magic string '[ERROR]' to TOOL_ERROR_PREFIX constant - Add null-safe error handling with direct error variable assignment - Include error codes in error messages for better debugging - Add JSDoc documentation for tool.execution_complete handler - Update tests to verify error codes are displayed - Add missing tool_use_id assertion in error test These changes improve: - Code maintainability (no magic strings) - Debugging experience (error codes now visible) - Type safety (explicit null checks) - Test coverage (verify error code formatting) Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Changes from fix/bug-fixes-1-0 * test(copilot): add edge case test for error with code field Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * Changes from fix/bug-fixes-1-0 * fix: Handle detached HEAD state in worktree discovery and recovery * fix: Remove unused isDevServerStarting prop and md: breakpoint classes * fix: Add missing dependency and sanitize persisted cache data * feat: Ensure NODE_ENV is set to test in vitest configs * feat: Configure Playwright to run only E2E tests * fix: Improve PR tracking and dev server lifecycle management * feat: Add settings-based defaults for planning mode, model config, and custom providers. Fixes #816 * feat: Add worktree and branch selector to graph view * fix: Add timeout and error handling for worktree HEAD ref resolution * fix: use absolute icon path and place icon outside asar on Linux The hicolor icon theme index only lists sizes up to 512x512, so an icon installed only at 1024x1024 is invisible to GNOME/KDE's theme resolver, causing both the app launcher and taskbar to show a generic icon. Additionally, BrowserWindow.icon cannot be read by the window manager when the file is inside app.asar. - extraResources: copy logo_larger.png to resources/ (outside asar) so it lands at /opt/Automaker/resources/logo_larger.png on install - linux.desktop.Icon: set to the absolute resources path, bypassing the hicolor theme lookup and its size constraints entirely - icon-manager.ts: on Linux production use process.resourcesPath so BrowserWindow receives a real filesystem path the WM can read directly Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: use linux.desktop.entry for custom desktop Icon field electron-builder v26 rejects arbitrary keys in linux.desktop — the correct schema wraps custom .desktop overrides inside desktop.entry. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * fix: set desktop name on Linux so taskbar uses the correct app icon Without app.setDesktopName(), the window manager cannot associate the running Electron process with automaker.desktop. GNOME/KDE fall back to _NET_WM_ICON which defaults to Electron's own bundled icon. Calling app.setDesktopName('automaker.desktop') before any window is created sets the _GTK_APPLICATION_ID hint and XDG app_id so the WM picks up the desktop entry's Icon for the taskbar. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com> * Fix: memory and context views mobile friendly (#818) * Changes from fix/memory-and-context-mobile-friendly * fix: Improve file extension detection and add path traversal protection * refactor: Extract file extension utilities and add path traversal guards Code review improvements: - Extract isMarkdownFilename and isImageFilename to shared image-utils.ts - Remove duplicated code from context-view.tsx and memory-view.tsx - Add path traversal guard for context fixture utilities (matching memory) - Add 7 new tests for context fixture path traversal protection - Total 61 tests pass Addresses code review feedback from PR #813 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * test: Add e2e tests for profiles crud and board background persistence * Update apps/ui/playwright.config.ts Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * fix: Add robust test navigation handling and file filtering * fix: Format NODE_OPTIONS configuration on single line * test: Update profiles and board background persistence tests * test: Replace iPhone 13 Pro with Pixel 5 for mobile test consistency * Update apps/ui/src/components/views/context-view.tsx Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * chore: Remove test project directory * feat: Filter context files by type and improve mobile menu visibility --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com> * fix: Improve test reliability and localhost handling * chore: Use explicit TEST_USE_EXTERNAL_BACKEND env var for server cleanup * feat: Add E2E/CI mock mode for provider factory and auth verification * feat: Add remoteBranch parameter to pull and rebase operations * chore: Enhance E2E testing setup with worker isolation and auth state management - Updated .gitignore to include worker-specific test fixtures. - Modified e2e-tests.yml to implement test sharding for improved CI performance. - Refactored global setup to authenticate once and save session state for reuse across tests. - Introduced worker-isolated fixture paths to prevent conflicts during parallel test execution. - Improved test navigation and loading handling for better reliability. - Updated various test files to utilize new auth state management and fixture paths. * fix: Update Playwright configuration and improve test reliability - Increased the number of workers in Playwright configuration for better parallelism in CI environments. - Enhanced the board background persistence test to ensure dropdown stability by waiting for the list to populate before interaction, improving test reliability. * chore: Simplify E2E test configuration and enhance mock implementations - Updated e2e-tests.yml to run tests in a single shard for streamlined CI execution. - Enhanced unit tests for worktree list handling by introducing a mock for execGitCommand, improving test reliability and coverage. - Refactored setup functions to better manage command mocks for git operations in tests. - Improved error handling in mkdirSafe function to account for undefined stats in certain environments. * refactor: Improve test configurations and enhance error handling - Updated Playwright configuration to clear VITE_SERVER_URL, ensuring the frontend uses the Vite proxy and preventing cookie domain mismatches. - Enhanced MergeRebaseDialog logic to normalize selectedBranch for better handling of various ref formats. - Improved global setup with a more robust backend health check, throwing an error if the backend is not healthy after retries. - Refactored project creation tests to handle file existence checks more reliably. - Added error handling for missing E2E source fixtures to guide setup process. - Enhanced memory navigation to handle sandbox dialog visibility more effectively. * refactor: Enhance Git command execution and improve test configurations - Updated Git command execution to merge environment paths correctly, ensuring proper command execution context. - Refactored the Git initialization process to handle errors more gracefully and ensure user configuration is set before creating the initial commit. - Improved test configurations by updating Playwright test identifiers for better clarity and consistency across different project states. - Enhanced cleanup functions in tests to handle directory removal more robustly, preventing errors during test execution. * fix: Resolve React hooks errors from duplicate instances in dependency tree * style: Format alias configuration for improved readability --------- Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: DhanushSantosh <dhanushsantoshs05@gmail.com> Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com> Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
371 lines
15 KiB
TypeScript
371 lines
15 KiB
TypeScript
import * as path from 'path';
|
|
import * as fs from 'fs';
|
|
import * as crypto from 'crypto';
|
|
import react from '@vitejs/plugin-react';
|
|
import tailwindcss from '@tailwindcss/vite';
|
|
import { defineConfig, type Plugin } from 'vite';
|
|
import electron from 'vite-plugin-electron/simple';
|
|
import { TanStackRouterVite } from '@tanstack/router-plugin/vite';
|
|
import { fileURLToPath } from 'url';
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
|
|
// Read version from package.json
|
|
const packageJson = JSON.parse(fs.readFileSync(path.resolve(__dirname, 'package.json'), 'utf-8'));
|
|
const appVersion = packageJson.version;
|
|
|
|
// Generate a build hash for cache busting.
|
|
// Uses git commit hash when available (deterministic across CI builds),
|
|
// falls back to version + timestamp for non-git environments.
|
|
// This ensures users get fresh SW caches after each deployment.
|
|
function getBuildHash(): string {
|
|
// Try git commit hash first (deterministic, same across CI workers)
|
|
try {
|
|
const { execSync } = require('child_process');
|
|
const gitHash = execSync('git rev-parse --short=8 HEAD', { encoding: 'utf-8' }).trim();
|
|
if (gitHash) return gitHash;
|
|
} catch {
|
|
// Not a git repo or git not available — fall back
|
|
}
|
|
// Fallback: version + timestamp (unique per build)
|
|
return crypto.createHash('md5').update(`${appVersion}-${Date.now()}`).digest('hex').slice(0, 8);
|
|
}
|
|
|
|
const buildHash = getBuildHash();
|
|
|
|
/**
|
|
* Vite plugin to inject the build hash into sw.js for cache busting.
|
|
*
|
|
* Problem: CACHE_NAME is hardcoded in the service worker.
|
|
* After a deployment, users may continue getting stale HTML from the SW cache
|
|
* if someone forgets to manually bump the version.
|
|
*
|
|
* Solution: Replace the hardcoded version with a build-time hash so the
|
|
* SW cache is automatically invalidated on each deployment.
|
|
*/
|
|
function swCacheBuster(): Plugin {
|
|
// Single constant for the cache name prefix — bump this when changing the SW cache version.
|
|
const CACHE_NAME_BASE = 'automaker-v5';
|
|
const CACHE_NAME_PATTERN = new RegExp(`const CACHE_NAME = '${CACHE_NAME_BASE}';`);
|
|
const CRITICAL_ASSETS_PATTERN = /const CRITICAL_ASSETS = \[\];/;
|
|
return {
|
|
name: 'sw-cache-buster',
|
|
// In build mode: copy sw.js to output with hash injected
|
|
// In dev mode: no transformation needed (sw.js is served from public/)
|
|
apply: 'build',
|
|
closeBundle() {
|
|
const swPath = path.resolve(__dirname, 'dist', 'sw.js');
|
|
if (!fs.existsSync(swPath)) {
|
|
console.warn('[sw-cache-buster] sw.js not found in dist/ — skipping cache bust');
|
|
return;
|
|
}
|
|
let swContent = fs.readFileSync(swPath, 'utf-8');
|
|
if (!CACHE_NAME_PATTERN.test(swContent)) {
|
|
console.error(
|
|
'[sw-cache-buster] Could not find CACHE_NAME declaration in sw.js. ' +
|
|
'The service worker cache will NOT be busted on this deploy! ' +
|
|
`Check that public/sw.js still contains: const CACHE_NAME = '${CACHE_NAME_BASE}';`
|
|
);
|
|
return;
|
|
}
|
|
swContent = swContent.replace(
|
|
CACHE_NAME_PATTERN,
|
|
`const CACHE_NAME = '${CACHE_NAME_BASE}-${buildHash}';`
|
|
);
|
|
console.log(`[sw-cache-buster] Injected build hash: ${CACHE_NAME_BASE}-${buildHash}`);
|
|
|
|
// Extract critical asset URLs from the built index.html and inject them
|
|
// into the SW so it can precache them on install (not just after the main
|
|
// thread sends PRECACHE_ASSETS). This ensures the very first visit populates
|
|
// the immutable cache, so PWA cold starts after memory eviction serve from cache.
|
|
const indexHtmlPath = path.resolve(__dirname, 'dist', 'index.html');
|
|
if (fs.existsSync(indexHtmlPath)) {
|
|
if (!CRITICAL_ASSETS_PATTERN.test(swContent)) {
|
|
console.warn(
|
|
'[sw-cache-buster] CRITICAL_ASSETS placeholder not found in sw.js — ' +
|
|
'precaching of critical assets was not injected. ' +
|
|
'Check that public/sw.js still contains: const CRITICAL_ASSETS = [];'
|
|
);
|
|
} else {
|
|
const indexHtml = fs.readFileSync(indexHtmlPath, 'utf-8');
|
|
// Use a Set to deduplicate — assetRegex may match the same path in both href and src.
|
|
const criticalAssetsSet = new Set<string>();
|
|
|
|
// Extract hashed asset URLs from all link and script tags.
|
|
// These are the JS/CSS bundles Vite produces with content hashes.
|
|
// Match: href="./assets/..." or src="./assets/..."
|
|
const assetRegex = /(?:href|src)="(\.\/(assets\/[^"]+))"/g;
|
|
let match;
|
|
while ((match = assetRegex.exec(indexHtml)) !== null) {
|
|
const assetPath = '/' + match[2]; // Convert ./assets/... to /assets/...
|
|
// Only include JS and CSS — skip images, fonts, etc. to keep cache small
|
|
if (assetPath.endsWith('.js') || assetPath.endsWith('.css')) {
|
|
criticalAssetsSet.add(assetPath);
|
|
}
|
|
}
|
|
|
|
const criticalAssets = Array.from(criticalAssetsSet);
|
|
if (criticalAssets.length > 0) {
|
|
swContent = swContent.replace(
|
|
CRITICAL_ASSETS_PATTERN,
|
|
`const CRITICAL_ASSETS = ${JSON.stringify(criticalAssets)};`
|
|
);
|
|
console.log(
|
|
`[sw-cache-buster] Injected ${criticalAssets.length} critical assets for install-time precaching`
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
fs.writeFileSync(swPath, swContent, 'utf-8');
|
|
},
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Vite plugin to optimize the HTML output for mobile PWA loading speed.
|
|
*
|
|
* Problem: Vite adds modulepreload links for ALL vendor chunks in index.html,
|
|
* including heavy route-specific libraries like ReactFlow (172KB), xterm (676KB),
|
|
* and CodeMirror (436KB). On mobile, these modulepreloads compete with critical
|
|
* resources for bandwidth, delaying First Contentful Paint by 500ms+.
|
|
*
|
|
* Solution: Convert modulepreload to prefetch for route-specific vendor chunks.
|
|
* - modulepreload: Browser parses + compiles immediately (blocks FCP)
|
|
* - prefetch: Browser downloads at lowest priority during idle (no FCP impact)
|
|
*
|
|
* This means these chunks are still cached for when the user navigates to their
|
|
* respective routes, but they don't block the initial page load.
|
|
*/
|
|
function mobilePreloadOptimizer(): Plugin {
|
|
// Vendor chunks that are route-specific and should NOT block initial load.
|
|
// These libraries are only needed on specific routes:
|
|
// - vendor-reactflow: /graph route only
|
|
// - vendor-xterm: /terminal route only
|
|
// - vendor-codemirror: spec/XML editor routes only
|
|
// - vendor-markdown: agent view, wiki, and other markdown-rendering routes
|
|
// - vendor-icons: lucide-react icons (587 KB) — not needed before React mounts.
|
|
// The !authChecked loading state uses a pure CSS spinner instead of a Lucide icon,
|
|
// so icons are not required until the authenticated UI renders (by which time this
|
|
// prefetch has usually completed on typical connections).
|
|
const deferredChunks = [
|
|
'vendor-reactflow',
|
|
'vendor-xterm',
|
|
'vendor-codemirror',
|
|
'vendor-markdown',
|
|
'vendor-icons',
|
|
];
|
|
|
|
return {
|
|
name: 'mobile-preload-optimizer',
|
|
enforce: 'post',
|
|
transformIndexHtml(html) {
|
|
// Convert modulepreload to prefetch for deferred chunks
|
|
// This preserves the caching benefit while eliminating the FCP penalty
|
|
for (const chunk of deferredChunks) {
|
|
// Match modulepreload links for this chunk
|
|
const modulePreloadRegex = new RegExp(
|
|
`<link rel="modulepreload" crossorigin href="(\\./assets/${chunk}-[^"]+\\.js)">`,
|
|
'g'
|
|
);
|
|
html = html.replace(modulePreloadRegex, (_match, href) => {
|
|
return `<link rel="prefetch" href="${href}" as="script">`;
|
|
});
|
|
|
|
// Also convert eagerly-loaded CSS for these chunks to lower priority
|
|
const cssRegex = new RegExp(
|
|
`<link rel="stylesheet" crossorigin href="(\\./assets/${chunk}-[^"]+\\.css)">`,
|
|
'g'
|
|
);
|
|
html = html.replace(cssRegex, (_match, href) => {
|
|
return `<link rel="prefetch" href="${href}" as="style">`;
|
|
});
|
|
}
|
|
|
|
return html;
|
|
},
|
|
};
|
|
}
|
|
|
|
export default defineConfig(({ command }) => {
|
|
// Only skip electron plugin during dev server in CI (no display available for Electron)
|
|
// Always include it during build - we need dist-electron/main.js for electron-builder
|
|
const skipElectron =
|
|
command === 'serve' && (process.env.CI === 'true' || process.env.VITE_SKIP_ELECTRON === 'true');
|
|
|
|
return {
|
|
plugins: [
|
|
// Only include electron plugin when not in CI/headless dev mode
|
|
...(skipElectron
|
|
? []
|
|
: [
|
|
electron({
|
|
main: {
|
|
entry: 'src/main.ts',
|
|
vite: {
|
|
build: {
|
|
outDir: 'dist-electron',
|
|
rollupOptions: {
|
|
external: ['electron'],
|
|
},
|
|
},
|
|
},
|
|
},
|
|
preload: {
|
|
input: 'src/preload.ts',
|
|
vite: {
|
|
build: {
|
|
outDir: 'dist-electron',
|
|
rollupOptions: {
|
|
external: ['electron'],
|
|
},
|
|
},
|
|
},
|
|
},
|
|
}),
|
|
]),
|
|
TanStackRouterVite({
|
|
target: 'react',
|
|
autoCodeSplitting: true,
|
|
routesDirectory: './src/routes',
|
|
generatedRouteTree: './src/routeTree.gen.ts',
|
|
}),
|
|
tailwindcss(),
|
|
react(),
|
|
// Mobile PWA optimization: demote route-specific vendor chunks from
|
|
// modulepreload (blocks FCP) to prefetch (background download)
|
|
mobilePreloadOptimizer(),
|
|
// Inject build hash into sw.js CACHE_NAME for automatic cache busting
|
|
swCacheBuster(),
|
|
],
|
|
resolve: {
|
|
alias: [
|
|
{ find: '@', replacement: path.resolve(__dirname, './src') },
|
|
// Force ALL React imports (including from nested deps like zustand@4 inside
|
|
// @xyflow/react) to resolve to the single copy in the workspace root node_modules.
|
|
// This prevents "Cannot read properties of null (reading 'useState')" caused by
|
|
// react-dom setting the hooks dispatcher on one React instance while component
|
|
// code reads it from a different instance.
|
|
{
|
|
find: /^react-dom(\/|$)/,
|
|
replacement: path.resolve(__dirname, '../../node_modules/react-dom') + '/',
|
|
},
|
|
{
|
|
find: /^react(\/|$)/,
|
|
replacement: path.resolve(__dirname, '../../node_modules/react') + '/',
|
|
},
|
|
],
|
|
dedupe: ['react', 'react-dom'],
|
|
},
|
|
server: {
|
|
host: process.env.HOST || '0.0.0.0',
|
|
port: parseInt(process.env.AUTOMAKER_WEB_PORT || '3007', 10),
|
|
allowedHosts: true,
|
|
proxy: {
|
|
'/api': {
|
|
target: 'http://localhost:' + (process.env.AUTOMAKER_SERVER_PORT ?? '3008'),
|
|
changeOrigin: true,
|
|
ws: true,
|
|
},
|
|
},
|
|
},
|
|
build: {
|
|
outDir: 'dist',
|
|
// Target modern browsers for smaller output (no legacy polyfills)
|
|
target: 'esnext',
|
|
// Enable CSS code splitting for smaller initial CSS payload
|
|
cssCodeSplit: true,
|
|
// Increase chunk size warning to avoid over-splitting (which hurts HTTP/2 multiplexing)
|
|
chunkSizeWarningLimit: 600,
|
|
rollupOptions: {
|
|
external: [
|
|
'child_process',
|
|
'fs',
|
|
'path',
|
|
'crypto',
|
|
'http',
|
|
'net',
|
|
'os',
|
|
'util',
|
|
'stream',
|
|
'events',
|
|
'readline',
|
|
],
|
|
output: {
|
|
// Manual chunks for optimal caching and loading on mobile
|
|
manualChunks(id) {
|
|
// Vendor: React core (rarely changes, cache long-term)
|
|
// Also include use-sync-external-store here since it uses CJS require('react')
|
|
// and must be in the same chunk as React to prevent null dispatcher errors.
|
|
if (
|
|
id.includes('node_modules/react/') ||
|
|
id.includes('node_modules/react-dom/') ||
|
|
id.includes('node_modules/use-sync-external-store/')
|
|
) {
|
|
return 'vendor-react';
|
|
}
|
|
// Vendor: TanStack Router + Query (used on every page)
|
|
if (id.includes('@tanstack/react-router') || id.includes('@tanstack/react-query')) {
|
|
return 'vendor-tanstack';
|
|
}
|
|
// Vendor: UI library - split Radix UI (critical) from Lucide icons (deferrable)
|
|
// Radix UI primitives are used on almost every page for dialogs, tooltips, etc.
|
|
if (id.includes('@radix-ui/')) {
|
|
return 'vendor-radix';
|
|
}
|
|
// Lucide icons: Split from Radix so tree-shaken icons don't bloat the critical path
|
|
if (id.includes('lucide-react')) {
|
|
return 'vendor-icons';
|
|
}
|
|
// Fonts: Each font family gets its own chunk (loaded on demand)
|
|
if (id.includes('@fontsource/')) {
|
|
const match = id.match(/@fontsource\/([^/]+)/);
|
|
if (match) return `font-${match[1]}`;
|
|
}
|
|
// CodeMirror: Heavy editor - only loaded when needed
|
|
if (id.includes('@codemirror/') || id.includes('@lezer/')) {
|
|
return 'vendor-codemirror';
|
|
}
|
|
// Xterm: Terminal - only loaded when needed
|
|
if (id.includes('xterm') || id.includes('@xterm/')) {
|
|
return 'vendor-xterm';
|
|
}
|
|
// React Flow: Graph visualization - only loaded on dependency graph view
|
|
if (id.includes('@xyflow/') || id.includes('reactflow')) {
|
|
return 'vendor-reactflow';
|
|
}
|
|
// Zustand + Zod: State management and validation
|
|
if (id.includes('zustand') || id.includes('zod')) {
|
|
return 'vendor-state';
|
|
}
|
|
// React Markdown: Only needed on routes with markdown rendering
|
|
if (id.includes('react-markdown') || id.includes('remark-') || id.includes('rehype-')) {
|
|
return 'vendor-markdown';
|
|
}
|
|
},
|
|
},
|
|
},
|
|
},
|
|
optimizeDeps: {
|
|
exclude: ['@automaker/platform'],
|
|
// Pre-bundle CJS packages that use require('react') so the CJS interop resolves to
|
|
// the same React instance as the rest of the app. The nested zustand@4 inside
|
|
// @xyflow/react uses use-sync-external-store/shim/with-selector which does
|
|
// require('react') — both the base and subpath must be included here.
|
|
include: [
|
|
'react',
|
|
'react-dom',
|
|
'use-sync-external-store',
|
|
'use-sync-external-store/shim/with-selector',
|
|
'@xyflow/react',
|
|
],
|
|
},
|
|
define: {
|
|
__APP_VERSION__: JSON.stringify(appVersion),
|
|
// Build hash injected for IDB cache busting — matches what swCacheBuster injects
|
|
// into the SW CACHE_NAME. When the build changes, both caches are invalidated together.
|
|
__APP_BUILD_HASH__: JSON.stringify(buildHash),
|
|
},
|
|
};
|
|
});
|