Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

5.7 KB
Raw Blame
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { _electron as electron } from '@playwright/test';
import { configureDesktopGitRepositories } from '../support/git-fixture.test-helper.ts';
import { waitForAgentsDockPublish } from './_helpers/dock-state-ready';
import { desktopLaunchOptions, resolveDesktopTarget } from './_helpers/launch-desktop';
import { waitForWindowByMode } from './_helpers/launch-readiness';
import { sumOfDeclaredBoundsMs } from './_helpers/parse-timeouts';
import {
  homeEnv,
  PTY_PLATFORM_SKIP_REASON,
  PTY_PLATFORM_SUPPORTED,
} from './_helpers/platform-gate';
import { expect, test } from './_helpers/smoke-test';

const TARGET = resolveDesktopTarget();
const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';

test.describe('terminal dock-state IPC', () => {
  test.skip(!SMOKE_ENABLED, 'Set OK_DESKTOP_E2E_SMOKE=1 to run Electron smoke tests.');
  test.skip(!PTY_PLATFORM_SUPPORTED, PTY_PLATFORM_SKIP_REASON);
  test.skip(!TARGET.exists, TARGET.missingReason);

  test('terminal tab snapshot survives renderer reload together', async ({ captureStderrFor }) => {
    test.setTimeout(sumOfDeclaredBoundsMs(test.info()));
    const testRoot = mkdtempSync(join(tmpdir(), 'ok-terminal-dock-state-'));
    const tmpHome = join(testRoot, 'home');
    mkdirSync(tmpHome, { recursive: true });
    const projectDir = join(testRoot, 'project');
    mkdirSync(join(projectDir, '.ok'), { recursive: true });
    writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n  dir: '.'\n");
    writeFileSync(join(projectDir, 'start.md'), '# Start\n');
    const userDataDir = join(testRoot, 'user-data');
    mkdirSync(userDataDir, { recursive: true });
    writeFileSync(
      join(userDataDir, 'state.json'),
      JSON.stringify({
        recentProjects: [
          { path: projectDir, name: 'Dock State Smoke', lastOpenedAt: new Date().toISOString() },
        ],
        lastOpenedProject: projectDir,
        versionPendingInstall: null,
        lastSeenVersion: null,
        lastSuccessfulCheckAt: null,
        stuckHintShown: false,
      }),
    );
    const app = await electron.launch(
      desktopLaunchOptions({
        target: TARGET,
        args: [`--user-data-dir=${userDataDir}`],
        timeout: 30_000,
        env: { ...process.env, ...homeEnv(tmpHome), OK_RECLAIM_DISABLE: '1' },
      }),
    );
    captureStderrFor(app, { home: tmpHome, cleanupDirs: [testRoot] });
    const editorPage = await waitForWindowByMode(app, 'editor');
    await configureDesktopGitRepositories(editorPage, projectDir);

    await waitForAgentsDockPublish(
      () => editorPage.evaluate(() => window.okDesktop?.terminal.getDockState()),
      undefined,
      { timeout: 35_000 },
    );
    await expect
      .poll(() => editorPage.evaluate(() => window.okDesktop?.terminal.getDockState()), {
        timeout: 10_000,
      })
      .toMatchObject({ agents: { order: [], activeKey: null } });

    await expect
      .poll(
        async () => {
          await editorPage.evaluate(() =>
            window.okDesktop?.terminal.setDockState({
              surface: 'agents',
              order: ['thread-a', 'thread-b'],
              activeKey: 'thread-a',
            }),
          );
          return editorPage.evaluate(() => window.okDesktop?.terminal.getDockState());
        },
        { timeout: 5_000 },
      )
      .toMatchObject({ agents: { order: ['thread-a', 'thread-b'], activeKey: 'thread-a' } });
    await expect
      .poll(
        () =>
          editorPage.evaluate(() =>
            window.okDesktop?.terminal.setDockState({
              surface: 'terminal',
              order: ['pty-a', 'pty-b'],
              activeKey: 'pty-b',
              terminalSnapshot: {
                tabs: [
                  { ordinal: 1, customLabel: null },
                  { ordinal: 2, customLabel: 'Build' },
                ],
                activeOrdinal: 2,
              },
            }),
          ),
        { timeout: 5_000 },
      )
      .toEqual({ ok: true });

    const expectedBeforeReload = {
      terminal: { order: ['pty-a', 'pty-b'], activeKey: 'pty-b' },
      terminalSnapshot: {
        tabs: [
          { ordinal: 1, customLabel: null },
          { ordinal: 2, customLabel: 'Build' },
        ],
        activeOrdinal: 2,
      },
      agents: { order: ['thread-a', 'thread-b'], activeKey: 'thread-a' },
    };
    await expect
      .poll(() => editorPage.evaluate(() => window.okDesktop?.terminal.getDockState()), {
        timeout: 5_000,
      })
      .toMatchObject(expectedBeforeReload);
    const dockState = await editorPage.evaluate(() => window.okDesktop?.terminal.getDockState());
    expect(dockState).not.toHaveProperty('placement');
    expect(dockState).not.toHaveProperty('rightWidth');

    await editorPage.reload({ waitUntil: 'domcontentloaded' });
    await waitForAgentsDockPublish(
      () => editorPage.evaluate(() => window.okDesktop?.terminal.getDockState()),
      expectedBeforeReload.agents,
      { timeout: 25_000 },
    );
    await expect
      .poll(
        () =>
          editorPage.evaluate(async () => {
            const state = await window.okDesktop?.terminal.getDockState();
            return {
              agents: state?.agents,
              terminalCount: state?.terminal?.order.length,
              activeIndex: state?.terminal?.order.indexOf(state.terminal.activeKey ?? ''),
              terminalSnapshot: state?.terminalSnapshot,
            };
          }),
        { timeout: 20_000 },
      )
      .toEqual({
        agents: { order: [], activeKey: null },
        terminalCount: 2,
        activeIndex: 1,
        terminalSnapshot: expectedBeforeReload.terminalSnapshot,
      });
  });
});