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88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
/**
 * API client utilities for making API calls in tests
 * Provides type-safe wrappers around common API operations
 */

import { Page, APIResponse } from '@playwright/test';
import { API_BASE_URL, API_ENDPOINTS, WEB_BASE_URL } from '../core/constants';

// ============================================================================
// Types
// ============================================================================

export interface WorktreeInfo {
  path: string;
  branch: string;
  isNew?: boolean;
  hasChanges?: boolean;
  changedFilesCount?: number;
}

export interface WorktreeListResponse {
  success: boolean;
  worktrees: WorktreeInfo[];
  error?: string;
}

export interface WorktreeCreateResponse {
  success: boolean;
  worktree?: WorktreeInfo;
  error?: string;
}

export interface WorktreeDeleteResponse {
  success: boolean;
  error?: string;
}

export interface CommitResult {
  committed: boolean;
  branch?: string;
  commitHash?: string;
  message?: string;
}

export interface CommitResponse {
  success: boolean;
  result?: CommitResult;
  error?: string;
}

export interface SwitchBranchResult {
  previousBranch: string;
  currentBranch: string;
  message: string;
}

export interface SwitchBranchResponse {
  success: boolean;
  result?: SwitchBranchResult;
  error?: string;
  code?: string;
}

export interface BranchInfo {
  name: string;
  isCurrent: boolean;
}

export interface ListBranchesResult {
  currentBranch: string;
  branches: BranchInfo[];
}

export interface ListBranchesResponse {
  success: boolean;
  result?: ListBranchesResult;
  error?: string;
}

// ============================================================================
// Worktree API Client
// ============================================================================

export class WorktreeApiClient {
  constructor(private page: Page) {}

  /**
   * Create a new worktree
   */
  async create(
    projectPath: string,
    branchName: string,
    baseBranch?: string
  ): Promise<{ response: APIResponse; data: WorktreeCreateResponse }> {
    const response = await this.page.request.post(API_ENDPOINTS.worktree.create, {
      data: {
        projectPath,
        branchName,
        baseBranch,
      },
    });
    const data = await response.json();
    return { response, data };
  }

  /**
   * Delete a worktree
   */
  async delete(
    projectPath: string,
    worktreePath: string,
    deleteBranch: boolean = true
  ): Promise<{ response: APIResponse; data: WorktreeDeleteResponse }> {
    const response = await this.page.request.post(API_ENDPOINTS.worktree.delete, {
      data: {
        projectPath,
        worktreePath,
        deleteBranch,
      },
    });
    const data = await response.json();
    return { response, data };
  }

  /**
   * List all worktrees
   */
  async list(
    projectPath: string,
    includeDetails: boolean = true
  ): Promise<{ response: APIResponse; data: WorktreeListResponse }> {
    const response = await this.page.request.post(API_ENDPOINTS.worktree.list, {
      data: {
        projectPath,
        includeDetails,
      },
    });
    const data = await response.json();
    return { response, data };
  }

  /**
   * Commit changes in a worktree
   */
  async commit(
    worktreePath: string,
    message: string
  ): Promise<{ response: APIResponse; data: CommitResponse }> {
    const response = await this.page.request.post(API_ENDPOINTS.worktree.commit, {
      data: {
        worktreePath,
        message,
      },
    });
    const data = await response.json();
    return { response, data };
  }

  /**
   * Switch branches in a worktree
   */
  async switchBranch(
    worktreePath: string,
    branchName: string
  ): Promise<{ response: APIResponse; data: SwitchBranchResponse }> {
    const response = await this.page.request.post(API_ENDPOINTS.worktree.switchBranch, {
      data: {
        worktreePath,
        branchName,
      },
    });
    const data = await response.json();
    return { response, data };
  }

  /**
   * List all branches
   */
  async listBranches(
    worktreePath: string
  ): Promise<{ response: APIResponse; data: ListBranchesResponse }> {
    const response = await this.page.request.post(API_ENDPOINTS.worktree.listBranches, {
      data: {
        worktreePath,
      },
    });
    const data = await response.json();
    return { response, data };
  }
}

// ============================================================================
// Factory Functions
// ============================================================================

/**
 * Create a WorktreeApiClient instance
 */
export function createWorktreeApiClient(page: Page): WorktreeApiClient {
  return new WorktreeApiClient(page);
}

// ============================================================================
// Convenience Functions (for direct use without creating a client)
// ============================================================================

/**
 * Create a worktree via API
 */
export async function apiCreateWorktree(
  page: Page,
  projectPath: string,
  branchName: string,
  baseBranch?: string
): Promise<{ response: APIResponse; data: WorktreeCreateResponse }> {
  return new WorktreeApiClient(page).create(projectPath, branchName, baseBranch);
}

/**
 * Delete a worktree via API
 */
export async function apiDeleteWorktree(
  page: Page,
  projectPath: string,
  worktreePath: string,
  deleteBranch: boolean = true
): Promise<{ response: APIResponse; data: WorktreeDeleteResponse }> {
  return new WorktreeApiClient(page).delete(projectPath, worktreePath, deleteBranch);
}

/**
 * List worktrees via API
 */
export async function apiListWorktrees(
  page: Page,
  projectPath: string,
  includeDetails: boolean = true
): Promise<{ response: APIResponse; data: WorktreeListResponse }> {
  return new WorktreeApiClient(page).list(projectPath, includeDetails);
}

/**
 * Commit changes in a worktree via API
 */
export async function apiCommitWorktree(
  page: Page,
  worktreePath: string,
  message: string
): Promise<{ response: APIResponse; data: CommitResponse }> {
  return new WorktreeApiClient(page).commit(worktreePath, message);
}

/**
 * Switch branches in a worktree via API
 */
export async function apiSwitchBranch(
  page: Page,
  worktreePath: string,
  branchName: string
): Promise<{ response: APIResponse; data: SwitchBranchResponse }> {
  return new WorktreeApiClient(page).switchBranch(worktreePath, branchName);
}

/**
 * List branches via API
 */
export async function apiListBranches(
  page: Page,
  worktreePath: string
): Promise<{ response: APIResponse; data: ListBranchesResponse }> {
  return new WorktreeApiClient(page).listBranches(worktreePath);
}

// ============================================================================
// Authentication Utilities
// ============================================================================

/**
 * Authenticate with the server using an API key
 * This sets a session cookie that will be used for subsequent requests
 * Uses browser context to ensure cookies are properly set
 */
export async function authenticateWithApiKey(page: Page, apiKey: string): Promise<boolean> {
  try {
    // Fast path: check if we already have a valid session (from global setup storageState)
    try {
      const statusRes = await page.request.get(`${API_BASE_URL}/api/auth/status`, {
        timeout: 3000,
      });
      const statusJson = (await statusRes.json().catch(() => null)) as {
        authenticated?: boolean;
      } | null;
      if (statusJson?.authenticated === true) {
        return true;
      }
    } catch {
      // Status check failed, proceed with full auth
    }

    // Ensure the backend is up before attempting login (especially in local runs where
    // the backend may be started separately from Playwright).
    const start = Date.now();
    let authBackoff = 250;
    while (Date.now() - start < 15000) {
      try {
        const health = await page.request.get(`${API_BASE_URL}/api/health`, {
          timeout: 3000,
        });
        if (health.ok()) break;
      } catch {
        // Retry
      }
      await page.waitForTimeout(authBackoff);
      authBackoff = Math.min(authBackoff * 2, 2000);
    }

    // Ensure we're on a page (needed for cookies to work)
    const currentUrl = page.url();
    if (!currentUrl || currentUrl === 'about:blank') {
      await page.goto(WEB_BASE_URL, { waitUntil: 'domcontentloaded' });
    }

    // Use Playwright request API (tied to this browser context) to avoid flakiness
    // with cross-origin fetch inside page.evaluate.
    const loginResponse = await page.request.post(`${API_BASE_URL}/api/auth/login`, {
      data: { apiKey },
      headers: { 'Content-Type': 'application/json' },
      timeout: 15000,
    });
    const response = (await loginResponse.json().catch(() => null)) as {
      success?: boolean;
      token?: string;
    } | null;

    if (response?.success && response.token) {
      // Manually set the cookie in the browser context
      // The server sets a cookie named 'automaker_session' (see SESSION_COOKIE_NAME in auth.ts)
      await page.context().addCookies([
        {
          name: 'automaker_session',
          value: response.token,
          domain: '127.0.0.1',
          path: '/',
          httpOnly: true,
          sameSite: 'Lax',
        },
      ]);

      // Single verification check (no polling loop needed)
      const verifyRes = await page.request.get(`${API_BASE_URL}/api/auth/status`, {
        timeout: 5000,
      });
      const verifyJson = (await verifyRes.json().catch(() => null)) as {
        authenticated?: boolean;
      } | null;

      return verifyJson?.authenticated === true;
    }

    return false;
  } catch (error) {
    console.error('Authentication error:', error);
    return false;
  }
}

/**
 * Authenticate using the API key from environment variable
 * Falls back to a test default if AUTOMAKER_API_KEY is not set
 */
export async function authenticateForTests(page: Page): Promise<boolean> {
  // Use the API key from environment, or a test default
  const apiKey = process.env.AUTOMAKER_API_KEY || 'test-api-key-for-e2e-tests';
  return authenticateWithApiKey(page, apiKey);
}

/**
 * Check if the backend server is healthy
 * Returns true if the server responds with status 200, false otherwise
 */
export async function checkBackendHealth(page: Page, timeout = 5000): Promise<boolean> {
  try {
    const response = await page.request.get(`${API_BASE_URL}/api/health`, {
      timeout,
    });
    return response.ok();
  } catch {
    return false;
  }
}

/**
 * Wait for the backend to be healthy, with retry logic
 * Throws an error if the backend doesn't become healthy within the timeout
 */
export async function waitForBackendHealth(
  page: Page,
  maxWaitMs = 30000,
  checkIntervalMs = 500
): Promise<void> {
  const startTime = Date.now();
  let backoff = checkIntervalMs;

  while (Date.now() - startTime < maxWaitMs) {
    if (await checkBackendHealth(page, Math.min(backoff, 3000))) {
      return;
    }
    await page.waitForTimeout(backoff);
    backoff = Math.min(backoff * 2, 2000);
  }

  throw new Error(
    `Backend did not become healthy within ${maxWaitMs}ms. ` +
      `Last health check failed or timed out.`
  );
}