Files
automaker/apps/ui/tests/utils/views/memory.ts
gsxdsm 0196911d59 Bug fixes and stability improvements (#815)
* 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>
2026-02-27 17:03:29 -08:00

287 lines
10 KiB
TypeScript

import { Page, Locator } from '@playwright/test';
import {
clickElement,
fillInput,
handleLoginScreenIfPresent,
closeDialogWithEscape,
} from '../core/interactions';
import { waitForElement, waitForElementHidden } from '../core/waiting';
import { getByTestId } from '../core/elements';
import { expect } from '@playwright/test';
import { authenticateForTests } from '../api/client';
/**
* Get the memory file list element
*/
export async function getMemoryFileList(page: Page): Promise<Locator> {
return page.locator('[data-testid="memory-file-list"]');
}
/**
* Click on a memory file in the list
*/
export async function clickMemoryFile(page: Page, fileName: string): Promise<void> {
const fileButton = page.locator(`[data-testid="memory-file-${fileName}"]`);
await fileButton.click();
}
/**
* Get the memory editor element
*/
export async function getMemoryEditor(page: Page): Promise<Locator> {
return page.locator('[data-testid="memory-editor"]');
}
/**
* Get the memory editor content
*/
export async function getMemoryEditorContent(page: Page): Promise<string> {
const editor = await getByTestId(page, 'memory-editor');
return await editor.inputValue();
}
/**
* Set the memory editor content
*/
export async function setMemoryEditorContent(page: Page, content: string): Promise<void> {
const editor = await getByTestId(page, 'memory-editor');
await editor.fill(content);
}
/**
* Open the create memory file dialog
*/
export async function openCreateMemoryDialog(page: Page): Promise<void> {
await clickElement(page, 'create-memory-button');
await waitForElement(page, 'create-memory-dialog');
}
/**
* Create a memory file via the UI
*/
export async function createMemoryFile(
page: Page,
filename: string,
content: string
): Promise<void> {
await openCreateMemoryDialog(page);
await fillInput(page, 'new-memory-name', filename);
await fillInput(page, 'new-memory-content', content);
await clickElement(page, 'confirm-create-memory');
await waitForElementHidden(page, 'create-memory-dialog');
}
/**
* Delete a memory file via the UI (must be selected first)
*/
export async function deleteSelectedMemoryFile(page: Page): Promise<void> {
await clickElement(page, 'delete-memory-file');
await waitForElement(page, 'delete-memory-dialog');
await clickElement(page, 'confirm-delete-memory');
await waitForElementHidden(page, 'delete-memory-dialog');
}
/**
* Save the current memory file
*/
export async function saveMemoryFile(page: Page): Promise<void> {
await clickElement(page, 'save-memory-file');
// Wait for save to complete across desktop/mobile variants
// On desktop: button text shows "Saved"
// On mobile: icon-only button uses aria-label or title
await page.waitForFunction(
() => {
const btn = document.querySelector('[data-testid="save-memory-file"]');
if (!btn) return false;
const stateText = [
btn.textContent ?? '',
btn.getAttribute('aria-label') ?? '',
btn.getAttribute('title') ?? '',
]
.join(' ')
.toLowerCase();
return stateText.includes('saved');
},
{ timeout: 5000 }
);
}
/**
* Toggle markdown preview mode
*/
export async function toggleMemoryPreviewMode(page: Page): Promise<void> {
await clickElement(page, 'toggle-preview-mode');
}
/**
* Wait for a specific file to appear in the memory file list
* Uses retry mechanism to handle race conditions with API/UI updates
*/
export async function waitForMemoryFile(
page: Page,
filename: string,
timeout: number = 15000
): Promise<void> {
await expect(async () => {
const locator = page.locator(`[data-testid="memory-file-${filename}"]`);
await expect(locator).toBeVisible();
}).toPass({ timeout, intervals: [200, 500, 1000] });
}
/**
* Click a file in the list and wait for it to be selected (toolbar visible)
* Uses retry mechanism to handle race conditions where element is visible but not yet interactive
*/
export async function selectMemoryFile(
page: Page,
filename: string,
timeout: number = 15000
): Promise<void> {
const fileButton = await getByTestId(page, `memory-file-${filename}`);
// Retry click + wait for content panel to handle timing issues
// Note: On mobile, delete button is hidden, so we wait for content panel instead
// Use shorter inner timeout so retries can run; loadFileContent is async (API read)
const innerTimeout = Math.min(2000, Math.floor(timeout / 3));
await expect(async () => {
// Use JavaScript click to ensure React onClick handler fires
await fileButton.evaluate((el) => (el as HTMLButtonElement).click());
// Wait for content to appear (editor or preview)
const contentLocator = page.locator(
'[data-testid="memory-editor"], [data-testid="markdown-preview"]'
);
await expect(contentLocator).toBeVisible({ timeout: innerTimeout });
}).toPass({ timeout, intervals: [200, 500, 1000] });
}
/**
* Wait for file content panel to load (either editor or preview)
* Uses retry mechanism to handle race conditions with file selection
*/
export async function waitForMemoryContentToLoad(
page: Page,
timeout: number = 15000
): Promise<void> {
const innerTimeout = Math.min(2000, Math.floor(timeout / 3));
await expect(async () => {
const contentLocator = page.locator(
'[data-testid="memory-editor"], [data-testid="markdown-preview"]'
);
await expect(contentLocator).toBeVisible({ timeout: innerTimeout });
}).toPass({ timeout, intervals: [200, 500, 1000] });
}
/**
* Switch from preview mode to edit mode for memory files
* Memory files open in preview mode by default, this helper switches to edit mode
*/
export async function switchMemoryToEditMode(page: Page): Promise<void> {
// First wait for content to load
await waitForMemoryContentToLoad(page);
const markdownPreview = await getByTestId(page, 'markdown-preview');
const isPreview = await markdownPreview.isVisible().catch(() => false);
if (isPreview) {
await clickElement(page, 'toggle-preview-mode');
await page.waitForSelector('[data-testid="memory-editor"]', {
timeout: 5000,
});
}
}
/**
* Refresh the memory file list (clicks the Refresh button).
* Use instead of page.reload() to avoid ERR_CONNECTION_REFUSED when the dev server
* is under load, and to match real user behavior.
*/
export async function refreshMemoryList(page: Page): Promise<void> {
// Desktop: refresh button is visible; mobile: open panel then click mobile refresh
const desktopRefresh = page.locator('[data-testid="refresh-memory-button"]');
const mobileRefresh = page.locator('[data-testid="refresh-memory-button-mobile"]');
if (await desktopRefresh.isVisible().catch(() => false)) {
await desktopRefresh.click();
} else {
await clickElement(page, 'header-actions-panel-trigger');
await mobileRefresh.click();
}
// Allow list to re-fetch
await page.waitForTimeout(150);
}
/**
* Navigate to the memory view
* Note: Navigates directly to /memory since index route shows WelcomeView
*/
export async function navigateToMemory(page: Page): Promise<void> {
// Authenticate before navigating (fast-path: skips if already authed via storageState)
await authenticateForTests(page);
// Navigate directly to /memory route
await page.goto('/memory', { waitUntil: 'domcontentloaded' });
// Handle login redirect if needed (e.g. when redirected to /logged-out)
await handleLoginScreenIfPresent(page);
// Wait for one of: memory-view, memory-view-no-project, or memory-view-loading.
// Store hydration and loadMemoryFiles can be async, so we accept any of these first.
const viewSelector =
'[data-testid="memory-view"], [data-testid="memory-view-no-project"], [data-testid="memory-view-loading"]';
await page.locator(viewSelector).first().waitFor({ state: 'visible', timeout: 15000 });
// If we see "no project", give hydration a moment then re-check (avoids flake when store hydrates after first paint).
const noProject = page.locator('[data-testid="memory-view-no-project"]');
if (await noProject.isVisible().catch(() => false)) {
// Poll for the view to appear rather than a fixed timeout
await page
.locator('[data-testid="memory-view"], [data-testid="memory-view-loading"]')
.first()
.waitFor({ state: 'visible', timeout: 5000 })
.catch(() => {
throw new Error(
'Memory view showed "No project selected". Ensure setupProjectWithFixture runs before navigateToMemory and store has time to hydrate.'
);
});
}
// Wait for loading to complete (if present)
const loadingElement = page.locator('[data-testid="memory-view-loading"]');
if (await loadingElement.isVisible().catch(() => false)) {
await loadingElement.waitFor({ state: 'hidden', timeout: 10000 });
}
// Wait for the memory view to be visible
await waitForElement(page, 'memory-view', { timeout: 15000 });
// On mobile, close the sidebar if open so the header actions trigger is clickable (not covered by backdrop)
// Use JavaScript click to avoid force:true hitting the sidebar (z-30) instead of the backdrop (z-20)
const backdrop = page.locator('[data-testid="sidebar-backdrop"]');
if (await backdrop.isVisible().catch(() => false)) {
await backdrop.evaluate((el) => (el as HTMLElement).click());
}
// Dismiss any open dialog that may block interactions (e.g. sandbox warning, onboarding).
// The sandbox dialog blocks Escape, so click "I Accept the Risks" if it becomes visible within 1s.
const sandboxAcceptBtn = page.locator('button:has-text("I Accept the Risks")');
const sandboxVisible = await sandboxAcceptBtn
.waitFor({ state: 'visible', timeout: 1000 })
.then(() => true)
.catch(() => false);
if (sandboxVisible) {
await sandboxAcceptBtn.click();
await page
.locator('[role="dialog"][data-state="open"]')
.first()
.waitFor({ state: 'hidden', timeout: 3000 })
.catch(() => {});
} else {
await closeDialogWithEscape(page, { timeout: 2000 });
}
// Ensure the header (and actions panel trigger on mobile) is interactive
await page
.locator('[data-testid="header-actions-panel-trigger"]')
.waitFor({ state: 'visible', timeout: 5000 })
.catch(() => {});
}