mirror of
https://github.com/tiddly-gittly/TidGi-Desktop.git
synced 2026-01-21 20:11:50 -08:00
* fix: not removed
* Optimize tidgi.config.json writes for workspace updates
Update logic to write tidgi.config.json only for the modified workspace instead of all wiki workspaces on each update. This reduces redundant file operations and improves performance during workspace updates.
* Refactor workspace saving and UI update logic
Introduced a private saveWorkspacesToSettings method to centralize logic for saving workspaces and removing syncable fields from wiki workspaces. The set and setWorkspaces methods now support skipping UI updates for batch operations, improving performance. Fixed minor issues in legacy migration and error messages.
* Add 'Ask AI' context menu and wiki embed split view
Introduces an 'Ask AI' option to the wiki context menu, enabling users to send selected text to an agent chat in a split view with the wiki embedded. Implements new tab type WIKI_EMBED, updates tab and channel types, adds localization, manages BrowserView bounds for embedding, and ensures persistence and IPC wiring for the new workflow.
* Update wiki
* electron chrome mcp mode sometimes wont show browser view
Clarified troubleshooting steps in docs/MCP.md regarding browser view issues and updated the instructions. Reordered the 'start:dev:mcp' script in package.json for better organization.
* Add agent selection to 'Talk with AI' context menu
Replaces the 'Ask AI' context menu with 'Talk with AI' and adds a submenu for selecting different agent definitions. Updates translations for all supported languages, modifies the askAIWithSelection channel to support agentDefId, and refactors tab creation logic to support split view with agent selection. Improves robustness in view management by handling case-insensitive workspace IDs and custom bounds logic.
* Add e2e test and refactor 'Talk with AI' split view logic
Introduces a new Cucumber feature for 'Talk with AI' from wiki selection, adds a step definition to trigger the workflow via IPC, and refactors split view tab creation to reuse existing tabs when possible. Updates the agent browser service to support finding or creating the appropriate split view tab, and adjusts menu and view services for improved robustness and code clarity. Also adds test IDs to relevant components for more reliable UI testing.
* Update defaultWiki.feature
* Add config error handling and i18n for agent errors
Introduces a new feature test for configuration error handling, adds step definition to remove AI settings for testing, and updates error message rendering to support new error types. Internationalized error messages and button labels for configuration issues are added in both English and Chinese locales. The error message renderer now uses a data-testid for easier testing and recognizes additional error types as fixable in settings.
* Refactor feature files to use two-column selector tables
Updated all feature files to use a standardized two-column format for selector tables, with explicit 'element description' and 'selector' columns. Step definitions in ui.ts were refactored to support this format, improving readability and maintainability of test steps and error handling.
* Delete tiddlywiki
* test: allow parallel
* test: implement scenario isolation for E2E tests
- Isolate each test scenario in test-artifacts/{scenarioSlug}/ directory
- Use dynamic ports for mock OpenAI server to avoid port conflicts
- Log VIEW_LOADED event via did-finish-load in main process (more reliable)
- Search all .log files when waiting for log markers
- Increase timeout for log marker steps to 15 seconds
- Fix ts-node cache issues by clearing cache before tests
- Move application launch to individual scenarios (required for mock server setup)
All 45 E2E test scenarios now pass consistently.
* refactor: optimize agent.feature by moving common steps to Background
- Add MockOpenAIServer.addRules() method to append responses dynamically
- Add 'I have started the mock OpenAI server without rules' step for Background
- Add 'I add mock OpenAI responses:' step to inject responses per scenario
- Move application launch and navigation to Background (shared by all scenarios)
- Keep scenario-specific mock responses in individual scenarios
This improves test maintainability by reducing duplication while keeping
scenario-specific configuration flexible.
* lint
* Refactor scenario path helpers into shared module
Moved scenario-specific path helper functions from individual step definition files to a centralized 'features/supports/paths.ts' module. Updated imports in step definitions to use the shared helpers, improving code reuse and maintainability. Also enhanced test for ContextService to skip optional runtime keys.
* Refactor slug generation to use shared slugify helper
Introduced a new src/helpers/slugify.ts utility for consistent slug generation across the codebase. Updated appPaths.ts to use the shared slugify function, improving maintainability and ensuring identical behavior for test scenario slugs. Added documentation and clarified slugification rules in relevant files. Minor comments and clarifications were added to E2E and mock server code.
* Enforce strict timeout rules in E2E test steps
Added and clarified critical warnings for AI agents regarding timeout modifications in application, cleanup, and wiki step definitions. All timeouts are now strictly limited to 5s local and 10s CI, with explicit comments and environment-based values. Updated documentation and code comments to reinforce that timeouts indicate real bugs and should not be increased.
* Update features/stepDefinitions/application.ts
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
* Refactor E2E helpers, improve test reliability and cleanup
Centralizes data table parsing for UI step definitions, refactors mock OpenAI server setup, and improves workspace settings path handling for tests. Adjusts timeouts for window and app closing to better reflect real-world performance. Fixes type usage in workspace ID lookups and adds error handling for resize observer and cleanup in WikiEmbedTabContent. Enhances agent browser tab logic and view service cleanup to prevent memory leaks and catch workspace ID casing issues.
* Update agent.ts
* fix: resolve all E2E test timeout issues
* fix: improve CI test reliability with better timing and cleanup
- Use exponential-backoff library for agent creation retry logic
- Extend agent cancel delay to 1000ms for CI environments
- Fix git log refresh marker timing with queueMicrotask
- Improve cleanup timeout handling with force close strategy
All E2E tests passing locally including previously failing CI tests.
* Improve Git log E2E signal and add debug logging
Renames the test artifact in the CI workflow for clarity. Moves the E2E test timing log in useGitLogData to after entries are rendered, using a more reliable signal. Adds a debug log to notifyGitStateChange for better traceability.
* test-artifacts-ci
* Optimize test artifact handling and Git log logging
Update CI workflow to clean up large cache folders in test artifacts and only upload logs, settings, and screenshots to reduce artifact size. Refactor useGitLogData to log immediately after state updates for improved E2E test reliability, removing unnecessary setTimeout.
* Update useGitLogData.ts
* Improve Git log E2E test logging and .gitignore
Added 'test-artifacts-ci.zip' to .gitignore. Moved the '[test-id-git-log-refreshed]' log to immediately after data load for more reliable E2E test detection, and removed redundant logging from the render effect in useGitLogData.ts.
* Update useGitLogData.ts
* Update useGitLogData.ts
* Fix git log refresh marker not appearing in CI
- Move git-log-refreshed marker before RAF to ensure it's recorded
- RAF callbacks may not execute reliably in headless CI environments
- Add debug logging to track loadGitLog execution
- Add try-catch around log call to catch any errors
- Keep git-log-data-rendered in useEffect for UI tracking
* Update useGitLogData.ts
* Update useGitLogData.ts
* Add comprehensive logging to diagnose git-log-refreshed issue
- Log before RAF and inside RAF to pinpoint exact failure location
- Add try-catch to capture any errors
- Two log markers: before-raf and in-raf
- This will definitively show where the logging fails in CI
* Fix race condition: prevent concurrent loadGitLog calls
Root cause: commit triggers 2 refreshes (gitStateChange$ + handleCommitSuccess)
- First loadGitLog (refreshTrigger=1) succeeds
- Second loadGitLog (refreshTrigger=2) starts but never completes
- Add loadGitLogInProgress guard to prevent concurrent execution
- Log when loadGitLog is skipped due to in-progress call
This ensures git-log-refreshed is always logged after commit.
* Remove redundant triggerRefresh calls causing race condition
- handleCommitSuccess/Revert/Undo no longer call triggerRefresh
- gitStateChange\$ observable already triggers refresh for these operations
- Redundant calls caused 2 concurrent loadGitLog, causing CI test failures
- Local tests passed because both completed; CI failed because 2nd never completed
This ensures only 1 loadGitLog runs per git operation.
* Remove unused triggerRefresh parameter from useCommitSelection
- triggerRefresh no longer used in handlers
- Remove from interface and call site
- Clean up lint errors
* Remove triggerRefresh completely - no longer needed
- Observable subscription handles all git state changes
- Remove function definition and exports
- Fix all lint errors
Root cause resolved: commit triggered double refresh causing race condition.
Now only single refresh via observable.
* Remove fixed time waits from gitLog.feature and fix race condition
- Remove all fixed time wait steps from gitLog.feature (14 instances)
- Remove redundant triggerRefresh calls in handleCommitSuccess/Revert/Undo
- Add loadGitLogInProgress guard to prevent concurrent loadGitLog
- Root cause: commit triggered 2 refreshes causing race condition
- Only gitStateChange\$ observable now triggers refresh
- All 4 gitLog tests pass locally
* Fix clear timing: clear log BEFORE commit, not after
Root cause: test cleared git-log-refreshed AFTER commit completed
- But commit already triggered refresh and logged git-log-refreshed
- Clear deleted it, then test waited for new log that would never come
- Solution: clear BEFORE clicking commit button
- This way commit's git-log-refreshed is the first one after clear
Test now passes locally.
* Update cleanup.ts
* Initial commit when init a new git.
* Refactor feature steps for multi-element and log marker tables
Updated multiple feature files and step definitions to support table-driven steps for clicking and asserting multiple elements, and for waiting for multiple log markers in sequence. This reduces redundant waits, improves test reliability, and streamlines Gherkin syntax for multi-element actions and assertions. Also removed unnecessary manual wait steps where content or element checks now handle waiting automatically.
* Minor code cleanup and formatting improvements
Reordered imports in browserView.ts, fixed whitespace in cleanup.ts and useGitLogData.ts, and improved line formatting in GitLog/index.tsx for better readability and consistency.
---------
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
Co-authored-by: tidgi <tiddlygit@gmail.com>
402 lines
16 KiB
TypeScript
402 lines
16 KiB
TypeScript
import { AfterStep, setWorldConstructor, When } from '@cucumber/cucumber';
|
|
import { backOff } from 'exponential-backoff';
|
|
import fs from 'fs-extra';
|
|
import path from 'path';
|
|
import { _electron as electron } from 'playwright';
|
|
import type { ElectronApplication, Page } from 'playwright';
|
|
import { windowDimension, WindowNames } from '../../src/services/windows/WindowProperties';
|
|
import { MockOAuthServer } from '../supports/mockOAuthServer';
|
|
import { MockOpenAIServer } from '../supports/mockOpenAI';
|
|
import { getPackedAppPath, makeSlugPath } from '../supports/paths';
|
|
import { captureScreenshot } from '../supports/webContentsViewHelper';
|
|
|
|
/**
|
|
* ═══════════════════════════════════════════════════════════════════════════
|
|
* ⚠️ CRITICAL WARNING FOR ALL AI AGENTS - READ THIS BEFORE ANY MODIFICATION ⚠️
|
|
* ═══════════════════════════════════════════════════════════════════════════
|
|
*
|
|
* ABSOLUTE RULES - NO EXCEPTIONS:
|
|
*
|
|
* 1. NEVER INCREASE TIMEOUT VALUES! TIMEOUT = FAILURE = REAL BUG!
|
|
* - Timeout is a SYMPTOM, not the disease
|
|
* - Fix the ROOT CAUSE in application code, not the timeout
|
|
*
|
|
* 2. MAXIMUM TIMEOUTS (STRICTLY ENFORCED):
|
|
* - Local: 5 seconds
|
|
* - CI: 10 seconds (exactly 2x local, NO MORE)
|
|
*
|
|
* 3. BEFORE MODIFYING ANY TIMEOUT:
|
|
* - STOP! Read docs/Testing.md completely
|
|
* - Investigate test-artifacts/{scenarioSlug}/userData-test/logs/
|
|
* - Find the REAL BUG (SQLite errors, missing elements, failed loads)
|
|
* - Fix the APPLICATION CODE, not the test
|
|
*
|
|
* 4. THIS HAS BEEN VIOLATED 3 TIMES - DO NOT MAKE IT 4!
|
|
*
|
|
* Per docs/Testing.md: "Timeout usually because of expected element not present."
|
|
* The test is waiting for something that will NEVER happen due to a BUG.
|
|
*
|
|
* ═══════════════════════════════════════════════════════════════════════════
|
|
*/
|
|
|
|
// Backoff configuration for retries
|
|
const BACKOFF_OPTIONS = {
|
|
numOfAttempts: 8,
|
|
startingDelay: 100,
|
|
timeMultiple: 2,
|
|
};
|
|
|
|
// Helper function to check if window type is valid and return the corresponding WindowNames
|
|
export function checkWindowName(windowType: string): WindowNames {
|
|
// Exact match - windowType must be a valid WindowNames enum key
|
|
if (windowType in WindowNames) {
|
|
return (WindowNames as Record<string, WindowNames>)[windowType];
|
|
}
|
|
throw new Error(`Window type "${windowType}" is not a valid WindowNames. Check the WindowNames enum in WindowProperties.ts. Available: ${Object.keys(WindowNames).join(', ')}`);
|
|
}
|
|
|
|
// Helper function to get window dimensions and ensure they are valid
|
|
export function checkWindowDimension(windowName: WindowNames): { width: number; height: number } {
|
|
const targetDimensions = windowDimension[windowName];
|
|
if (!targetDimensions.width || !targetDimensions.height) {
|
|
throw new Error(`Window "${windowName}" does not have valid dimensions defined in windowDimension`);
|
|
}
|
|
return targetDimensions as { width: number; height: number };
|
|
}
|
|
|
|
export class ApplicationWorld {
|
|
app: ElectronApplication | undefined;
|
|
mainWindow: Page | undefined; // Keep for compatibility during transition
|
|
currentWindow: Page | undefined; // New state-managed current window
|
|
mockOpenAIServer: MockOpenAIServer | undefined;
|
|
mockOAuthServer: MockOAuthServer | undefined;
|
|
savedWorkspaceId: string | undefined; // For storing workspace ID between steps
|
|
scenarioName: string = 'default'; // Scenario name from Cucumber pickle
|
|
scenarioSlug: string = 'default'; // Sanitized scenario name for file paths
|
|
providerConfig: import('@services/externalAPI/interface').AIProviderConfig | undefined; // Scenario-specific AI provider config
|
|
|
|
// Helper method to check if window is visible
|
|
async isWindowVisible(page: Page): Promise<boolean> {
|
|
if (!this.app) return false;
|
|
try {
|
|
const browserWindow = await this.app.browserWindow(page);
|
|
return await browserWindow.evaluate((win: Electron.BrowserWindow) => win.isVisible());
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Helper method to wait for window with retry logic
|
|
async waitForWindowCondition(
|
|
windowType: string,
|
|
condition: (window: Page | undefined, isVisible: boolean) => boolean,
|
|
): Promise<boolean> {
|
|
if (!this.app) return false;
|
|
|
|
try {
|
|
await backOff(
|
|
async () => {
|
|
const targetWindow = await this.findWindowByType(windowType);
|
|
const visible = targetWindow ? await this.isWindowVisible(targetWindow) : false;
|
|
|
|
if (!condition(targetWindow, visible)) {
|
|
throw new Error('Condition not met');
|
|
}
|
|
},
|
|
BACKOFF_OPTIONS,
|
|
);
|
|
return true;
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
|
|
// Helper method to find window by type - strict WindowNames matching
|
|
async findWindowByType(windowType: string): Promise<Page | undefined> {
|
|
if (!this.app) return undefined;
|
|
|
|
// Validate window type first
|
|
const windowName = checkWindowName(windowType);
|
|
|
|
const pages = this.app.windows();
|
|
|
|
if (windowName === WindowNames.main) {
|
|
// Main window is the first/primary window, typically showing guide, agent, help, or wiki pages
|
|
// It's the window that opens on app launch
|
|
const allWindows = pages.filter(page => !page.isClosed());
|
|
if (allWindows.length > 0) {
|
|
// Return the first window (main window is always the first one created)
|
|
return allWindows[0];
|
|
}
|
|
return undefined;
|
|
} else if (windowName === WindowNames.tidgiMiniWindow) {
|
|
// Special handling for tidgi mini window
|
|
// First try to find by Electron window dimensions (more reliable than title)
|
|
const windowDimensions = checkWindowDimension(windowName);
|
|
try {
|
|
const electronWindowInfo = await this.app.evaluate(
|
|
async ({ BrowserWindow }, size: { width: number; height: number }) => {
|
|
const allWindows = BrowserWindow.getAllWindows();
|
|
const tidgiMiniWindow = allWindows.find(win => {
|
|
const bounds = win.getBounds();
|
|
return bounds.width === size.width && bounds.height === size.height;
|
|
});
|
|
return tidgiMiniWindow ? { id: tidgiMiniWindow.id } : null;
|
|
},
|
|
windowDimensions,
|
|
);
|
|
|
|
if (electronWindowInfo) {
|
|
// Found by dimensions, now match with Playwright page
|
|
const allWindows = pages.filter(page => !page.isClosed());
|
|
for (const page of allWindows) {
|
|
try {
|
|
// Try to match by checking if this page belongs to the found electron window
|
|
// For now, use title as fallback verification
|
|
const title = await page.title();
|
|
if (title.includes('太记小窗') || title.includes('TidGi Mini Window') || title.includes('TidGiMiniWindow')) {
|
|
return page;
|
|
}
|
|
} catch {
|
|
continue;
|
|
}
|
|
}
|
|
}
|
|
} catch {
|
|
// If Electron API fails, fallback to title matching
|
|
}
|
|
|
|
// Fallback: Match by window title
|
|
const allWindows = pages.filter(page => !page.isClosed());
|
|
for (const page of allWindows) {
|
|
try {
|
|
const title = await page.title();
|
|
if (title.includes('太记小窗') || title.includes('TidGi Mini Window') || title.includes('TidGiMiniWindow')) {
|
|
return page;
|
|
}
|
|
} catch {
|
|
// Page might be closed or not ready, continue to next
|
|
continue;
|
|
}
|
|
}
|
|
return undefined;
|
|
} else {
|
|
// For regular windows (preferences, about, addWorkspace, etc.)
|
|
return pages.find(page => {
|
|
if (page.isClosed()) return false;
|
|
const url = page.url() || '';
|
|
// Match exact route paths: /#/windowType or ending with /windowType
|
|
return url.includes(`#/${windowType}`) || url.endsWith(`/${windowType}`);
|
|
});
|
|
}
|
|
}
|
|
|
|
async getWindow(windowType: string = 'main'): Promise<Page | undefined> {
|
|
if (!this.app) return undefined;
|
|
|
|
// Special case for 'current' window
|
|
if (windowType === 'current') {
|
|
return this.currentWindow;
|
|
}
|
|
|
|
// Use the findWindowByType method with retry logic using backoff
|
|
try {
|
|
return await backOff(
|
|
async () => {
|
|
const window = await this.findWindowByType(windowType);
|
|
if (!window) {
|
|
throw new Error(`Window ${windowType} not found`);
|
|
}
|
|
return window;
|
|
},
|
|
BACKOFF_OPTIONS,
|
|
);
|
|
} catch (error) {
|
|
// If it's an invalid window type error, re-throw it
|
|
if (error instanceof Error && error.message.includes('is not a valid WindowNames')) {
|
|
throw error;
|
|
}
|
|
return undefined;
|
|
}
|
|
}
|
|
}
|
|
|
|
setWorldConstructor(ApplicationWorld);
|
|
|
|
AfterStep(async function(this: ApplicationWorld, { pickle, pickleStep, result }) {
|
|
// Only take screenshots in CI environment
|
|
// if (!process.env.CI) return;
|
|
|
|
try {
|
|
const stepText = pickleStep.text;
|
|
|
|
// Skip screenshots for wait steps to avoid too many screenshots
|
|
if (stepText.match(/^I wait for/i)) {
|
|
return;
|
|
}
|
|
if (stepText.match(/^I clear log/i)) {
|
|
return;
|
|
}
|
|
|
|
// Prefer an existing currentWindow if it's still open
|
|
let pageToUse: Page | undefined;
|
|
|
|
if (this.currentWindow && !this.currentWindow.isClosed()) {
|
|
pageToUse = this.currentWindow;
|
|
}
|
|
|
|
// If currentWindow is not available, try to re-acquire any open window from the app
|
|
if ((!pageToUse || pageToUse.isClosed()) && this.app) {
|
|
const openPages = this.app.windows().filter(p => !p.isClosed());
|
|
if (openPages.length > 0) {
|
|
pageToUse = openPages[0];
|
|
}
|
|
}
|
|
|
|
const scenarioName = pickle.name;
|
|
// Limit scenario slug to avoid extremely long directory names
|
|
const cleanScenarioName = makeSlugPath(scenarioName, 60);
|
|
|
|
// Limit step text slug to avoid excessively long filenames which can trigger ENAMETOOLONG
|
|
const cleanStepText = makeSlugPath(stepText, 80);
|
|
const stepStatus = result && typeof result.status === 'string' ? result.status : 'unknown-status';
|
|
|
|
// Use scenario-specific screenshots directory
|
|
const scenarioScreenshotsDirectory = path.resolve(process.cwd(), 'test-artifacts', cleanScenarioName, 'userData-test', 'logs', 'screenshots');
|
|
// Create directory asynchronously to avoid blocking the event loop in CI
|
|
await fs.ensureDir(scenarioScreenshotsDirectory);
|
|
|
|
// Sometimes window close and don't wait for use to take picture, or window haven't open in this step, never mind, just skip.
|
|
/**
|
|
* Typical steps like:
|
|
* - I add test ai settings
|
|
* - I cleanup test wiki so it could create a new one on start
|
|
* - I clear test ai settings
|
|
*/
|
|
if (!pageToUse || pageToUse.isClosed()) {
|
|
// console.warn(`Skipping screenshot: ${cleanStepText}`);
|
|
return;
|
|
}
|
|
|
|
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
|
|
// Try to capture both WebContentsView and Page screenshots
|
|
let webViewCaptured = false;
|
|
if (this.app) {
|
|
const webViewScreenshotPath = path.resolve(scenarioScreenshotsDirectory, `${timestamp}-${cleanStepText}-${stepStatus}-webview.png`);
|
|
webViewCaptured = await captureScreenshot(this.app, webViewScreenshotPath);
|
|
}
|
|
|
|
// Always capture page screenshot (UI chrome/window)
|
|
const pageScreenshotPath = path.resolve(scenarioScreenshotsDirectory, `${timestamp}-${cleanStepText}-${stepStatus}${webViewCaptured ? '-page' : ''}.png`);
|
|
await pageToUse.screenshot({ path: pageScreenshotPath, fullPage: true, type: 'png' });
|
|
} catch (screenshotError) {
|
|
console.warn('Failed to take screenshot:', screenshotError);
|
|
}
|
|
});
|
|
|
|
// CRITICAL WARNING FOR ALL AI AGENTS:
|
|
// DO NOT MODIFY TIMEOUT VALUES! NEVER!
|
|
// If a test times out, it means there is a REAL BUG to fix, not a timeout to increase.
|
|
// Timeout is a symptom, not the disease. Fix the root cause.
|
|
// Read docs/Testing.md section "Key E2E Testing Patterns" point 6 before attempting any changes.
|
|
// Maximum allowed timeouts: Local 5s, CI 10s (exactly 2x local, no more)
|
|
When('I launch the TidGi application', { timeout: process.env.CI ? 10000 : 5000 }, async function(this: ApplicationWorld) {
|
|
// For E2E tests on dev mode, use the packaged test version with NODE_ENV environment variable baked in
|
|
const packedAppPath = getPackedAppPath();
|
|
|
|
try {
|
|
this.app = await electron.launch({
|
|
executablePath: packedAppPath,
|
|
// Add debugging options to prevent app from closing and CI-specific args
|
|
args: [
|
|
// Pass slugified scenario name to application for exact path isolation matching
|
|
// This ensures consistency with the slug generated in appPaths.ts
|
|
`--test-scenario=${this.scenarioSlug}`,
|
|
'--no-sandbox',
|
|
'--disable-dev-shm-usage',
|
|
'--disable-gpu',
|
|
'--disable-software-rasterizer',
|
|
'--disable-background-timer-throttling',
|
|
'--disable-backgrounding-occluded-windows',
|
|
'--disable-renderer-backgrounding',
|
|
'--disable-features=TranslateUI',
|
|
'--disable-ipc-flooding-protection',
|
|
'--force-device-scale-factor=1',
|
|
'--high-dpi-support=1',
|
|
'--force-color-profile=srgb',
|
|
'--disable-extensions',
|
|
'--disable-plugins',
|
|
'--disable-default-apps',
|
|
'--virtual-time-budget=1000',
|
|
'--run-all-compositor-stages-before-draw',
|
|
'--disable-checker-imaging',
|
|
// Linux CI specific arguments
|
|
...(process.env.CI && process.platform === 'linux'
|
|
? [
|
|
'--disable-background-mode',
|
|
'--disable-features=VizDisplayCompositor',
|
|
'--use-gl=swiftshader',
|
|
'--disable-accelerated-2d-canvas',
|
|
'--disable-accelerated-jpeg-decoding',
|
|
'--disable-accelerated-mjpeg-decode',
|
|
'--disable-accelerated-video-decode',
|
|
]
|
|
: []),
|
|
],
|
|
env: {
|
|
...process.env,
|
|
NODE_ENV: 'test',
|
|
E2E_TEST: 'true',
|
|
// Ensure tests run in Chinese locale so i18n UI strings match expectations
|
|
// set multiple variables for cross-platform coverage
|
|
LANG: process.env.LANG || 'zh-Hans.UTF-8',
|
|
LANGUAGE: process.env.LANGUAGE || 'zh-Hans:zh',
|
|
LC_ALL: process.env.LC_ALL || 'zh-Hans.UTF-8',
|
|
// Force display settings for CI
|
|
ELECTRON_DISABLE_SECURITY_WARNINGS: 'true',
|
|
...(process.env.CI && {
|
|
ELECTRON_ENABLE_LOGGING: 'true',
|
|
ELECTRON_DISABLE_HARDWARE_ACCELERATION: 'true',
|
|
}),
|
|
},
|
|
// Set cwd to repo root; scenario isolation is handled via --test-scenario argument
|
|
cwd: process.cwd(),
|
|
// Align Electron launch timeout with step definition (max 10s in CI, 5s locally)
|
|
timeout: process.env.CI ? 10000 : 5000,
|
|
});
|
|
|
|
// Wait longer for window in CI environment
|
|
const windowTimeout = process.env.CI ? 45000 : 10000;
|
|
this.mainWindow = await this.app.firstWindow({ timeout: windowTimeout });
|
|
this.currentWindow = this.mainWindow;
|
|
} catch (error) {
|
|
throw new Error(
|
|
`Failed to launch TidGi application: ${error as Error}. You should run \`pnpm run test:prepare-e2e\` before running the tests to ensure the app is built, and build with binaries like "dugite" and "tiddlywiki", see scripts/afterPack.js for more details.`,
|
|
);
|
|
}
|
|
});
|
|
|
|
When('I prepare to select directory in dialog {string}', async function(this: ApplicationWorld, directoryName: string) {
|
|
if (!this.app) {
|
|
throw new Error('Application is not launched');
|
|
}
|
|
// Use scenario-specific path for isolation
|
|
const targetPath = path.resolve(process.cwd(), 'test-artifacts', this.scenarioSlug, directoryName);
|
|
// Ensure parent directory exists (but do NOT remove target directory - it may be an existing wiki we want to import)
|
|
await fs.ensureDir(path.dirname(targetPath));
|
|
// Setup one-time dialog handler that restores after use
|
|
await this.app.evaluate(({ dialog }, targetDirectory: string) => {
|
|
// Save original function with proper binding
|
|
const originalShowOpenDialog = dialog.showOpenDialog.bind(dialog);
|
|
// Override with one-time mock
|
|
dialog.showOpenDialog = async () => {
|
|
// Restore original immediately after first call
|
|
dialog.showOpenDialog = originalShowOpenDialog;
|
|
return {
|
|
canceled: false,
|
|
filePaths: [targetDirectory],
|
|
};
|
|
};
|
|
}, targetPath);
|
|
});
|