File size: 2,172 Bytes
1dbc34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
 * Kill any existing servers on test ports before running tests
 * This ensures the test server starts fresh with the correct API key
 */

import { exec } from 'child_process';
import { promisify } from 'util';

const execAsync = promisify(exec);

const SERVER_PORT = process.env.TEST_SERVER_PORT || 3108;
const UI_PORT = process.env.TEST_PORT || 3107;
// Match Playwright config semantics: only explicit opt-in should skip backend startup/cleanup.
// VITE_SERVER_URL may exist in local shells and should not implicitly affect test behavior.
const USE_EXTERNAL_SERVER = process.env.TEST_USE_EXTERNAL_BACKEND === 'true';
console.log(`[KillTestServers] SERVER_PORT ${SERVER_PORT}`);
console.log(`[KillTestServers] UI_PORT ${UI_PORT}`);
async function killProcessOnPort(port) {
  try {
    const hasLsof = await execAsync('command -v lsof').then(
      () => true,
      () => false
    );

    if (hasLsof) {
      const { stdout } = await execAsync(`lsof -ti:${port}`);
      const pids = stdout.trim().split('\n').filter(Boolean);

      if (pids.length > 0) {
        console.log(`[KillTestServers] Found process(es) on port ${port}: ${pids.join(', ')}`);
        for (const pid of pids) {
          try {
            await execAsync(`kill -9 ${pid}`);
            console.log(`[KillTestServers] Killed process ${pid}`);
          } catch (_error) {
            // Process might have already exited
          }
        }
        await new Promise((resolve) => setTimeout(resolve, 500));
      }
      return;
    }

    const hasFuser = await execAsync('command -v fuser').then(
      () => true,
      () => false
    );
    if (hasFuser) {
      await execAsync(`fuser -k -9 ${port}/tcp`).catch(() => undefined);
      await new Promise((resolve) => setTimeout(resolve, 500));
      return;
    }
  } catch (_error) {
    // No process on port, which is fine
  }
}

async function main() {
  console.log('[KillTestServers] Checking for existing test servers...');
  if (!USE_EXTERNAL_SERVER) {
    await killProcessOnPort(Number(SERVER_PORT));
  }
  await killProcessOnPort(Number(UI_PORT));
  console.log('[KillTestServers] Done');
}

main().catch(console.error);