Use Claude Max API Credits with the Agent SDK: A Claude Code-Like Chat

スポンサーリンク
Use Claude Max API Credits with the Agent SDK: A Claude Code-Like Chat Claude
スポンサーリンク

Claude Max plans now come with $100 of API credits every month, but you can’t spend them in the interactive Claude Code you use every day (terminal, VS Code, desktop app).

So I used the Claude Agent SDK, which the credits do cover, to build my own chat page that runs in the browser. Claude reads files, runs commands and asks for permission when needed, just like Claude Code. I can also move a conversation back and forth between this page and my subscription (desktop app or terminal).

Short answer: the Max plan API credits are used when you run the Agent SDK with an API key issued in your Claude Console organization. The full code (six files) is at the end of this post. ChatGPT wrote the first version and Claude Code reviewed it.

My chat page built with the Agent SDK
The chat page. Pick the working folder and past conversations on the left, choose model and permission mode at the bottom, then type (screenshot taken with a sample folder; the UI is in Japanese)

What the API credits cover

According to the Claude Help Center, Max plans get $100 of API credits per month, usable as follows:

Covered Not covered
Claude API (Messages API, Message Batches API) Interactive Claude Code (terminal, IDE, desktop, web)
Console Playground Extra usage of Claude, Claude Code, Claude Cowork
Claude Managed Agents Claude via Amazon Bedrock, Google Cloud Vertex AI, Microsoft Foundry
Claude Agent SDK Third-party apps paid through linked billing

In the Claude Console billing page they show up as “promotional credits”, and the list of eligible products includes the Agent SDK, API, Batch API, Playground and Managed Agents.

Promotional credits shown in the Claude Console billing page
Console billing page: the Agent SDK is listed as eligible

There is a condition for the Agent SDK and claude -p (the mode that runs once without the interactive UI). Credits are only used when you run them yourself with an API key from your Console organization. If you run them while signed in with your Claude plan, your plan usage goes down instead. Also, runs started from the IDE extension or the desktop app count as Claude Code usage even with -p, so they’re excluded.

In other words: to spend the credits, run the Agent SDK yourself, authenticated with an API key.

Architecture

The Agent SDK is a library that gives your own program the same tools (reading and writing files, running commands, search) and agent loop that Claude Code uses. It has no UI, so I built the part that takes instructions and shows results.

Browser (chat page)
   ↕  http://127.0.0.1:(free port)   streamed as one JSON object per line
Node.js server (agent_web.mjs)
   ↕  calls query()
Claude Agent SDK (does the file operations and commands)
   ↕  authenticates with the API key
Claude API (billed to the API credits of the Console organization)

The files are laid out like this:

api_credit\
├─ web_chat.bat      ← double-click to start
├─ agent_web.mjs     ← the server (calls the Agent SDK)
├─ package.json
├─ .runtime\         ← API key and UI state (keep out of Git)
└─ web\
   ├─ index.html     ← chat page
   ├─ app.js
   └─ style.css

Setup

Claim the API credits

The credits aren’t added automatically; you have to claim them. The steps from the Help Center:

  1. Open claude.ai in a browser and go to Settings → Billing
  2. Under “API credits”, choose “Link organization”
  3. Pick an existing Claude Console organization, or create one
  4. Review the Supplemental Credit Terms, then link the organization

You need to have been on an eligible plan for 7 days. You don’t need a payment method in the Claude Console.

Create an API key and save it to a file

Create an API key in the Claude Console of the linked organization. Don’t put the key in the code; save it as a text file with the name below inside the tool’s .runtime folder. The file contains just the key on one line.

.runtime\anthropic_api_key.txt

Keep .runtime out of Git. My .gitignore contains these three lines:

node_modules/
.runtime/
*.log

To keep the key somewhere else, set the environment variable CHAT_WEB_KEY_FILE to the file path; it takes priority.

Install the Agent SDK and start

You need Node.js (I use v26.13.1). Put the six files from the end of this post in the layout above and run this in that folder. It installs the Agent SDK (0.3.329 on my PC) plus markdown-it for rendering replies.

npm install

Start it with the command below; the server picks a free port and the browser opens automatically. Day to day I double-click the batch file (web_chat.bat), which also checks for Node.js and runs npm install.

node agent_web.mjs

The initial working folder is two levels above the tool folder (I keep the tool in tools\api_credit inside my workspace). You can switch the working folder at any time from the top left of the page.

The core: options passed to query()

The Agent SDK has a single entry point, query(). You give it the instructions plus options, and Claude’s replies and tool activity come back as a stream of messages. This is the options part:

  const { query } = await sdk();
  const abortController = new AbortController();
  currentAbort = abortController;
  const opts = {
    cwd: workingDirectory,
    model: selectedModel,
    permissionMode: selectedMode,
    canUseTool: (toolName, input, options) => takeApproval(toolName, input, options),
    includePartialMessages: true,
    abortController,
    settingSources: ['user', 'project', 'local'],
    hooks: { PreToolUse: [{ hooks: [async (input) => guardKey(input)] }] },
    env: { ...process.env, ANTHROPIC_API_KEY: apiKey, ENABLE_CLAUDEAI_MCP_SERVERS: 'false' },
  };
  if (sessionId) opts.resume = sessionId;
Option Meaning
cwd Working folder chosen in the page
model Model ID chosen in the dropdown
permissionMode Permission mode. The page offers auto (a model decides to allow or deny each action automatically) or default (manual approval)
canUseTool Called when Claude asks for permission or asks you a question
includePartialMessages When true, you also receive partial chunks while a reply is being written
abortController Lets the Stop button interrupt the run
settingSources Which settings to load. user, project, local make it read CLAUDE.md and settings.json
hooks Functions called before a tool runs. Used to keep Claude from reading the API key file (see below)
env Environment variables for the SDK. The API key is passed here
resume ID of the conversation to continue
prompt (outside options) The instructions. I pass a stream of messages instead of a string (see below)

The important part for the credits is ANTHROPIC_API_KEY in env. The key read from the file is passed only when the SDK runs. It isn’t set as a system-wide environment variable, so my regular Claude Code (signed in with the Max plan) is unaffected.

ENABLE_CLAUDEAI_MCP_SERVERS is set to false because I got the following warning when running with an API key. claude.ai connectors can’t be used while authenticated with an API key, so I don’t load them at all.

claude.ai connectors are disabled because ANTHROPIC_API_KEY or another auth source is set and takes precedence over your claude.ai login · Unset it to load your organization's connectors

Making it feel like interactive Claude Code

The full code is at the end; here is just what it can do and which SDK feature each part uses.

Feature How
Keep the context of earlier turns Save the returned session_id and pass it as resume next time
Show text and tool runs in the order they happen, with a “done” line (cost, end time) after the final reply Append each incoming message to the page in turn
Reloading the page doesn’t stop the work The server logs every event; the browser picks up from where it left off
Answer approvals, plus Claude’s multiple-choice questions, in the browser canUseTool. “Always allow” is saved to .claude\settings.local.json via updatedPermissions
Send extra instructions or images while it works Pass an async generator as prompt (streaming input)
My usual CLAUDE.md and settings apply settingSources set to user, project, local
Chat page showing text & tool runs in chronological order
Text and tool runs listed in the order they happened (taken in a test mode with dummy replies)
Confirmation shown before running a command
Confirmation before a command runs (test mode)
A message sent while Claude was working, shown in the chat
Messages sent mid-task are labeled as added during work, with the continued answer below (test mode)

Moving conversations between this page and your subscription

When I run out of plan usage I switch to this page, then switch back when the limit resets. Claude Code stores conversation logs in the location below whichever way you sign in (plan or API key). So as long as the working folder is the same, you can continue any conversation by passing its ID to resume.

~/.claude/projects/<フォルダ>/<会話のID>.jsonl

Continue a subscription conversation on this page

“会話の履歴” (conversation history) on the left lists the conversations of the current working folder, newest first. Pick one, its earlier messages appear, and your next instruction continues it (conversations started from desktop app project threads are listed too).

Continue this page’s conversation on your subscription

The menu at the top right opens a PowerShell window without the API key variable and runs one of the commands below. Typing them yourself: the first is for the terminal, the second for the desktop app (which must be signed in with your plan, Claude Code v2.1.285 or later).

claude --resume <会話のID>
claude --desktop --resume <会話のID>
Menu for continuing on the subscription side
The top-right menu hands the current conversation to the desktop app or a terminal

Three caveats. Running the same conversation in both places at once can lose parts of the log. Continuing a long conversation re-reads the whole thing once, which is expensive (logs over 3MB ask for confirmation first). Only conversations from the same working folder on the same PC can be continued.

Keeping it local to my PC

This server can edit files and run commands, so it has these safeguards:

  • Listens only on 127.0.0.1 and returns 403 when the Host or Origin header isn’t itself
  • A Content-Security-Policy limits scripts and connections to the page’s own origin
  • The API key never appears in the page or in error messages
  • A PreToolUse hook blocks any tool call that mentions the key file’s name or location, so Claude can’t read it. It can’t catch wildcards or dumping environment variables, so use manual approval if that worries you

Differences from interactive Claude Code

This is my own page built on the Agent SDK, not Claude Code itself. Right now:

  • Only two permission modes: auto, manual approval
  • Only images can be attached
  • The page shows at most the latest 120 past messages (the log itself is kept)
  • The cost shown is what the SDK reports, for reference. Check the real balance in the Claude Console billing page

Things to know

  • Credits don’t roll over. Unused credits expire at the end of the billing cycle
  • What happens after the credits run out depends on Console settings. With purchased credits or auto-reload enabled, usage continues from those; with neither, API requests stop until the next credits arrive. Nothing is charged to your Claude plan
  • Everyone using API keys from the linked organization shares the same balance
  • If you offer something built on the Agent SDK to other people, you may not let it use claude.ai login or plan usage (unless approved in advance), nor use the name “Claude Code” or a look imitating Claude Code. Mine is a personal tool on my own PC, named Claude Agent

Summary

  • Max plan API credits ($100/month) can’t be used by interactive Claude Code. Run the Agent SDK with a Console organization API key to use them
  • Approvals and questions can be shown in the browser through canUseTool. Pass the conversation ID to resume to move between this page and your subscription

Related posts

References

Full code

Here are all six files. Place them as shown in “Architecture”, run npm install, then start. No API key is included. UI labels and comments are in Japanese. Feel free to use the code.

package.json

{
  "name": "claude-api-credit-agent-ui",
  "private": true,
  "version": "4.0.0",
  "type": "module",
  "description": "Local browser-based Claude Agent SDK interface",
  "dependencies": {
    "@anthropic-ai/claude-agent-sdk": "^0.3.329",
    "markdown-it": "^14.1.0"
  }
}

web_chat.bat

@echo off
setlocal EnableExtensions
chcp 65001 >nul
cd /d "%~dp0"
if errorlevel 1 goto :cd_failed

where node.exe >nul 2>&1
if errorlevel 1 goto :node_missing
where npm.cmd >nul 2>&1
if errorlevel 1 goto :npm_missing
if not exist "package.json" goto :files_missing
if not exist "agent_web.mjs" goto :files_missing
if not exist "web\index.html" goto :files_missing

if not exist "node_modules\@anthropic-ai\claude-agent-sdk\package.json" goto :install
if not exist "node_modules\markdown-it\dist\markdown-it.min.js" goto :install
goto :start

:install
echo [SETUP] Installing Claude Agent SDK and Markdown renderer...
call npm.cmd install --no-fund --no-audit
if errorlevel 1 goto :install_failed
if not exist "node_modules\markdown-it\dist\markdown-it.min.js" goto :install_failed
if not exist "node_modules\@anthropic-ai\claude-agent-sdk\package.json" goto :install_failed

:start
echo [START] Opening browser chat...
node.exe "%~dp0agent_web.mjs"
set "RUN_EXIT=%ERRORLEVEL%"
if not "%RUN_EXIT%"=="0" echo [ERROR] Web chat exited with code %RUN_EXIT%.
goto :end

:cd_failed
echo [ERROR] Could not change directory.
goto :end
:node_missing
echo [ERROR] Node.js is not installed or not on PATH.
goto :end
:npm_missing
echo [ERROR] npm.cmd was not found.
goto :end
:files_missing
echo [ERROR] Package files are missing. Extract all ZIP files.
goto :end
:install_failed
echo [ERROR] npm install failed. Check your network, proxy, and npm configuration.
echo [HINT] Try npm.cmd install --no-fund --no-audit in this folder.
goto :end
:end
echo.
pause
endlocal

agent_web.mjs

/**
 * Claude Agent SDK local web chat (v4).
 * Run from this folder using Node.js 20+.
 * Binds ONLY to 127.0.0.1, with no remote access.
 *
 * v4: runs keep going when the browser tab is closed or reloaded, the
 * conversation is stored in the order things happened, sessions made by other
 * Claude Code surfaces in the same folder can be opened and continued, and a
 * session can be handed back to the desktop app or the terminal.
 */
import http from 'node:http';
import path from 'node:path';
import { readFile, writeFile, mkdir, rename, stat, realpath, readdir, open } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { homedir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { randomUUID } from 'node:crypto';
import { spawn } from 'node:child_process';

const HERE = path.dirname(fileURLToPath(import.meta.url));
// The tool is meant to live in <project>/tools/api_credit, so the folder two
// levels up is the project opened on the very first start.
const DEFAULT_PROJECT = process.env.CHAT_WEB_DEFAULT_PROJECT || path.resolve(HERE, '..', '..');
const WEB = path.join(HERE, 'web');
// UI state is kept beside the application, not inside the currently opened project.
const APP_RUNTIME = process.env.CHAT_WEB_STATE_DIR || path.join(HERE, '.runtime');
const STATE_FILE = path.join(APP_RUNTIME, 'projects.json');
const LEGACY_STATE_FILE = path.join(DEFAULT_PROJECT, '.runtime', 'agent_web_state.json');
const KEY_FILE_NAME = 'anthropic_api_key.txt';
const KEY_FILE_CANDIDATES = [
  process.env.CHAT_WEB_KEY_FILE,
  path.join(HERE, '.runtime', KEY_FILE_NAME),
  path.join(DEFAULT_PROJECT, '.runtime', KEY_FILE_NAME),
].filter(Boolean);
const HOST = '127.0.0.1';
const API_VERSION = 4;
// JSON base64 is ~4/3 of the original image bytes; four images * 5 MiB.
const MAX_BODY = 32 * 1024 * 1024;
const MAX_IMAGES = 4;
const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
const IMAGE_MIME = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
const HISTORY_LIMIT = 120;
const SESSION_LIST_LIMIT = 60;
const TOOL_INPUT_CLIP = 4000;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const TEST_MODE = process.env.CHAT_WEB_TEST_MODE === '1';

let apiKey = '';
let keyFile = '';
let busy = false;
let currentAbort = null;
let run = null; // { id, events: [], listeners: Set<ServerResponse>, done }
let currentProject = DEFAULT_PROJECT;
let recentProjects = [DEFAULT_PROJECT];
const projectStates = {};
let stateWriteQueue = Promise.resolve();
let pickerBusy = false;
let sessionId = null;
let model = 'claude-fable-5-2';
let permissionMode = 'auto';
let history = [];
let totalCost = 0;
let syncedAt = 0;
const pending = new Map();
let sdkModule = null;

function sdk() {
  if (!sdkModule) sdkModule = import('@anthropic-ai/claude-agent-sdk');
  return sdkModule;
}

function json(res, code, value) {
  res.writeHead(code, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
  res.end(JSON.stringify(value));
}

function fail(statusCode, message) {
  return Object.assign(new Error(message), { statusCode });
}

function safeError(err) {
  const message = String(err?.message ?? err);
  return apiKey ? message.replaceAll(apiKey, '[API KEY HIDDEN]') : message;
}

async function readJson(req) {
  if (!(req.headers['content-type'] || '').startsWith('application/json')) {
    throw fail(415, 'Content-Type must be application/json');
  }
  const chunks = [];
  let size = 0;
  for await (const chunk of req) {
    size += chunk.length;
    if (size > MAX_BODY) throw fail(413, 'Payload too large');
    chunks.push(chunk);
  }
  try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
  catch { throw fail(400, 'Invalid JSON'); }
}

function validImageMagic(bytes, mimeType) {
  if (mimeType === 'image/png') return bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]));
  if (mimeType === 'image/jpeg') return bytes.length > 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
  if (mimeType === 'image/gif') return bytes.subarray(0, 6).toString('ascii') === 'GIF87a' || bytes.subarray(0, 6).toString('ascii') === 'GIF89a';
  if (mimeType === 'image/webp') return bytes.subarray(0, 4).toString('ascii') === 'RIFF' && bytes.subarray(8, 12).toString('ascii') === 'WEBP';
  return false;
}

function parseImages(raw) {
  if (raw === undefined || raw === null) return [];
  if (!Array.isArray(raw) || raw.length > MAX_IMAGES) {
    throw fail(400, '画像は最大' + MAX_IMAGES + '枚までです。');
  }
  return raw.map((item, index) => {
    const mimeType = item?.mimeType;
    const base64 = item?.data;
    if (!IMAGE_MIME.has(mimeType) || typeof base64 !== 'string' || !base64 ||
        base64.length > Math.ceil(MAX_IMAGE_BYTES / 3) * 4 + 4 ||
        !/^[A-Za-z0-9+/]+={0,2}$/.test(base64)) {
      throw fail(400, '画像' + (index + 1) + ': 形式またはサイズが不正です。');
    }
    const bytes = Buffer.from(base64, 'base64');
    if (!bytes.length || bytes.length > MAX_IMAGE_BYTES || bytes.toString('base64') !== base64 || !validImageMagic(bytes, mimeType)) {
      throw fail(400, '画像' + (index + 1) + ': 画像ファイルを確認してください(最大5MB)。');
    }
    const name = typeof item.name === 'string' ? item.name.slice(0, 120) : '画像' + (index + 1);
    // Save only a small client-generated preview, not the original image bytes, to local chat history.
    const preview = typeof item.preview === 'string' &&
      /^data:image\/(jpeg|png|webp);base64,[A-Za-z0-9+/]+={0,2}$/.test(item.preview) &&
      item.preview.length < 140000 ? item.preview : '';
    return { name, mimeType, data: base64, preview };
  });
}

// ---------------------------------------------------------------- state

function captureProject() {
  projectStates[currentProject] = {
    sessionId,
    model,
    permissionMode,
    totalCost,
    syncedAt,
    history: history.slice(-HISTORY_LIMIT),
  };
}

function loadProject(projectPath) {
  const state = projectStates[projectPath] || {};
  sessionId = typeof state.sessionId === 'string' ? state.sessionId : null;
  model = typeof state.model === 'string' && state.model.length <= 120
    ? state.model : 'claude-fable-5-2';
  permissionMode = ['auto', 'default'].includes(state.permissionMode) ? state.permissionMode : 'auto';
  totalCost = Number.isFinite(Number(state.totalCost)) ? Number(state.totalCost) : 0;
  syncedAt = Number.isFinite(Number(state.syncedAt)) ? Number(state.syncedAt) : 0;
  history = Array.isArray(state.history)
    ? state.history.slice(-HISTORY_LIMIT).filter(x => x && ['user', 'assistant'].includes(x.role) && typeof x.text === 'string')
    : [];
}

async function saveState() {
  captureProject();
  const snapshot = JSON.stringify({
    version: 3,
    currentProject,
    recentProjects,
    projectStates,
  }, null, 2);
  stateWriteQueue = stateWriteQueue.catch(() => {}).then(async () => {
    await mkdir(APP_RUNTIME, { recursive: true });
    const tmp = STATE_FILE + '.' + process.pid + '.' + randomUUID() + '.tmp';
    await writeFile(tmp, snapshot, { encoding: 'utf8', mode: 0o600 });
    await rename(tmp, STATE_FILE);
  });
  return stateWriteQueue;
}

async function validDirectory(folder) {
  if (typeof folder !== 'string' || !folder.trim() || folder.length > 2048 || !path.isAbsolute(folder.trim())) {
    throw fail(400, '作業フォルダの絶対パスを指定してください。');
  }
  let canonical;
  try {
    canonical = await realpath(folder.trim());
    if (!(await stat(canonical)).isDirectory()) throw new Error('Not a directory');
  } catch {
    throw fail(400, 'フォルダが存在しないか、アクセスできません。');
  }
  return canonical;
}

async function loadState() {
  try {
    const stored = JSON.parse(await readFile(STATE_FILE, 'utf8'));
    if (stored && stored.version === 3 && stored.projectStates && typeof stored.projectStates === 'object') {
      for (const [folder, state] of Object.entries(stored.projectStates)) {
        if (typeof folder === 'string' && path.isAbsolute(folder) && state && typeof state === 'object') {
          projectStates[folder] = state;
        }
      }
      recentProjects = Array.isArray(stored.recentProjects)
        ? [...new Set(stored.recentProjects.filter(x => typeof x === 'string' && path.isAbsolute(x)))].slice(0, 12)
        : [DEFAULT_PROJECT];
      try { currentProject = await validDirectory(stored.currentProject); }
      catch { currentProject = DEFAULT_PROJECT; }
      if (!recentProjects.includes(currentProject)) recentProjects.unshift(currentProject);
      loadProject(currentProject);
      return;
    }
  } catch (e) {
    if (e.code !== 'ENOENT') console.warn('Could not read project list. Starting fresh.');
  }
  // Import the previous single-project conversation once; do not alter its original file.
  try {
    const old = JSON.parse(await readFile(LEGACY_STATE_FILE, 'utf8'));
    if (old && typeof old === 'object') projectStates[DEFAULT_PROJECT] = old;
  } catch (e) {
    if (e.code !== 'ENOENT') console.warn('Legacy session state unreadable.');
  }
  recentProjects = [DEFAULT_PROJECT];
  currentProject = DEFAULT_PROJECT;
  loadProject(DEFAULT_PROJECT);
  await saveState();
}

function assertIdle(message) {
  if (busy || pickerBusy) throw fail(409, message || '実行中は変更できません。');
}

async function activateProject(projectPath) {
  assertIdle('実行中は作業フォルダを切り替えられません。');
  const nextPath = await validDirectory(projectPath);
  captureProject();
  currentProject = nextPath;
  recentProjects = [currentProject, ...recentProjects.filter(x => x !== currentProject)].slice(0, 12);
  loadProject(currentProject);
  await saveState();
  return currentState();
}

function currentState() {
  return {
    apiVersion: API_VERSION,
    model,
    mode: permissionMode,
    history,
    busy,
    runId: run && !run.done ? run.id : null,
    sessionId,
    sessionExists: !!sessionId,
    totalCost,
    projectName: path.basename(currentProject) || currentProject,
    projectPath: currentProject,
    recentProjects: recentProjects.map(folder => ({ path: folder, name: path.basename(folder) || folder, active: folder === currentProject })),
    nativePicker: process.platform === 'win32',
    handoff: process.platform === 'win32',
  };
}

function chooseNativeFolder() {
  const script = [
    'Add-Type -AssemblyName System.Windows.Forms',
    '[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)',
    '$dialog = New-Object System.Windows.Forms.FolderBrowserDialog',
    "$dialog.Description = 'Choose a project folder'",
    '$dialog.ShowNewFolderButton = $false',
    'if (Test-Path -LiteralPath $env:CLAUDE_AGENT_PICK_INITIAL -PathType Container) {',
    '  $dialog.SelectedPath = $env:CLAUDE_AGENT_PICK_INITIAL',
    '}',
    'if ($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {',
    '  [Console]::WriteLine($dialog.SelectedPath)',
    '}',
    '$dialog.Dispose()',
  ].join('\n');
  return new Promise((resolve, reject) => {
    const encoded = Buffer.from(script, 'utf16le').toString('base64');
    const child = spawn('powershell.exe', ['-NoProfile', '-STA', '-EncodedCommand', encoded], {
      env: { ...process.env, CLAUDE_AGENT_PICK_INITIAL: currentProject },
      windowsHide: false,
    });
    let output = '';
    let errors = '';
    child.stdout.setEncoding('utf8');
    child.stderr.setEncoding('utf8');
    child.stdout.on('data', chunk => { if (output.length < 8192) output += chunk; });
    child.stderr.on('data', chunk => { if (errors.length < 4096) errors += chunk; });
    child.on('error', reject);
    child.on('close', code => {
      if (code !== 0) reject(new Error('フォルダ選択画面を開けませんでした。パス入力を利用してください。' + (errors ? ' (' + errors.slice(0, 150) + ')' : '')));
      else resolve(output.trim() || null);
    });
  });
}

async function handleProjectSelect(req, res) {
  const data = await readJson(req);
  json(res, 200, await activateProject(data.path));
}

async function handleProjectPick(req, res) {
  await readJson(req);
  assertIdle('処理中はフォルダを選択できません。');
  if (process.platform !== 'win32') return json(res, 501, { error: 'このOSではパスを直接入力してください。' });
  pickerBusy = true;
  let folder;
  try { folder = await chooseNativeFolder(); }
  finally { pickerBusy = false; }
  if (!folder) return json(res, 200, { cancelled: true });
  json(res, 200, { cancelled: false, ...(await activateProject(folder)) });
}

async function handleProjectRemove(req, res) {
  assertIdle();
  const data = await readJson(req);
  if (typeof data.path !== 'string' || data.path === currentProject) {
    return json(res, 400, { error: '現在使用中のプロジェクトは履歴から削除できません。' });
  }
  // Hiding a recent project does not delete its files, session, or saved conversation.
  recentProjects = recentProjects.filter(x => x !== data.path);
  await saveState();
  json(res, 200, currentState());
}

// ---------------------------------------------------------------- run events

// Every event of a run is kept in memory, so a browser that reloads or
// reconnects can replay the run from the start instead of losing it.
function emit(event) {
  if (!run || run.done) return;
  run.events.push(event);
  const line = JSON.stringify(event) + '\n';
  for (const res of run.listeners) {
    if (!res.destroyed && !res.writableEnded) res.write(line);
  }
}

function finishRun() {
  if (!run) return;
  run.done = true;
  for (const res of run.listeners) res.end();
  run.listeners.clear();
}

function handleEvents(req, res, url) {
  const id = url.searchParams.get('run');
  if (!run || run.id !== id) return json(res, 404, { error: 'この実行はもう残っていません。' });
  const after = Math.max(0, Number.parseInt(url.searchParams.get('after') || '0', 10) || 0);
  res.writeHead(200, { 'Content-Type': 'application/x-ndjson; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'X-Accel-Buffering': 'no' });
  res.flushHeaders();
  for (const event of run.events.slice(after)) res.write(JSON.stringify(event) + '\n');
  if (run.done) return res.end();
  const current = run;
  current.listeners.add(res);
  // Closing the tab only stops listening. The run itself continues.
  res.on('close', () => current.listeners.delete(res));
}

function clip(value) {
  let text;
  try { text = JSON.stringify(value ?? {}, null, 2); }
  catch { text = String(value); }
  return text.length > TOOL_INPUT_CLIP ? text.slice(0, TOOL_INPUT_CLIP) + '\n…(以下省略)' : text;
}

// Turn the recorded events into history entries. The parts of an assistant
// entry keep the order in which text and tool calls happened, and a message
// the user sent in the middle of the run starts a new entry.
function buildEntries(events, selectedModel) {
  const out = [];
  let parts = [];
  let cost = null;
  let success = false;
  const toolParts = new Map();
  const flush = () => {
    if (parts.length) {
      out.push({
        id: randomUUID(), role: 'assistant',
        text: parts.filter(p => p.type === 'text').map(p => p.text).join('\n\n'),
        parts,
        createdAt: new Date().toISOString(), model: selectedModel,
        success, cost,
      });
    }
    parts = [];
    cost = null;
    success = false;
  };
  for (const ev of events) {
    if (ev.type === 'user_message') {
      flush();
      out.push({ id: randomUUID(), role: 'user', text: ev.text || '', images: ev.images || [], createdAt: new Date().toISOString(), model: selectedModel });
      continue;
    }
    if (ev.type === 'result') {
      success = !!ev.success;
      if (Number.isFinite(ev.cost)) cost = (cost || 0) + ev.cost;
      continue;
    }
    if (ev.type === 'text' && ev.text) {
      const last = parts[parts.length - 1];
      if (last && last.type === 'text') last.text += ev.text;
      else if (ev.text.trim()) parts.push({ type: 'text', text: ev.text });
    } else if (ev.type === 'tool') {
      const part = { type: 'tool', name: ev.name || 'Tool', input: clip(ev.input), sub: !!ev.sub };
      if (ev.id) toolParts.set(ev.id, part);
      parts.push(part);
    } else if (ev.type === 'tool_result' && toolParts.has(ev.id)) {
      toolParts.get(ev.id).status = ev.isError ? 'error' : 'ok';
    } else if (ev.type === 'notice' || ev.type === 'error') {
      parts.push({ type: 'notice', text: (ev.type === 'error' ? 'エラー: ' : '') + (ev.message || '') });
    }
  }
  flush();
  return out;
}

// ---------------------------------------------------------------- input queue

// The prompt of query() is a stream, not a string. The stream stays open while
// Claude works, so a message typed in the middle of a run can be pushed into
// it. Claude reads such a message once the tool calls in progress finish.
let inbox = null; // { pending: [], wake, closed, unanswered: Set<uuid> }

function openInbox() {
  inbox = { pending: [], wake: null, closed: false, unanswered: new Set() };
}

function pushInbox(text, images) {
  const uuid = randomUUID();
  const content = images.length
    ? [
      { type: 'text', text },
      ...images.map(image => ({
        type: 'image',
        source: { type: 'base64', media_type: image.mimeType, data: image.data },
      })),
    ]
    : text;
  inbox.unanswered.add(uuid);
  inbox.pending.push({ type: 'user', uuid, message: { role: 'user', content }, parent_tool_use_id: null });
  inbox.wake?.();
}

function closeInbox() {
  if (!inbox) return;
  inbox.closed = true;
  inbox.wake?.();
}

async function* inboxStream(box) {
  while (true) {
    const next = box.pending.shift();
    if (next) yield next;
    else if (box.closed) return;
    else {
      await new Promise(resolve => { box.wake = resolve; });
      box.wake = null;
    }
  }
}

// ---------------------------------------------------------------- approvals

function takeApproval(toolName, input, options) {
  return new Promise((resolve) => {
    const requestId = randomUUID();
    const suggestions = Array.isArray(options?.suggestions)
      ? options.suggestions.filter(s => s && s.destination === 'localSettings') : [];
    const canRemember = toolName !== 'AskUserQuestion' && suggestions.length > 0 && options?.suppressAlwaysAllowRule !== true;
    pending.set(requestId, {
      decide: (decision, answers) => {
        pending.delete(requestId);
        emit({ type: 'approval_closed', requestId, decision });
        if (decision !== 'allow' && decision !== 'always') {
          return resolve({ behavior: 'deny', message: 'User denied this operation.' });
        }
        if (toolName === 'AskUserQuestion') {
          if (!answers || typeof answers !== 'object') return resolve({ behavior: 'deny', message: 'No answers provided.' });
          return resolve({ behavior: 'allow', updatedInput: { ...input, answers } });
        }
        if (decision === 'always' && canRemember) {
          // Writes the suggested rule to .claude/settings.local.json of the project.
          return resolve({ behavior: 'allow', updatedInput: input, updatedPermissions: suggestions });
        }
        resolve({ behavior: 'allow', updatedInput: input });
      },
    });
    emit({
      type: 'approval', requestId, toolName,
      input,
      questions: toolName === 'AskUserQuestion' ? input?.questions : undefined,
      reason: options?.decisionReason || '',
      canRemember,
    });
  });
}

function denyOutstanding() {
  for (const item of [...pending.values()]) item.decide('deny');
  pending.clear();
}

// ---------------------------------------------------------------- key guard

// Best effort: stop the agent from reading the API key through its own tools.
// This is not a sandbox. A command that reaches the file by a wildcard, or
// that dumps every environment variable, is not caught here.
function guardKey(hookInput) {
  if (!keyFile) return {};
  let text;
  try { text = JSON.stringify(hookInput?.tool_input ?? {}); }
  catch { return {}; }
  const haystack = text.replaceAll('\\\\', '/').replaceAll('\\', '/').toLowerCase();
  const keyDir = path.dirname(keyFile).replaceAll('\\', '/').toLowerCase();
  const shell = hookInput?.tool_name === 'Bash' || hookInput?.tool_name === 'PowerShell';
  const hit = haystack.includes(KEY_FILE_NAME) || haystack.includes(keyDir) ||
    (shell && haystack.includes('anthropic_api_key'));
  if (!hit) return {};
  return {
    hookSpecificOutput: {
      hookEventName: 'PreToolUse',
      permissionDecision: 'deny',
      permissionDecisionReason: 'The API key of this chat tool is off limits. Do not read, print, or copy it.',
    },
  };
}

// ---------------------------------------------------------------- one turn

async function runMockTurn(images) {
  const wait = ms => new Promise(r => setTimeout(r, ms));
  emit({ type: 'image_received', count: images.length });
  emit({ type: 'text', text: 'フォルダの中を確認します。\n\n' });
  await wait(300);
  emit({ type: 'tool', name: 'Glob', id: 't1', input: { pattern: '**/*.md' } });
  await wait(300);
  emit({ type: 'tool_result', id: 't1', isError: false });
  emit({ type: 'tool', name: 'Read', id: 't2', input: { file_path: 'README.md' } });
  await wait(300);
  emit({ type: 'tool_result', id: 't2', isError: false });
  emit({ type: 'text', text: 'README を読みました。次に、テスト用のコマンドを実行します。\n\n' });
  const d = await takeApproval('Bash', { command: 'echo test', description: 'Mock approval for UI validation' }, {});
  emit({ type: 'tool', name: 'Bash', id: 't3', input: { command: 'echo test' } });
  await wait(200);
  emit({ type: 'tool_result', id: 't3', isError: d.behavior !== 'allow' });
  emit({ type: 'text', text: '## 確認の結果\n\n**Markdown が整形されます。**\n\n| 項目 | 内容 |\n|---|---|\n| ファイル | README.md |\n| 承認の結果 | ' + d.behavior + ' |\n\n作業はここまでです。' });
  inbox.pending.shift(); // the first prompt
  while (inbox.pending.length) {
    inbox.pending.shift();
    emit({ type: 'text', text: '\n\n途中で送られた追加の指示も読みました。' });
  }
  closeInbox();
  emit({ type: 'result', success: true, cost: 0.0012, final: true, denials: [] });
  if (!sessionId) sessionId = randomUUID();
  return { success: true, cost: 0.0012 };
}

async function runSdkTurn(selectedModel, selectedMode, workingDirectory) {
  const { query } = await sdk();
  const abortController = new AbortController();
  currentAbort = abortController;
  const opts = {
    cwd: workingDirectory,
    model: selectedModel,
    permissionMode: selectedMode,
    canUseTool: (toolName, input, options) => takeApproval(toolName, input, options),
    includePartialMessages: true,
    abortController,
    settingSources: ['user', 'project', 'local'],
    hooks: { PreToolUse: [{ hooks: [async (input) => guardKey(input)] }] },
    env: { ...process.env, ANTHROPIC_API_KEY: apiKey, ENABLE_CLAUDEAI_MCP_SERVERS: 'false' },
  };
  if (sessionId) opts.resume = sessionId;
  let sawText = false;
  let resultSeen = false;
  let success = false;
  let cost = null;
  let currentMsgHadTextDeltas = false;
  const box = inbox;

  for await (const message of query({ prompt: inboxStream(box), options: opts })) {
    if (typeof message.session_id === 'string' && message.session_id) sessionId = message.session_id;
    // Messages of a subagent carry the id of the tool call that started it.
    const sub = !!message.parent_tool_use_id;
    if (message.type === 'stream_event') {
      const ev = message.event;
      if (ev?.type === 'message_start' && !sub) currentMsgHadTextDeltas = false;
      if (ev?.type === 'content_block_delta' && ev.delta?.type === 'text_delta' && !sub) {
        const delta = ev.delta.text || '';
        sawText = true;
        currentMsgHadTextDeltas = true;
        emit({ type: 'text', text: delta });
      }
      if (ev?.type === 'content_block_start' && ev.content_block?.type === 'tool_use') {
        emit({ type: 'tool_start', name: ev.content_block.name, id: ev.content_block.id });
      }
    } else if (message.type === 'assistant') {
      const blocks = message.message?.content || [];
      for (const block of blocks) {
        if (block.type === 'tool_use') emit({ type: 'tool', name: block.name, input: block.input, id: block.id, sub });
        if (block.type === 'text' && !sub && !currentMsgHadTextDeltas && block.text) {
          sawText = true;
          emit({ type: 'text', text: block.text });
        }
      }
      if (!sub) {
        currentMsgHadTextDeltas = false;
        // Keep text of separate assistant messages apart in the rendered Markdown.
        emit({ type: 'text', text: '\n\n' });
      }
    } else if (message.type === 'user') {
      const blocks = Array.isArray(message.message?.content) ? message.message.content : [];
      for (const block of blocks) {
        if (block?.type === 'tool_result') emit({ type: 'tool_result', id: block.tool_use_id, isError: !!block.is_error });
      }
    } else if (message.type === 'system' && message.subtype === 'permission_denied') {
      emit({ type: 'notice', message: '権限がないため、一部の操作が拒否されました。' });
    } else if (message.type === 'system' && message.subtype === 'compact_boundary') {
      emit({ type: 'notice', message: '会話が長くなったため、ここまでの内容が自動で要約されました。' });
    } else if (message.type === 'result') {
      resultSeen = true;
      success = message.subtype === 'success' && !message.is_error;
      const lastResult = String(message.result || '');
      const denials = Array.isArray(message.permission_denials) ? message.permission_denials : [];
      if (!sawText && lastResult) emit({ type: 'text', text: lastResult });
      sawText = false;
      // total_cost_usd counts up over the whole query() call, so the cost of
      // this response is the difference from the previous result.
      const total = Number.isFinite(Number(message.total_cost_usd)) ? Number(message.total_cost_usd) : null;
      const responseCost = total === null ? null : Math.max(0, total - (cost || 0));
      if (total !== null) cost = total;
      // The result names the messages it answered. When every message that was
      // pushed has been answered, close the stream so that query() can end.
      const answered = Array.isArray(message.user_message_uuids) ? message.user_message_uuids
        : (message.user_message_uuid ? [message.user_message_uuid] : null);
      let matched = 0;
      for (const id of answered || []) if (box.unanswered.delete(id)) matched += 1;
      // A CLI that does not report the ids: take the result as the answer to everything sent so far.
      if (!matched) box.unanswered.clear();
      const final = !success || box.unanswered.size === 0;
      if (final) closeInbox();
      emit({
        type: 'result', success, subtype: message.subtype, cost: responseCost, final,
        denials: denials.map(x => ({ name: x.tool_name || x.toolName || 'Tool' })),
        errors: message.errors || [],
      });
    }
  }
  if (!resultSeen) emit({ type: 'notice', message: 'SDKから最終結果が返りませんでした。' });
  return { success: resultSeen && success, cost };
}

async function executeRun(images, selectedModel, selectedMode, workingDirectory) {
  let answer = { success: false, cost: null };
  try {
    answer = TEST_MODE
      ? await runMockTurn(images)
      : await runSdkTurn(selectedModel, selectedMode, workingDirectory);
  } catch (e) {
    emit({ type: 'error', message: safeError(e) });
  } finally {
    closeInbox();
    denyOutstanding();
    history.push(...buildEntries(run.events, selectedModel));
    if (Number.isFinite(answer.cost)) totalCost += answer.cost;
    syncedAt = Date.now();
    busy = false;
    currentAbort = null;
    try { await saveState(); } catch (err) { console.warn('Could not save session:', safeError(err)); }
    emit({ type: 'done', success: answer.success, totalCost, sessionId });
    finishRun();
  }
}

async function handleRun(req, res) {
  const data = await readJson(req);
  const images = parseImages(data.images);
  let prompt = typeof data.prompt === 'string' ? data.prompt.trim() : '';
  if (!prompt && images.length) prompt = '添付画像を確認してください。';
  if (!prompt || prompt.length > 200000) return json(res, 400, { error: '指示を入力するか、画像を添付してください(最大20万文字)。' });
  const previews = images.map(({ name, preview }) => ({ name, preview }));
  if (busy && run && !run.done) {
    // A run is in progress: hand the message to the running agent.
    if (!inbox || inbox.closed) return json(res, 409, { error: '前の作業がちょうど終わるところです。', retry: true });
    pushInbox(prompt, images);
    emit({ type: 'user_message', text: prompt, images: previews });
    return json(res, 200, { ok: true, queued: true, runId: run.id });
  }
  assertIdle('別の処理を実行中です。');
  const selectedModel = typeof data.model === 'string' && data.model.trim() && data.model.trim().length <= 120 ? data.model.trim() : model;
  const selectedMode = ['auto', 'default'].includes(data.mode) ? data.mode : permissionMode;
  model = selectedModel;
  permissionMode = selectedMode;
  busy = true;
  run = { id: randomUUID(), events: [], listeners: new Set(), done: false };
  openInbox();
  pushInbox(prompt, images);
  history.push({ id: randomUUID(), role: 'user', text: prompt, images: previews, createdAt: new Date().toISOString(), model });
  await saveState();
  emit({ type: 'started', model, mode: permissionMode });
  json(res, 200, { ok: true, runId: run.id });
  // Not awaited: the run is independent of this HTTP request.
  executeRun(images, selectedModel, selectedMode, currentProject)
    .catch(err => console.error('[Run]', safeError(err)));
}

async function handleApproval(req, res) {
  const data = await readJson(req);
  const item = pending.get(data.requestId);
  if (!item) return json(res, 404, { error: '承認依頼は既に終了しています。' });
  item.decide(['allow', 'always'].includes(data.decision) ? data.decision : 'deny', data.answers);
  json(res, 200, { ok: true });
}

async function handleSettings(req, res) {
  assertIdle('実行中は設定を変更できません。');
  const data = await readJson(req);
  if (typeof data.model === 'string' && data.model.trim() && data.model.length <= 120) model = data.model.trim();
  if (['auto', 'default'].includes(data.mode)) permissionMode = data.mode;
  await saveState();
  json(res, 200, { model, mode: permissionMode });
}

async function handleNew(req, res) {
  assertIdle('実行中は新規会話を開始できません。');
  await readJson(req);
  // Only this screen is reset. The transcript of the old session stays on disk.
  sessionId = null;
  history = [];
  totalCost = 0;
  syncedAt = Date.now();
  await saveState();
  json(res, 200, currentState());
}

async function handleStop(req, res) {
  await readJson(req);
  if (!busy) return json(res, 409, { error: '実行中の処理はありません。' });
  denyOutstanding();
  currentAbort?.abort();
  json(res, 200, { ok: true });
}

// ---------------------------------------------------------------- sessions

// Sessions live in ~/.claude/projects/<folder>/ no matter which Claude Code
// surface created them, so sessions of the desktop app or the terminal in the
// same folder show up here as well.
async function handleSessionList(req, res) {
  const { listSessions } = await sdk();
  const listed = await listSessions({ dir: currentProject, limit: SESSION_LIST_LIMIT });
  const rows = listed.map(s => ({
    id: s.sessionId,
    title: String(s.customTitle || s.summary || s.firstPrompt || '').slice(0, 160),
    lastModified: s.lastModified,
    fileSize: s.fileSize || 0,
  }));
  const known = new Set(rows.map(r => r.id));
  for (const extra of await unlistedSessions(currentProject, known)) rows.push(extra);
  rows.sort((a, b) => b.lastModified - a.lastModified);
  json(res, 200, {
    sessions: rows.slice(0, SESSION_LIST_LIMIT).map(r => ({
      ...r,
      title: r.title || '(題名なし)',
      current: r.id === sessionId,
      // Somebody else (desktop app, terminal) appended to it after we last looked.
      changedOutside: r.id === sessionId && !busy && r.lastModified > syncedAt + 5000,
    })),
  });
}

// Where Claude Code keeps the transcripts of one folder: every character of
// the path that is not a letter or a digit becomes "-".
function transcriptDir(folder) {
  const name = folder.replace(/[^a-zA-Z0-9]/g, '-');
  if (name.length > 200) return null; // long names get a hash appended; not handled here
  const base = process.env.CLAUDE_CONFIG_DIR || path.join(homedir(), '.claude');
  return path.join(base, 'projects', name);
}

const titleCache = new Map();

// listSessions() leaves out a session when it cannot find a title for it. That
// happens to sessions started from a project thread of the desktop app, whose
// prompts are wrapped in <wake> tags. Add those from the transcript folder.
// The transcript format is internal to Claude Code, so this only reads the
// start of each file and falls back to an empty title when anything is odd.
async function unlistedSessions(folder, known) {
  const dir = transcriptDir(folder);
  if (!dir) return [];
  let names;
  try { names = await readdir(dir); } catch { return []; }
  const out = [];
  for (const name of names) {
    if (!name.endsWith('.jsonl')) continue;
    const id = name.slice(0, -6);
    if (!UUID.test(id) || known.has(id)) continue;
    const file = path.join(dir, name);
    let info;
    try { info = await stat(file); } catch { continue; }
    if (!info.isFile() || info.size < 200) continue;
    const cacheKey = id + ':' + info.mtimeMs;
    if (!titleCache.has(cacheKey)) titleCache.set(cacheKey, await headTitle(file));
    const title = titleCache.get(cacheKey);
    if (title === null) continue; // a subagent transcript
    out.push({ id, title, lastModified: Math.round(info.mtimeMs), fileSize: info.size });
  }
  return out;
}

async function headTitle(file) {
  let text = '';
  let handle;
  try {
    handle = await open(file, 'r');
    const buffer = Buffer.alloc(262144);
    const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
    text = buffer.subarray(0, bytesRead).toString('utf8');
  } catch { return ''; }
  finally { await handle?.close(); }
  const lines = text.split('\n');
  if (lines[0].includes('"isSidechain":true')) return null;
  for (const line of lines) {
    if (!line.includes('"type":"user"')) continue;
    try {
      const entry = JSON.parse(line);
      if (entry.type !== 'user' || entry.isSidechain) continue;
      const title = userText(entry.message?.content).replace(/\s+/g, ' ').trim();
      if (title) return title.slice(0, 160);
    } catch { /* a line cut off at the end of the buffer */ }
  }
  return '';
}

function unescapeXml(text) {
  return text.replaceAll('&lt;', '<').replaceAll('&gt;', '>').replaceAll('&quot;', '"').replaceAll('&apos;', "'").replaceAll('&amp;', '&');
}

function userText(content) {
  let text = '';
  if (typeof content === 'string') text = content;
  else if (Array.isArray(content)) {
    text = content.filter(b => b && b.type === 'text' && typeof b.text === 'string').map(b => b.text).join('\n');
  }
  text = text.replace(/<system-reminder>[\s\S]*?<\/system-reminder>/g, '').trim();
  // A prompt that arrived through a project thread of the desktop app: keep
  // only what the person wrote.
  if (text.startsWith('<wake')) {
    const pick = pattern => [...text.matchAll(pattern)].map(m => unescapeXml(m[1]).trim()).filter(Boolean);
    // The message that woke the session; earlier messages of the thread may be quoted beside it.
    const trigger = pick(/<message\b[^>]*\btrigger="true"[^>]*>([\s\S]*?)<\/message>/g);
    const said = trigger.length ? trigger : pick(/<message\b[^>]*\bfrom="human"[^>]*>([\s\S]*?)<\/message>/g);
    return said.join('\n\n');
  }
  // Wrappers written by slash commands, hooks and background tasks are not something the user typed.
  if (/^<(command-name|command-message|command-args|local-command-|task-notification|bash-|user-prompt-submit-hook)/.test(text)) return '';
  return text;
}

function transcriptToHistory(messages) {
  const out = [];
  let assistant = null;
  const toolParts = new Map();
  for (const m of messages) {
    if (!m || m.parent_tool_use_id) continue;
    const content = m.message?.content;
    if (m.type === 'user') {
      if (Array.isArray(content)) {
        for (const b of content) {
          if (b?.type === 'tool_result' && toolParts.has(b.tool_use_id)) {
            toolParts.get(b.tool_use_id).status = b.is_error ? 'error' : 'ok';
          }
        }
      }
      const text = userText(content);
      if (!text) continue;
      const imageCount = Array.isArray(content) ? content.filter(b => b?.type === 'image').length : 0;
      assistant = null;
      out.push({
        id: m.uuid || randomUUID(), role: 'user', text,
        images: Array.from({ length: imageCount }, (_, i) => ({ name: '画像' + (i + 1), preview: '' })),
      });
    } else if (m.type === 'assistant' && Array.isArray(content)) {
      for (const b of content) {
        let part = null;
        if (b?.type === 'text' && b.text) part = { type: 'text', text: b.text };
        if (b?.type === 'tool_use') {
          part = { type: 'tool', name: b.name || 'Tool', input: clip(b.input) };
          if (b.id) toolParts.set(b.id, part);
        }
        if (!part) continue;
        if (!assistant) {
          assistant = { id: m.uuid || randomUUID(), role: 'assistant', text: '', parts: [], model: m.message?.model || '', success: true, cost: null };
          out.push(assistant);
        }
        assistant.parts.push(part);
        if (part.type === 'text') assistant.text += (assistant.text ? '\n\n' : '') + part.text;
      }
    }
  }
  return out;
}

async function handleSessionOpen(req, res) {
  assertIdle('実行中は会話を切り替えられません。');
  const data = await readJson(req);
  const id = typeof data.sessionId === 'string' ? data.sessionId.trim() : '';
  if (!UUID.test(id)) return json(res, 400, { error: '会話のIDが正しくありません。' });
  const { getSessionInfo, getSessionMessages } = await sdk();
  const dir = transcriptDir(currentProject);
  const found = await getSessionInfo(id, { dir: currentProject }) || (dir && existsSync(path.join(dir, id + '.jsonl')));
  if (!found) return json(res, 404, { error: 'このフォルダの会話の中に見つかりませんでした。' });
  const messages = await getSessionMessages(id, { dir: currentProject });
  const converted = transcriptToHistory(messages);
  const reopening = id === sessionId;
  history = converted.slice(-HISTORY_LIMIT);
  sessionId = id;
  if (!reopening) totalCost = 0;
  syncedAt = Date.now();
  await saveState();
  json(res, 200, { ...currentState(), truncated: converted.length > HISTORY_LIMIT });
}

// Hand the current session back to the subscription side. The key is removed
// from the environment so that the launched program signs in with the plan.
async function handleHandoff(req, res) {
  assertIdle('実行中は引き継げません。');
  const data = await readJson(req);
  if (process.platform !== 'win32') return json(res, 501, { error: 'この機能はWindowsだけで使えます。表示されたコマンドを手で実行してください。' });
  if (!sessionId || !UUID.test(sessionId)) return json(res, 400, { error: '引き継ぐ会話がありません。' });
  const env = { ...process.env };
  delete env.ANTHROPIC_API_KEY;
  // "claude --desktop" refuses to run without a real console, so both
  // targets are started in a new PowerShell window. The id was checked against
  // the UUID pattern above, so it is safe to put on a command line.
  const commands = {
    terminal: 'claude --resume ' + sessionId,
    desktop: 'claude --desktop --resume ' + sessionId,
  };
  const command = commands[data.target];
  if (!command) return json(res, 400, { error: 'Unknown target.' });
  const child = spawn('cmd.exe', ['/c', 'start', '', 'powershell.exe', '-NoExit', '-Command', command], {
    cwd: currentProject, env, stdio: 'ignore', detached: true, windowsHide: false,
  });
  child.on('error', () => {});
  child.unref();
  json(res, 200, {
    ok: true,
    message: data.target === 'desktop'
      ? '新しいウインドウで claude --desktop を実行しました。結果はそのウインドウに表示されます。'
      : 'ターミナルを開きました。',
  });
}

// ---------------------------------------------------------------- http

async function serve(res, file, mime) {
  try {
    const data = await readFile(file);
    res.writeHead(200, { 'Content-Type': mime, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' });
    res.end(data);
  } catch { json(res, 404, { error: 'File not found. Run npm install if markdown renderer is missing.' }); }
}

async function requestHandler(req, res) {
  res.setHeader('Content-Security-Policy', "default-src 'none'; connect-src 'self'; style-src 'self'; script-src 'self'; img-src 'self' data:; font-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'");
  res.setHeader('Referrer-Policy', 'no-referrer');
  res.setHeader('X-Frame-Options', 'DENY');
  const port = server.address()?.port;
  const host = req.headers.host || '';
  if (host !== '127.0.0.1:' + port && host !== 'localhost:' + port) return json(res, 403, { error: 'Invalid host.' });
  const origin = req.headers.origin;
  if (origin && !['http://127.0.0.1:' + port, 'http://localhost:' + port].includes(origin)) return json(res, 403, { error: 'Invalid origin.' });
  const url = new URL(req.url, 'http://' + host);
  const pathname = url.pathname;
  try {
    if (req.method === 'GET' && pathname === '/') return await serve(res, path.join(WEB, 'index.html'), 'text/html; charset=utf-8');
    if (req.method === 'GET' && pathname === '/app.js') return await serve(res, path.join(WEB, 'app.js'), 'application/javascript; charset=utf-8');
    if (req.method === 'GET' && pathname === '/style.css') return await serve(res, path.join(WEB, 'style.css'), 'text/css; charset=utf-8');
    if (req.method === 'GET' && pathname === '/vendor/markdown-it.min.js') return await serve(res, path.join(HERE, 'node_modules', 'markdown-it', 'dist', 'markdown-it.min.js'), 'application/javascript; charset=utf-8');
    if (req.method === 'GET' && pathname === '/api/state') return json(res, 200, currentState());
    if (req.method === 'GET' && pathname === '/api/events') return handleEvents(req, res, url);
    if (req.method === 'GET' && pathname === '/api/sessions') return await handleSessionList(req, res);
    if (req.method === 'POST' && pathname === '/api/sessions/open') return await handleSessionOpen(req, res);
    if (req.method === 'POST' && pathname === '/api/handoff') return await handleHandoff(req, res);
    if (req.method === 'POST' && pathname === '/api/projects/select') return await handleProjectSelect(req, res);
    if (req.method === 'POST' && pathname === '/api/projects/pick') return await handleProjectPick(req, res);
    if (req.method === 'POST' && pathname === '/api/projects/remove') return await handleProjectRemove(req, res);
    if (req.method === 'POST' && pathname === '/api/run') return await handleRun(req, res);
    if (req.method === 'POST' && pathname === '/api/approval') return await handleApproval(req, res);
    if (req.method === 'POST' && pathname === '/api/settings') return await handleSettings(req, res);
    if (req.method === 'POST' && pathname === '/api/new') return await handleNew(req, res);
    if (req.method === 'POST' && pathname === '/api/stop') return await handleStop(req, res);
    json(res, 404, { error: 'Not found.' });
  } catch (e) {
    if (!e.statusCode) console.error('[Server]', safeError(e));
    if (!res.headersSent) json(res, e.statusCode || 500, { error: safeError(e) });
    else res.end();
  }
}

function openBrowser(url) {
  if (process.env.CHAT_WEB_NO_BROWSER === '1') return;
  try {
    if (process.platform === 'win32') {
      const child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', "Start-Process '" + url + "'"], { stdio: 'ignore', windowsHide: true, detached: true });
      child.unref();
    } else if (process.platform === 'darwin') {
      spawn('open', [url], { stdio: 'ignore', detached: true }).unref();
    } else {
      spawn('xdg-open', [url], { stdio: 'ignore', detached: true }).unref();
    }
  } catch { console.log('Open this URL in your browser: ' + url); }
}

if (!TEST_MODE) {
  keyFile = KEY_FILE_CANDIDATES.find(candidate => existsSync(candidate)) || '';
  if (!keyFile) {
    console.error('API key file is missing. Save the key to one of:');
    for (const candidate of KEY_FILE_CANDIDATES) console.error('  ' + candidate);
    process.exit(1);
  }
  apiKey = (await readFile(keyFile, 'utf8')).trim();
  if (!apiKey) { console.error('API key file is empty.'); process.exit(1); }
}
await loadState();
const server = http.createServer(requestHandler);
server.listen(Number(process.env.CHAT_WEB_PORT) || 0, HOST, () => {
  const url = 'http://' + HOST + ':' + server.address().port;
  console.log('===========================================');
  console.log('Claude Agent SDK - Local Web Chat');
  console.log('===========================================');
  console.log('Project:', currentProject);
  console.log('Open:', url);
  console.log(TEST_MODE ? 'TEST MODE: no API calls are made.' : 'API key: loaded (not displayed)');
  console.log('To stop: close this terminal or press Ctrl+C.');
  openBrowser(url);
});

for (const sig of ['SIGINT', 'SIGTERM']) {
  process.on(sig, () => { denyOutstanding(); currentAbort?.abort(); server.close(() => process.exit(0)); });
}

web\index.html

<!doctype html>
<html lang="ja">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta name="color-scheme" content="dark" />
  <title>Claude Agent Chat — ローカルワークスペース</title>
  <link rel="stylesheet" href="/style.css" />
  <script defer src="/vendor/markdown-it.min.js"></script>
  <script defer src="/app.js"></script>
</head>
<body>
  <div class="app">
    <aside class="sidebar" id="sidebar">
      <div class="brand"><div class="brand-symbol">✦</div><div><strong>Claude Agent</strong><small>LOCAL WORKSPACE</small></div></div>
      <button class="new-chat" id="newChat"><span class="plus">+</span> 新しい会話</button>
      <div class="side-section-title">作業スペース</div>
      <button class="workspace workspace-button" id="projectSwitch" title="作業フォルダを切り替える">
        <span class="workspace-icon">▣</span>
        <span class="workspace-info"><strong id="projectName">プロジェクト</strong><small id="projectPath">作業フォルダを選択</small></span>
        <span class="workspace-chevron">⌄</span>
      </button>
      <div class="side-section-title">会話の履歴(このフォルダ)</div>
      <div class="session-list" id="sessionList" aria-label="このフォルダの会話の履歴"></div>
      <div class="side-section-title recent-title">最近使ったプロジェクト</div>
      <div class="recent-list" id="recentProjects" aria-label="最近使ったプロジェクト"></div>
      <div class="side-section-title">利用モード</div>
      <div class="mode-info"><span class="info-dot"></span><span id="sideMode">Autoモード</span></div>
      <div class="sidebar-bottom">
        <button class="notify-button" id="notifyButton" type="button">🔔 完了を通知する</button>
        <div class="private-note">⌁ この画面はお使いのPCの中だけで動きます。サーバーは127.0.0.1に限定しています。</div>
        <div class="sidebar-version">Agent SDK · Web UI v4</div>
      </div>
    </aside>

    <main class="main">
      <header class="topbar">
        <button class="menu-toggle" id="menuToggle" aria-label="メニューを開く">☰</button>
        <div class="top-title"><strong>チャット</strong><small id="sessionLabel">新しい会話</small><small class="cost-label" id="costLabel"></small></div>
        <div class="top-actions">
          <details class="handoff hidden" id="handoff">
            <summary>サブスク側で続ける ▾</summary>
            <div class="handoff-menu">
              <button type="button" id="handoffDesktop"><strong>デスクトップアプリで開く</strong><small>claude --desktop --resume を実行します</small></button>
              <button type="button" id="handoffTerminal"><strong>ターミナルで開く</strong><small>このフォルダで claude --resume を実行します</small></button>
              <button type="button" id="handoffCopy"><strong>コマンドをコピー</strong><small>claude --resume と会話のID</small></button>
            </div>
          </details>
          <span class="status"><span class="status-dot" id="statusDot"></span><span id="statusText">準備完了</span></span>
        </div>
      </header>
      <div class="banner hidden" id="banner" role="status"></div>

      <div class="chat-scroll" id="chatScroll">
        <div class="chat-content" id="chatContent"></div>
      </div>

      <div class="composer-area">
        <div class="composer-wrap">
          <div class="composer-toolbar">
            <div class="selector-group"><label for="modelSelect">モデル</label><select id="modelSelect"><option value="claude-fable-5-2">Fable 5.2</option><option value="claude-opus-5-5">Opus 5.5</option><option value="claude-sonnet-5-5">Sonnet 5.5</option><option value="claude-haiku-5-5">Haiku 5.5</option><option value="custom">カスタムID…</option></select></div>
            <div class="selector-group"><label for="modeSelect">権限</label><select id="modeSelect"><option value="auto">Auto</option><option value="default">手動承認</option></select></div>
          </div>
          <div class="composer" id="composer" aria-label="ここに画像をドラッグして添付できます">
            <div class="attachment-list hidden" id="attachmentList" aria-live="polite"></div>
            <textarea id="prompt" rows="2" placeholder="Claudeへの指示を入力…" aria-label="メッセージを入力"></textarea>
            <div class="composer-footer"><span class="helptext"><kbd>Enter</kbd> 送信 <span class="separator">·</span> <kbd>Shift + Enter</kbd> 改行 <span class="separator">·</span> <kbd>Ctrl + V</kbd> 画像貼付</span><div class="send-actions"><input id="imageFileInput" type="file" class="hidden" accept="image/png,image/jpeg,image/gif,image/webp" multiple aria-label="画像ファイルを選択" /><button class="attach-button" id="attachButton" type="button" title="画像を添付" aria-label="画像を添付">📎</button><button class="stop-button hidden" id="stopButton">停止</button><button class="send-button" id="sendButton" aria-label="送信">➤</button></div></div>
          </div>
          <p class="footnote">画像は貼り付け・ドラッグ&ドロップ・📎ボタンに対応(PNG/JPEG/GIF/WebP、最大4枚・各5MB) · タブを閉じても作業は続きます</p>
        </div>
      </div>
    </main>
  </div>

  <div class="modal-backdrop hidden" id="projectModal" role="dialog" aria-modal="true" aria-labelledby="projectModalTitle">
    <div class="modal project-modal">
      <div class="modal-eyebrow">ワークスペース</div>
      <h2 id="projectModalTitle">作業フォルダを選択</h2>
      <p>切り替えたフォルダがClaudeの作業対象になります。プロジェクトごとに会話履歴・モデル・承認モードを保存します。</p>
      <button class="folder-picker-button" id="projectPick">▣ Windowsのフォルダ選択画面を開く</button>
      <div class="path-divider">または絶対パスを入力</div>
      <label for="projectPathInput" class="path-label">フォルダのパス</label>
      <input id="projectPathInput" type="text" placeholder="D:\work\my-project" autocomplete="off" spellcheck="false" />
      <div class="modal-actions"><button class="secondary-button" id="projectCancel">キャンセル</button><button class="primary-button" id="projectApply">このフォルダを開く</button></div>
      <p class="project-hint" id="projectHint">※ 切り替えてもプロジェクトのファイルや過去の会話履歴は削除されません。</p>
    </div>
  </div>
  <div class="modal-backdrop hidden" id="customModal" role="dialog" aria-modal="true" aria-labelledby="customTitle">
    <div class="modal small-modal"><div class="modal-eyebrow">モデル設定</div><h2 id="customTitle">モデルIDを指定</h2><p>Anthropic APIで利用可能なモデルIDを入力してください。</p><input id="customModelInput" type="text" placeholder="claude-..." maxlength="120" /><div class="modal-actions"><button class="secondary-button" id="customCancel">キャンセル</button><button class="primary-button" id="customSave">適用する</button></div></div>
  </div>
  <div class="modal-backdrop hidden" id="approvalModal" role="dialog" aria-modal="true" aria-labelledby="approvalTitle">
    <div class="modal approval-modal"><div class="modal-eyebrow">実行前の確認</div><h2 id="approvalTitle">この操作を許可しますか?</h2><p id="approvalDescription">Claudeが操作の承認を求めています。</p><div class="tool-heading" id="approvalTool"></div><div id="approvalQuestions"></div><details class="approval-details" open><summary>実行内容の詳細</summary><pre id="approvalInput"></pre></details><div class="modal-actions"><button class="secondary-button" id="approvalDeny">拒否する</button><button class="secondary-button hidden" id="approvalAlways" title="このフォルダの .claude/settings.local.json に許可ルールを保存します">今後も許可(このフォルダ)</button><button class="primary-button" id="approvalAllow">今回だけ許可</button></div><p class="approval-tip">Autoで拒否される操作は、手動承認モードに切り替えて再度指示してください。</p></div>
  </div>
  <div class="toast hidden" id="toast" role="status"></div>
</body>
</html>

web\app.js

(() => {
  'use strict';
  const $ = (id) => document.getElementById(id);
  const node = {
    chat: $('chatContent'), scroll: $('chatScroll'),
    prompt: $('prompt'), send: $('sendButton'), stop: $('stopButton'),
    model: $('modelSelect'), mode: $('modeSelect'),
    status: $('statusText'), statusDot: $('statusDot'),
    newChat: $('newChat'), sessionLabel: $('sessionLabel'), costLabel: $('costLabel'),
    customModal: $('customModal'), customInput: $('customModelInput'),
    approvalModal: $('approvalModal'), approvalTool: $('approvalTool'),
    approvalInput: $('approvalInput'), approvalDescription: $('approvalDescription'),
    approvalQuestions: $('approvalQuestions'), approvalAlways: $('approvalAlways'),
    approvalTitle: $('approvalTitle'), toast: $('toast'),
    projectSwitch: $('projectSwitch'), projectModal: $('projectModal'),
    projectPick: $('projectPick'), projectApply: $('projectApply'),
    projectCancel: $('projectCancel'), projectPathInput: $('projectPathInput'),
    recentProjects: $('recentProjects'), sessionList: $('sessionList'),
    composer: $('composer'), attachmentList: $('attachmentList'),
    attach: $('attachButton'), imageInput: $('imageFileInput'),
    handoff: $('handoff'), banner: $('banner'), notify: $('notifyButton'),
  };

  const md = typeof window.markdownit === 'function'
    ? window.markdownit({ html: false, linkify: true, breaks: true, typographer: false })
    : null;
  if (md) {
    const oldLinkOpen = md.renderer.rules.link_open || ((tokens, i, options, env, self) => self.renderToken(tokens, i, options));
    md.renderer.rules.link_open = (tokens, i, options, env, self) => {
      tokens[i].attrSet('target', '_blank');
      tokens[i].attrSet('rel', 'noopener noreferrer');
      return oldLinkOpen(tokens, i, options, env, self);
    };
  }
  let running = false;
  let currentModel = 'claude-fable-5-2';
  let currentMode = 'auto';
  let currentSessionId = null;
  let approval = null;
  let toastTimer = null;
  let switching = false;
  let activeProjectPath = '';
  let baseTitle = 'Claude Agent Chat';
  let live = null; // the assistant message that is being written right now
  const projectDrafts = new Map();
  const MAX_IMAGES = 4;
  const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
  const IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']);
  const BIG_SESSION_BYTES = 3 * 1024 * 1024;
  let attachments = [];
  let readingImages = false;

  async function post(url, body) {
    const r = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
    const out = await r.json();
    if (!r.ok) throw new Error(out.error || 'HTTP ' + r.status);
    return out;
  }
  function toast(message) {
    node.toast.textContent = message;
    node.toast.classList.remove('hidden');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(() => node.toast.classList.add('hidden'), 3300);
  }
  function showBanner(message) {
    node.banner.textContent = message;
    node.banner.classList.toggle('hidden', !message);
  }
  function setStatus(s, working = false) {
    node.status.textContent = s;
    node.statusDot.classList.toggle('working', working);
  }
  function setRunning(value) {
    running = value;
    // Sending stays possible during a run: the message goes to the running agent.
    node.prompt.placeholder = value
      ? '作業中でも送れます(今のツールの実行が終わったあとに Claude へ届きます)'
      : 'Claudeへの指示を入力…';
    node.stop.classList.toggle('hidden', !value);
    node.model.disabled = value;
    node.mode.disabled = value;
    node.newChat.disabled = value;
    node.projectSwitch.disabled = value;
    for (const button of document.querySelectorAll('#recentProjects button, #sessionList button, #handoff button')) button.disabled = value;
    setStatus(value ? '作業中…' : '準備完了', value);
  }
  function autoScroll(force = false) {
    const el = node.scroll;
    if (force || el.scrollHeight - el.scrollTop - el.clientHeight < 300) {
      requestAnimationFrame(() => { el.scrollTop = el.scrollHeight; });
    }
  }
  function setModelUI(id) {
    currentModel = id;
    for (const e of [...node.model.options]) {
      if (e.dataset.userModel === 'yes') e.remove();
    }
    const predefined = [...node.model.options].some(o => o.value === id);
    if (!predefined) {
      const option = new Option(id, id);
      option.dataset.userModel = 'yes';
      node.model.add(option, node.model.querySelector('option[value="custom"]'));
    }
    node.model.value = id;
  }
  function setModeUI(mode) {
    currentMode = mode;
    node.mode.value = mode;
    $('sideMode').textContent = mode === 'auto' ? 'Autoモード' : '手動承認モード';
  }
  function setSession(id, cost) {
    currentSessionId = id || null;
    node.handoff.classList.toggle('hidden', !currentSessionId);
    node.sessionLabel.textContent = currentSessionId ? '会話を継続中' : '新しい会話';
    node.costLabel.textContent = Number(cost) > 0 ? 'この会話の費用(参考) $' + Number(cost).toFixed(Number(cost) < 0.1 ? 4 : 2) : '';
  }
  function el(tag, className, text) {
    const e = document.createElement(tag);
    if (className) e.className = className;
    if (text !== undefined) e.textContent = text;
    return e;
  }
  function clearMessages() {
    node.chat.replaceChildren();
    const welcome = el('section', 'welcome');
    welcome.append(el('div', 'welcome-icon', '✦'), el('h1', '', '何から始めましょうか?'),
      el('p', '', 'フォルダの調査、設計の相談、ファイルの編集まで。左の「会話の履歴」から、前の会話の続きもできます。'));
    const suggestions = el('div', 'suggestions');
    for (const [label, example] of [
      ['フォルダの構成を確認', 'このフォルダの現在の構成を確認して、概要を説明してください。'],
      ['前回の続きを確認', 'この会話でここまでにやったことと、残っている作業を整理してください。'],
    ]) {
      const b = el('button', 'suggestion', label);
      b.addEventListener('click', () => { node.prompt.value = example; resizeInput(); node.prompt.focus(); });
      suggestions.append(b);
    }
    welcome.append(suggestions);
    node.chat.append(welcome);
  }

  // ------------------------------------------------------------ messages

  // An assistant message is a "flow": text, tool calls and notices are
  // appended in the order they happen, so the newest thing is always at the
  // bottom and the final answer comes last.
  function createMessage(role, selectedModel) {
    const w = node.chat.querySelector('.welcome');
    if (w) w.remove();
    const wrap = el('article', 'message ' + (role === 'user' ? 'message-user' : 'message-ai'));
    const avatar = el('div', 'avatar ' + (role === 'user' ? 'avatar-user' : 'avatar-ai'), role === 'user' ? '人' : '✦');
    const body = el('div', 'message-body');
    const header = el('div', 'message-header');
    header.append(el('strong', '', role === 'user' ? 'あなた' : 'Claude'), el('small', '', role === 'user' ? '' : (selectedModel || '')));
    const flow = el('div', role === 'user' ? 'message-text user-text' : 'flow');
    const actions = el('div', 'message-actions');
    const copy = el('button', 'copy-button', 'コピー');
    actions.append(copy);
    body.append(header, flow, actions);
    wrap.append(avatar, body);
    node.chat.append(wrap);
    const message = { wrap, flow, header, copy, model: selectedModel, text: '', segment: null, segmentText: '', timer: null, tools: new Map() };
    copy.addEventListener('click', async () => {
      try { await navigator.clipboard.writeText(message.text); toast('コピーしました'); }
      catch { toast('コピーできませんでした'); }
    });
    return message;
  }
  function renderMarkdown(target, text) {
    if (md) target.innerHTML = md.render(text || '');
    else target.textContent = text || '';
  }
  function flushText(message) {
    if (message.timer) { clearTimeout(message.timer); message.timer = null; }
    if (message.segment) renderMarkdown(message.segment, message.segmentText);
  }
  function closeText(message) {
    flushText(message);
    if (message.segment && !message.segmentText.trim()) message.segment.remove();
    message.segment = null;
    message.segmentText = '';
  }
  function place(message, element) {
    // Keep the "working" line as the last child while a run is in progress.
    if (message.working && message.working.parentNode === message.flow) message.flow.insertBefore(element, message.working);
    else message.flow.append(element);
  }
  function flowText(message, delta, immediate) {
    if (!delta) return;
    if (!message.segment) {
      if (!delta.trim()) return;
      message.segment = el('div', 'message-text markdown');
      place(message, message.segment);
    }
    message.segmentText += delta;
    message.text += delta;
    if (immediate) return flushText(message);
    if (!message.timer) message.timer = setTimeout(() => { message.timer = null; flushText(message); autoScroll(); }, 65);
  }
  function flowTool(message, part) {
    closeText(message);
    const details = el('details', 'tool-chip');
    const summary = el('summary');
    const mark = el('span', 'tool-mark', '◈');
    summary.append(mark, document.createTextNode(' ' + (part.sub ? '(サブエージェント) ' : '') + (part.name || 'Tool')));
    let input = part.input;
    if (typeof input !== 'string') {
      try { input = JSON.stringify(input || {}, null, 2); } catch { input = String(input); }
      if (input.length > 4000) input = input.slice(0, 4000) + '\n…(以下省略)';
    }
    details.append(summary, el('pre', '', input));
    place(message, details);
    const chip = { details, mark };
    if (part.id) message.tools.set(part.id, chip);
    if (part.status) markTool(chip, part.status === 'error');
    return chip;
  }
  function markTool(chip, isError) {
    chip.mark.textContent = isError ? '✕' : '✓';
    chip.details.classList.add(isError ? 'tool-error' : 'tool-ok');
  }
  function flowNotice(message, text) {
    closeText(message);
    place(message, el('div', 'notice', text));
  }
  function flowResult(message, event) {
    closeText(message);
    const line = el('div', 'result-line');
    // A result that is not the last one: Claude goes on to a message sent during the run.
    if (event.success && event.final === false) line.append(el('span', '', '↓ 途中で送られた指示に、続けて対応します'));
    else line.append(el('span', event.success ? 'success' : 'failure', event.success ? '✓ 完了' : '⚠ 処理が正常終了していません'));
    if (Number.isFinite(Number(event.cost)) && event.cost !== null) {
      line.append(el('span', '', 'この回の費用 $' + Number(event.cost).toFixed(4) + '(SDKの報告値・参考)'));
    }
    line.append(el('span', '', new Date().toLocaleTimeString('ja-JP', { hour: '2-digit', minute: '2-digit' }) + ' 終了'));
    place(message, line);
    if (event.denials?.length) flowNotice(message, event.denials.length + '件の操作が拒否されました。Autoモードの場合は手動承認に切り替え、再度依頼してください。');
    if (event.errors?.length) flowNotice(message, event.errors.join('\n'));
  }
  function renderMessageImages(container, images) {
    if (!images?.length) return;
    const grid = el('div', 'message-image-grid');
    for (const image of images) {
      if (image.preview && /^data:image\/(jpeg|png|webp);base64,/.test(image.preview)) {
        const img = document.createElement('img');
        img.src = image.preview;
        img.alt = image.name || '添付画像';
        img.title = image.name || '';
        grid.append(img);
      } else {
        grid.append(el('span', 'message-image-fallback', '🖼 ' + (image.name || '添付画像')));
      }
    }
    container.append(grid);
  }
  function addUser(text, images, duringRun) {
    const m = createMessage('user');
    if (duringRun) m.header.querySelector('small').textContent = '作業中に追加';
    m.flow.textContent = text;
    m.text = text;
    renderMessageImages(m.flow, images);
    return m;
  }
  // A message sent during a run: end the assistant message shown so far, show
  // the user message, and continue the run in a new assistant message below it.
  function splitLive(ev) {
    const old = live;
    closeText(old);
    const working = old.working;
    old.working = null;
    if (working) working.remove();
    if (!old.flow.childElementCount) old.wrap.remove();
    addUser(ev.text || '', ev.images, true);
    const next = createMessage('assistant', old.model);
    next.tools = old.tools; // results of tools started above still find their chip
    if (working) { next.working = working; next.flow.append(working); }
    live = next;
    autoScroll(true);
  }
  function addPast(entry) {
    if (entry.role === 'user') return addUser(entry.text, entry.images);
    const m = createMessage('assistant', entry.model);
    if (Array.isArray(entry.parts) && entry.parts.length) {
      for (const part of entry.parts) {
        if (part.type === 'text') { flowText(m, part.text, true); closeText(m); }
        else if (part.type === 'tool') flowTool(m, part);
        else if (part.type === 'notice') flowNotice(m, part.text || '');
      }
    } else {
      flowText(m, entry.text, true);
      closeText(m);
    }
    m.text = entry.text || m.text;
    if (entry.cost !== null && entry.cost !== undefined && Number.isFinite(Number(entry.cost))) {
      const line = el('div', 'result-line');
      line.append(el('span', entry.success === false ? 'failure' : 'success', entry.success === false ? '⚠ 正常終了していません' : '✓ 完了'),
        el('span', '', 'この回の費用 $' + Number(entry.cost).toFixed(4) + '(参考)'));
      m.flow.append(line);
    }
    return m;
  }

  // ------------------------------------------------------------ attachments

  function renderAttachments() {
    node.attachmentList.replaceChildren();
    node.attachmentList.classList.toggle('hidden', !attachments.length);
    attachments.forEach((attachment, index) => {
      const item = el('div', 'attachment-item');
      const img = document.createElement('img');
      img.src = attachment.preview || 'data:' + attachment.mimeType + ';base64,' + attachment.data;
      img.alt = attachment.name;
      const remove = el('button', 'attachment-remove', '×');
      remove.type = 'button';
      remove.title = attachment.name + ' を削除';
      remove.setAttribute('aria-label', remove.title);
      remove.addEventListener('click', () => { attachments.splice(index, 1); renderAttachments(); });
      item.append(img, el('span', 'attachment-name', attachment.name), remove);
      node.attachmentList.append(item);
    });
  }
  function readDataURL(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => resolve(String(reader.result));
      reader.onerror = () => reject(new Error('画像を読み取れませんでした。'));
      reader.readAsDataURL(file);
    });
  }
  function imagePreview(file) {
    return new Promise(resolve => {
      const src = URL.createObjectURL(file);
      const img = new Image();
      const cleanup = () => URL.revokeObjectURL(src);
      img.onload = () => {
        try {
          const ratio = Math.min(1, 240 / Math.max(img.naturalWidth, img.naturalHeight));
          const canvas = document.createElement('canvas');
          canvas.width = Math.max(1, Math.round(img.naturalWidth * ratio));
          canvas.height = Math.max(1, Math.round(img.naturalHeight * ratio));
          const ctx = canvas.getContext('2d');
          ctx.fillStyle = '#ffffff'; ctx.fillRect(0, 0, canvas.width, canvas.height);
          ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
          resolve(canvas.toDataURL('image/jpeg', 0.72));
        } catch { resolve(''); }
        cleanup();
      };
      img.onerror = () => { cleanup(); resolve(''); };
      img.src = src;
    });
  }
  async function addImages(files) {
    if (switching || readingImages) return;
    const images = [...files];
    if (!images.length) return;
    if (attachments.length + images.length > MAX_IMAGES) return toast('画像は最大' + MAX_IMAGES + '枚です。');
    readingImages = true;
    node.attach.disabled = true;
    try {
      for (const file of images) {
        if (!IMAGE_TYPES.has(file.type)) { toast('PNG・JPEG・GIF・WebPだけ添付できます。'); continue; }
        if (!file.size || file.size > MAX_IMAGE_BYTES) { toast((file.name || '画像') + ' は5MB以下にしてください。'); continue; }
        const url = await readDataURL(file);
        const data = url.slice(url.indexOf(',') + 1);
        const preview = await imagePreview(file);
        attachments.push({ name: file.name || '貼り付け画像', mimeType: file.type, data, preview });
      }
      renderAttachments();
      node.prompt.focus();
    } catch (e) { toast('画像の添付に失敗: ' + e.message); }
    finally { readingImages = false; node.attach.disabled = switching; }
  }
  function resizeInput() {
    node.prompt.style.height = 'auto';
    node.prompt.style.height = Math.min(Math.max(node.prompt.scrollHeight, 55), 230) + 'px';
  }

  // ------------------------------------------------------------ approvals

  function showApproval(ev) {
    approval = ev;
    const isQuestion = ev.toolName === 'AskUserQuestion';
    node.approvalTitle.textContent = isQuestion ? 'Claudeからの質問' : 'この操作を許可しますか?';
    node.approvalTool.textContent = '◈ ' + ev.toolName;
    node.approvalTool.classList.toggle('hidden', isQuestion);
    node.approvalDescription.textContent = isQuestion
      ? '選択肢を選ぶか、自由に入力して回答してください。'
      : (ev.reason || '実行内容を確認し、許可または拒否を選択してください。');
    node.approvalInput.textContent = JSON.stringify(ev.input || {}, null, 2);
    node.approvalInput.parentElement.open = !isQuestion;
    node.approvalAlways.classList.toggle('hidden', !ev.canRemember);
    $('approvalAllow').textContent = isQuestion ? '回答する' : '今回だけ許可';
    $('approvalDeny').textContent = isQuestion ? '答えない' : '拒否する';
    node.approvalQuestions.replaceChildren();
    if (Array.isArray(ev.questions)) {
      for (const q of ev.questions) {
        const block = el('div', 'question-block');
        block.dataset.question = q.question;
        block.dataset.multi = q.multiSelect ? 'yes' : 'no';
        block.append(el('div', 'question-label', q.question));
        const options = el('div', 'question-options');
        for (const o of (Array.isArray(q.options) ? q.options : [])) {
          const b = el('button', 'question-option');
          b.type = 'button';
          b.dataset.label = o.label;
          b.append(el('strong', '', o.label));
          if (o.description) b.append(el('small', '', o.description));
          b.addEventListener('click', () => {
            if (!q.multiSelect) for (const other of options.children) if (other !== b) other.classList.remove('selected');
            b.classList.toggle('selected');
          });
          options.append(b);
        }
        const input = el('input', 'question-answer');
        input.type = 'text';
        input.placeholder = 'その他(自由に入力)';
        block.append(options, input);
        node.approvalQuestions.append(block);
      }
    }
    node.approvalModal.classList.remove('hidden');
    if (document.hidden) document.title = '● 確認待ち — ' + baseTitle;
  }
  function hideApproval(requestId) {
    if (approval && (!requestId || approval.requestId === requestId)) {
      approval = null;
      node.approvalModal.classList.add('hidden');
    }
  }
  async function submitApproval(decision) {
    if (!approval) return;
    const ev = approval;
    const answers = {};
    if (decision !== 'deny' && Array.isArray(ev.questions)) {
      for (const block of node.approvalQuestions.querySelectorAll('.question-block')) {
        const typed = block.querySelector('input').value.trim();
        const labels = [...block.querySelectorAll('.question-option.selected')].map(b => b.dataset.label);
        const answer = typed ? (labels.length && block.dataset.multi === 'yes' ? labels.concat(typed).join(', ') : typed) : labels.join(', ');
        if (!answer) return toast('質問に回答してください');
        answers[block.dataset.question] = answer;
      }
    }
    try {
      await post('/api/approval', { requestId: ev.requestId, decision, answers });
      hideApproval(ev.requestId);
    } catch (e) { toast('承認エラー: ' + e.message); hideApproval(ev.requestId); }
  }

  // ------------------------------------------------------------ a run

  function startLive(selectedModel) {
    const message = createMessage('assistant', selectedModel);
    message.working = el('div', 'thinking');
    message.working.append(el('span', 'spinner'), el('span', 'working-text', 'Claudeが考えています…'));
    message.flow.append(message.working);
    live = message;
    setRunning(true);
    autoScroll(true);
    return message;
  }
  function setWorking(text) {
    if (live?.working) live.working.querySelector('.working-text').textContent = text;
  }
  function handleEvent(ev) {
    if (!live) return;
    if (ev.type === 'text') { flowText(live, ev.text || ''); setWorking('回答を書いています…'); }
    else if (ev.type === 'tool_start') setWorking((ev.name || 'ツール') + ' を準備しています…');
    else if (ev.type === 'tool') { flowTool(live, ev); setWorking((ev.name || 'ツール') + ' を実行しています…'); }
    else if (ev.type === 'tool_result') {
      const chip = live.tools.get(ev.id);
      if (chip) markTool(chip, ev.isError);
      setWorking('Claudeが考えています…');
    }
    else if (ev.type === 'approval') { showApproval(ev); setWorking('あなたの確認を待っています…'); }
    else if (ev.type === 'approval_closed') { hideApproval(ev.requestId); setWorking('Claudeが考えています…'); }
    else if (ev.type === 'user_message') splitLive(ev);
    else if (ev.type === 'notice') flowNotice(live, ev.message || '');
    else if (ev.type === 'error') flowNotice(live, 'エラー: ' + ev.message);
    else if (ev.type === 'result') flowResult(live, ev);
    autoScroll();
  }
  function finishLive(doneEvent) {
    const message = live;
    live = null;
    if (message) {
      closeText(message);
      if (message.working) message.working.remove();
      message.working = null;
      if (!message.flow.childElementCount) message.flow.append(el('div', 'notice', '回答がありませんでした。'));
      message.wrap.classList.add('just-finished');
    }
    hideApproval();
    setRunning(false);
    if (doneEvent) setSession(doneEvent.sessionId || currentSessionId, doneEvent.totalCost);
    autoScroll(true);
    node.prompt.focus();
    if (document.hidden) {
      document.title = '✓ 完了 — ' + baseTitle;
      if ('Notification' in window && Notification.permission === 'granted') {
        try { new Notification('Claude Agent: 作業が終わりました', { body: baseTitle }); } catch { /* ignore */ }
      }
    }
    loadSessions();
  }
  // Read the events of a run. If the connection drops, reconnect and continue
  // from the number of events already shown.
  async function attachRun(runId) {
    let seen = 0;
    let failures = 0;
    while (true) {
      let doneEvent = null;
      try {
        const response = await fetch('/api/events?run=' + encodeURIComponent(runId) + '&after=' + seen);
        if (response.status === 404) { await refreshState(); return; }
        if (!response.ok) throw new Error('HTTP ' + response.status);
        failures = 0;
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let unparsed = '';
        while (true) {
          const { done, value } = await reader.read();
          if (done) break;
          unparsed += decoder.decode(value, { stream: true });
          const lines = unparsed.split('\n');
          unparsed = lines.pop();
          for (const line of lines) {
            if (!line.trim()) continue;
            let ev;
            try { ev = JSON.parse(line); } catch { continue; }
            seen += 1;
            if (ev.type === 'done') doneEvent = ev;
            else handleEvent(ev);
          }
        }
      } catch (e) {
        failures += 1;
        if (failures > 20) {
          if (live) flowNotice(live, 'サーバーに接続できません: ' + e.message);
          return finishLive(null);
        }
      }
      if (doneEvent) return finishLive(doneEvent);
      setWorking('再接続しています…');
      await new Promise(r => setTimeout(r, 1000));
    }
  }
  let sending = false;
  async function send() {
    if (switching || sending) return;
    if (readingImages) return toast('画像の読み込みが終わってから送信してください。');
    const prompt = node.prompt.value.trim();
    if (!prompt && !attachments.length) return;
    const images = attachments.slice();
    const submittedText = prompt || '添付画像を確認してください。';
    if (running) {
      // Hand the message to the running agent. It appears in the chat when the
      // server reports it back through the event stream.
      sending = true;
      try {
        for (let attempt = 0; running && attempt < 20; attempt += 1) {
          const r = await fetch('/api/run', {
            method: 'POST', headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ prompt: submittedText, images }),
          });
          const out = await r.json();
          if (r.ok) {
            node.prompt.value = ''; attachments = []; renderAttachments(); resizeInput();
            return;
          }
          if (!out.retry) return toast('送信できませんでした: ' + (out.error || 'HTTP ' + r.status));
          // The run is just ending: wait, then send it as a normal message.
          await new Promise(resolve => setTimeout(resolve, 300));
        }
      } catch (e) { return toast('送信できませんでした: ' + e.message); }
      finally { sending = false; }
      if (running) return toast('送信できませんでした。少し待ってからもう一度送ってください。');
    }
    setRunning(true);
    let started;
    try {
      started = await post('/api/run', { prompt: submittedText, images, model: currentModel, mode: currentMode });
    } catch (e) {
      setRunning(false);
      return toast('送信できませんでした: ' + e.message);
    }
    node.prompt.value = ''; attachments = []; renderAttachments(); resizeInput();
    addUser(submittedText, images);
    startLive(currentModel);
    attachRun(started.runId);
  }

  // ------------------------------------------------------------ sessions

  function when(ms) {
    const d = new Date(ms);
    const today = new Date();
    const time = d.toLocaleTimeString('ja-JP', { hour: '2-digit', minute: '2-digit' });
    if (d.toDateString() === today.toDateString()) return '今日 ' + time;
    return (d.getMonth() + 1) + '/' + d.getDate() + ' ' + time;
  }
  async function openSession(session, quiet) {
    if (running || switching) return toast('処理中は切り替えできません');
    if (!quiet && !session.current && session.fileSize > BIG_SESSION_BYTES &&
        !confirm('長い会話です。APIクレジットで続けると、最初の1回は会話全体を読み直すぶんの費用がかかります。開きますか?')) return;
    try {
      const state = await post('/api/sessions/open', { sessionId: session.id });
      applyState(state);
      if (!quiet) toast(state.truncated ? '会話を開きました(画面には新しいほうから一部だけ表示)' : '会話を開きました');
      $('sidebar').classList.remove('open');
      loadSessions();
    } catch (e) { toast('開けませんでした: ' + e.message); }
  }
  async function loadSessions() {
    let data;
    try {
      const r = await fetch('/api/sessions');
      if (!r.ok) throw new Error('HTTP ' + r.status);
      data = await r.json();
    } catch { return; }
    node.sessionList.replaceChildren();
    if (!data.sessions.length) node.sessionList.append(el('div', 'session-empty', 'このフォルダの会話はまだありません'));
    for (const s of data.sessions) {
      const b = el('button', 'session-item' + (s.current ? ' active' : ''));
      b.type = 'button';
      b.disabled = running || switching;
      b.title = s.title + '\n' + s.id + (s.current ? '\n(クリックで読み込み直す)' : '');
      b.append(el('strong', '', s.title), el('small', '', when(s.lastModified) + (s.current ? ' · 表示中' : '')));
      b.addEventListener('click', () => openSession(s, false));
      node.sessionList.append(b);
    }
    // The desktop app or the terminal continued this session: show their part too.
    const current = data.sessions.find(s => s.current);
    if (current?.changedOutside && !running) {
      await openSession(current, true);
      toast('ほかのアプリで進んだ分を読み込みました');
    }
  }
  async function handoff(target) {
    if (!currentSessionId) return;
    if (running) return toast('作業が終わってから引き継いでください');
    node.handoff.open = false;
    if (target === 'copy') {
      try { await navigator.clipboard.writeText('claude --resume ' + currentSessionId); toast('コマンドをコピーしました(このフォルダのターミナルで実行)'); }
      catch { toast('コピーできませんでした'); }
      return;
    }
    try {
      const out = await post('/api/handoff', { target });
      toast(out.message || '引き継ぎました');
      showBanner('この会話をサブスク側に引き継ぎました。向こうで作業している間は、こちらから同じ会話に指示を出さないでください(同時に書き込むと会話が欠けることがあります)。戻るときは、左の一覧からこの会話を選び直します。');
    } catch (e) { toast(e.message); }
  }

  // ------------------------------------------------------------ projects

  async function saveSettings() {
    try { await post('/api/settings', { model: currentModel, mode: currentMode }); }
    catch (e) { toast('設定保存エラー: ' + e.message); }
  }
  function renderProjects(projects) {
    node.recentProjects.replaceChildren();
    for (const project of projects || []) {
      const row = el('div', 'recent-row' + (project.active ? ' active' : ''));
      const open = el('button', 'recent-project');
      open.type = 'button';
      open.disabled = running || switching;
      open.title = project.path;
      open.append(el('strong', '', project.name), el('small', '', project.path));
      open.addEventListener('click', () => switchProject(project.path));
      row.append(open);
      if (!project.active) {
        const remove = el('button', 'recent-remove', '×');
        remove.type = 'button';
        remove.title = '最近使った一覧から外す(ファイル・履歴は削除しません)';
        remove.setAttribute('aria-label', project.name + ' を一覧から外す');
        remove.disabled = running || switching;
        remove.addEventListener('click', async (ev) => {
          ev.stopPropagation();
          try { renderProjects((await post('/api/projects/remove', { path: project.path })).recentProjects); }
          catch (e) { toast(e.message); }
        });
        row.append(remove);
      }
      node.recentProjects.append(row);
    }
  }
  function applyState(data) {
    if (activeProjectPath && activeProjectPath !== data.projectPath) {
      projectDrafts.set(activeProjectPath, { text: node.prompt.value, attachments: attachments.slice() });
    }
    const changedProject = activeProjectPath !== data.projectPath;
    activeProjectPath = data.projectPath;
    setModelUI(data.model || 'claude-fable-5-2');
    setModeUI(data.mode || 'auto');
    $('projectName').textContent = data.projectName || 'プロジェクト';
    $('projectPath').textContent = data.projectPath || '';
    node.projectSwitch.title = data.projectPath || '作業フォルダを切り替える';
    setSession(data.sessionId, data.totalCost);
    $('handoffDesktop').classList.toggle('hidden', !data.handoff);
    $('handoffTerminal').classList.toggle('hidden', !data.handoff);
    renderProjects(data.recentProjects);
    showBanner('');
    clearMessages();
    for (const entry of data.history || []) addPast(entry);
    if (data.history?.length) autoScroll(true);
    if (changedProject) {
      const draft = projectDrafts.get(activeProjectPath);
      node.prompt.value = draft?.text || '';
      attachments = draft?.attachments?.slice() || [];
      renderAttachments(); resizeInput();
    }
    baseTitle = (data.projectName || 'プロジェクト') + ' — Claude Agent Chat';
    document.title = baseTitle;
    node.projectPick.classList.toggle('hidden', !data.nativePicker);
  }
  async function refreshState() {
    const r = await fetch('/api/state');
    if (!r.ok) throw new Error('HTTP ' + r.status);
    const data = await r.json();
    live = null;
    setRunning(false);
    applyState(data);
    if (!data.apiVersion) {
      showBanner('画面は新しい版ですが、サーバーが古い版のまま動いています。起動した黒い画面を閉じて、web_chat.bat を開き直してください。');
      node.send.disabled = true;
      return data;
    }
    // A run is still going (for example the page was reloaded): show it again from its first event.
    if (data.runId) {
      startLive(data.model);
      attachRun(data.runId);
    }
    return data;
  }

  function closeProjectModal() { node.projectModal.classList.add('hidden'); }
  function openProjectModal() {
    if (running || switching) return toast('処理中は切り替えできません');
    node.projectPathInput.value = activeProjectPath;
    node.projectModal.classList.remove('hidden');
    node.projectPathInput.focus();
    node.projectPathInput.select();
  }
  function setSwitching(value, message = 'フォルダを切り替えています…') {
    switching = value;
    node.projectApply.disabled = value;
    node.projectPick.disabled = value;
    node.projectCancel.disabled = value;
    node.projectPathInput.disabled = value;
    node.projectSwitch.disabled = value || running;
    for (const button of document.querySelectorAll('#recentProjects button, #sessionList button')) button.disabled = value || running;
    if (value) setStatus(message, true);
    else setStatus('準備完了', false);
  }
  async function switchProject(folderPath) {
    if (running || switching) return toast('処理中は切り替えできません');
    setSwitching(true);
    try {
      const state = await post('/api/projects/select', { path: folderPath });
      applyState(state);
      closeProjectModal();
      $('sidebar').classList.remove('open');
      toast('「' + state.projectName + '」に切り替えました');
      node.prompt.focus();
    } catch (e) { toast('切り替え失敗: ' + e.message); }
    finally { setSwitching(false); loadSessions(); }
  }

  async function init() {
    clearMessages();
    try {
      const data = await refreshState();
      if (!md) toast('Markdown描画ライブラリがありません。npm installを確認してください。');
      if (data.apiVersion) loadSessions();
    } catch (e) { toast('サーバーに接続できません: ' + e.message); }
    node.prompt.focus();
  }

  node.projectSwitch.addEventListener('click', openProjectModal);
  node.projectCancel.addEventListener('click', closeProjectModal);
  node.projectApply.addEventListener('click', () => switchProject(node.projectPathInput.value.trim()));
  node.projectPathInput.addEventListener('keydown', e => {
    if (e.key === 'Enter') { e.preventDefault(); switchProject(node.projectPathInput.value.trim()); }
  });
  node.projectPick.addEventListener('click', async () => {
    if (running || switching) return;
    setSwitching(true, 'Windowsのフォルダ選択画面を確認してください…');
    try {
      const state = await post('/api/projects/pick', {});
      if (!state.cancelled) {
        applyState(state);
        closeProjectModal();
        toast('「' + state.projectName + '」に切り替えました');
      }
    } catch (e) { toast('フォルダ選択に失敗: ' + e.message); }
    finally { setSwitching(false); loadSessions(); }
  });
  node.attach.addEventListener('click', () => node.imageInput.click());
  node.imageInput.addEventListener('change', async () => {
    await addImages(node.imageInput.files || []);
    node.imageInput.value = '';
  });
  document.addEventListener('paste', async event => {
    if (document.querySelector('.modal-backdrop:not(.hidden)')) return;
    const files = [...(event.clipboardData?.items || [])]
      .filter(item => item.kind === 'file' && item.type.startsWith('image/'))
      .map(item => item.getAsFile()).filter(Boolean);
    if (files.length) { event.preventDefault(); await addImages(files); }
  });
  document.addEventListener('dragover', event => {
    if (!event.dataTransfer?.types?.includes('Files')) return;
    event.preventDefault();
    event.dataTransfer.dropEffect = 'copy';
    node.composer.classList.add('drag-active');
  });
  document.addEventListener('dragleave', event => {
    if (!event.relatedTarget || !document.documentElement.contains(event.relatedTarget)) {
      node.composer.classList.remove('drag-active');
    }
  });
  document.addEventListener('drop', async event => {
    if (!event.dataTransfer?.files?.length) return;
    event.preventDefault(); node.composer.classList.remove('drag-active');
    await addImages(event.dataTransfer.files);
  });
  document.addEventListener('visibilitychange', () => {
    if (!document.hidden) document.title = baseTitle;
  });
  node.prompt.addEventListener('input', resizeInput);
  node.prompt.addEventListener('keydown', (ev) => {
    if (ev.key === 'Enter' && !ev.shiftKey && !ev.isComposing && !ev.ctrlKey) {
      ev.preventDefault(); send();
    }
  });
  node.send.addEventListener('click', send);
  node.stop.addEventListener('click', async () => {
    try { await post('/api/stop', {}); toast('停止を要求しました'); }
    catch (e) { toast(e.message); }
  });
  node.newChat.addEventListener('click', async () => {
    if (running) return;
    try {
      applyState(await post('/api/new', {}));
      toast('新しい会話を開始しました(前の会話は左の履歴に残ります)');
      loadSessions();
    } catch (e) { toast(e.message); }
  });
  node.model.addEventListener('change', async () => {
    if (node.model.value === 'custom') {
      node.customInput.value = currentModel;
      node.customModal.classList.remove('hidden');
      node.customInput.focus(); node.customInput.select(); return;
    }
    currentModel = node.model.value;
    await saveSettings();
  });
  node.mode.addEventListener('change', async () => {
    setModeUI(node.mode.value);
    await saveSettings();
  });
  node.notify.addEventListener('click', async () => {
    if (!('Notification' in window)) return toast('このブラウザは通知に対応していません');
    const result = await Notification.requestPermission();
    toast(result === 'granted' ? '別のタブを見ているときに、完了を通知します' : '通知は許可されませんでした');
  });
  $('customCancel').addEventListener('click', () => { node.customModal.classList.add('hidden'); setModelUI(currentModel); });
  $('customSave').addEventListener('click', async () => {
    const value = node.customInput.value.trim();
    if (!value) return toast('モデルIDを入力してください');
    setModelUI(value); node.customModal.classList.add('hidden'); await saveSettings();
  });
  node.customInput.addEventListener('keydown', ev => { if (ev.key === 'Enter') $('customSave').click(); });
  $('approvalAllow').addEventListener('click', () => submitApproval('allow'));
  node.approvalAlways.addEventListener('click', () => submitApproval('always'));
  $('approvalDeny').addEventListener('click', () => submitApproval('deny'));
  $('handoffDesktop').addEventListener('click', () => handoff('desktop'));
  $('handoffTerminal').addEventListener('click', () => handoff('terminal'));
  $('handoffCopy').addEventListener('click', () => handoff('copy'));
  $('menuToggle').addEventListener('click', () => $('sidebar').classList.toggle('open'));
  init();
})();

web\style.css

:root{color-scheme:dark;font-family:Inter,"Segoe UI","Yu Gothic UI","Meiryo",sans-serif;font-size:14px;font-weight:400;line-height:1.6;background:#101318;color:#e7ebf0}
*{box-sizing:border-box}
html,body{margin:0;width:100%;height:100%}
button,input,select,textarea{font:inherit}
button{cursor:pointer}
button:disabled{cursor:not-allowed;opacity:.46}
.hidden{display:none!important}
.app{display:flex;width:100%;height:100dvh;overflow:hidden}
.sidebar{background:#15191f;border-right:1px solid #252b34;width:258px;flex:0 0 258px;display:flex;flex-direction:column;padding:25px 16px}
.brand{display:flex;align-items:center;gap:12px;margin:0 7px 31px}
.brand-symbol{width:38px;height:38px;display:grid;place-items:center;background:#244e52;border:1px solid #386e71;border-radius:11px;color:#7ae4d3;font-size:24px}
.brand strong{font-size:16px;letter-spacing:-.3px}
.brand small{display:block;color:#83919f;font-size:10px;letter-spacing:1.5px;margin-top:-2px}
.new-chat{display:flex;align-items:center;justify-content:flex-start;gap:9px;width:100%;padding:12px;border-radius:10px;border:1px solid #373f4a;background:#20262e;color:#e8eef3;font-weight:650;text-align:left}
.new-chat:hover{background:#2b333d}
.plus{font-size:19px;font-weight:400}
.side-section-title{color:#788595;font-size:11px;font-weight:700;letter-spacing:.07em;margin:30px 8px 11px}
.workspace{padding:11px 9px;display:flex;align-items:center;gap:12px;background:#1c222a;border-radius:10px}
.workspace-icon{color:#6fc7be;font-size:22px}
.workspace strong{display:block;font-size:12.5px;max-width:168px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.workspace small{display:block;font-size:10.5px;color:#8694a1}
.mode-info{padding:7px 11px;display:flex;align-items:center;gap:10px;color:#bfc8d3;font-size:12px}
.info-dot{width:8px;height:8px;background:#69cdb3;border-radius:50%;box-shadow:0 0 9px #68cdb34b}
.sidebar-bottom{margin-top:auto}
.private-note{color:#85919e;background:#1c222a;border:1px solid #262d36;padding:12px;border-radius:10px;font-size:11px;line-height:1.8}
.sidebar-version{font-size:11px;color:#657381;margin-top:18px;padding:0 4px}
.main{min-width:0;flex:1;display:flex;flex-direction:column;background:#101318}
.topbar{min-height:69px;display:flex;align-items:center;justify-content:space-between;padding:0 31px;border-bottom:1px solid #262b32;gap:10px}
.top-title{display:flex;align-items:center;gap:13px}
.top-title strong{font-size:16px;font-weight:700}
.top-title small{color:#87939f;border-left:1px solid #3a424a;padding-left:13px;font-size:12px}
.top-actions{display:flex;gap:15px;align-items:center}
.status{display:flex;align-items:center;gap:8px;color:#9ca9b4;font-size:12px}
.status-dot{width:7px;height:7px;border-radius:50%;background:#67cbb4}
.status-dot.working{background:#e5b56d;animation:pulse 1.3s infinite}
.menu-toggle{display:none;border:none;background:transparent;color:#eee;font-size:20px}
@keyframes pulse{50%{opacity:.3}
}
.chat-scroll{flex:1;min-height:0;overflow:auto;scroll-behavior:smooth}
.chat-content{max-width:920px;min-height:100%;margin:0 auto;padding:28px 32px 22px}
.welcome{text-align:center;min-height:calc(100dvh - 325px);display:flex;flex-direction:column;align-items:center;justify-content:center;max-width:620px;margin:0 auto}
.welcome-icon{width:72px;height:72px;display:grid;place-items:center;background:radial-gradient(circle at 40% 30%,#286c6c,#153039);color:#b1fff2;font-size:42px;border:1px solid #2f636a;border-radius:22px;margin-bottom:20px}
.welcome h1{font-size:28px;letter-spacing:-1px;font-weight:750;margin:0 0 6px}
.welcome p{color:#97a4af;margin:0;font-size:13px;line-height:1.9}
.suggestions{display:flex;flex-wrap:wrap;gap:10px;justify-content:center;margin-top:29px}
.suggestion{background:#20262d;border:1px solid #3b444e;border-radius:11px;color:#cbd4db;padding:12px 16px;font-size:12px}
.suggestion:hover{background:#2b343e}
.message{display:flex;gap:14px;margin:16px 0 27px;min-width:0}
.avatar{flex:0 0 31px;height:31px;border-radius:10px;display:grid;place-items:center;font-size:17px;font-weight:600}
.avatar-user{background:#273744;color:#afd8ef}
.avatar-ai{background:#224540;color:#9eecdd}
.message-body{min-width:0;flex:1}
.message-header{display:flex;align-items:baseline;gap:10px;margin:2px 0 9px}
.message-header strong{font-size:13px}
.message-header small{font-size:11px;color:#84909c}
.message-text{font-size:14px;line-height:1.85;min-width:0;overflow-wrap:anywhere}
.user-text{white-space:pre-wrap;background:#1e2630;padding:13px 17px;border-radius:6px 15px 15px 15px;border:1px solid #303b48;color:#e6eaf0;max-width:100%}
.markdown{color:#dce2e9}
.markdown h1,.markdown h2,.markdown h3,.markdown h4{color:#eff4f8;line-height:1.35;letter-spacing:-.35px;margin:1.5em 0 .65em;font-weight:720}
.markdown h1{font-size:24px}
.markdown h2{font-size:19px;border-bottom:1px solid #313a44;padding-bottom:9px}
.markdown h3{font-size:16px}
.markdown h4{font-size:14px}
.markdown p{margin:0 0 1em}
.markdown h1:first-child,.markdown h2:first-child,.markdown h3:first-child{margin-top:0}
.markdown strong{color:#f7f9fb;font-weight:700}
.markdown ul,.markdown ol{padding-left:23px;margin:0 0 1.1em}
.markdown li{padding-left:2px;margin:.2em 0}
.markdown li::marker{color:#81cdbd}
.markdown code{background:#29333e;color:#a7e5ce;font-family:"Cascadia Code","Consolas",monospace;padding:2px 5px;border-radius:4px;font-size:.89em}
.markdown pre{background:#181f27;border:1px solid #313e49;padding:15px 16px;border-radius:10px;overflow:auto;line-height:1.6;max-height:650px}
.markdown pre code{background:transparent;padding:0;border-radius:0;color:#d1dae2}
.markdown table{width:100%;border-collapse:collapse;font-size:12.5px;margin:17px 0 22px;display:block;overflow-x:auto;border:1px solid #37424c;border-radius:8px}
.markdown th,.markdown td{padding:10px 13px;text-align:left;border-right:1px solid #35404a;border-bottom:1px solid #35404a;min-width:90px;vertical-align:top}
.markdown th{background:#26323c;color:#f2f5f6;font-weight:700}
.markdown tr:nth-child(2n){background:#1a222b}
.markdown tr:last-child td{border-bottom:0}
.markdown blockquote{border-left:3px solid #569f99;color:#bac8d0;background:#1a2529;padding:9px 17px;margin:16px 0;border-radius:0 8px 8px 0}
.markdown hr{border:0;border-top:1px solid #313943;margin:25px 0}
.markdown a{color:#88d7d5;text-decoration:underline;text-underline-offset:3px}
.markdown img{max-width:100%;border-radius:7px}
.message-actions{display:flex;gap:10px;margin-top:10px}
.copy-button{font-size:11px;background:transparent;color:#7f8e9e;border:none;padding:3px 0}
.copy-button:hover{color:#bcd9e1}
.tool-list{display:flex;flex-direction:column;gap:8px;margin:12px 0}
.tool-chip{border:1px solid #36434a;background:#1b252b;border-radius:9px;overflow:hidden}
.tool-chip summary{cursor:pointer;color:#a5ccc4;font-size:11px;padding:7px 10px;font-weight:600}
.tool-chip pre{white-space:pre-wrap;overflow-wrap:anywhere;margin:0;padding:10px;font-size:11px;color:#a3adb7;border-top:1px solid #303a42;max-height:280px;overflow:auto}
.notice{font-size:12px;padding:9px 11px;border:1px solid #594932;background:#2e271c;color:#ecc68d;border-radius:8px;margin:11px 0}
.result-line{display:flex;flex-wrap:wrap;gap:12px;margin:11px 0;color:#8799a6;font-size:11px}
.result-line .success{color:#72ccb0}
.result-line .failure{color:#ff9893}
.thinking{color:#8d9daa;font-size:12px;display:flex;align-items:center;gap:8px;margin:10px 0}
.spinner{display:inline-block;width:13px;height:13px;border:2px solid #43535b;border-top-color:#85ddcc;border-radius:50%;animation:spin .8s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}
}
.composer-area{border-top:1px solid #242b33;background:linear-gradient(to bottom,#13181e,#101318);padding:13px 30px 17px}
.composer-wrap{max-width:920px;margin:0 auto}
.composer-toolbar{display:flex;flex-wrap:wrap;gap:22px;align-items:center;margin:0 0 9px;padding:0 5px}
.selector-group{display:flex;align-items:center;gap:8px}
.selector-group label{color:#80919e;font-size:11px;font-weight:700}
.selector-group select{background:#202831;color:#dce8ec;border:1px solid #3a4754;border-radius:7px;padding:6px 29px 6px 10px;font-size:12px;max-width:210px}
.composer{border:1px solid #3d5158;background:#202830;border-radius:15px;padding:12px 14px 10px;box-shadow:0 5px 26px #00000020}
.composer:focus-within{border-color:#629c9c;box-shadow:0 0 0 2px #538b8b18}
.composer textarea{display:block;resize:none;overflow-y:auto;max-height:230px;min-height:55px;width:100%;border:none;outline:none;color:#f2f3f5;background:transparent;line-height:1.7;font-size:14px}
.composer textarea::placeholder{color:#81909d}
.composer-footer{display:flex;justify-content:space-between;align-items:center;gap:8px}
.helptext{color:#8495a1;font-size:11px}
.helptext kbd{font-size:11px;font-family:inherit;color:#b2c1c9}
.separator{padding:0 5px}
.send-actions{display:flex;gap:8px}
.send-button{width:35px;height:35px;border:0;border-radius:10px;background:#71cbbb;color:#0c2423;font-size:18px;font-weight:800}
.send-button:hover{background:#8fddcf}
.stop-button{background:#3c2c2f;border:1px solid #905758;color:#f4b5af;border-radius:8px;padding:7px 13px;font-size:12px}
.footnote{text-align:center;margin:8px 0 0;color:#687786;font-size:10.5px}
.modal-backdrop{position:fixed;inset:0;background:#000b;z-index:50;display:flex;align-items:center;justify-content:center;padding:16px}
.modal{width:min(650px,100%);max-height:90dvh;overflow:auto;border:1px solid #405058;border-radius:17px;background:#1a222b;box-shadow:0 20px 80px #0009;padding:25px}
.small-modal{max-width:440px}
.modal-eyebrow{font-size:11px;letter-spacing:.1em;font-weight:750;color:#80d7c7;margin-bottom:7px}
.modal h2{font-size:19px;margin:0 0 7px}
.modal p{margin:0 0 17px;color:#a4b0bc;font-size:13px;line-height:1.7}
.modal input[type=text]{background:#10171d;color:#edf1f4;border:1px solid #45535c;border-radius:8px;padding:11px 12px;width:100%;outline-color:#73cabb}
.modal-actions{display:flex;justify-content:flex-end;gap:11px;margin-top:20px}
.secondary-button,.primary-button{border-radius:9px;padding:10px 15px;font-size:12px;font-weight:700}
.secondary-button{background:#28313a;color:#ecf0f4;border:1px solid #42515b}
.primary-button{background:#69c7b8;color:#0f2525;border:1px solid #69c7b8}
.tool-heading{font-size:12px;color:#9ce2d5;background:#25363a;border:1px solid #3d5b5e;border-radius:8px;padding:9px 12px;margin:15px 0}
.approval-details{margin-top:16px;border:1px solid #374650;border-radius:9px;overflow:hidden}
.approval-details summary{font-size:12px;padding:10px 12px;cursor:pointer;color:#b3c3cd}
.approval-details pre{font-size:11px;white-space:pre-wrap;word-break:break-word;background:#111920;margin:0;padding:13px;max-height:310px;overflow:auto;color:#c8d3df}
.modal .approval-tip{margin-top:14px;font-size:11px;color:#8393a1}
.question-label{font-size:12px;font-weight:650;margin:16px 0 5px}
.question-answer{width:100%;padding:10px;color:#eceff3;background:#111920;border:1px solid #41505c;border-radius:7px}
.toast{position:fixed;bottom:18px;left:50%;transform:translateX(-50%);background:#2b3a40;border:1px solid #517474;color:#e5f8f4;padding:10px 17px;border-radius:9px;z-index:100;box-shadow:0 12px 30px #0008;font-size:12px}
@media(max-width:850px){.sidebar{position:fixed;z-index:30;inset:0 auto 0 0;transform:translateX(-100%);transition:transform .2s}
.sidebar.open{transform:translateX(0)}
.menu-toggle{display:block}
.topbar{padding:0 17px;min-height:57px}
.chat-content{padding:15px 16px}
.composer-area{padding:10px 13px}
.welcome h1{font-size:23px}
.top-title small{display:none}
.markdown table{font-size:12px}
.helptext{font-size:10px}
}
/* Project switcher */
.workspace-button{width:100%;text-align:left;color:inherit;border:1px solid #35414b;cursor:pointer;transition:background .15s}
.workspace-button:hover{background:#28343e}
.workspace-info{min-width:0;flex:1;display:block}
.workspace-info strong{max-width:100%;font-size:12.5px}
.workspace-info small{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.workspace-chevron{font-size:21px;color:#9dafb7}
.recent-title{margin-top:19px}
.recent-list{display:flex;flex-direction:column;gap:4px;overflow:auto;max-height:min(33vh,260px);min-height:30px;padding:0 2px}
.recent-row{display:flex;align-items:center;min-width:0;gap:4px;border-radius:9px}
.recent-row.active{background:#213139}
.recent-project{padding:8px 9px;display:flex;flex-direction:column;align-items:flex-start;flex:1;min-width:0;background:none;color:#c0cbd2;border:0;border-radius:8px;text-align:left}
.recent-project:hover{background:#28323c}
.recent-project strong{font-size:12px;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.recent-project small{font-size:10px;color:#81919d;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.recent-remove{flex:0 0 24px;color:#93a4af;background:transparent;border:0;border-radius:6px;padding:5px 0;font-size:15px}
.recent-remove:hover{background:#3f3033;color:#ffc2c2}
.project-modal{max-width:560px}
.folder-picker-button{width:100%;padding:13px 12px;border:1px solid #508880;background:#24453f;color:#e6fff9;border-radius:10px;text-align:center;font-weight:650}
.folder-picker-button:hover{background:#2d584f}
.path-divider{margin:17px 0 10px;color:#94a3ad;font-size:12px;text-align:center}
.path-label{display:block;color:#b1bec9;margin:0 0 6px;font-size:12px}
.project-modal input[type=text]{font-family:'Cascadia Code','Consolas',monospace;font-size:13px}
.modal .project-hint{font-size:11px;color:#8297a5;margin:15px 0 0}
/* Image attachments */
.attach-button{width:35px;height:35px;border:1px solid #44535d;border-radius:10px;background:#2b3843;color:#dbe8ef;font-size:19px;display:grid;place-items:center}
.attach-button:hover{background:#38505a;border-color:#78cabe}
.composer.drag-active{border-color:#76d4bf;background:#263c3c;box-shadow:0 0 0 3px #76d4bf33}
.attachment-list{display:flex;flex-wrap:wrap;gap:10px;padding:0 0 13px}
.attachment-item{position:relative;width:106px;min-width:0;border:1px solid #465661;background:#172027;border-radius:10px;overflow:hidden}
.attachment-item img{display:block;width:100%;height:84px;object-fit:cover;background:#26323d}
.attachment-item .attachment-name{display:block;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;padding:4px 7px;color:#cfdae2}
.attachment-remove{position:absolute;top:3px;right:3px;width:23px;height:23px;display:grid;place-items:center;background:#1b232cef;border:1px solid #59646e;color:white;border-radius:50%;font-size:17px;line-height:1}
.attachment-remove:hover{background:#743a3a}
.message-image-grid{display:flex;flex-wrap:wrap;gap:8px;margin-top:9px}
.message-image-grid img{max-width:min(240px,100%);max-height:200px;object-fit:contain;border:1px solid #475560;border-radius:9px;background:#12191f}
.message-image-fallback{display:inline-block;font-size:11px;border:1px solid #4b5c69;border-radius:8px;padding:7px 9px;color:#b8ccd7}
@media(max-width:850px){.attachment-item{width:90px}
.attachment-item img{height:74px}
.helptext{font-size:9px}
}

/* v4: sidebar scrolls as a whole, session history list */
.sidebar{overflow-y:auto}
.side-section-title{margin:22px 8px 9px}
.session-list{display:flex;flex-direction:column;gap:3px;overflow:auto;max-height:min(38vh,330px);min-height:34px;padding:0 2px;flex:0 0 auto}
.session-item{padding:7px 9px;display:flex;flex-direction:column;align-items:flex-start;background:none;color:#c0cbd2;border:0;border-radius:8px;text-align:left;min-width:0}
.session-item:hover{background:#28323c}
.session-item.active{background:#213139}
.session-item strong{font-size:12px;font-weight:600;max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.session-item small{font-size:10px;color:#81919d}
.session-empty{font-size:11px;color:#71808d;padding:6px 9px}
.sidebar-bottom{padding-top:18px}
.notify-button{width:100%;margin-bottom:9px;padding:8px 10px;font-size:11px;color:#b6c5cf;background:#1c222a;border:1px solid #2c3540;border-radius:9px;text-align:left}
.notify-button:hover{background:#28323c}

/* v4: messages are a flow in time order */
.flow{display:flex;flex-direction:column;gap:9px;min-width:0}
.flow .message-text{min-width:0}
.flow .markdown>:last-child{margin-bottom:0}
.flow .notice,.flow .result-line,.flow .thinking{margin:0}
.tool-mark{display:inline-block;width:1.1em;color:#7fb7ad}
.tool-chip.tool-ok .tool-mark{color:#72ccb0}
.tool-chip.tool-error{border-color:#6a4144}
.tool-chip.tool-error .tool-mark,.tool-chip.tool-error summary{color:#ff9d98}
.result-line{border-top:1px solid #2a323b;padding-top:10px;font-size:12px}
.result-line .success{font-weight:700}
.thinking{position:sticky;bottom:0;background:#101318;padding:6px 0}
.message.just-finished .result-line .success{animation:finished 1.6s ease-out 1}
@keyframes finished{0%{background:#2f6f61;box-shadow:0 0 0 6px #2f6f61}100%{background:transparent;box-shadow:0 0 0 6px transparent}}

/* v4: top bar extras */
.cost-label{border-left:1px solid #3a424a;padding-left:13px;color:#87939f;font-size:12px}
.cost-label:empty{display:none}
.handoff{position:relative}
.handoff summary{list-style:none;cursor:pointer;font-size:12px;color:#cfe6e1;background:#20303a;border:1px solid #3a5560;border-radius:8px;padding:6px 11px;white-space:nowrap}
.handoff summary::-webkit-details-marker{display:none}
.handoff summary:hover{background:#28404a}
.handoff-menu{position:absolute;right:0;top:calc(100% + 6px);z-index:20;width:300px;background:#1a222b;border:1px solid #405058;border-radius:11px;box-shadow:0 14px 40px #0009;padding:6px;display:flex;flex-direction:column;gap:2px}
.handoff-menu button{display:flex;flex-direction:column;align-items:flex-start;gap:1px;background:none;border:0;border-radius:8px;color:#e3eaf0;padding:9px 10px;text-align:left}
.handoff-menu button:hover{background:#28323c}
.handoff-menu strong{font-size:12.5px}
.handoff-menu small{font-size:10.5px;color:#8a99a6}
.banner{background:#2e271c;border-bottom:1px solid #594932;color:#ecc68d;font-size:12px;line-height:1.7;padding:9px 31px}

/* v4: approval dialog */
.question-block{margin:14px 0 4px}
.question-options{display:flex;flex-direction:column;gap:6px;margin:0 0 8px}
.question-option{display:flex;flex-direction:column;align-items:flex-start;gap:1px;text-align:left;background:#111920;border:1px solid #41505c;border-radius:9px;color:#e6edf2;padding:9px 12px}
.question-option:hover{border-color:#6aa9a0}
.question-option.selected{border-color:#69c7b8;background:#1d3a38}
.question-option strong{font-size:13px}
.question-option small{font-size:11px;color:#9aa9b5}
.modal-actions{flex-wrap:wrap}
@media(max-width:850px){.banner{padding:8px 17px}.cost-label{display:none}.handoff-menu{width:260px}}

コメント

Copied title and URL