All files / src/lib pipeline-client.ts

0% Statements 0/280
0% Branches 0/1
0% Functions 0/1
0% Lines 0/280

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 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 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * Pipeline Client (Tauri)
 *
 * Client for discovering, running, and monitoring Pipelines.
 * Pipelines are DSL-based workflows that orchestrate Skills and Hands.
 */
 
import { invoke } from '@tauri-apps/api/core';
import { listen, type UnlistenFn } from '@tauri-apps/api/event';
 
// Re-export UnlistenFn for external use
export type { UnlistenFn };
 
// === Types ===
 
export interface PipelineInputInfo {
  name: string;
  inputType: string;
  required: boolean;
  label: string;
  placeholder?: string;
  default?: unknown;
  options: string[];
}
 
export interface PipelineInfo {
  id: string;
  displayName: string;
  description: string;
  category: string;
  tags: string[];
  icon: string;
  version: string;
  author: string;
  inputs: PipelineInputInfo[];
}
 
export interface RunPipelineRequest {
  pipelineId: string;
  inputs: Record<string, unknown>;
}
 
export interface RunPipelineResponse {
  runId: string;
  pipelineId: string;
  status: string;
}
 
export interface PipelineRunResponse {
  runId: string;
  pipelineId: string;
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';
  currentStep?: string;
  percentage: number;
  message: string;
  outputs?: unknown;
  error?: string;
  startedAt: string;
  endedAt?: string;
}
 
export interface PipelineCompleteEvent {
  runId: string;
  pipelineId: string;
  status: string;
  outputs?: unknown;
  error?: string;
}
 
// === Pipeline Client ===
 
export class PipelineClient {
  /**
   * List all available pipelines
   */
  static async listPipelines(options?: {
    category?: string;
  }): Promise<PipelineInfo[]> {
    try {
      const pipelines = await invoke<PipelineInfo[]>('pipeline_list', {
        category: options?.category || null,
      });
      return pipelines;
    } catch (error) {
      console.error('Failed to list pipelines:', error);
      throw new Error(`Failed to list pipelines: ${error}`);
    }
  }
 
  /**
   * Get a specific pipeline by ID
   */
  static async getPipeline(pipelineId: string): Promise<PipelineInfo> {
    try {
      const pipeline = await invoke<PipelineInfo>('pipeline_get', {
        pipelineId,
      });
      return pipeline;
    } catch (error) {
      console.error(`Failed to get pipeline ${pipelineId}:`, error);
      throw new Error(`Failed to get pipeline: ${error}`);
    }
  }
 
  /**
   * Run a pipeline with the given inputs
   */
  static async runPipeline(request: RunPipelineRequest): Promise<RunPipelineResponse> {
    try {
      const response = await invoke<RunPipelineResponse>('pipeline_run', {
        request,
      });
      return response;
    } catch (error) {
      console.error('Failed to run pipeline:', error);
      throw new Error(`Failed to run pipeline: ${error}`);
    }
  }
 
  /**
   * Get the progress of a running pipeline
   */
  static async getProgress(runId: string): Promise<PipelineRunResponse> {
    try {
      const progress = await invoke<PipelineRunResponse>('pipeline_progress', {
        runId,
      });
      return progress;
    } catch (error) {
      console.error(`Failed to get progress for run ${runId}:`, error);
      throw new Error(`Failed to get progress: ${error}`);
    }
  }
 
  /**
   * Get the result of a completed pipeline run
   */
  static async getResult(runId: string): Promise<PipelineRunResponse> {
    try {
      const result = await invoke<PipelineRunResponse>('pipeline_result', {
        runId,
      });
      return result;
    } catch (error) {
      console.error(`Failed to get result for run ${runId}:`, error);
      throw new Error(`Failed to get result: ${error}`);
    }
  }
 
  /**
   * Cancel a running pipeline
   */
  static async cancel(runId: string): Promise<void> {
    try {
      await invoke('pipeline_cancel', { runId });
    } catch (error) {
      console.error(`Failed to cancel run ${runId}:`, error);
      throw new Error(`Failed to cancel run: ${error}`);
    }
  }
 
  /**
   * List all runs
   */
  static async listRuns(): Promise<PipelineRunResponse[]> {
    try {
      const runs = await invoke<PipelineRunResponse[]>('pipeline_runs');
      return runs;
    } catch (error) {
      console.error('Failed to list runs:', error);
      throw new Error(`Failed to list runs: ${error}`);
    }
  }
 
  /**
   * Refresh pipeline discovery (rescan filesystem)
   */
  static async refresh(): Promise<PipelineInfo[]> {
    try {
      const pipelines = await invoke<PipelineInfo[]>('pipeline_refresh');
      return pipelines;
    } catch (error) {
      console.error('Failed to refresh pipelines:', error);
      throw new Error(`Failed to refresh pipelines: ${error}`);
    }
  }
 
  /**
   * Subscribe to pipeline completion events
   */
  static async onComplete(
    callback: (event: PipelineCompleteEvent) => void
  ): Promise<UnlistenFn> {
    return listen<PipelineCompleteEvent>('pipeline-complete', (event) => {
      callback(event.payload);
    });
  }
 
  /**
   * Run a pipeline and wait for completion
   * Returns the final result
   */
  static async runAndWait(
    request: RunPipelineRequest,
    onProgress?: (progress: PipelineRunResponse) => void,
    pollIntervalMs: number = 1000
  ): Promise<PipelineRunResponse> {
    // Start the pipeline
    const { runId } = await this.runPipeline(request);
 
    // Poll for progress until completion
    let result = await this.getProgress(runId);
 
    while (result.status === 'running' || result.status === 'pending') {
      if (onProgress) {
        onProgress(result);
      }
 
      await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
      result = await this.getProgress(runId);
    }
 
    return result;
  }
}
 
// === Utility Functions ===
 
/**
 * Format pipeline input type for display
 */
export function formatInputType(type: string): string {
  const typeMap: Record<string, string> = {
    string: '文本',
    number: '数字',
    boolean: '布尔值',
    select: '单选',
    'multi-select': '多选',
    file: '文件',
    text: '多行文本',
  };
  return typeMap[type] || type;
}
 
/**
 * Get default value for input type
 */
export function getDefaultForType(type: string): unknown {
  switch (type) {
    case 'string':
    case 'text':
      return '';
    case 'number':
      return 0;
    case 'boolean':
      return false;
    case 'select':
      return null;
    case 'multi-select':
      return [];
    case 'file':
      return null;
    default:
      return null;
  }
}
 
/**
 * Validate pipeline inputs against schema
 */
export function validateInputs(
  inputs: PipelineInputInfo[],
  values: Record<string, unknown>
): { valid: boolean; errors: string[] } {
  const errors: string[] = [];
 
  for (const input of inputs) {
    const value = values[input.name];
 
    // Check required
    if (input.required && (value === undefined || value === null || value === '')) {
      errors.push(`${input.label || input.name} 是必填项`);
      continue;
    }
 
    // Skip validation if not provided and not required
    if (value === undefined || value === null) {
      continue;
    }
 
    // Type-specific validation
    switch (input.inputType) {
      case 'number':
        if (typeof value !== 'number') {
          errors.push(`${input.label || input.name} 必须是数字`);
        }
        break;
      case 'boolean':
        if (typeof value !== 'boolean') {
          errors.push(`${input.label || input.name} 必须是布尔值`);
        }
        break;
      case 'select':
        if (input.options.length > 0 && !input.options.includes(String(value))) {
          errors.push(`${input.label || input.name} 必须是有效选项`);
        }
        break;
      case 'multi-select':
        if (!Array.isArray(value)) {
          errors.push(`${input.label || input.name} 必须是数组`);
        } else if (input.options.length > 0) {
          const invalid = value.filter((v) => !input.options.includes(String(v)));
          if (invalid.length > 0) {
            errors.push(`${input.label || input.name} 包含无效选项`);
          }
        }
        break;
    }
  }
 
  return {
    valid: errors.length === 0,
    errors,
  };
}
 
// === React Hook ===
 
import { useState, useEffect, useCallback } from 'react';
 
export interface UsePipelineOptions {
  category?: string;
  autoRefresh?: boolean;
  refreshInterval?: number;
}
 
export function usePipelines(options: UsePipelineOptions = {}) {
  const [pipelines, setPipelines] = useState<PipelineInfo[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
 
  const loadPipelines = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await PipelineClient.listPipelines({
        category: options.category,
      });
      setPipelines(result);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }, [options.category]);
 
  const refresh = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const result = await PipelineClient.refresh();
      // Filter by category if specified
      const filtered = options.category
        ? result.filter((p) => p.category === options.category)
        : result;
      setPipelines(filtered);
    } catch (err) {
      setError(err instanceof Error ? err.message : String(err));
    } finally {
      setLoading(false);
    }
  }, [options.category]);
 
  useEffect(() => {
    loadPipelines();
  }, [loadPipelines]);
 
  useEffect(() => {
    if (options.autoRefresh && options.refreshInterval) {
      const interval = setInterval(loadPipelines, options.refreshInterval);
      return () => clearInterval(interval);
    }
  }, [options.autoRefresh, options.refreshInterval, loadPipelines]);
 
  return {
    pipelines,
    loading,
    error,
    refresh,
    reload: loadPipelines,
  };
}
 
export interface UsePipelineRunOptions {
  onComplete?: (result: PipelineRunResponse) => void;
  onProgress?: (progress: PipelineRunResponse) => void;
}
 
export function usePipelineRun(options: UsePipelineRunOptions = {}) {
  const [running, setRunning] = useState(false);
  const [progress, setProgress] = useState<PipelineRunResponse | null>(null);
  const [error, setError] = useState<string | null>(null);
 
  const run = useCallback(
    async (pipelineId: string, inputs: Record<string, unknown>) => {
      setRunning(true);
      setError(null);
      setProgress(null);
 
      try {
        const result = await PipelineClient.runAndWait(
          { pipelineId, inputs },
          (p) => {
            setProgress(p);
            options.onProgress?.(p);
          }
        );
 
        setProgress(result);
        options.onComplete?.(result);
        return result;
      } catch (err) {
        const errorMsg = err instanceof Error ? err.message : String(err);
        setError(errorMsg);
        throw err;
      } finally {
        setRunning(false);
      }
    },
    [options]
  );
 
  const cancel = useCallback(async () => {
    if (progress?.runId) {
      await PipelineClient.cancel(progress.runId);
      setRunning(false);
    }
  }, [progress?.runId]);
 
  return {
    run,
    cancel,
    running,
    progress,
    error,
  };
}