1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ミニPC(Ollama+Dify)だけでWebアプリのAI自動テスト環境を作った話 〜ブラウザ操作・画面崩れ診断・修正プロンプト生成まで〜

1
Last updated at Posted at 2026-11-27

はじめに

Webアプリを開発していると、機能追加やリファクタリングのたびに発生する「動作確認」や「画面崩れチェック」が地味に大変です。
クラウドAI(OpenAIやClaudeなど)のAPIを使ってテストを自動化する方法もありますが、以下の悩みがありました。

  • API料金:画面操作やコード精査を毎回AIに投げるとコストがかさむ
  • プライバシー:未公開のソースコードやDB構造を外部サーバーに送りたくない

そこで今回、自宅の**ミニPC(ローカルLLM環境)だけで完結する、「Difyの実行ボタンを押すだけでWebアプリの自動テスト〜修正依頼用プロンプト作成まで行うシステム」**を構築しました。

できたもの(ワークフロー全体像)

Difyの入力画面に「プロジェクト全体の構造とソースコードのテキスト」を貼り付けて**「実行」ボタン**を押すと、裏側で以下の処理が全自動で走ります。

  1. 入力テキストの自動保存:貼り付けたデータをタイムスタンプ付き .md として保存
  2. PHP構文チェック (php -l):対象PHPファイルの構文エラーを100%機械的に検出
  3. 自律ブラウザE2Eテスト(Playwright + qwen2.5:14b):
    • AIがソースコードとDB構造からテスト計画を立案
    • GUIなしのヘッドレスChromeで実際に画面を操作(PHPエラー、JSエラー、HTTP 4xx/5xx、画像切れ、横はみ出しを検知)
  4. AIコード精査(自動分割):規約違反や潜在バグをバッチ分割でチェック
  5. AI画面崩れ診断(qwen2.5vl:7b):撮影したスクリーンショットを視覚認識モデルが目視チェック
  6. レポート & 修正依頼用プロンプト生成:
    • スクショ付きHTMLレポートを出力
    • 検出された問題点をまとめた**「修正依頼用プロンプト(.md)」**を自動保存
[Windows PC (ブラウザ)]
   ├── Dify WebUI (:80) ── テキスト貼り付け & 実行ボタン
   └── 進捗モニタ / レポート閲覧 (:8090) ── 経過時間・残り時間・途中中断ボタン

[ミニPC (Ubuntu Server 26.04 / GUIなし)]
   ├── Dify (Docker Compose)
   ├── テストランナーAPI (Node.js + Playwright / systemd常時稼働 :8090)
   ├── Ollama (:11434 / AMD ROCm GPU推論)
   │     ├── qwen2.5:14b (テスト計画・ブラウザ操作・コード精査)
   │     └── qwen2.5vl:7b (スクリーンショット画面崩れ診断)
   └── テスト対象Webサーバー (Docker Compose)
         ├── Apache 2.4 + PHP 8.5 (:8080)
         ├── MariaDB 11.4 (:3307)
         └── phpMyAdmin (:8081)

ハードウェア・前提環境

  • ミニPC:GMKtec EVO-X1 Pro(AMD Ryzen AI 9 HX 470 / Radeon 890M)
  • メモリ:64GB LPDDR5X(VRAM固定 32GB / システムRAM 31GB)
  • OS:Ubuntu Server 26.04 LTS(GUIなし・CUI環境)
  • 構築済みAI基盤:
    • Ollama:qwen2.5:14b(9GB)、qwen2.5vl:7b(画像認識)導入済み、OLLAMA_HOST=0.0.0.0 で公開
    • Dify:Docker Compose(:80)で稼働、host.docker.internal 接続およびプライベートIPアクセス許可済み

構築手順

1. テスト対象 Web+DB環境の構築(Docker Compose)

Difyがすでに 80 番ポートを使用しているため、テスト対象サーバーは別ポート(Web: 8080、phpMyAdmin: 8081、MariaDB: 3307)で隔離構築します。

mkdir -p ~/web-test-env/html ~/web-test-env/php ~/web-test-env/db_data

~/web-test-env/php/Dockerfile を作成します(Apache 2.4同梱のPHPイメージに必要拡張を組み込み)。

FROM php:8.5.12-apache

RUN apt-get update && apt-get install -y \
    libpng-dev libjpeg-dev libfreetype6-dev libzip-dev unzip \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) pdo_mysql mysqli gd zip \
    && a2enmod rewrite \
    && rm -rf /var/lib/apt/lists/*

~/web-test-env/docker-compose.yml を作成して起動します。

services:
  web:
    build: ./php
    container_name: test-web-php
    ports:
      - "8080:80"
    volumes:
      - ./html:/var/www/html
    restart: unless-stopped

  db:
    image: mariadb:11.4
    container_name: test-mariadb
    environment:
      MYSQL_ROOT_PASSWORD: test_root_password
      MYSQL_DATABASE: test_db
      MYSQL_USER: test_user
      MYSQL_PASSWORD: test_password
    ports:
      - "3307:3306"
    volumes:
      - ./db_data:/var/lib/mysql
    restart: unless-stopped

  phpmyadmin:
    image: phpmyadmin:latest
    container_name: test-phpmyadmin
    environment:
      PMA_HOST: db
      PMA_PORT: 3306
    ports:
      - "8081:80"
    depends_on:
      - db
    restart: unless-stopped
cd ~/web-test-env && docker compose up -d --build

(※開発用PCからソースを高速転送するため、Ubuntu側に Samba を入れて ~/web-test-env/html を共有フォルダ化しておくと非常に快適です)

2. GUIなしUbuntuでのPlaywright準備(日本語フォント必須!)

GUIなしのUbuntu Serverでも、ヘッドレスChromeを使えばブラウザ操作とスクリーンショット撮影が可能です。
ただし、日本語フォントが入っていないとスクリーンショットの文字がすべて「□□□(豆腐)」になり、画面崩れ診断もVLM認識も破綻するため、必ず fonts-noto-cjk を入れます。

# 日本語フォント(文字化け防止)
sudo apt update && sudo apt install -y fonts-noto-cjk curl

# Node.js 22 LTS の導入
curl -fsSL https://deb.nodesource.com/setup_22.x | sudo -E bash -
sudo apt install -y nodejs

# 作業ディレクトリに Playwright + Chromium を導入
mkdir -p ~/ai-tester && cd ~/ai-tester
npm init -y
npm install -D @playwright/test
npx playwright install --with-deps chromium

3. テストランナーAPIサーバー(~/ai-tester/test-server.mjs)の構築

Difyからのリクエストを受け取り、非同期で自動テスト〜レポート・修正プロンプト保存までを実行するサーバーを Node.js 標準モジュールのみで構築します(外部フレームワーク不要)。

以下のポイントを組み込んでいます:

  • 非同期ジョブ化 + リアルタイム進捗画面(/status):経過時間(1秒更新)、実測速度からの推定残り時間、プログレスバー表示
  • AbortController による途中中断対応:中断ボタンを押すと推論中のOllama通信も即座に止め、その時点までの完了分でレポート&プロンプトを出力
  • keep_alive: 0 によるVRAM自動解放:try ... finally で終了時や中断時に必ずモデルをVRAMから降ろし、ComfyUI等と共存

~/ai-tester/test-server.mjs を作成します(LAN_HOST はお使いのミニPCのIPアドレスに書き換えてください)。

cat << 'EOF' > ~/ai-tester/test-server.mjs
import http from 'node:http';
import fs from 'node:fs';
import path from 'node:path';
import { execSync } from 'node:child_process';
import { chromium } from '@playwright/test';

const PORT = 8090;
const LAN_HOST = '192.168.1.20';
const OLLAMA_URL = 'http://127.0.0.1:11434';
const BRAIN_MODEL = 'qwen2.5:14b';
const VLM_MODEL = 'qwen2.5vl:7b';
const MAX_CRAWL_PAGES = 22;

const BASE_DIR = path.resolve(process.env.HOME, 'ai-tester');
const REPORT_DIR = path.join(BASE_DIR, 'reports');
const SCREEN_DIR = path.join(REPORT_DIR, 'auto_screens');
const PROMPT_DIR = path.join(REPORT_DIR, 'prompts');
const DOC_DIR = path.join(REPORT_DIR, 'docs');
const DB_BACKUP_DIR = path.join(BASE_DIR, 'db_backups');

fs.mkdirSync(SCREEN_DIR, { recursive: true });
fs.mkdirSync(PROMPT_DIR, { recursive: true });
fs.mkdirSync(DOC_DIR, { recursive: true });
fs.mkdirSync(DB_BACKUP_DIR, { recursive: true });

const jobs = new Map();
let latestJobId = null;
let lastDetectedDb = null;

function escapeHtml(str) {
  return String(str)
    .replace(/&/g, '&amp;').replace(/</g, '&lt;')
    .replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

function getJstTimestamp(date = new Date()) {
  const jst = new Date(date.getTime() + 9 * 60 * 60 * 1000);
  return jst.toISOString().replace(/[-:T]/g, '').slice(0, 14);
}

function formatDurationSec(totalSec) {
  const sec = Math.max(0, Math.round(totalSec));
  const h = Math.floor(sec / 3600);
  const m = Math.floor((sec % 3600) / 60);
  const s = sec % 60;
  if (h > 0) return `${h}時間${String(m).padStart(2, '0')}分${String(s).padStart(2, '0')}秒`;
  if (m > 0) return `${m}分${String(s).padStart(2, '0')}秒`;
  return `${s}秒`;
}

function joinUrl(baseUrl, subPath) {
  const normalizedBase = baseUrl.endsWith('/') ? baseUrl : baseUrl + '/';
  const cleanPath = String(subPath || '').replace(/^\/+/, '');
  return new URL(cleanPath, normalizedBase).href;
}

function normalizeUrlForVisit(rawUrl) {
  try {
    const u = new URL(rawUrl);
    u.hash = '';
    u.pathname = u.pathname.replace(/\/index\.(php|html?)$/i, '/');
    return u.href;
  } catch {
    return null;
  }
}

// ドキュメントからDB名を汎用抽出し、MariaDB内の実在DBと照合
function detectTargetDatabase(files) {
  const candidates = [];
  for (const f of files) {
    const m1 = f.content.match(/define\s*\(\s*['"]DB_NAME['"]\s*,\s*['"]([a-zA-Z0-9_-]+)['"]\s*\)/i);
    if (m1) candidates.push(m1[1]);
    const m2 = f.content.match(/DB_DATABASE\s*=\s*['"]?([a-zA-Z0-9_-]+)['"]?/i);
    if (m2) candidates.push(m2[1]);
    const m3 = f.content.match(/dbname=([a-zA-Z0-9_-]+)/i);
    if (m3) candidates.push(m3[1]);
  }
  candidates.push('test_db');

  try {
    const out = execSync('docker exec -i test-mariadb mariadb -u root -ptest_root_password -N -e "SHOW DATABASES;"', {
      encoding: 'utf-8',
      stdio: ['pipe', 'pipe', 'pipe']
    });
    const existing = new Set(out.split(/\r?\n/).map((s) => s.trim()).filter(Boolean));
    for (const c of candidates) {
      if (/^[a-zA-Z0-9_-]+$/.test(c) && existing.has(c)) return c;
    }
  } catch (e) {
    console.error('DB一覧取得スキップ:', e.message);
  }
  return null;
}

function backupDatabase(dbName) {
  if (!dbName || !/^[a-zA-Z0-9_-]+$/.test(dbName)) return { ok: false, msg: '対象DBなし' };
  const backupPath = path.join(DB_BACKUP_DIR, `${dbName}_clean.sql`);
  const sql = execSync(
    `docker exec test-mariadb sh -c "mariadb-dump -u root -ptest_root_password --single-transaction --add-drop-table --routines --triggers --default-character-set=utf8mb4 ${dbName} || mysqldump -u root -ptest_root_password --single-transaction --add-drop-table --routines --triggers --default-character-set=utf8mb4 ${dbName}"`,
    { encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
  );
  fs.writeFileSync(backupPath, `SET FOREIGN_KEY_CHECKS=0;\n${sql}\nSET FOREIGN_KEY_CHECKS=1;\n`, 'utf-8');
  return { ok: true, path: backupPath, msg: `初期バックアップ作成 (${dbName})` };
}

function restoreDatabase(dbName) {
  if (!dbName || !/^[a-zA-Z0-9_-]+$/.test(dbName)) return { ok: false, msg: '対象DBなし' };
  const backupPath = path.join(DB_BACKUP_DIR, `${dbName}_clean.sql`);
  if (!fs.existsSync(backupPath)) return { ok: false, msg: 'バックアップファイル未作成' };
  const sql = fs.readFileSync(backupPath, 'utf-8');
  execSync(
    `docker exec -i test-mariadb mariadb -u root -ptest_root_password --default-character-set=utf8mb4 ${dbName}`,
    { input: sql, encoding: 'utf-8', maxBuffer: 50 * 1024 * 1024 }
  );
  return { ok: true, path: backupPath, msg: `初期バックアップからDB復元完了 (${dbName})` };
}

function prepareDatabaseForTest(dbName) {
  if (!dbName) return 'DB連携なし(スキップ)';
  const backupPath = path.join(DB_BACKUP_DIR, `${dbName}_clean.sql`);
  try {
    if (fs.existsSync(backupPath)) {
      const res = restoreDatabase(dbName);
      return res.msg;
    } else {
      const res = backupDatabase(dbName);
      return res.msg;
    }
  } catch (e) {
    return `DBバックアップ/復元エラー (${dbName}): ${e.message.split('\n')[0]}`;
  }
}

function parseProjectDocument(docText) {
  const files = [];
  const regex = /^--- ([^\n]+?) ---\s*\n```[a-zA-Z0-9_-]*\n([\s\S]*?)```/gm;
  let match;
  while ((match = regex.exec(docText)) !== null) {
    files.push({ path: match[1].trim(), content: match[2] });
  }
  const specMatch = docText.match(/## 3\. 技術仕様([\s\S]*?)(?=## \d+\.|$)/);
  const dbMatch = docText.match(/## 5\. データベース情報([\s\S]*?)(?=## \d+\.|$)/);

  const accMatch = docText.match(/(?:アカウント|ユーザー名|ID|Email)\s*[::]\s*([^\s\r\n]+)/i);
  const passMatch = docText.match(/(?:パスワード|Password)\s*[::]\s*([^\s\r\n]+)/i);

  const definedFuncs = new Set();
  const definedConsts = new Set();
  for (const f of files) {
    for (const m of f.content.matchAll(/\bfunction\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/g)) definedFuncs.add(m[1]);
    for (const m of f.content.matchAll(/\bdef\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\(/g)) definedFuncs.add(m[1]);
    for (const m of f.content.matchAll(/\bdefine\(\s*['"]([A-Z0-9_]+)['"]/g)) definedConsts.add(m[1]);
  }

  return {
    specs: specMatch ? specMatch[1].trim() : '',
    dbInfo: dbMatch ? dbMatch[1].trim() : '',
    adminAccount: accMatch ? accMatch[1].trim() : null,
    adminPassword: passMatch ? passMatch[1].trim() : null,
    definedSymbols: `定義済み関数: ${Array.from(definedFuncs).slice(0, 120).join(', ')}\n定義済み定数: ${Array.from(definedConsts).slice(0, 120).join(', ')}`,
    files
  };
}

function buildReviewBatches(files) {
  const targetFiles = files.filter((f) =>
    /\.(php|js|ts|jsx|tsx|py|rb|go)$/i.test(f.path) &&
    !f.path.includes('sw') && !f.path.includes('manifest') &&
    !f.path.endsWith('.min.js') && f.content.length > 0
  );

  const chunks = [];
  for (const f of targetFiles) {
    const lines = f.content.split('\n');
    const totalLines = lines.length;
    let start = 0;
    while (start < totalLines) {
      let buf = '';
      let end = start;
      while (end < totalLines) {
        const lineText = `${end + 1}: ${lines[end]}\n`;
        if (buf.length + lineText.length > 9000 && end > start) break;
        buf += lineText;
        end++;
      }
      chunks.push({
        path: f.path,
        rangeInfo: `${start + 1}〜${end}行目 (全${totalLines}行中の分割表示)`,
        content: buf
      });
      start = end;
    }
  }

  const batches = [];
  let currentBatch = [];
  let currentChars = 0;
  for (const c of chunks) {
    if (currentChars + c.content.length > 16000 && currentBatch.length > 0) {
      batches.push(currentBatch);
      currentBatch = [];
      currentChars = 0;
    }
    currentBatch.push(c);
    currentChars += c.content.length;
  }
  if (currentBatch.length > 0) batches.push(currentBatch);
  return batches;
}

function getJobTiming(job) {
  if (!job) return { elapsedSec: 0, remainingSec: null, percent: 0 };
  const now = job.endMs || Date.now();
  const elapsedSec = Math.max(0, Math.round((now - job.startMs) / 1000));
  if (job.status !== 'running') return { elapsedSec, remainingSec: 0, percent: 100 };

  const avgPageSec = job.donePages > 0 ? (job.pageDurationMs / 1000 / job.donePages) : 8;
  const avgBatchSec = job.doneBatches > 0 ? (job.batchDurationMs / 1000 / job.doneBatches) : 35;
  const avgVlmSec = job.doneVlm > 0 ? (job.vlmDurationMs / 1000 / job.doneVlm) : 7;

  let remainingSec = 0;
  if (job.phase === 'init' || job.phase === 'lint' || job.phase === 'discover') {
    remainingSec = (job.totalPages * avgPageSec) + (job.totalBatches * avgBatchSec) + (job.totalPages * avgVlmSec) + 20;
  } else if (job.phase === 'browser') {
    remainingSec = Math.max(0, job.totalPages - job.donePages) * avgPageSec + (job.totalBatches * avgBatchSec) + (job.totalPages * avgVlmSec) + 20;
  } else if (job.phase === 'review') {
    remainingSec = Math.max(0, job.totalBatches - job.doneBatches) * avgBatchSec + (job.totalVlm * avgVlmSec) + 15;
  } else if (job.phase === 'vlm') {
    remainingSec = Math.max(0, job.totalVlm - job.doneVlm) * avgVlmSec + 10;
  } else if (job.phase === 'prompt') {
    remainingSec = 5;
  }

  const totalUnits = Math.max(1, job.totalPages) + job.totalBatches + Math.max(1, job.totalVlm) + 1;
  let doneUnits = 0;
  if (job.phase === 'browser') doneUnits = job.donePages;
  else if (job.phase === 'review') doneUnits = Math.max(1, job.totalPages) + job.doneBatches;
  else if (job.phase === 'vlm') doneUnits = Math.max(1, job.totalPages) + job.totalBatches + job.doneVlm;
  else if (job.phase === 'prompt') doneUnits = totalUnits - 1;
  const percent = Math.min(99, Math.max(2, Math.round((doneUnits / totalUnits) * 100)));

  return { elapsedSec, remainingSec: Math.round(remainingSec), percent };
}

async function callOllama(model, prompt, jsonSchema = null, keepAlive = '5m', images = null, abortSignal = null) {
  const msg = { role: 'user', content: prompt };
  if (images) msg.images = images;

  const body = {
    model,
    messages: [msg],
    stream: false,
    keep_alive: keepAlive,
    options: { num_ctx: 16384, temperature: 0.1 }
  };
  if (jsonSchema) body.format = jsonSchema;

  const timeoutSig = AbortSignal.timeout(120000);
  const combinedSignal = abortSignal && AbortSignal.any
    ? AbortSignal.any([timeoutSig, abortSignal])
    : timeoutSig;

  const res = await fetch(`${OLLAMA_URL}/api/chat`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body),
    signal: combinedSignal
  });
  if (!res.ok) throw new Error(`Ollama Error: ${res.status} ${await res.text()}`);
  const data = await res.json();
  const content = data.message?.content || '';
  return jsonSchema ? JSON.parse(content) : content;
}

async function unloadModel(model) {
  await fetch(`${OLLAMA_URL}/api/generate`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ model, keep_alive: 0 })
  }).catch(() => {});
}

function runPhpLintChecks(files) {
  const lintErrors = [];
  const phpFiles = files.filter((f) => f.path.endsWith('.php'));
  if (phpFiles.length === 0) return lintErrors;
  for (const file of phpFiles) {
    try {
      execSync('docker exec -i test-web-php php -l', {
        input: file.content,
        encoding: 'utf-8',
        stdio: ['pipe', 'pipe', 'pipe']
      });
    } catch (e) {
      const errOut = (e.stderr || e.stdout || e.message).trim();
      const lineMatch = errOut.match(/on line (\d+)/i);
      lintErrors.push({ file: file.path, line: lineMatch ? Number(lineMatch[1]) : null, error: errOut });
    }
  }
  return lintErrors;
}

async function discoverEntryPoints(parsed, job) {
  job.phase = 'discover';
  job.progress = 'プロジェクト構成からテスト対象URLを自動解析中...';
  const exactPaths = parsed.files.map((f) => f.path);
  const schema = {
    type: 'object',
    properties: {
      entry_path: { type: 'string' },
      login_path: { type: 'string' }
    },
    required: ['entry_path', 'login_path']
  };

  const prompt = `以下はWebアプリに実際に存在するファイルパスの正確な一覧です。
必ずこの一覧の中に存在するパスだけを使って、以下2つをJSONで返してください(存在しないパスを推測で作らないでください):
- entry_path: 公開トップページのパス(例: "index.php"、見つからなければ "")
- login_path: ログイン画面のパス(例: "admin/login.php" や "login.php"、ログイン機能がなければ "")

【ファイルパス一覧】
${exactPaths.join('\n')}`;

  try {
    return await callOllama(BRAIN_MODEL, prompt, schema, '5m', null, job.abortController.signal);
  } catch {
    return { entry_path: '', login_path: '' };
  }
}

// フォームやモーダル内の入力欄に汎用テストデータを入力するヘルパー
async function fillVisibleInputs(containerLocator) {
  const inputs = containerLocator.locator('input:visible:not([type="hidden"]):not([type="submit"]):not([type="button"]):not([readonly]):not([disabled]), textarea:visible:not([readonly]):not([disabled])');
  const count = await inputs.count();
  for (let i = 0; i < Math.min(count, 8); i++) {
    const inp = inputs.nth(i);
    const type = (await inp.getAttribute('type') || 'text').toLowerCase();
    const name = (await inp.getAttribute('name') || '').toLowerCase();
    const curVal = await inp.inputValue().catch(() => '');
    if (curVal && type !== 'password') continue;

    if (type === 'email' || name.includes('email') || name.includes('mail')) {
      await inp.fill('autotest@example.com').catch(() => {});
    } else if (type === 'tel' || name.includes('phone') || name.includes('tel')) {
      await inp.fill('09012345678').catch(() => {});
    } else if (type === 'number' || name.includes('fee') || name.includes('rate') || name.includes('distance')) {
      await inp.fill('10').catch(() => {});
    } else if (type === 'date') {
      await inp.fill('2026-12-01').catch(() => {});
    } else if (type === 'time') {
      await inp.fill('09:00').catch(() => {});
    } else if (type === 'password') {
      await inp.fill('Test_Pass123!').catch(() => {});
    } else if (type === 'checkbox' || type === 'radio') {
      // skip
    } else if (name.includes('zip')) {
      await inp.fill('1000001').catch(() => {});
    } else {
      await inp.fill('自動テスト').catch(() => {});
    }
  }
}

// ページ内のタブ・ボタン(<button>)・リンクボタン(a.btn)の操作テスト
async function interactWithPageButtons(page, targetUrl, originalUrl, isDestructivePhase = false) {
  const normalizedBase = targetUrl.endsWith('/') ? targetUrl : targetUrl + '/';
  const testedLogs = [];
  const errorsFound = [];
  const clickedKeys = new Set();

  // 1. タブ切り替えテスト
  const tabs = page.locator('.ui-tabs-anchor:visible, [role="tab"]:visible, .nav-tabs a:visible, .nav-tabs button:visible');
  const tabCount = await tabs.count().catch(() => 0);
  for (let t = 0; t < Math.min(tabCount, 6); t++) {
    try {
      const tab = tabs.nth(t);
      const label = (await tab.innerText().catch(() => '')).trim() || `タブ${t + 1}`;
      await tab.click({ timeout: 3000 });
      await page.waitForTimeout(300);
      testedLogs.push(`タブ切替: [${label}]`);
    } catch (e) {
      errorsFound.push(`タブ切替エラー: ${e.message.split('\n')[0]}`);
    }
  }

  // 2. ページ内のボタン・アクションリンクを列挙
  const buttonInfos = await page.evaluate(() => {
    const items = [];
    const selectors = 'button, input[type="button"], input[type="submit"], a.btn, a[class*="btn-"], [role="button"]';
    document.querySelectorAll(selectors).forEach((el, idx) => {
      const rect = el.getBoundingClientRect();
      if (rect.width === 0 || rect.height === 0) return;
      if (el.disabled || el.getAttribute('disabled') !== null) return;
      // ヘッダーナビ・サイドバーの戻る/更新/折りたたみ等は除外
      if (el.closest('.sidebar, .browser-nav, .header-actions')) return;
      const text = (el.innerText || el.value || el.getAttribute('title') || '').replace(/\s+/g, ' ').trim();
      const cls = el.className || '';
      const href = el.tagName.toLowerCase() === 'a' ? (el.getAttribute('href') || '') : '';
      el.setAttribute('data-btn-test-id', String(idx));
      items.push({ idx, text, cls, href, tag: el.tagName.toLowerCase() });
    });
    return items;
  }).catch(() => []);

  const skipPattern = /google|line|アプリurl|qr|csv|pdf|ダウンロード|download|プリント|印刷/i;
  const logoutOrWithdrawPattern = /ログアウト|logout|signout|退会|withdraw/i;

  for (const b of buttonInfos) {
    if (clickedKeys.size >= 8) break; // 1ページ最大8ボタンまで操作
    const label = b.text || b.href || `btn-${b.idx}`;
    if (clickedKeys.has(label)) continue;
    if (skipPattern.test(label) || skipPattern.test(b.href)) continue;
    // 通常フェーズではログアウト・退会はスキップ(最後尾フェーズでのみ実行)
    if (!isDestructivePhase && logoutOrWithdrawPattern.test(label + ' ' + b.href)) continue;

    clickedKeys.add(label);
    try {
      // クリック前に元のページにいることを保証
      if (!page.url().startsWith(normalizedBase)) {
        await page.goto(originalUrl, { waitUntil: 'networkidle', timeout: 10000 }).catch(() => {});
      }

      const loc = page.locator(`[data-btn-test-id="${b.idx}"]`).first();
      if (!(await loc.isVisible().catch(() => false))) continue;

      // ページ内フォームのボタンなら軽くダミー入力してから押す
      const inForm = await loc.evaluate((el) => !!el.closest('form')).catch(() => false);
      if (inForm && b.tag !== 'a') {
        await fillVisibleInputs(page.locator('form').first());
      }

      await loc.click({ timeout: 4000 });
      await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {});
      await page.waitForTimeout(450);

      // jQuery UI / 汎用モーダルダイアログが開いたか確認
      const openDialog = page.locator('.ui-dialog:visible, .modal.show:visible, [role="dialog"]:visible').last();
      if (await openDialog.count() > 0 && await openDialog.isVisible().catch(() => false)) {
        testedLogs.push(`ボタン押下→ダイアログ表示: [${label}]`);
        // ダイアログ内に入力欄があれば入力して送信系ボタンを試す
        await fillVisibleInputs(openDialog);
        const submitInDialog = openDialog.locator('button:visible').filter({ hasNotText: /キャンセル|閉じる|close|cancel|いいえ/i }).first();
        if (await submitInDialog.count() > 0) {
          const subLabel = (await submitInDialog.innerText().catch(() => '')).trim();
          await submitInDialog.click({ timeout: 4000 }).catch(() => {});
          await page.waitForLoadState('networkidle', { timeout: 5000 }).catch(() => {});
          await page.waitForTimeout(400);
          testedLogs.push(`  ダイアログ内操作: [${subLabel}]`);
        }
        // まだダイアログが開いていたら閉じる
        if (await openDialog.isVisible().catch(() => false)) {
          const closeBtn = openDialog.locator('button:visible').filter({ hasText: /キャンセル|閉じる|OK|close|cancel/i }).first();
          if (await closeBtn.count() > 0) await closeBtn.click().catch(() => {});
          else await page.keyboard.press('Escape').catch(() => {});
          await page.waitForTimeout(250);
        }
      } else {
        testedLogs.push(`ボタン押下: [${label}]`);
      }

      // 画面遷移したり外部へ飛んだら元の画面に戻して次のボタンへ
      if (page.url() !== originalUrl && !isDestructivePhase) {
        // 遷移先でPHPエラーがないかチェック
        const errHit = await page.evaluate(() => {
          const t = document.body?.innerText || '';
          const m = t.match(/Fatal error:.*|Parse error:.*|Uncaught (Error|Exception).*/i);
          return m ? m[0] : null;
        }).catch(() => null);
        if (errHit) errorsFound.push(`ボタン[${label}]遷移先でPHPエラー: ${errHit}`);
        await page.goto(originalUrl, { waitUntil: 'networkidle', timeout: 10000 }).catch(() => {});
      }
    } catch (e) {
      testedLogs.push(`ボタンスキップ/エラー [${label}]: ${e.message.split('\n')[0]}`);
    }
  }

  return { testedLogs, errorsFound };
}

async function checkSinglePage(page, url, id, name, baseUrl, runButtons = true) {
  const consoleErrors = [];
  const httpErrors = [];
  const dialogMessages = [];

  const onConsole = (m) => { if (m.type() === 'error') consoleErrors.push(m.text()); };
  const onPageErr = (e) => consoleErrors.push(e.message);
  const onRes = (r) => { if (r.status() >= 400) httpErrors.push(`${r.status()} ${r.url()}`); };
  const onDialog = async (d) => {
    dialogMessages.push(`${d.type()}: ${d.message()}`);
    await d.accept().catch(() => {});
  };

  page.on('console', onConsole);
  page.on('pageerror', onPageErr);
  page.on('response', onRes);
  page.on('dialog', onDialog);

  let status = 'pass';
  let reason = '正常に表示・動作しました';
  let mainHttpStatus = 200;

  try {
    const res = await page.goto(url, { waitUntil: 'networkidle', timeout: 15000 });
    mainHttpStatus = res ? res.status() : 0;
  } catch (e) {
    status = 'fail';
    reason = `ページ遷移エラー: ${e.message.split('\n')[0]}`;
  }

  const normalizedBase = baseUrl.endsWith('/') ? baseUrl : baseUrl + '/';
  const domState = await page.evaluate((baseHref) => {
    const text = (document.body?.innerText || '').replace(/\s+/g, ' ').trim();
    const runtimeErrorPatterns = [
      /Fatal error:.*$/im, /Parse error:.*$/im, /Warning:.*on line \d+/im,
      /Notice:.*on line \d+/im, /Uncaught (Error|Exception).*$/im,
      /SQLSTATE\[[^\]]+\].*$/im, /Traceback \(most recent call last\):/i
    ];
    const runtimeErrors = runtimeErrorPatterns.map((re) => text.match(re)?.[0]).filter(Boolean);
    const overflow = document.documentElement.scrollWidth > window.innerWidth;
    const brokenImgs = Array.from(document.querySelectorAll('img')).filter((i) => !i.complete || i.naturalWidth === 0).map((i) => i.getAttribute('src'));

    const foundLinks = [];
    const skipPattern = /logout|signout|delete|remove|withdraw|destroy|reset|google_login|line_login|callback|\.pdf$|\.csv$|\.zip$|\.png$|\.jpg$/i;
    const specialLinks = [];
    document.querySelectorAll('a[href]').forEach((a) => {
      const raw = a.getAttribute('href') || '';
      if (!raw || raw.startsWith('#') || raw.startsWith('javascript:') || raw.startsWith('mailto:')) return;
      try {
        const resolved = new URL(raw, location.href);
        resolved.hash = '';
        if (resolved.href.startsWith(baseHref)) {
          const label = (a.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 25);
          if (/logout|signout|ログアウト|withdraw|退会/i.test(resolved.href + ' ' + label)) {
            specialLinks.push({ url: resolved.href, label });
          } else if (!skipPattern.test(resolved.href)) {
            foundLinks.push({ url: resolved.href, label });
          }
        }
      } catch {}
    });

    return { url: location.href, title: document.title, textLen: text.length, runtimeErrors, overflow, brokenImgs, foundLinks, specialLinks };
  }, normalizedBase).catch(() => ({ url, title: '', textLen: 0, runtimeErrors: [], overflow: false, brokenImgs: [], foundLinks: [], specialLinks: [] }));

  // スクショはクリーンな表示状態で先に撮影
  const screenFile = `${id.replace(/[^a-zA-Z0-9_-]/g, '_')}.png`;
  const screenPath = path.join(SCREEN_DIR, screenFile);
  await page.screenshot({ path: screenPath, fullPage: true }).catch(() => {});

  // ページ表示自体がOKならボタン・タブ・ダイアログ操作テストを実行
  let buttonTest = { testedLogs: [], errorsFound: [] };
  if (runButtons && mainHttpStatus < 400 && domState.textLen > 0) {
    buttonTest = await interactWithPageButtons(page, baseUrl, domState.url, false);
  }

  if (mainHttpStatus >= 400 || mainHttpStatus === 0) {
    status = 'fail';
    reason = `HTTPステータス異常 (${mainHttpStatus})`;
  } else if (domState.runtimeErrors.length > 0) {
    status = 'fail';
    reason = `実行時エラー検出: ${domState.runtimeErrors.join(' / ')}`;
  } else if (domState.textLen === 0) {
    status = 'fail';
    reason = '画面が真っ白(コンテンツ0文字)です';
  } else if (domState.overflow) {
    status = 'fail';
    reason = '横スクロールはみ出し(レイアウト崩れ)を検出';
  } else if (buttonTest.errorsFound.length > 0) {
    status = 'fail';
    reason = `ボタン操作エラー: ${buttonTest.errorsFound.join(' / ')}`;
  } else if (httpErrors.some((e) => e.startsWith('5'))) {
    status = 'fail';
    reason = `ボタン操作/通信中に500系エラー発生: ${httpErrors.filter((e) => e.startsWith('5')).join(', ')}`;
  }

  page.off('console', onConsole);
  page.off('pageerror', onPageErr);
  page.off('response', onRes);
  page.off('dialog', onDialog);

  return {
    id, name: name || domState.title || url,
    status, reason, domState, mainHttpStatus, consoleErrors, httpErrors,
    buttonLogs: buttonTest.testedLogs, dialogMessages,
    screenFile, screenPath, vlmCheck: '(未診断)'
  };
}

async function performGenericLogin(page, loginUrl, account, password) {
  await page.goto(loginUrl, { waitUntil: 'networkidle', timeout: 15000 }).catch(() => {});
  const passInput = page.locator('input[type="password"]').first();
  if (await passInput.count() === 0) return { ok: false, msg: 'ログインフォームが見つかりませんでした' };

  const userInput = page.locator('form input[type="text"], form input[type="email"], form input:not([type])').first();
  await userInput.fill(account, { timeout: 5000 });
  await passInput.fill(password, { timeout: 5000 });
  const submitBtn = page.locator('form button[type="submit"], form input[type="submit"], form button').first();
  await Promise.all([
    page.waitForNavigation({ waitUntil: 'networkidle', timeout: 10000 }).catch(() => {}),
    submitBtn.click({ timeout: 5000 })
  ]);
  await page.waitForTimeout(500);
  const stillHasPassword = (await page.locator('input[type="password"]').count()) > 0;
  if (!stillHasPassword && page.url() !== loginUrl) {
    return { ok: true, msg: `ログイン成功 -> ${page.url()}` };
  }
  const errText = await page.locator('.error-message').innerText().catch(() => '');
  return { ok: false, msg: `ログイン後の遷移を確認できず (${page.url()})${errText ? ' / 表示エラー: ' + errText : ''}` };
}

async function runBrowserTests(targetUrl, parsed, job) {
  if (job.cancelRequested) return [];
  const entryInfo = await discoverEntryPoints(parsed, job);
  if (job.cancelRequested) return [];

  job.phase = 'browser';
  const normalizedBase = targetUrl.endsWith('/') ? targetUrl : targetUrl + '/';
  const visited = new Set();
  const queue = [];
  const specialQueue = []; // 退会・ログアウト等(最後尾にテスト)

  const startUrl = normalizeUrlForVisit(joinUrl(targetUrl, entryInfo.entry_path || ''));
  if (startUrl) queue.push({ url: startUrl, name: 'トップページ', group: 'PUB' });

  if (entryInfo.login_path) {
    const lu = normalizeUrlForVisit(joinUrl(targetUrl, entryInfo.login_path));
    if (lu && lu !== startUrl) queue.push({ url: lu, name: 'ログイン画面', group: 'PUB' });
  }

  job.totalPages = Math.min(MAX_CRAWL_PAGES, Math.max(queue.length, 4));
  const browser = await chromium.launch({ headless: true });
  const context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
  const page = await context.newPage();
  const results = [];
  let idx = 1;

  try {
    // 1. 公開側ページの自動クロール&ボタンテスト
    while (queue.length > 0 && results.length < Math.floor(MAX_CRAWL_PAGES / 2) && !job.cancelRequested) {
      const item = queue.shift();
      if (visited.has(item.url)) continue;
      visited.add(item.url);

      const t0 = Date.now();
      job.progress = `公開側テスト中 (${results.length + 1}): ${item.name}`;
      const r = await checkSinglePage(page, item.url, `${item.group}-${idx++}`, item.name, targetUrl, true);
      results.push(r);
      job.donePages++;
      job.pageDurationMs += (Date.now() - t0);

      for (const link of (r.domState?.foundLinks || [])) {
        const nu = normalizeUrlForVisit(link.url);
        if (nu && !visited.has(nu) && !queue.some((q) => q.url === nu)) {
          queue.push({ url: nu, name: link.label || nu.replace(normalizedBase, ''), group: 'PUB' });
        }
      }
      job.totalPages = Math.min(MAX_CRAWL_PAGES, results.length + queue.length + (entryInfo.login_path ? 8 : 0));
    }

    // 2. 汎用ログイン試行 & 認証後全ページ巡回+ボタン操作テスト
    if (!job.cancelRequested && entryInfo.login_path && parsed.adminAccount && parsed.adminPassword) {
      const t0 = Date.now();
      const loginUrl = joinUrl(targetUrl, entryInfo.login_path);
      job.progress = `汎用ログイン実行中 (${parsed.adminAccount})...`;
      const loginRes = await performGenericLogin(page, loginUrl, parsed.adminAccount, parsed.adminPassword);

      const loginScreen = 'AUTH-LOGIN.png';
      await page.screenshot({ path: path.join(SCREEN_DIR, loginScreen), fullPage: true }).catch(() => {});
      results.push({
        id: 'AUTH-1', name: 'ログイン実行', status: loginRes.ok ? 'pass' : 'fail', reason: loginRes.msg,
        domState: { url: page.url(), runtimeErrors: [], overflow: false, brokenImgs: [], foundLinks: [] },
        consoleErrors: [], httpErrors: [], buttonLogs: [], dialogMessages: [],
        screenFile: loginScreen, screenPath: path.join(SCREEN_DIR, loginScreen), vlmCheck: '(未診断)'
      });
      job.donePages++;
      job.pageDurationMs += (Date.now() - t0);

      if (loginRes.ok) {
        const authQueue = [];
        const currentUrl = normalizeUrlForVisit(page.url());
        if (currentUrl) authQueue.push({ url: currentUrl, name: 'ログイン後トップ' });

        let authIdx = 1;
        while (authQueue.length > 0 && results.length < MAX_CRAWL_PAGES && !job.cancelRequested) {
          const item = authQueue.shift();
          if (visited.has(item.url)) continue;
          visited.add(item.url);

          const pt0 = Date.now();
          job.progress = `認証後画面&ボタン操作テスト中 (${results.length + 1}/${MAX_CRAWL_PAGES}): ${item.name}`;

          // もし前のボタン操作等でセッションが切れていたら自動再ログイン
          if (page.url().includes('login')) {
            await performGenericLogin(page, loginUrl, parsed.adminAccount, parsed.adminPassword);
          }

          const r = await checkSinglePage(page, item.url, `AUTH-${authIdx++}`, item.name, targetUrl, true);
          results.push(r);
          job.donePages++;
          job.pageDurationMs += (Date.now() - pt0);

          for (const link of (r.domState?.foundLinks || [])) {
            const nu = normalizeUrlForVisit(link.url);
            if (nu && !visited.has(nu) && !authQueue.some((q) => q.url === nu)) {
              authQueue.push({ url: nu, name: link.label || nu.replace(normalizedBase, '') });
            }
          }
          for (const sp of (r.domState?.specialLinks || [])) {
            const su = normalizeUrlForVisit(sp.url);
            if (su && !specialQueue.some((q) => q.url === su)) {
              specialQueue.push({ url: su, name: sp.label || su });
            }
          }
          job.totalPages = Math.min(MAX_CRAWL_PAGES + specialQueue.length, results.length + authQueue.length + specialQueue.length);
        }

        // 3. 最後尾フェーズ:退会(withdraw)とログアウト(logout)を最後にテスト
        // 退会を先、ログアウトを最後に並び替え
        specialQueue.sort((a, b) => (/logout|ログアウト/i.test(a.url + a.name) ? 1 : -1));
        let spIdx = 1;
        for (const sp of specialQueue) {
          if (job.cancelRequested) break;
          const pt0 = Date.now();
          job.progress = `最終フローテスト (退会/ログアウト): ${sp.name}`;
          const r = await checkSinglePage(page, sp.url, `END-${spIdx++}`, `最終フロー: ${sp.name}`, targetUrl, false);
          // 退会画面などでボタンがあれば最後に押してみる
          if (/withdraw|退会/i.test(sp.url + sp.name)) {
            const bt = await interactWithPageButtons(page, targetUrl, r.domState.url, true);
            r.buttonLogs.push(...bt.testedLogs);
            if (bt.errorsFound.length) {
              r.status = 'fail';
              r.reason = bt.errorsFound.join(' / ');
            }
            await page.screenshot({ path: r.screenPath, fullPage: true }).catch(() => {});
          }
          results.push(r);
          job.donePages++;
          job.pageDurationMs += (Date.now() - pt0);
        }
      }
    }
    job.totalPages = job.donePages;
  } finally {
    await context.close().catch(() => {});
    await browser.close();
  }
  return results;
}

async function runStaticCodeReview(parsed, batches, job) {
  job.phase = 'review';
  const reviewFindings = [];
  const schema = {
    type: 'object',
    properties: {
      issues: {
        type: 'array',
        items: {
          type: 'object',
          properties: {
            file: { type: 'string' },
            line: { type: 'integer' },
            severity: { type: 'string', enum: ['error', 'warning'] },
            summary: { type: 'string' },
            detail: { type: 'string' }
          },
          required: ['file', 'line', 'severity', 'summary', 'detail']
        }
      }
    },
    required: ['issues']
  };

  for (let i = 0; i < batches.length; i++) {
    if (job.cancelRequested) break;
    const batchStart = Date.now();
    job.progress = `AIコード精査中: バッチ ${i + 1} / ${batches.length}`;

    const filesText = batches[i].map((c) => `--- ${c.path} (${c.rangeInfo}) ---\n${c.content}`).join('\n\n');
    const prompt = `あなたは熟練コードレビュアーです。
以下は行番号付きのソースコード(大きいファイルは分割チャンク)です。
**確実なバグ・問題のみ** を抽出し、必ず該当する「行番号 (line)」を記載してください。

【絶対守るべき禁止事項(誤検知防止)】
1. 「定義済みシンボル一覧」に載っている関数・定数・インクルード元共通変数について「未定義かもしれない」と推測で指摘しないこと。
2. 分割チャンクの切れ目を見て「コードが途中で切れています」と指摘しないこと。
3. 技術仕様の規約違反は、**対象コードの中に違反記述が実際に存在する場合のみ** 指摘すること。
4. JavaScriptファイル(.js)に対してサーバー側の「SQLインジェクションリスク」を指摘しないこと。また、prepare()+bind_param()を使っているSQLにも「SQLインジェクションリスク」と指摘しないこと。
5. 問題がなければ必ず空配列 {"issues": []} を返すこと。

【severityの基準】
- "error": 確実に実行時エラー・バグになるもの(構文エラー、HTMLタグ誤字、SQL文ミス、未初期化/誤った変数名、明らかに壊れるロジック)
- "warning": セキュリティ上の実害リスク(エスケープ漏れ、SQL変数直埋め)、または技術仕様規約の明確な違反

【プロジェクト技術仕様】
${parsed.specs.slice(0, 1500)}

【定義済みシンボル一覧】
${parsed.definedSymbols}

【対象コード】
${filesText}`;

    try {
      const res = await callOllama(BRAIN_MODEL, prompt, schema, '5m', null, job.abortController.signal);
      if (Array.isArray(res.issues)) reviewFindings.push(...res.issues);
    } catch (e) {
      if (job.cancelRequested) break;
      console.error(`  バッチ ${i + 1} エラー:`, e.message);
    }
    job.doneBatches++;
    job.batchDurationMs += (Date.now() - batchStart);
  }
  return reviewFindings;
}

function buildFixPromptText(parsed, lintErrors, reviewFindings, browserResults, isCancelled, doneBatches, totalBatches) {
  const errorItems = reviewFindings.filter((i) => i.severity === 'error');
  const warningItems = reviewFindings.filter((i) => i.severity === 'warning');
  const formatIssue = (i) => `- [${i.severity}] **${i.file} (${i.line}行目)**: ${i.summary}\n  詳細: ${i.detail}`;

  return `## 1. 依頼目的: 開発・追加修正
あなたは非常に優秀なSE兼プログラマーです。
**【重要】修正箇所以外のメソッドやロジックなどは一切省略せずに、修正が必要な個所をクラス単位ではなく、メソッド単位で差し替え(コピー&ペースト)可能な形式で出力してください。また、修正箇所以外のロジックが維持されていることを出力前に自己確認してください。**

${isCancelled ? `> ※このプロンプトはユーザーによる途中中断時点(コード精査 ${doneBatches}/${totalBatches} バッチ完了時点)の結果から出力されました。\n` : ''}
## 2. 技術仕様・制約
${parsed.specs || '(指定なし)'}

## 3. 修正が必要な箇所一覧(自動テスト検出結果)

### 【PHP構文チェック (php -l) 検出エラー ([error])】
${lintErrors.length ? lintErrors.map((e) => `- [error] **${e.file}${e.line ? ` (${e.line}行目)` : ''}**: ${e.error}`).join('\n') : '- 検出なし'}

### 【実機ブラウザテスト 検出エラー ([fail])】
${browserResults.filter((r) => r.status === 'fail').length ? browserResults.filter((r) => r.status === 'fail').map((r) => `- [error] **${r.name}** (${r.domState?.url || '-'}): ${r.reason}${r.httpErrors.length ? ' / HTTPエラー: ' + r.httpErrors.slice(0, 3).join(', ') : ''}`).join('\n') : '- 失敗なし'}

### 【AI静的コード精査: 重大バグ ([error])】
${errorItems.length ? errorItems.map(formatIssue).join('\n') : '- 検出なし'}

### 【AI静的コード精査: 警告・改善推奨 ([warning])】
${warningItems.length ? warningItems.map(formatIssue).join('\n') : '- 検出なし'}
`;
}

async function handleRunTest(payload, job) {
  const startTime = new Date(job.startMs);
  const ts = job.id;
  const targetUrl = payload.target_url || 'http://127.0.0.1:8080';
  const projectDoc = payload.project_doc || '';

  const docFileName = `project_doc_${ts}.md`;
  fs.writeFileSync(path.join(DOC_DIR, docFileName), projectDoc, 'utf-8');

  job.progress = 'ドキュメントを解析中...';
  const parsed = parseProjectDocument(projectDoc);
  const batches = buildReviewBatches(parsed.files);
  job.totalBatches = batches.length;

  // DB自動検出 & 初回バックアップ / 既存バックアップからの復元
  job.progress = 'テスト用DBのバックアップ/復元を実行中...';
  const dbName = detectTargetDatabase(parsed.files);
  if (dbName) lastDetectedDb = dbName;
  const dbStatusMsg = prepareDatabaseForTest(dbName);
  console.log(`DB状態: ${dbStatusMsg}`);

  let lintErrors = [];
  let browserResults = [];
  let reviewFindings = [];

  try {
    job.phase = 'lint';
    job.progress = '構文チェック実行中...';
    lintErrors = runPhpLintChecks(parsed.files);

    if (!job.cancelRequested) {
      browserResults = await runBrowserTests(targetUrl, parsed, job);
      job.totalVlm = browserResults.length; // 全画面をVLM診断対象にする
    }

    if (!job.cancelRequested && batches.length > 0) {
      reviewFindings = await runStaticCodeReview(parsed, batches, job);
    }

    if (!job.cancelRequested && browserResults.length > 0) {
      job.phase = 'vlm';
      await unloadModel(BRAIN_MODEL);
      for (const r of browserResults) {
        if (job.cancelRequested) break;
        const vt0 = Date.now();
        job.progress = `VLM (${VLM_MODEL}) で全画面を崩れ診断中 (${job.doneVlm + 1}/${browserResults.length})...`;
        if (!fs.existsSync(r.screenPath)) { job.doneVlm++; continue; }
        const b64 = fs.readFileSync(r.screenPath).toString('base64');
        try {
          r.vlmCheck = await callOllama(VLM_MODEL, `Web画面「${r.name}」のスクリーンショットです。レイアウト崩れ、文字化け、エラー表示の有無を2行で診断してください。`, null, '3m', [b64], job.abortController.signal);
        } catch (e) {
          r.vlmCheck = job.cancelRequested ? '(中断により診断スキップ)' : `(診断エラー: ${e.message})`;
        }
        job.doneVlm++;
        job.vlmDurationMs += (Date.now() - vt0);
      }
      await unloadModel(VLM_MODEL);
    }

    job.phase = 'prompt';
    job.progress = '修正依頼用プロンプトを生成中...';
  } finally {
    await unloadModel(BRAIN_MODEL);
    await unloadModel(VLM_MODEL);
  }

  const fixPrompt = buildFixPromptText(parsed, lintErrors, reviewFindings, browserResults, job.cancelRequested, job.doneBatches, job.totalBatches);
  const promptFileName = `fix_prompt_${ts}.md`;
  fs.writeFileSync(path.join(PROMPT_DIR, promptFileName), fixPrompt, 'utf-8');

  job.endMs = Date.now();
  const elapsedSec = Math.round((job.endMs - job.startMs) / 1000);
  const errCount = reviewFindings.filter((i) => i.severity === 'error').length;
  const warnCount = reviewFindings.filter((i) => i.severity === 'warning').length;
  const statusBanner = job.cancelRequested
    ? '<div style="background:#fff3cd;border-left:5px solid #f0ad4e;padding:12px 16px;margin-bottom:16px;font-weight:bold;">⚠️ このテストは途中で中断されました(中断時点までに完了した結果を出力しています)。</div>'
    : '';

  const html = `<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>Dify連携 AI自動テストレポート</title>
<style>
  body { font-family: sans-serif; margin: 24px; background: #f5f7fa; color: #222; }
  .card { background: #fff; border-radius: 8px; padding: 20px; margin-bottom: 20px; box-shadow: 0 2px 6px rgba(0,0,0,0.08); }
  .pass { background: #dafbe1; color: #1a7f37; padding: 2px 8px; border-radius: 10px; font-weight: bold; }
  .fail { background: #ffebe9; color: #cf222e; padding: 2px 8px; border-radius: 10px; font-weight: bold; }
  .error { color: #cf222e; font-weight: bold; }
  .warning { color: #9a6700; font-weight: bold; }
  pre { background: #24292f; color: #f6f8fa; padding: 14px; border-radius: 6px; white-space: pre-wrap; font-size: 13px; }
  .grid { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
  .btn-logs { background: #f6f8fa; border: 1px solid #d0d7de; padding: 8px 12px; border-radius: 6px; font-size: 12px; margin-top: 8px; white-space: pre-wrap; }
  img { max-width: 100%; border: 1px solid #ccc; }
</style>
</head>
<body>
  <h1>🤖 AI自動テスト & 修正プロンプト生成レポート</h1>
  ${statusBanner}
  <div class="card">
    <p><strong>実行日時:</strong> ${startTime.toLocaleString('ja-JP')} (処理時間: ${formatDurationSec(elapsedSec)}) / <strong>対象URL:</strong> ${escapeHtml(targetUrl)}</p>
    <p><strong>DB状態:</strong> ${escapeHtml(dbStatusMsg)}</p>
    <p><strong>解析ファイル数:</strong> ${parsed.files.length} / <strong>構文エラー:</strong> ${lintErrors.length}件 / <strong>コード精査:</strong> ${job.doneBatches}/${job.totalBatches}バッチ完了 (<span class="error">error: ${errCount}件</span> / <span class="warning">warning: ${warnCount}件</span>)</p>
    <p><strong>保存済み入力データ:</strong> <a href="docs/${docFileName}" target="_blank">${docFileName}</a></p>
    <p><strong>保存済み修正プロンプト:</strong> <a href="prompts/${promptFileName}" target="_blank">${promptFileName}</a></p>
  </div>
  <div class="card">
    <h2>1. 構文チェック (php -l)</h2>
    ${lintErrors.length === 0 ? '<p>構文エラーは検出されませんでした。</p>' : `<ul>${lintErrors.map((e) => `<li class="error">[error] ${escapeHtml(e.file)}${e.line ? ` (${e.line}行目)` : ''}: ${escapeHtml(e.error)}</li>`).join('')}</ul>`}
  </div>
  <div class="card">
    <h2>2. AIコード精査結果</h2>
    ${reviewFindings.length === 0 ? '<p>指摘はありませんでした。</p>' : `<ul>${reviewFindings.map((i) => `<li><span class="${escapeHtml(i.severity)}">[${escapeHtml(i.severity)}]</span> <strong>${escapeHtml(i.file)} (${i.line}行目)</strong>: ${escapeHtml(i.summary)}<br><small>${escapeHtml(i.detail)}</small></li>`).join('')}</ul>`}
  </div>
  <div class="card">
    <h2>3. 実機ブラウザ自動巡回 & ボタン操作テスト (${browserResults.filter((r) => r.status === 'pass').length}/${browserResults.length}件合格)</h2>
    ${browserResults.length === 0 ? '<p>実行されたブラウザテストはありません。</p>' : browserResults.map((r) => `
    <div style="border-top: 1px solid #eee; padding-top: 12px; margin-top: 12px;">
      <h3><span class="${escapeHtml(r.status)}">${escapeHtml(r.status.toUpperCase())}</span> ${escapeHtml(r.id)}: ${escapeHtml(r.name)}</h3>
      <div class="grid">
        <div>
          <p><strong>判定理由:</strong> ${escapeHtml(r.reason)}</p>
          <p><strong>URL:</strong> ${escapeHtml(r.domState?.url)} / <strong>横はみ出し:</strong> ${r.domState?.overflow ? 'あり' : 'なし'} / <strong>HTTPエラー:</strong> ${r.httpErrors.length}件 / <strong>JSエラー:</strong> ${r.consoleErrors.length}件</p>
          <p><strong>画面崩れ診断:</strong> ${escapeHtml(r.vlmCheck)}</p>
          ${r.buttonLogs?.length ? `<div class="btn-logs"><strong>実行したボタン/タブ操作:</strong>\n${escapeHtml(r.buttonLogs.join('\n'))}</div>` : ''}
        </div>
        <div>${fs.existsSync(r.screenPath) ? `<a href="auto_screens/${r.screenFile}" target="_blank"><img src="auto_screens/${r.screenFile}"></a>` : '(スクショなし)'}</div>
      </div>
    </div>`).join('')}
  </div>
  <div class="card">
    <h2>4. 生成された修正依頼用プロンプト (保存済み)</h2>
    <pre>${escapeHtml(fixPrompt)}</pre>
  </div>
</body>
</html>`;

  fs.writeFileSync(path.join(REPORT_DIR, 'auto-report.html'), html, 'utf-8');

  return {
    success: true,
    cancelled: job.cancelRequested,
    summary: `${job.cancelRequested ? '[途中中断] ' : ''}処理時間: ${formatDurationSec(elapsedSec)} / ${dbStatusMsg} / 構文エラー: ${lintErrors.length}件 / コード精査: error ${errCount}件・warning ${warnCount}件 / ブラウザ: ${browserResults.filter((r) => r.status === 'pass').length}/${browserResults.length}件合格`,
    report_url: `http://${LAN_HOST}:${PORT}/reports/auto-report.html`,
    doc_url: `http://${LAN_HOST}:${PORT}/reports/docs/${docFileName}`,
    prompt_url: `http://${LAN_HOST}:${PORT}/reports/prompts/${promptFileName}`,
    fix_prompt: fixPrompt
  };
}

function parseBodyPayload(req, raw) {
  const contentType = (req.headers['content-type'] || '').toLowerCase();
  if (contentType.includes('application/json')) return JSON.parse(raw || '{}');
  if (contentType.includes('application/x-www-form-urlencoded')) {
    const params = new URLSearchParams(raw);
    return { target_url: params.get('target_url') || req.headers['x-target-url'], project_doc: params.get('project_doc') || '' };
  }
  return { target_url: req.headers['x-target-url'] || 'http://127.0.0.1:8080', project_doc: raw };
}

const server = http.createServer(async (req, res) => {
  const urlObj = new URL(req.url || '/', `http://localhost:${PORT}`);
  const reqPath = urlObj.pathname;

  if (req.method === 'POST' && reqPath === '/api/start-test') {
    const runningJob = latestJobId ? jobs.get(latestJobId) : null;
    if (runningJob && runningJob.status === 'running') {
      res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
      res.end(JSON.stringify({
        success: false, job_id: runningJob.id,
        message: '現在別のテストが実行中です。進捗画面から確認または中断してください。',
        status_url: `http://${LAN_HOST}:${PORT}/status`,
        report_url: `http://${LAN_HOST}:${PORT}/reports/auto-report.html`
      }));
      return;
    }

    const chunks = [];
    req.on('data', (c) => chunks.push(c));
    req.on('end', () => {
      try {
        const raw = Buffer.concat(chunks).toString('utf-8');
        const payload = parseBodyPayload(req, raw);
        const jobId = getJstTimestamp();
        const job = {
          id: jobId, status: 'running', phase: 'init', progress: 'テスト開始準備中...',
          startMs: Date.now(), endMs: null,
          totalPages: 4, donePages: 0, pageDurationMs: 0,
          totalBatches: 0, doneBatches: 0, batchDurationMs: 0,
          totalVlm: 4, doneVlm: 0, vlmDurationMs: 0,
          abortController: new AbortController(), cancelRequested: false,
          result: null, error: null
        };
        jobs.set(jobId, job);
        latestJobId = jobId;

        handleRunTest(payload, job)
          .then((result) => {
            job.endMs = job.endMs || Date.now();
            job.status = job.cancelRequested ? 'cancelled' : 'done';
            job.phase = job.status;
            job.progress = job.cancelRequested ? '途中中断(ここまでの結果を出力済み)' : '全工程完了';
            job.result = result;
          })
          .catch((err) => {
            console.error(err);
            job.endMs = Date.now();
            job.status = 'error'; job.phase = 'error';
            job.progress = 'エラー終了'; job.error = err.message;
          });

        res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
        res.end(JSON.stringify({
          success: true, job_id: jobId,
          status_url: `http://${LAN_HOST}:${PORT}/status`,
          report_url: `http://${LAN_HOST}:${PORT}/reports/auto-report.html`
        }));
      } catch (err) {
        res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
        res.end(JSON.stringify({ success: false, error: err.message }));
      }
    });
    return;
  }

  if (req.method === 'POST' && reqPath === '/api/cancel-job') {
    const job = latestJobId ? jobs.get(latestJobId) : null;
    if (job && job.status === 'running') {
      job.cancelRequested = true;
      job.progress = '中断処理中(VRAM解放と途中レポート出力中)...';
      job.abortController.abort();
      res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
      res.end(JSON.stringify({ success: true, message: '中断を受け付けました。数秒後にここまでのレポートが出力されます。' }));
    } else {
      res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
      res.end(JSON.stringify({ success: false, message: '現在実行中のテストはありません。' }));
    }
    return;
  }

  // DB手動復元・初期バックアップ更新API
  if (req.method === 'POST' && (reqPath === '/api/db-restore' || reqPath === '/api/db-backup-refresh')) {
    try {
      const db = urlObj.searchParams.get('db') || lastDetectedDb || 'youx4_cloudio';
      const result = reqPath === '/api/db-restore' ? restoreDatabase(db) : backupDatabase(db);
      res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
      res.end(JSON.stringify({ success: result.ok, message: result.msg }));
    } catch (e) {
      res.writeHead(500, { 'Content-Type': 'application/json; charset=utf-8' });
      res.end(JSON.stringify({ success: false, message: e.message }));
    }
    return;
  }

  if (req.method === 'GET' && reqPath === '/api/status') {
    const job = latestJobId ? jobs.get(latestJobId) : null;
    if (!job) {
      res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
      res.end(JSON.stringify({ status: 'idle', progress: '実行中のテストはありません', elapsedSec: 0, remainingSec: null, percent: 0 }));
      return;
    }
    const timing = getJobTiming(job);
    res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
    res.end(JSON.stringify({
      id: job.id, status: job.status, progress: job.progress, cancelRequested: job.cancelRequested,
      elapsedSec: timing.elapsedSec, remainingSec: timing.remainingSec, percent: timing.percent,
      summary: job.result?.summary || '', report_url: job.result?.report_url || '',
      prompt_url: job.result?.prompt_url || '', error: job.error || ''
    }));
    return;
  }

  if (req.method === 'GET' && reqPath === '/status') {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.end(`<!DOCTYPE html><html lang="ja"><head><meta charset="UTF-8"><title>AI自動テスト 実行状況</title>
      <style>
        body{font-family:sans-serif;margin:40px;background:#f5f7fa;color:#222;}
        .box{background:#fff;padding:28px;border-radius:10px;max-width:720px;box-shadow:0 2px 10px rgba(0,0,0,0.08);}
        .bar-bg{width:100%;height:18px;background:#e1e4e8;border-radius:9px;overflow:hidden;margin:14px 0;}
        .bar-fill{height:100%;background:#0969da;width:0%;transition:width 0.4s ease;}
        .time-grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;background:#f6f8fa;padding:14px;border-radius:8px;margin:14px 0;}
        .time-val{font-size:1.3em;font-weight:bold;color:#0969da;}
        .btn-cancel{background:#cf222e;color:#fff;border:none;padding:12px 20px;border-radius:6px;font-size:15px;font-weight:bold;cursor:pointer;margin-top:14px;}
        .btn-db{background:#6e7781;color:#fff;border:none;padding:8px 14px;border-radius:6px;font-size:13px;cursor:pointer;margin-right:8px;}
        .btn-link{display:inline-block;background:#0969da;color:#fff;text-decoration:none;padding:10px 18px;border-radius:6px;font-weight:bold;margin-top:12px;margin-right:10px;}
      </style></head><body><div class="box">
      <h2>🤖 AI自動テスト 実行状況</h2>
      <p><strong>状態:</strong> <span id="st-status">読み込み中...</span> (<span id="st-pct">0</span>%)</p>
      <div class="bar-bg"><div class="bar-fill" id="st-bar"></div></div>
      <p><strong>現在の工程:</strong> <span id="st-progress">-</span></p>
      <div class="time-grid">
        <div><small>経過時間</small><div class="time-val" id="st-elapsed">0秒</div></div>
        <div><small>推定残り時間</small><div class="time-val" id="st-remain">-</div></div>
      </div>
      <div id="st-actions"></div>
      <div id="st-result" style="margin-top:16px;"></div>
      <hr style="margin:24px 0;border:none;border-top:1px solid #e1e4e8;">
      <div>
        <p style="margin-bottom:8px;"><strong>DBバックアップ管理</strong></p>
        <button class="btn-db" onclick="dbAction('/api/db-restore')">🔄 初期バックアップからDBを復元</button>
        <button class="btn-db" style="background:#8250df;" onclick="dbAction('/api/db-backup-refresh')">💾 現在のDBを初期バックアップに保存し直す</button>
      </div>
      </div>
      <script>
        let currentStatus='idle', localElapsed=0;
        function fmt(sec){
          if(sec===null||sec===undefined)return'計算中...';
          sec=Math.max(0,Math.round(sec));
          const h=Math.floor(sec/3600),m=Math.floor((sec%3600)/60),s=sec%60;
          if(h>0)return h+'時間'+String(m).padStart(2,'0')+'分'+String(s).padStart(2,'0')+'秒';
          if(m>0)return m+'分'+String(s).padStart(2,'0')+'秒';
          return s+'秒';
        }
        function cancelTest(){
          if(!confirm('テストを途中で中断し、ここまでの結果をレポート出力しますか?'))return;
          fetch('/api/cancel-job',{method:'POST'}).then(r=>r.json()).then(d=>{alert(d.message);fetchStatus();});
        }
        function dbAction(ep){
          if(!confirm('DB操作を実行しますか?'))return;
          fetch(ep,{method:'POST'}).then(r=>r.json()).then(d=>alert(d.message));
        }
        function fetchStatus(){
          fetch('/api/status').then(r=>r.json()).then(d=>{
            currentStatus=d.status; localElapsed=d.elapsedSec||0;
            const labels={idle:'待機中',running:'実行中',done:'完了',cancelled:'途中中断 (出力済み)',error:'エラー'};
            document.getElementById('st-status').textContent=labels[d.status]||d.status;
            document.getElementById('st-pct').textContent=d.percent||0;
            document.getElementById('st-bar').style.width=(d.percent||0)+'%';
            document.getElementById('st-progress').textContent=d.progress||'-';
            document.getElementById('st-elapsed').textContent=fmt(localElapsed);
            document.getElementById('st-remain').textContent=d.status==='running'?('約 '+fmt(d.remainingSec)):'0秒';
            const act=document.getElementById('st-actions'), res=document.getElementById('st-result');
            if(d.status==='running'&&!d.cancelRequested){
              act.innerHTML='<button class="btn-cancel" onclick="cancelTest()">🛑 テストを中断してここまでの結果を出力</button>'; res.innerHTML='';
            }else{act.innerHTML='';}
            if(d.status==='done'||d.status==='cancelled'){
              res.innerHTML='<p><strong>結果サマリー:</strong> '+d.summary+'</p>'+
                '<a class="btn-link" href="/reports/auto-report.html">📊 テストレポートを開く</a>'+
                '<a class="btn-link" style="background:#1a7f37;" href="'+d.prompt_url+'" target="_blank">📝 修正プロンプト(.md)を開く</a>';
            }else if(d.status==='error'){
              res.innerHTML='<p style="color:#cf222e;font-weight:bold;">エラー: '+d.error+'</p>';
            }
          });
        }
        fetchStatus();
        setInterval(()=>{if(currentStatus==='running'){localElapsed++;document.getElementById('st-elapsed').textContent=fmt(localElapsed);}},1000);
        setInterval(()=>{if(currentStatus==='running'||currentStatus==='idle')fetchStatus();},3000);
      </script></body></html>`);
    return;
  }

  if (req.method === 'GET' && reqPath.startsWith('/reports/')) {
    const rel = reqPath.replace(/^\/reports\//, '');
    const safePath = path.normalize(path.join(REPORT_DIR, rel));
    if (!safePath.startsWith(REPORT_DIR) || !fs.existsSync(safePath) || fs.statSync(safePath).isDirectory()) {
      res.writeHead(404); res.end('Not Found'); return;
    }
    const ext = path.extname(safePath).toLowerCase();
    const mime = ext === '.html' ? 'text/html; charset=utf-8'
      : ext === '.png' ? 'image/png'
      : (ext === '.md' || ext === '.txt') ? 'text/plain; charset=utf-8'
      : 'application/octet-stream';
    res.writeHead(200, { 'Content-Type': mime });
    fs.createReadStream(safePath).pipe(res);
    return;
  }

  res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' });
  res.end('AI Auto Tester API is running.');
});

server.requestTimeout = 900000;
server.listen(PORT, '0.0.0.0', () => {
  console.log(`AI Tester API Server listening on http://0.0.0.0:${PORT}`);
});
EOF

4. systemd で常時稼働させる(OS再起動後も自動起動)

NODE_BIN=$(which node)

sudo tee /etc/systemd/system/ai-tester.service > /dev/null << EOF
[Unit]
Description=AI Auto Tester API Server
After=network.target ollama.service docker.service

[Service]
Type=simple
User=$USER
WorkingDirectory=/home/$USER/ai-tester
ExecStart=$NODE_BIN /home/$USER/ai-tester/test-server.mjs
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
EOF

sudo systemctl daemon-reload
sudo systemctl enable --now ai-tester
sudo systemctl status ai-tester --no-pager

5. Dify ワークフローの組み方

Dify側は驚くほどシンプルに 4ノード で組めます。

  1. ユーザー入力:project_doc(段落・最大長 500000)、target_url(短文テキスト)
  2. HTTP リクエスト:
    • POST http://host.docker.internal:8090/api/start-test
    • Header:Content-Type: text/plain; charset=utf-8、X-Target-Url: {{#target_url#}}
    • Body(raw):{{#project_doc#}}(※JSON形式ではなく raw で送ることで、コード内の改行や記号によるJSONエスケープエラーを完全回避!)
  3. コード実行 (Python3):返ってきたJSONからURLを取り出す
import json

def main(body: str) -> dict:
    data = json.loads(body)
    return {
        "summary": f"テストを開始しました (Job ID: {data.get('job_id', '')})",
        "status_url": data.get("status_url", ""),
        "report_url": data.get("report_url", "")
    }
  1. 出力:summary, status_url, report_url を表示

実際にハマったポイントと解決策(知見まとめ)

構築する中でいくつかリアルな壁にぶつかりましたが、以下の設計で解決しました。

ハマり①:Dify HTTPリクエストの「300秒タイムアウト」の壁

当初、DifyのHTTPリクエストノードから同期呼び出ししたところ、処理が5分を超えた瞬間に 299.7s: Server disconnected without sending a response. で切断されました。

  • 解決策:上述の通り POST /api/start-test で 0.1秒でJob IDと進捗URL(/status)を返す非同期方式 に変更することで完全回避しました

ハマり②:コンテキスト長によるCPUオフロード激遅問題

最初、推論モデル(17GB)に num_ctx: 24576 を指定したところ、VRAM 32GBをわずかに溢れて 7% CPU / 93% GPU(CPUオフロード)が発生し、1バッチのコード精査に 約5分 かかってしまいました。

  • 解決策:高速でThinkingトークンの出ない qwen2.5:14b(9GB) + num_ctx: 16384 に切り替え、100% GPU推論 を維持しつつ、ファイルをバッチ分割して処理しました

ハマり③:Docker環境でのDB接続・Cookie・reCAPTCHAの罠

PHPアプリをDockerテスト環境で動かす際、以下の3点に注意が必要でした。

  1. DBユーザーのホスト名:Dockerコンテナ間通信では localhost ではなく別IPから接続するため、DBユーザーは 'user'@'%' で作成し、DB_HOST はサービス名の 'db' にする
  2. Cookieドメインのポート番号::8080 付きでアクセスすると $_SERVER['HTTP_HOST'] にポート番号が含まれ、ブラウザがセッションCookieを保存してくれない。explode(':', $_SERVER['HTTP_HOST'])[0] でポート番号を外す
  3. reCAPTCHA v3のボット判定:Playwrightのヘッドレスブラウザは自動操作と判定されスコアが低く弾かれやすいため、ローカルネットワークからのテストアクセス時はバイパスできる分岐を用意する(※Dockerコンテナ内から見えるIPは 127.0.0.1 ではなくブリッジの 172.x.x.x になる点は注意)

実行結果

約117ファイル(約57万バイト)のPHP勤怠管理システムを実際にテストさせたところ、以下のような結果が得られました。

  • php -l 構文チェック:数秒で全PHPファイルをスキャンし、セミコロン抜けの Parse error をピンポイント検出
  • ブラウザテスト & VLM画面診断:ヘッドレスChromeで主要ページを開き、PC/スマホの画面崩れやエラー表示を診断
  • プロンプト自動保存:検出された不具合とプロジェクトの技術仕様・コーディング規約を統合した「修正依頼用プロンプト(.md)」が自動保存され、そのまま次の開発AIにコピペして修正作業に移れるようになりました。

おわりに:プロジェクト全体をAIに渡すなら「CodePromptAI」が便利!

今回構築した自動テストでは、「プロジェクト全体のファイル構成・DB定義・大量のソースコードを、1つの整理されたテキストとしてDifyに渡す」 ことがポイントでした。

もし「自分のWebアプリや開発中のプロジェクトを、同じようにDifyやChatGPT / Claude / Geminiに丸ごと理解させてテスト・レビューさせたい!」という方には、CodePromptAI がとても便利です。

CodePromptAI:エンジニアの思考を、AIへダイレクトに繋ぐ
https://www.microsoft.com/store/apps/9mwct97mx886


ScreenShot_jp_new.png

ScreenShot2_jp.png

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?