diff --git a/.gitignore b/.gitignore index be8843e0..7d6c7b0e 100644 --- a/.gitignore +++ b/.gitignore @@ -90,9 +90,8 @@ pnpm-lock.yaml yarn.lock # Fork-specific workflow files (should never be committed) -DEVELOPMENT_WORKFLOW.md -check-sync.sh # API key files data/.api-key data/credentials.json data/ +.codex/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a3fed705..61ad83f4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -24,6 +24,7 @@ For complete details on contribution terms and rights assignment, please review - [Development Setup](#development-setup) - [Project Structure](#project-structure) - [Pull Request Process](#pull-request-process) + - [Branching Strategy (RC Branches)](#branching-strategy-rc-branches) - [Branch Naming Convention](#branch-naming-convention) - [Commit Message Format](#commit-message-format) - [Submitting a Pull Request](#submitting-a-pull-request) @@ -186,6 +187,59 @@ automaker/ This section covers everything you need to know about contributing changes through pull requests, from creating your branch to getting your code merged. +### Branching Strategy (RC Branches) + +Automaker uses **Release Candidate (RC) branches** for all development work. Understanding this workflow is essential before contributing. + +**How it works:** + +1. **All development happens on RC branches** - We maintain version-specific RC branches (e.g., `v0.10.0rc`, `v0.11.0rc`) where all active development occurs +2. **RC branches are eventually merged to main** - Once an RC branch is stable and ready for release, it gets merged into `main` +3. **Main branch is for releases only** - The `main` branch contains only released, stable code + +**Before creating a PR:** + +1. **Check for the latest RC branch** - Before starting work, check the repository for the current RC branch: + + ```bash + git fetch upstream + git branch -r | grep rc + ``` + +2. **Base your work on the RC branch** - Create your feature branch from the latest RC branch, not from `main`: + + ```bash + # Find the latest RC branch (e.g., v0.11.0rc) + git checkout upstream/v0.11.0rc + git checkout -b feature/your-feature-name + ``` + +3. **Target the RC branch in your PR** - When opening your pull request, set the base branch to the current RC branch, not `main` + +**Example workflow:** + +```bash +# 1. Fetch latest changes +git fetch upstream + +# 2. Check for RC branches +git branch -r | grep rc +# Output: upstream/v0.11.0rc + +# 3. Create your branch from the RC +git checkout -b feature/add-dark-mode upstream/v0.11.0rc + +# 4. Make your changes and commit +git commit -m "feat: Add dark mode support" + +# 5. Push to your fork +git push origin feature/add-dark-mode + +# 6. Open PR targeting the RC branch (v0.11.0rc), NOT main +``` + +**Important:** PRs opened directly against `main` will be asked to retarget to the current RC branch. + ### Branch Naming Convention We use a consistent branch naming pattern to keep our repository organized: @@ -275,14 +329,14 @@ Follow these steps to submit your contribution: #### 1. Prepare Your Changes -Ensure you've synced with the latest upstream changes: +Ensure you've synced with the latest upstream changes from the RC branch: ```bash # Fetch latest changes from upstream git fetch upstream -# Rebase your branch on main (if needed) -git rebase upstream/main +# Rebase your branch on the current RC branch (if needed) +git rebase upstream/v0.11.0rc # Use the current RC branch name ``` #### 2. Run Pre-submission Checks @@ -314,18 +368,19 @@ git push origin feature/your-feature-name 1. Go to your fork on GitHub 2. Click "Compare & pull request" for your branch -3. Ensure the base repository is `AutoMaker-Org/automaker` and base branch is `main` +3. **Important:** Set the base repository to `AutoMaker-Org/automaker` and the base branch to the **current RC branch** (e.g., `v0.11.0rc`), not `main` 4. Fill out the PR template completely #### PR Requirements Checklist Your PR should include: +- [ ] **Targets the current RC branch** (not `main`) - see [Branching Strategy](#branching-strategy-rc-branches) - [ ] **Clear title** describing the change (use conventional commit format) - [ ] **Description** explaining what changed and why - [ ] **Link to related issue** (if applicable): `Closes #123` or `Fixes #456` - [ ] **All CI checks passing** (format, lint, build, tests) -- [ ] **No merge conflicts** with main branch +- [ ] **No merge conflicts** with the RC branch - [ ] **Tests included** for new functionality - [ ] **Documentation updated** if adding/changing public APIs diff --git a/DEVELOPMENT_WORKFLOW.md b/DEVELOPMENT_WORKFLOW.md new file mode 100644 index 00000000..0ce198ce --- /dev/null +++ b/DEVELOPMENT_WORKFLOW.md @@ -0,0 +1,253 @@ +# Development Workflow + +This document defines the standard workflow for keeping a branch in sync with the upstream +release candidate (RC) and for shipping feature work. It is paired with `check-sync.sh`. + +## Quick Decision Rule + +1. Ask the user to select a workflow: + - **Sync Workflow** → you are maintaining the current RC branch with fixes/improvements + and will push the same fixes to both origin and upstream RC when you have local + commits to publish. + - **PR Workflow** → you are starting new feature work on a new branch; upstream updates + happen via PR only. +2. After the user selects, run: + ```bash + ./check-sync.sh + ``` +3. Use the status output to confirm alignment. If it reports **diverged**, default to + merging `upstream/` into the current branch and preserving local commits. + For Sync Workflow, when the working tree is clean and you are behind upstream RC, + proceed with the fetch + merge without asking for additional confirmation. + +## Target RC Resolution + +The target RC is resolved dynamically so the workflow stays current as the RC changes. + +Resolution order: + +1. Latest `upstream/v*rc` branch (auto-detected) +2. `upstream/HEAD` (fallback) +3. If neither is available, you must pass `--rc ` + +Override for a single run: + +```bash +./check-sync.sh --rc +``` + +## Pre-Flight Checklist + +1. Confirm a clean working tree: + ```bash + git status + ``` +2. Confirm the current branch: + ```bash + git branch --show-current + ``` +3. Ensure remotes exist (origin + upstream): + ```bash + git remote -v + ``` + +## Sync Workflow (Upstream Sync) + +Use this flow when you are updating the current branch with fixes or improvements and +intend to keep origin and upstream RC in lockstep. + +1. **Check sync status** + ```bash + ./check-sync.sh + ``` +2. **Update from upstream RC before editing (no pulls)** + - **Behind upstream RC** → fetch and merge RC into your branch: + ```bash + git fetch upstream + git merge upstream/ --no-edit + ``` + When the working tree is clean and the user selected Sync Workflow, proceed without + an extra confirmation prompt. + - **Diverged** → stop and resolve manually. +3. **Resolve conflicts if needed** + - Handle conflicts intelligently: preserve upstream behavior and your local intent. +4. **Make changes and commit (if you are delivering fixes)** + ```bash + git add -A + git commit -m "type: description" + ``` +5. **Build to verify** + ```bash + npm run build:packages + npm run build + ``` +6. **Push after a successful merge to keep remotes aligned** + - If you only merged upstream RC changes, push **origin only** to sync your fork: + ```bash + git push origin + ``` + - If you have local fixes to publish, push **origin + upstream**: + ```bash + git push origin + git push upstream : + ``` + - Always ask the user which push to perform. + - Origin (origin-only sync): + ```bash + git push origin + ``` + - Upstream RC (publish the same fixes when you have local commits): + ```bash + git push upstream : + ``` +7. **Re-check sync** + ```bash + ./check-sync.sh + ``` + +## PR Workflow (Feature Work) + +Use this flow only for new feature work on a new branch. Do not push to upstream RC. + +1. **Create or switch to a feature branch** + ```bash + git checkout -b + ``` +2. **Make changes and commit** + ```bash + git add -A + git commit -m "type: description" + ``` +3. **Merge upstream RC before shipping** + ```bash + git merge upstream/ --no-edit + ``` +4. **Build and/or test** + ```bash + npm run build:packages + npm run build + ``` +5. **Push to origin** + ```bash + git push -u origin + ``` +6. **Create or update the PR** + - Use `gh pr create` or the GitHub UI. +7. **Review and follow-up** + +- Apply feedback, commit changes, and push again. +- Re-run `./check-sync.sh` if additional upstream sync is needed. + +## Conflict Resolution Checklist + +1. Identify which changes are from upstream vs. local. +2. Preserve both behaviors where possible; avoid dropping either side. +3. Prefer minimal, safe integrations over refactors. +4. Re-run build commands after resolving conflicts. +5. Re-run `./check-sync.sh` to confirm status. + +## Build/Test Matrix + +- **Sync Workflow**: `npm run build:packages` and `npm run build`. +- **PR Workflow**: `npm run build:packages` and `npm run build` (plus relevant tests). + +## Post-Sync Verification + +1. `git status` should be clean. +2. `./check-sync.sh` should show expected alignment. +3. Verify recent commits with: + ```bash + git log --oneline -5 + ``` + +## check-sync.sh Usage + +- Uses dynamic Target RC resolution (see above). +- Override target RC: + ```bash + ./check-sync.sh --rc + ``` +- Optional preview limit: + ```bash + ./check-sync.sh --preview 10 + ``` +- The script prints sync status for both origin and upstream and previews recent commits + when you are behind. + +## Stop Conditions + +Stop and ask for guidance if any of the following are true: + +- The working tree is dirty and you are about to merge or push. +- `./check-sync.sh` reports **diverged** during PR Workflow, or a merge cannot be completed. +- The script cannot resolve a target RC and requests `--rc`. +- A build fails after sync or conflict resolution. + +## AI Agent Guardrails + +- Always run `./check-sync.sh` before merges or pushes. +- Always ask for explicit user approval before any push command. +- Do not ask for additional confirmation before a Sync Workflow fetch + merge when the + working tree is clean and the user has already selected the Sync Workflow. +- Choose Sync vs PR workflow based on intent (RC maintenance vs new feature work), not + on the script's workflow hint. +- Only use force push when the user explicitly requests a history rewrite. +- Ask for explicit approval before dependency installs, branch deletion, or destructive operations. +- When resolving merge conflicts, preserve both upstream changes and local intent where possible. +- Do not create or switch to new branches unless the user explicitly requests it. + +## AI Agent Decision Guidance + +Agents should provide concrete, task-specific suggestions instead of repeatedly asking +open-ended questions. Use the user's stated goal and the `./check-sync.sh` status to +propose a default path plus one or two alternatives, and only ask for confirmation when +an action requires explicit approval. + +Default behavior: + +- If the intent is RC maintenance, recommend the Sync Workflow and proceed with + safe preparation steps (status checks, previews). If the branch is behind upstream RC, + fetch and merge without additional confirmation when the working tree is clean, then + push to origin to keep the fork aligned. Push upstream only when there are local fixes + to publish. +- If the intent is new feature work, recommend the PR Workflow and proceed with safe + preparation steps (status checks, identifying scope). Ask for approval before merges, + pushes, or dependency installs. +- If `./check-sync.sh` reports **diverged** during Sync Workflow, merge + `upstream/` into the current branch and preserve local commits. +- If `./check-sync.sh` reports **diverged** during PR Workflow, stop and ask for guidance + with a short explanation of the divergence and the minimal options to resolve it. + If the user's intent is RC maintenance, prefer the Sync Workflow regardless of the + script hint. When the intent is new feature work, use the PR Workflow and avoid upstream + RC pushes. + +Suggestion format (keep it short): + +- **Recommended**: one sentence with the default path and why it fits the task. +- **Alternatives**: one or two options with the tradeoff or prerequisite. +- **Approval points**: mention any upcoming actions that need explicit approval (exclude sync + workflow pushes and merges). + +## Failure Modes and How to Avoid Them + +Sync Workflow: + +- Wrong RC target: verify the auto-detected RC in `./check-sync.sh` output before merging. +- Diverged from upstream RC: stop and resolve manually before any merge or push. +- Dirty working tree: commit or stash before syncing to avoid accidental merges. +- Missing remotes: ensure both `origin` and `upstream` are configured before syncing. +- Build breaks after sync: run `npm run build:packages` and `npm run build` before pushing. + +PR Workflow: + +- Branch not synced to current RC: re-run `./check-sync.sh` and merge RC before shipping. +- Pushing the wrong branch: confirm `git branch --show-current` before pushing. +- Unreviewed changes: always commit and push to origin before opening or updating a PR. +- Skipped tests/builds: run the build commands before declaring the PR ready. + +## Notes + +- Avoid merging with uncommitted changes; commit or stash first. +- Prefer merge over rebase for PR branches; rebases rewrite history and often require a force push, + which should only be done with an explicit user request. +- Use clear, conventional commit messages and split unrelated changes into separate commits. diff --git a/Dockerfile b/Dockerfile index c32b1764..f40b1287 100644 --- a/Dockerfile +++ b/Dockerfile @@ -59,6 +59,11 @@ FROM node:22-slim AS server ARG GIT_COMMIT_SHA=unknown LABEL automaker.git.commit.sha="${GIT_COMMIT_SHA}" +# Build arguments for user ID matching (allows matching host user for mounted volumes) +# Override at build time: docker build --build-arg UID=$(id -u) --build-arg GID=$(id -g) ... +ARG UID=1001 +ARG GID=1001 + # Install git, curl, bash (for terminal), gosu (for user switching), and GitHub CLI (pinned version, multi-arch) RUN apt-get update && apt-get install -y --no-install-recommends \ git curl bash gosu ca-certificates openssh-client \ @@ -79,8 +84,10 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ RUN npm install -g @anthropic-ai/claude-code # Create non-root user with home directory BEFORE installing Cursor CLI -RUN groupadd -g 1001 automaker && \ - useradd -u 1001 -g automaker -m -d /home/automaker -s /bin/bash automaker && \ +# Uses UID/GID build args to match host user for mounted volume permissions +# Use -o flag to allow non-unique IDs (GID 1000 may already exist as 'node' group) +RUN groupadd -o -g ${GID} automaker && \ + useradd -o -u ${UID} -g automaker -m -d /home/automaker -s /bin/bash automaker && \ mkdir -p /home/automaker/.local/bin && \ mkdir -p /home/automaker/.cursor && \ chown -R automaker:automaker /home/automaker && \ @@ -95,6 +102,12 @@ RUN curl https://cursor.com/install -fsS | bash && \ ls -la /home/automaker/.local/bin/ && \ echo "=== PATH is: $PATH ===" && \ (which cursor-agent && cursor-agent --version) || echo "cursor-agent installed (may need auth setup)" + +# Install OpenCode CLI (for multi-provider AI model access) +RUN curl -fsSL https://opencode.ai/install | bash && \ + echo "=== Checking OpenCode CLI installation ===" && \ + ls -la /home/automaker/.local/bin/ && \ + (which opencode && opencode --version) || echo "opencode installed (may need auth setup)" USER root # Add PATH to profile so it's available in all interactive shells (for login shells) diff --git a/Dockerfile.dev b/Dockerfile.dev index 87ac6bf6..1acd7742 100644 --- a/Dockerfile.dev +++ b/Dockerfile.dev @@ -27,9 +27,15 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ # Install Claude CLI globally RUN npm install -g @anthropic-ai/claude-code -# Create non-root user -RUN groupadd -g 1001 automaker && \ - useradd -u 1001 -g automaker -m -d /home/automaker -s /bin/bash automaker && \ +# Build arguments for user ID matching (allows matching host user for mounted volumes) +# Override at build time: docker-compose build --build-arg UID=$(id -u) --build-arg GID=$(id -g) +ARG UID=1001 +ARG GID=1001 + +# Create non-root user with configurable UID/GID +# Use -o flag to allow non-unique IDs (GID 1000 may already exist as 'node' group) +RUN groupadd -o -g ${GID} automaker && \ + useradd -o -u ${UID} -g automaker -m -d /home/automaker -s /bin/bash automaker && \ mkdir -p /home/automaker/.local/bin && \ mkdir -p /home/automaker/.cursor && \ chown -R automaker:automaker /home/automaker && \ diff --git a/apps/server/package.json b/apps/server/package.json index 56190122..23e6a2a9 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -1,6 +1,6 @@ { "name": "@automaker/server", - "version": "0.9.0", + "version": "0.10.0", "description": "Backend server for Automaker - provides API for both web and Electron modes", "author": "AutoMaker Team", "license": "SEE LICENSE IN LICENSE", diff --git a/apps/server/src/lib/sdk-options.ts b/apps/server/src/lib/sdk-options.ts index 4d3e670f..cc1df2f5 100644 --- a/apps/server/src/lib/sdk-options.ts +++ b/apps/server/src/lib/sdk-options.ts @@ -129,10 +129,30 @@ export const TOOL_PRESETS = { specGeneration: ['Read', 'Glob', 'Grep'] as const, /** Full tool access for feature implementation */ - fullAccess: ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash', 'WebSearch', 'WebFetch'] as const, + fullAccess: [ + 'Read', + 'Write', + 'Edit', + 'Glob', + 'Grep', + 'Bash', + 'WebSearch', + 'WebFetch', + 'TodoWrite', + ] as const, /** Tools for chat/interactive mode */ - chat: ['Read', 'Write', 'Edit', 'Glob', 'Grep', 'Bash', 'WebSearch', 'WebFetch'] as const, + chat: [ + 'Read', + 'Write', + 'Edit', + 'Glob', + 'Grep', + 'Bash', + 'WebSearch', + 'WebFetch', + 'TodoWrite', + ] as const, } as const; /** diff --git a/apps/server/src/providers/claude-provider.ts b/apps/server/src/providers/claude-provider.ts index ba86bfad..ecdd46af 100644 --- a/apps/server/src/providers/claude-provider.ts +++ b/apps/server/src/providers/claude-provider.ts @@ -99,6 +99,8 @@ export class ClaudeProvider extends BaseProvider { ...(maxThinkingTokens && { maxThinkingTokens }), // Subagents configuration for specialized task delegation ...(options.agents && { agents: options.agents }), + // Pass through outputFormat for structured JSON outputs + ...(options.outputFormat && { outputFormat: options.outputFormat }), }; // Build prompt payload diff --git a/apps/server/src/providers/codex-provider.ts b/apps/server/src/providers/codex-provider.ts index 2e3962a0..e0f38ee9 100644 --- a/apps/server/src/providers/codex-provider.ts +++ b/apps/server/src/providers/codex-provider.ts @@ -45,6 +45,7 @@ import { getCodexTodoToolName, } from './codex-tool-mapping.js'; import { SettingsService } from '../services/settings-service.js'; +import { createTempEnvOverride } from '../lib/auth-utils.js'; import { checkSandboxCompatibility } from '../lib/sdk-options.js'; import { CODEX_MODELS } from './codex-models.js'; @@ -142,6 +143,7 @@ type CodexExecutionMode = typeof CODEX_EXECUTION_MODE_CLI | typeof CODEX_EXECUTI type CodexExecutionPlan = { mode: CodexExecutionMode; cliPath: string | null; + openAiApiKey?: string | null; }; const ALLOWED_ENV_VARS = [ @@ -166,6 +168,22 @@ function buildEnv(): Record { return env; } +async function resolveOpenAiApiKey(): Promise { + const envKey = process.env[OPENAI_API_KEY_ENV]; + if (envKey) { + return envKey; + } + + try { + const settingsService = new SettingsService(getCodexSettingsDir()); + const credentials = await settingsService.getCredentials(); + const storedKey = credentials.apiKeys.openai?.trim(); + return storedKey ? storedKey : null; + } catch { + return null; + } +} + function hasMcpServersConfigured(options: ExecuteOptions): boolean { return Boolean(options.mcpServers && Object.keys(options.mcpServers).length > 0); } @@ -181,18 +199,21 @@ function isSdkEligible(options: ExecuteOptions): boolean { async function resolveCodexExecutionPlan(options: ExecuteOptions): Promise { const cliPath = await findCodexCliPath(); const authIndicators = await getCodexAuthIndicators(); - const hasApiKey = Boolean(process.env[OPENAI_API_KEY_ENV]); + const openAiApiKey = await resolveOpenAiApiKey(); + const hasApiKey = Boolean(openAiApiKey); const cliAuthenticated = authIndicators.hasOAuthToken || authIndicators.hasApiKey || hasApiKey; const sdkEligible = isSdkEligible(options); const cliAvailable = Boolean(cliPath); + if (hasApiKey) { + return { + mode: CODEX_EXECUTION_MODE_SDK, + cliPath, + openAiApiKey, + }; + } + if (sdkEligible) { - if (hasApiKey) { - return { - mode: CODEX_EXECUTION_MODE_SDK, - cliPath, - }; - } if (!cliAvailable) { throw new Error(ERROR_CODEX_SDK_AUTH_REQUIRED); } @@ -209,6 +230,7 @@ async function resolveCodexExecutionPlan(options: ExecuteOptions): Promise { const cliPath = await findCodexCliPath(); - const hasApiKey = !!process.env[OPENAI_API_KEY_ENV]; + const hasApiKey = Boolean(await resolveOpenAiApiKey()); const authIndicators = await getCodexAuthIndicators(); const installed = !!cliPath; @@ -1013,7 +1047,7 @@ export class CodexProvider extends BaseProvider { */ async checkAuth(): Promise { const cliPath = await findCodexCliPath(); - const hasApiKey = !!process.env[OPENAI_API_KEY_ENV]; + const hasApiKey = Boolean(await resolveOpenAiApiKey()); const authIndicators = await getCodexAuthIndicators(); // Check for API key in environment diff --git a/apps/server/src/providers/index.ts b/apps/server/src/providers/index.ts index a1da283b..b53695f6 100644 --- a/apps/server/src/providers/index.ts +++ b/apps/server/src/providers/index.ts @@ -30,3 +30,11 @@ export { OpencodeProvider } from './opencode-provider.js'; // Provider factory export { ProviderFactory } from './provider-factory.js'; + +// Simple query service - unified interface for basic AI queries +export { simpleQuery, streamingQuery } from './simple-query-service.js'; +export type { + SimpleQueryOptions, + SimpleQueryResult, + StreamingQueryOptions, +} from './simple-query-service.js'; diff --git a/apps/server/src/providers/simple-query-service.ts b/apps/server/src/providers/simple-query-service.ts new file mode 100644 index 00000000..5882b96f --- /dev/null +++ b/apps/server/src/providers/simple-query-service.ts @@ -0,0 +1,254 @@ +/** + * Simple Query Service - Simplified interface for basic AI queries + * + * Use this for routes that need simple text responses without + * complex event handling. This service abstracts away the provider + * selection and streaming details, providing a clean interface + * for common query patterns. + * + * Benefits: + * - No direct SDK imports needed in route files + * - Consistent provider routing based on model + * - Automatic text extraction from streaming responses + * - Structured output support for JSON schema responses + * - Eliminates duplicate extractTextFromStream() functions + */ + +import { ProviderFactory } from './provider-factory.js'; +import type { + ProviderMessage, + ContentBlock, + ThinkingLevel, + ReasoningEffort, +} from '@automaker/types'; +import { stripProviderPrefix } from '@automaker/types'; + +/** + * Options for simple query execution + */ +export interface SimpleQueryOptions { + /** The prompt to send to the AI (can be text or multi-part content) */ + prompt: string | Array<{ type: string; text?: string; source?: object }>; + /** Model to use (with or without provider prefix) */ + model?: string; + /** Working directory for the query */ + cwd: string; + /** System prompt (combined with user prompt for some providers) */ + systemPrompt?: string; + /** Maximum turns for agentic operations (default: 1) */ + maxTurns?: number; + /** Tools to allow (default: [] for simple queries) */ + allowedTools?: string[]; + /** Abort controller for cancellation */ + abortController?: AbortController; + /** Structured output format for JSON responses */ + outputFormat?: { + type: 'json_schema'; + schema: Record; + }; + /** Thinking level for Claude models */ + thinkingLevel?: ThinkingLevel; + /** Reasoning effort for Codex/OpenAI models */ + reasoningEffort?: ReasoningEffort; + /** If true, runs in read-only mode (no file writes) */ + readOnly?: boolean; + /** Setting sources for CLAUDE.md loading */ + settingSources?: Array<'user' | 'project' | 'local'>; +} + +/** + * Result from a simple query + */ +export interface SimpleQueryResult { + /** The accumulated text response */ + text: string; + /** Structured output if outputFormat was specified and provider supports it */ + structured_output?: Record; +} + +/** + * Options for streaming query execution + */ +export interface StreamingQueryOptions extends SimpleQueryOptions { + /** Callback for each text chunk received */ + onText?: (text: string) => void; + /** Callback for tool use events */ + onToolUse?: (tool: string, input: unknown) => void; + /** Callback for thinking blocks (if available) */ + onThinking?: (thinking: string) => void; +} + +/** + * Default model to use when none specified + */ +const DEFAULT_MODEL = 'claude-sonnet-4-20250514'; + +/** + * Execute a simple query and return the text result + * + * Use this for simple, non-streaming queries where you just need + * the final text response. For more complex use cases with progress + * callbacks, use streamingQuery() instead. + * + * @example + * ```typescript + * const result = await simpleQuery({ + * prompt: 'Generate a title for: user authentication', + * cwd: process.cwd(), + * systemPrompt: 'You are a title generator...', + * maxTurns: 1, + * allowedTools: [], + * }); + * console.log(result.text); // "Add user authentication" + * ``` + */ +export async function simpleQuery(options: SimpleQueryOptions): Promise { + const model = options.model || DEFAULT_MODEL; + const provider = ProviderFactory.getProviderForModel(model); + const bareModel = stripProviderPrefix(model); + + let responseText = ''; + let structuredOutput: Record | undefined; + + // Build provider options + const providerOptions = { + prompt: options.prompt, + model: bareModel, + originalModel: model, + cwd: options.cwd, + systemPrompt: options.systemPrompt, + maxTurns: options.maxTurns ?? 1, + allowedTools: options.allowedTools ?? [], + abortController: options.abortController, + outputFormat: options.outputFormat, + thinkingLevel: options.thinkingLevel, + reasoningEffort: options.reasoningEffort, + readOnly: options.readOnly, + settingSources: options.settingSources, + }; + + for await (const msg of provider.executeQuery(providerOptions)) { + // Handle error messages + if (msg.type === 'error') { + const errorMessage = msg.error || 'Provider returned an error'; + throw new Error(errorMessage); + } + + // Extract text from assistant messages + if (msg.type === 'assistant' && msg.message?.content) { + for (const block of msg.message.content) { + if (block.type === 'text' && block.text) { + responseText += block.text; + } + } + } + + // Handle result messages + if (msg.type === 'result') { + if (msg.subtype === 'success') { + // Use result text if longer than accumulated text + if (msg.result && msg.result.length > responseText.length) { + responseText = msg.result; + } + // Capture structured output if present + if (msg.structured_output) { + structuredOutput = msg.structured_output; + } + } else if (msg.subtype === 'error_max_turns') { + // Max turns reached - return what we have + break; + } else if (msg.subtype === 'error_max_structured_output_retries') { + throw new Error('Could not produce valid structured output after retries'); + } + } + } + + return { text: responseText, structured_output: structuredOutput }; +} + +/** + * Execute a streaming query with event callbacks + * + * Use this for queries where you need real-time progress updates, + * such as when displaying streaming output to a user. + * + * @example + * ```typescript + * const result = await streamingQuery({ + * prompt: 'Analyze this project and suggest improvements', + * cwd: '/path/to/project', + * maxTurns: 250, + * allowedTools: ['Read', 'Glob', 'Grep'], + * onText: (text) => emitProgress(text), + * onToolUse: (tool, input) => emitToolUse(tool, input), + * }); + * ``` + */ +export async function streamingQuery(options: StreamingQueryOptions): Promise { + const model = options.model || DEFAULT_MODEL; + const provider = ProviderFactory.getProviderForModel(model); + const bareModel = stripProviderPrefix(model); + + let responseText = ''; + let structuredOutput: Record | undefined; + + // Build provider options + const providerOptions = { + prompt: options.prompt, + model: bareModel, + originalModel: model, + cwd: options.cwd, + systemPrompt: options.systemPrompt, + maxTurns: options.maxTurns ?? 250, + allowedTools: options.allowedTools ?? ['Read', 'Glob', 'Grep'], + abortController: options.abortController, + outputFormat: options.outputFormat, + thinkingLevel: options.thinkingLevel, + reasoningEffort: options.reasoningEffort, + readOnly: options.readOnly, + settingSources: options.settingSources, + }; + + for await (const msg of provider.executeQuery(providerOptions)) { + // Handle error messages + if (msg.type === 'error') { + const errorMessage = msg.error || 'Provider returned an error'; + throw new Error(errorMessage); + } + + // Extract content from assistant messages + if (msg.type === 'assistant' && msg.message?.content) { + for (const block of msg.message.content) { + if (block.type === 'text' && block.text) { + responseText += block.text; + options.onText?.(block.text); + } else if (block.type === 'tool_use' && block.name) { + options.onToolUse?.(block.name, block.input); + } else if (block.type === 'thinking' && block.thinking) { + options.onThinking?.(block.thinking); + } + } + } + + // Handle result messages + if (msg.type === 'result') { + if (msg.subtype === 'success') { + // Use result text if longer than accumulated text + if (msg.result && msg.result.length > responseText.length) { + responseText = msg.result; + } + // Capture structured output if present + if (msg.structured_output) { + structuredOutput = msg.structured_output; + } + } else if (msg.subtype === 'error_max_turns') { + // Max turns reached - return what we have + break; + } else if (msg.subtype === 'error_max_structured_output_retries') { + throw new Error('Could not produce valid structured output after retries'); + } + } + } + + return { text: responseText, structured_output: structuredOutput }; +} diff --git a/apps/server/src/routes/app-spec/generate-features-from-spec.ts b/apps/server/src/routes/app-spec/generate-features-from-spec.ts index d89e5eff..55bf792b 100644 --- a/apps/server/src/routes/app-spec/generate-features-from-spec.ts +++ b/apps/server/src/routes/app-spec/generate-features-from-spec.ts @@ -5,15 +5,12 @@ * (defaults to Sonnet for balanced speed and quality). */ -import { query } from '@anthropic-ai/claude-agent-sdk'; import * as secureFs from '../../lib/secure-fs.js'; import type { EventEmitter } from '../../lib/events.js'; import { createLogger } from '@automaker/utils'; -import { DEFAULT_PHASE_MODELS, isCursorModel, stripProviderPrefix } from '@automaker/types'; +import { DEFAULT_PHASE_MODELS } from '@automaker/types'; import { resolvePhaseModel } from '@automaker/model-resolver'; -import { createFeatureGenerationOptions } from '../../lib/sdk-options.js'; -import { ProviderFactory } from '../../providers/provider-factory.js'; -import { logAuthStatus } from './common.js'; +import { streamingQuery } from '../../providers/simple-query-service.js'; import { parseAndCreateFeatures } from './parse-and-create-features.js'; import { getAppSpecPath } from '@automaker/platform'; import type { SettingsService } from '../../services/settings-service.js'; @@ -115,121 +112,30 @@ IMPORTANT: Do not ask for clarification. The specification is provided above. Ge logger.info('Using model:', model); - let responseText = ''; - let messageCount = 0; + // Use streamingQuery with event callbacks + const result = await streamingQuery({ + prompt, + model, + cwd: projectPath, + maxTurns: 250, + allowedTools: ['Read', 'Glob', 'Grep'], + abortController, + thinkingLevel, + readOnly: true, // Feature generation only reads code, doesn't write + settingSources: autoLoadClaudeMd ? ['user', 'project', 'local'] : undefined, + onText: (text) => { + logger.debug(`Feature text block received (${text.length} chars)`); + events.emit('spec-regeneration:event', { + type: 'spec_regeneration_progress', + content: text, + projectPath: projectPath, + }); + }, + }); - // Route to appropriate provider based on model type - if (isCursorModel(model)) { - // Use Cursor provider for Cursor models - logger.info('[FeatureGeneration] Using Cursor provider'); + const responseText = result.text; - const provider = ProviderFactory.getProviderForModel(model); - // Strip provider prefix - providers expect bare model IDs - const bareModel = stripProviderPrefix(model); - - // Add explicit instructions for Cursor to return JSON in response - const cursorPrompt = `${prompt} - -CRITICAL INSTRUCTIONS: -1. DO NOT write any files. Return the JSON in your response only. -2. Respond with ONLY a JSON object - no explanations, no markdown, just raw JSON. -3. Your entire response should be valid JSON starting with { and ending with }. No text before or after.`; - - for await (const msg of provider.executeQuery({ - prompt: cursorPrompt, - model: bareModel, - cwd: projectPath, - maxTurns: 250, - allowedTools: ['Read', 'Glob', 'Grep'], - abortController, - readOnly: true, // Feature generation only reads code, doesn't write - })) { - messageCount++; - - if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text' && block.text) { - responseText += block.text; - logger.debug(`Feature text block received (${block.text.length} chars)`); - events.emit('spec-regeneration:event', { - type: 'spec_regeneration_progress', - content: block.text, - projectPath: projectPath, - }); - } - } - } else if (msg.type === 'result' && msg.subtype === 'success' && msg.result) { - // Use result if it's a final accumulated message - if (msg.result.length > responseText.length) { - responseText = msg.result; - } - } - } - } else { - // Use Claude SDK for Claude models - logger.info('[FeatureGeneration] Using Claude SDK'); - - const options = createFeatureGenerationOptions({ - cwd: projectPath, - abortController, - autoLoadClaudeMd, - model, - thinkingLevel, // Pass thinking level for extended thinking - }); - - logger.debug('SDK Options:', JSON.stringify(options, null, 2)); - logger.info('Calling Claude Agent SDK query() for features...'); - - logAuthStatus('Right before SDK query() for features'); - - let stream; - try { - stream = query({ prompt, options }); - logger.debug('query() returned stream successfully'); - } catch (queryError) { - logger.error('❌ query() threw an exception:'); - logger.error('Error:', queryError); - throw queryError; - } - - logger.debug('Starting to iterate over feature stream...'); - - try { - for await (const msg of stream) { - messageCount++; - logger.debug( - `Feature stream message #${messageCount}:`, - JSON.stringify({ type: msg.type, subtype: (msg as any).subtype }, null, 2) - ); - - if (msg.type === 'assistant' && msg.message.content) { - for (const block of msg.message.content) { - if (block.type === 'text') { - responseText += block.text; - logger.debug(`Feature text block received (${block.text.length} chars)`); - events.emit('spec-regeneration:event', { - type: 'spec_regeneration_progress', - content: block.text, - projectPath: projectPath, - }); - } - } - } else if (msg.type === 'result' && (msg as any).subtype === 'success') { - logger.debug('Received success result for features'); - responseText = (msg as any).result || responseText; - } else if ((msg as { type: string }).type === 'error') { - logger.error('❌ Received error message from feature stream:'); - logger.error('Error message:', JSON.stringify(msg, null, 2)); - } - } - } catch (streamError) { - logger.error('❌ Error while iterating feature stream:'); - logger.error('Stream error:', streamError); - throw streamError; - } - } - - logger.info(`Feature stream complete. Total messages: ${messageCount}`); + logger.info(`Feature stream complete.`); logger.info(`Feature response length: ${responseText.length} chars`); logger.info('========== FULL RESPONSE TEXT =========='); logger.info(responseText); diff --git a/apps/server/src/routes/app-spec/generate-spec.ts b/apps/server/src/routes/app-spec/generate-spec.ts index fe293da2..4af42b48 100644 --- a/apps/server/src/routes/app-spec/generate-spec.ts +++ b/apps/server/src/routes/app-spec/generate-spec.ts @@ -5,8 +5,6 @@ * (defaults to Opus for high-quality specification generation). */ -import { query } from '@anthropic-ai/claude-agent-sdk'; -import path from 'path'; import * as secureFs from '../../lib/secure-fs.js'; import type { EventEmitter } from '../../lib/events.js'; import { @@ -16,12 +14,10 @@ import { type SpecOutput, } from '../../lib/app-spec-format.js'; import { createLogger } from '@automaker/utils'; -import { DEFAULT_PHASE_MODELS, isCursorModel, stripProviderPrefix } from '@automaker/types'; +import { DEFAULT_PHASE_MODELS, isCursorModel } from '@automaker/types'; import { resolvePhaseModel } from '@automaker/model-resolver'; -import { createSpecGenerationOptions } from '../../lib/sdk-options.js'; import { extractJson } from '../../lib/json-extractor.js'; -import { ProviderFactory } from '../../providers/provider-factory.js'; -import { logAuthStatus } from './common.js'; +import { streamingQuery } from '../../providers/simple-query-service.js'; import { generateFeaturesFromSpec } from './generate-features-from-spec.js'; import { ensureAutomakerDir, getAppSpecPath } from '@automaker/platform'; import type { SettingsService } from '../../services/settings-service.js'; @@ -109,21 +105,15 @@ ${getStructuredSpecPromptInstruction()}`; logger.info('Using model:', model); let responseText = ''; - let messageCount = 0; let structuredOutput: SpecOutput | null = null; - // Route to appropriate provider based on model type - if (isCursorModel(model)) { - // Use Cursor provider for Cursor models - logger.info('[SpecGeneration] Using Cursor provider'); + // Determine if we should use structured output (Claude supports it, Cursor doesn't) + const useStructuredOutput = !isCursorModel(model); - const provider = ProviderFactory.getProviderForModel(model); - // Strip provider prefix - providers expect bare model IDs - const bareModel = stripProviderPrefix(model); - - // For Cursor, include the JSON schema in the prompt with clear instructions - // to return JSON in the response (not write to a file) - const cursorPrompt = `${prompt} + // Build the final prompt - for Cursor, include JSON schema instructions + let finalPrompt = prompt; + if (!useStructuredOutput) { + finalPrompt = `${prompt} CRITICAL INSTRUCTIONS: 1. DO NOT write any files. DO NOT create any files like "project_specification.json". @@ -133,153 +123,57 @@ CRITICAL INSTRUCTIONS: ${JSON.stringify(specOutputSchema, null, 2)} Your entire response should be valid JSON starting with { and ending with }. No text before or after.`; - - for await (const msg of provider.executeQuery({ - prompt: cursorPrompt, - model: bareModel, - cwd: projectPath, - maxTurns: 250, - allowedTools: ['Read', 'Glob', 'Grep'], - abortController, - readOnly: true, // Spec generation only reads code, we write the spec ourselves - })) { - messageCount++; - - if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text' && block.text) { - responseText += block.text; - logger.info( - `Text block received (${block.text.length} chars), total now: ${responseText.length} chars` - ); - events.emit('spec-regeneration:event', { - type: 'spec_regeneration_progress', - content: block.text, - projectPath: projectPath, - }); - } else if (block.type === 'tool_use') { - logger.info('Tool use:', block.name); - events.emit('spec-regeneration:event', { - type: 'spec_tool', - tool: block.name, - input: block.input, - }); - } - } - } else if (msg.type === 'result' && msg.subtype === 'success' && msg.result) { - // Use result if it's a final accumulated message - if (msg.result.length > responseText.length) { - responseText = msg.result; - } - } - } - - // Parse JSON from the response text using shared utility - if (responseText) { - structuredOutput = extractJson(responseText, { logger }); - } - } else { - // Use Claude SDK for Claude models - logger.info('[SpecGeneration] Using Claude SDK'); - - const options = createSpecGenerationOptions({ - cwd: projectPath, - abortController, - autoLoadClaudeMd, - model, - thinkingLevel, // Pass thinking level for extended thinking - outputFormat: { - type: 'json_schema', - schema: specOutputSchema, - }, - }); - - logger.debug('SDK Options:', JSON.stringify(options, null, 2)); - logger.info('Calling Claude Agent SDK query()...'); - - // Log auth status right before the SDK call - logAuthStatus('Right before SDK query()'); - - let stream; - try { - stream = query({ prompt, options }); - logger.debug('query() returned stream successfully'); - } catch (queryError) { - logger.error('❌ query() threw an exception:'); - logger.error('Error:', queryError); - throw queryError; - } - - logger.info('Starting to iterate over stream...'); - - try { - for await (const msg of stream) { - messageCount++; - logger.info( - `Stream message #${messageCount}: type=${msg.type}, subtype=${(msg as any).subtype}` - ); - - if (msg.type === 'assistant') { - const msgAny = msg as any; - if (msgAny.message?.content) { - for (const block of msgAny.message.content) { - if (block.type === 'text') { - responseText += block.text; - logger.info( - `Text block received (${block.text.length} chars), total now: ${responseText.length} chars` - ); - events.emit('spec-regeneration:event', { - type: 'spec_regeneration_progress', - content: block.text, - projectPath: projectPath, - }); - } else if (block.type === 'tool_use') { - logger.info('Tool use:', block.name); - events.emit('spec-regeneration:event', { - type: 'spec_tool', - tool: block.name, - input: block.input, - }); - } - } - } - } else if (msg.type === 'result' && (msg as any).subtype === 'success') { - logger.info('Received success result'); - // Check for structured output - this is the reliable way to get spec data - const resultMsg = msg as any; - if (resultMsg.structured_output) { - structuredOutput = resultMsg.structured_output as SpecOutput; - logger.info('✅ Received structured output'); - logger.debug('Structured output:', JSON.stringify(structuredOutput, null, 2)); - } else { - logger.warn('⚠️ No structured output in result, will fall back to text parsing'); - } - } else if (msg.type === 'result') { - // Handle error result types - const subtype = (msg as any).subtype; - logger.info(`Result message: subtype=${subtype}`); - if (subtype === 'error_max_turns') { - logger.error('❌ Hit max turns limit!'); - } else if (subtype === 'error_max_structured_output_retries') { - logger.error('❌ Failed to produce valid structured output after retries'); - throw new Error('Could not produce valid spec output'); - } - } else if ((msg as { type: string }).type === 'error') { - logger.error('❌ Received error message from stream:'); - logger.error('Error message:', JSON.stringify(msg, null, 2)); - } else if (msg.type === 'user') { - // Log user messages (tool results) - logger.info(`User message (tool result): ${JSON.stringify(msg).substring(0, 500)}`); - } - } - } catch (streamError) { - logger.error('❌ Error while iterating stream:'); - logger.error('Stream error:', streamError); - throw streamError; - } } - logger.info(`Stream iteration complete. Total messages: ${messageCount}`); + // Use streamingQuery with event callbacks + const result = await streamingQuery({ + prompt: finalPrompt, + model, + cwd: projectPath, + maxTurns: 250, + allowedTools: ['Read', 'Glob', 'Grep'], + abortController, + thinkingLevel, + readOnly: true, // Spec generation only reads code, we write the spec ourselves + settingSources: autoLoadClaudeMd ? ['user', 'project', 'local'] : undefined, + outputFormat: useStructuredOutput + ? { + type: 'json_schema', + schema: specOutputSchema, + } + : undefined, + onText: (text) => { + responseText += text; + logger.info( + `Text block received (${text.length} chars), total now: ${responseText.length} chars` + ); + events.emit('spec-regeneration:event', { + type: 'spec_regeneration_progress', + content: text, + projectPath: projectPath, + }); + }, + onToolUse: (tool, input) => { + logger.info('Tool use:', tool); + events.emit('spec-regeneration:event', { + type: 'spec_tool', + tool, + input, + }); + }, + }); + + // Get structured output if available + if (result.structured_output) { + structuredOutput = result.structured_output as unknown as SpecOutput; + logger.info('✅ Received structured output'); + logger.debug('Structured output:', JSON.stringify(structuredOutput, null, 2)); + } else if (!useStructuredOutput && responseText) { + // For non-Claude providers, parse JSON from response text + structuredOutput = extractJson(responseText, { logger }); + } + + logger.info(`Stream iteration complete.`); logger.info(`Response text length: ${responseText.length} chars`); // Determine XML content to save diff --git a/apps/server/src/routes/context/routes/describe-file.ts b/apps/server/src/routes/context/routes/describe-file.ts index 1e312ff3..ca8c2b4a 100644 --- a/apps/server/src/routes/context/routes/describe-file.ts +++ b/apps/server/src/routes/context/routes/describe-file.ts @@ -11,13 +11,11 @@ */ import type { Request, Response } from 'express'; -import { query } from '@anthropic-ai/claude-agent-sdk'; import { createLogger } from '@automaker/utils'; -import { DEFAULT_PHASE_MODELS, isCursorModel, stripProviderPrefix } from '@automaker/types'; +import { DEFAULT_PHASE_MODELS } from '@automaker/types'; import { PathNotAllowedError } from '@automaker/platform'; import { resolvePhaseModel } from '@automaker/model-resolver'; -import { createCustomOptions } from '../../../lib/sdk-options.js'; -import { ProviderFactory } from '../../../providers/provider-factory.js'; +import { simpleQuery } from '../../../providers/simple-query-service.js'; import * as secureFs from '../../../lib/secure-fs.js'; import * as path from 'path'; import type { SettingsService } from '../../../services/settings-service.js'; @@ -49,31 +47,6 @@ interface DescribeFileErrorResponse { error: string; } -/** - * Extract text content from Claude SDK response messages - */ -async function extractTextFromStream( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - stream: AsyncIterable -): Promise { - let responseText = ''; - - for await (const msg of stream) { - if (msg.type === 'assistant' && msg.message?.content) { - const blocks = msg.message.content as Array<{ type: string; text?: string }>; - for (const block of blocks) { - if (block.type === 'text' && block.text) { - responseText += block.text; - } - } - } else if (msg.type === 'result' && msg.subtype === 'success') { - responseText = msg.result || responseText; - } - } - - return responseText; -} - /** * Create the describe-file request handler * @@ -159,16 +132,14 @@ export function createDescribeFileHandler( // Build prompt with file content passed as structured data // The file content is included directly, not via tool invocation - const instructionText = `Analyze the following file and provide a 1-2 sentence description suitable for use as context in an AI coding assistant. Focus on what the file contains, its purpose, and why an AI agent might want to use this context in the future (e.g., "API documentation for the authentication endpoints", "Configuration file for database connections", "Coding style guidelines for the project"). + const prompt = `Analyze the following file and provide a 1-2 sentence description suitable for use as context in an AI coding assistant. Focus on what the file contains, its purpose, and why an AI agent might want to use this context in the future (e.g., "API documentation for the authentication endpoints", "Configuration file for database connections", "Coding style guidelines for the project"). Respond with ONLY the description text, no additional formatting, preamble, or explanation. -File: ${fileName}${truncated ? ' (truncated)' : ''}`; +File: ${fileName}${truncated ? ' (truncated)' : ''} - const promptContent = [ - { type: 'text' as const, text: instructionText }, - { type: 'text' as const, text: `\n\n--- FILE CONTENT ---\n${contentToAnalyze}` }, - ]; +--- FILE CONTENT --- +${contentToAnalyze}`; // Use the file's directory as the working directory const cwd = path.dirname(resolvedPath); @@ -190,67 +161,19 @@ File: ${fileName}${truncated ? ' (truncated)' : ''}`; logger.info(`Resolved model: ${model}, thinkingLevel: ${thinkingLevel}`); - let description: string; + // Use simpleQuery - provider abstraction handles routing to correct provider + const result = await simpleQuery({ + prompt, + model, + cwd, + maxTurns: 1, + allowedTools: [], + thinkingLevel, + readOnly: true, // File description only reads, doesn't write + settingSources: autoLoadClaudeMd ? ['user', 'project', 'local'] : undefined, + }); - // Route to appropriate provider based on model type - if (isCursorModel(model)) { - // Use Cursor provider for Cursor models - logger.info(`Using Cursor provider for model: ${model}`); - - const provider = ProviderFactory.getProviderForModel(model); - // Strip provider prefix - providers expect bare model IDs - const bareModel = stripProviderPrefix(model); - - // Build a simple text prompt for Cursor (no multi-part content blocks) - const cursorPrompt = `${instructionText}\n\n--- FILE CONTENT ---\n${contentToAnalyze}`; - - let responseText = ''; - for await (const msg of provider.executeQuery({ - prompt: cursorPrompt, - model: bareModel, - cwd, - maxTurns: 1, - allowedTools: [], - readOnly: true, // File description only reads, doesn't write - })) { - if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text' && block.text) { - responseText += block.text; - } - } - } - } - description = responseText; - } else { - // Use Claude SDK for Claude models - logger.info(`Using Claude SDK for model: ${model}`); - - // Use centralized SDK options with proper cwd validation - // No tools needed since we're passing file content directly - const sdkOptions = createCustomOptions({ - cwd, - model, - maxTurns: 1, - allowedTools: [], - autoLoadClaudeMd, - thinkingLevel, // Pass thinking level for extended thinking - }); - - const promptGenerator = (async function* () { - yield { - type: 'user' as const, - session_id: '', - message: { role: 'user' as const, content: promptContent }, - parent_tool_use_id: null, - }; - })(); - - const stream = query({ prompt: promptGenerator, options: sdkOptions }); - - // Extract the description from the response - description = await extractTextFromStream(stream); - } + const description = result.text; if (!description || description.trim().length === 0) { logger.warn('Received empty response from Claude'); diff --git a/apps/server/src/routes/context/routes/describe-image.ts b/apps/server/src/routes/context/routes/describe-image.ts index 0ff8e143..e5e50963 100644 --- a/apps/server/src/routes/context/routes/describe-image.ts +++ b/apps/server/src/routes/context/routes/describe-image.ts @@ -12,12 +12,10 @@ */ import type { Request, Response } from 'express'; -import { query } from '@anthropic-ai/claude-agent-sdk'; import { createLogger, readImageAsBase64 } from '@automaker/utils'; -import { DEFAULT_PHASE_MODELS, isCursorModel, stripProviderPrefix } from '@automaker/types'; +import { DEFAULT_PHASE_MODELS, isCursorModel } from '@automaker/types'; import { resolvePhaseModel } from '@automaker/model-resolver'; -import { createCustomOptions } from '../../../lib/sdk-options.js'; -import { ProviderFactory } from '../../../providers/provider-factory.js'; +import { simpleQuery } from '../../../providers/simple-query-service.js'; import * as secureFs from '../../../lib/secure-fs.js'; import * as path from 'path'; import type { SettingsService } from '../../../services/settings-service.js'; @@ -178,57 +176,10 @@ function mapDescribeImageError(rawMessage: string | undefined): { return baseResponse; } -/** - * Extract text content from Claude SDK response messages and log high-signal stream events. - */ -async function extractTextFromStream( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - stream: AsyncIterable, - requestId: string -): Promise { - let responseText = ''; - let messageCount = 0; - - logger.info(`[${requestId}] [Stream] Begin reading SDK stream...`); - - for await (const msg of stream) { - messageCount++; - const msgType = msg?.type; - const msgSubtype = msg?.subtype; - - // Keep this concise but informative. Full error object is logged in catch blocks. - logger.info( - `[${requestId}] [Stream] #${messageCount} type=${String(msgType)} subtype=${String(msgSubtype ?? '')}` - ); - - if (msgType === 'assistant' && msg.message?.content) { - const blocks = msg.message.content as Array<{ type: string; text?: string }>; - logger.info(`[${requestId}] [Stream] assistant blocks=${blocks.length}`); - for (const block of blocks) { - if (block.type === 'text' && block.text) { - responseText += block.text; - } - } - } - - if (msgType === 'result' && msgSubtype === 'success') { - if (typeof msg.result === 'string' && msg.result.length > 0) { - responseText = msg.result; - } - } - } - - logger.info( - `[${requestId}] [Stream] End of stream. messages=${messageCount} textLength=${responseText.length}` - ); - - return responseText; -} - /** * Create the describe-image request handler * - * Uses Claude SDK query with multi-part content blocks to include the image (base64), + * Uses the provider abstraction with multi-part content blocks to include the image (base64), * matching the agent runner behavior. * * @param settingsService - Optional settings service for loading autoLoadClaudeMd setting @@ -309,27 +260,6 @@ export function createDescribeImageHandler( `[${requestId}] image meta filename=${imageData.filename} mime=${imageData.mimeType} base64Len=${base64Length} estBytes=${estimatedBytes}` ); - // Build multi-part prompt with image block (no Read tool required) - const instructionText = - `Describe this image in 1-2 sentences suitable for use as context in an AI coding assistant. ` + - `Focus on what the image shows and its purpose (e.g., "UI mockup showing login form with email/password fields", ` + - `"Architecture diagram of microservices", "Screenshot of error message in terminal").\n\n` + - `Respond with ONLY the description text, no additional formatting, preamble, or explanation.`; - - const promptContent = [ - { type: 'text' as const, text: instructionText }, - { - type: 'image' as const, - source: { - type: 'base64' as const, - media_type: imageData.mimeType, - data: imageData.base64, - }, - }, - ]; - - logger.info(`[${requestId}] Built multi-part prompt blocks=${promptContent.length}`); - const cwd = path.dirname(actualPath); logger.info(`[${requestId}] Using cwd=${cwd}`); @@ -348,85 +278,59 @@ export function createDescribeImageHandler( logger.info(`[${requestId}] Using model: ${model}`); - let description: string; + // Build the instruction text + const instructionText = + `Describe this image in 1-2 sentences suitable for use as context in an AI coding assistant. ` + + `Focus on what the image shows and its purpose (e.g., "UI mockup showing login form with email/password fields", ` + + `"Architecture diagram of microservices", "Screenshot of error message in terminal").\n\n` + + `Respond with ONLY the description text, no additional formatting, preamble, or explanation.`; + + // Build prompt based on provider capability + // Some providers (like Cursor) may not support image content blocks + let prompt: string | Array<{ type: string; text?: string; source?: object }>; - // Route to appropriate provider based on model type if (isCursorModel(model)) { - // Use Cursor provider for Cursor models - // Note: Cursor may have limited support for image content blocks - logger.info(`[${requestId}] Using Cursor provider for model: ${model}`); - - const provider = ProviderFactory.getProviderForModel(model); - // Strip provider prefix - providers expect bare model IDs - const bareModel = stripProviderPrefix(model); - - // Build prompt with image reference for Cursor - // Note: Cursor CLI may not support base64 image blocks directly, - // so we include the image path as context - const cursorPrompt = `${instructionText}\n\nImage file: ${actualPath}\nMIME type: ${imageData.mimeType}`; - - let responseText = ''; - const queryStart = Date.now(); - for await (const msg of provider.executeQuery({ - prompt: cursorPrompt, - model: bareModel, - cwd, - maxTurns: 1, - allowedTools: ['Read'], // Allow Read tool so Cursor can read the image if needed - readOnly: true, // Image description only reads, doesn't write - })) { - if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text' && block.text) { - responseText += block.text; - } - } - } - } - logger.info(`[${requestId}] Cursor query completed in ${Date.now() - queryStart}ms`); - description = responseText; + // Cursor may not support base64 image blocks directly + // Use text prompt with image path reference + logger.info(`[${requestId}] Using text prompt for Cursor model`); + prompt = `${instructionText}\n\nImage file: ${actualPath}\nMIME type: ${imageData.mimeType}`; } else { - // Use Claude SDK for Claude models (supports image content blocks) - logger.info(`[${requestId}] Using Claude SDK for model: ${model}`); - - // Use the same centralized option builder used across the server (validates cwd) - const sdkOptions = createCustomOptions({ - cwd, - model, - maxTurns: 1, - allowedTools: [], - autoLoadClaudeMd, - thinkingLevel, // Pass thinking level for extended thinking - }); - - logger.info( - `[${requestId}] SDK options model=${sdkOptions.model} maxTurns=${sdkOptions.maxTurns} allowedTools=${JSON.stringify( - sdkOptions.allowedTools - )}` - ); - - const promptGenerator = (async function* () { - yield { - type: 'user' as const, - session_id: '', - message: { role: 'user' as const, content: promptContent }, - parent_tool_use_id: null, - }; - })(); - - logger.info(`[${requestId}] Calling query()...`); - const queryStart = Date.now(); - const stream = query({ prompt: promptGenerator, options: sdkOptions }); - logger.info(`[${requestId}] query() returned stream in ${Date.now() - queryStart}ms`); - - // Extract the description from the response - const extractStart = Date.now(); - description = await extractTextFromStream(stream, requestId); - logger.info(`[${requestId}] extractMs=${Date.now() - extractStart}`); + // Claude and other vision-capable models support multi-part prompts with images + logger.info(`[${requestId}] Using multi-part prompt with image block`); + prompt = [ + { type: 'text', text: instructionText }, + { + type: 'image', + source: { + type: 'base64', + media_type: imageData.mimeType, + data: imageData.base64, + }, + }, + ]; } + logger.info(`[${requestId}] Calling simpleQuery...`); + const queryStart = Date.now(); + + // Use simpleQuery - provider abstraction handles routing + const result = await simpleQuery({ + prompt, + model, + cwd, + maxTurns: 1, + allowedTools: isCursorModel(model) ? ['Read'] : [], // Allow Read for Cursor to read image if needed + thinkingLevel, + readOnly: true, // Image description only reads, doesn't write + settingSources: autoLoadClaudeMd ? ['user', 'project', 'local'] : undefined, + }); + + logger.info(`[${requestId}] simpleQuery completed in ${Date.now() - queryStart}ms`); + + const description = result.text; + if (!description || description.trim().length === 0) { - logger.warn(`[${requestId}] Received empty response from Claude`); + logger.warn(`[${requestId}] Received empty response from AI`); const response: DescribeImageErrorResponse = { success: false, error: 'Failed to generate description - empty response', diff --git a/apps/server/src/routes/enhance-prompt/routes/enhance.ts b/apps/server/src/routes/enhance-prompt/routes/enhance.ts index 73043284..5861b418 100644 --- a/apps/server/src/routes/enhance-prompt/routes/enhance.ts +++ b/apps/server/src/routes/enhance-prompt/routes/enhance.ts @@ -1,23 +1,16 @@ /** * POST /enhance-prompt endpoint - Enhance user input text * - * Uses Claude AI or Cursor to enhance text based on the specified enhancement mode. - * Supports modes: improve, technical, simplify, acceptance + * Uses the provider abstraction to enhance text based on the specified + * enhancement mode. Works with any configured provider (Claude, Cursor, etc.). + * Supports modes: improve, technical, simplify, acceptance, ux-reviewer */ import type { Request, Response } from 'express'; -import { query } from '@anthropic-ai/claude-agent-sdk'; import { createLogger } from '@automaker/utils'; import { resolveModelString } from '@automaker/model-resolver'; -import { - CLAUDE_MODEL_MAP, - isCursorModel, - isOpencodeModel, - stripProviderPrefix, - ThinkingLevel, - getThinkingTokenBudget, -} from '@automaker/types'; -import { ProviderFactory } from '../../../providers/provider-factory.js'; +import { CLAUDE_MODEL_MAP, type ThinkingLevel } from '@automaker/types'; +import { simpleQuery } from '../../../providers/simple-query-service.js'; import type { SettingsService } from '../../../services/settings-service.js'; import { getPromptCustomization } from '../../../lib/settings-helpers.js'; import { @@ -38,7 +31,7 @@ interface EnhanceRequestBody { enhancementMode: string; /** Optional model override */ model?: string; - /** Optional thinking level for Claude models (ignored for Cursor models) */ + /** Optional thinking level for Claude models */ thinkingLevel?: ThinkingLevel; } @@ -58,80 +51,6 @@ interface EnhanceErrorResponse { error: string; } -/** - * Extract text content from Claude SDK response messages - * - * @param stream - The async iterable from the query function - * @returns The extracted text content - */ -async function extractTextFromStream( - stream: AsyncIterable<{ - type: string; - subtype?: string; - result?: string; - message?: { - content?: Array<{ type: string; text?: string }>; - }; - }> -): Promise { - let responseText = ''; - - for await (const msg of stream) { - if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text' && block.text) { - responseText += block.text; - } - } - } else if (msg.type === 'result' && msg.subtype === 'success') { - responseText = msg.result || responseText; - } - } - - return responseText; -} - -/** - * Execute enhancement using a provider (Cursor, OpenCode, etc.) - * - * @param prompt - The enhancement prompt - * @param model - The model to use - * @returns The enhanced text - */ -async function executeWithProvider(prompt: string, model: string): Promise { - const provider = ProviderFactory.getProviderForModel(model); - // Strip provider prefix - providers expect bare model IDs - const bareModel = stripProviderPrefix(model); - - let responseText = ''; - - for await (const msg of provider.executeQuery({ - prompt, - model: bareModel, - cwd: process.cwd(), // Enhancement doesn't need a specific working directory - readOnly: true, // Prompt enhancement only generates text, doesn't write files - })) { - if (msg.type === 'error') { - // Throw error with the message from the provider - const errorMessage = msg.error || 'Provider returned an error'; - throw new Error(errorMessage); - } else if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text' && block.text) { - responseText += block.text; - } - } - } else if (msg.type === 'result' && msg.subtype === 'success' && msg.result) { - // Use result if it's a final accumulated message - if (msg.result.length > responseText.length) { - responseText = msg.result; - } - } - } - - return responseText; -} - /** * Create the enhance request handler * @@ -200,7 +119,6 @@ export function createEnhanceHandler( logger.debug(`Using ${validMode} system prompt (length: ${systemPrompt.length} chars)`); // Build the user prompt with few-shot examples - // This helps the model understand this is text transformation, not a coding task const userPrompt = buildUserPrompt(validMode, trimmedText, true); // Resolve the model - use the passed model, default to sonnet for quality @@ -208,47 +126,20 @@ export function createEnhanceHandler( logger.debug(`Using model: ${resolvedModel}`); - let enhancedText: string; + // Use simpleQuery - provider abstraction handles routing to correct provider + // The system prompt is combined with user prompt since some providers + // don't have a separate system prompt concept + const result = await simpleQuery({ + prompt: `${systemPrompt}\n\n${userPrompt}`, + model: resolvedModel, + cwd: process.cwd(), // Enhancement doesn't need a specific working directory + maxTurns: 1, + allowedTools: [], + thinkingLevel, + readOnly: true, // Prompt enhancement only generates text, doesn't write files + }); - // Route to appropriate provider based on model - if (isCursorModel(resolvedModel)) { - // Use Cursor provider for Cursor models - logger.info(`Using Cursor provider for model: ${resolvedModel}`); - - // Cursor doesn't have a separate system prompt concept, so combine them - const combinedPrompt = `${systemPrompt}\n\n${userPrompt}`; - enhancedText = await executeWithProvider(combinedPrompt, resolvedModel); - } else if (isOpencodeModel(resolvedModel)) { - // Use OpenCode provider for OpenCode models (static and dynamic) - logger.info(`Using OpenCode provider for model: ${resolvedModel}`); - - // OpenCode CLI handles the system prompt, so combine them - const combinedPrompt = `${systemPrompt}\n\n${userPrompt}`; - enhancedText = await executeWithProvider(combinedPrompt, resolvedModel); - } else { - // Use Claude SDK for Claude models - logger.info(`Using Claude provider for model: ${resolvedModel}`); - - // Convert thinkingLevel to maxThinkingTokens for SDK - const maxThinkingTokens = getThinkingTokenBudget(thinkingLevel); - const queryOptions: Parameters[0]['options'] = { - model: resolvedModel, - systemPrompt, - maxTurns: 1, - allowedTools: [], - permissionMode: 'acceptEdits', - }; - if (maxThinkingTokens) { - queryOptions.maxThinkingTokens = maxThinkingTokens; - } - - const stream = query({ - prompt: userPrompt, - options: queryOptions, - }); - - enhancedText = await extractTextFromStream(stream); - } + const enhancedText = result.text; if (!enhancedText || enhancedText.trim().length === 0) { logger.warn('Received empty response from AI'); diff --git a/apps/server/src/routes/features/routes/generate-title.ts b/apps/server/src/routes/features/routes/generate-title.ts index 2602de03..a838e5aa 100644 --- a/apps/server/src/routes/features/routes/generate-title.ts +++ b/apps/server/src/routes/features/routes/generate-title.ts @@ -1,13 +1,14 @@ /** * POST /features/generate-title endpoint - Generate a concise title from description * - * Uses Claude Haiku to generate a short, descriptive title from feature description. + * Uses the provider abstraction to generate a short, descriptive title + * from a feature description. Works with any configured provider (Claude, Cursor, etc.). */ import type { Request, Response } from 'express'; -import { query } from '@anthropic-ai/claude-agent-sdk'; import { createLogger } from '@automaker/utils'; import { CLAUDE_MODEL_MAP } from '@automaker/model-resolver'; +import { simpleQuery } from '../../../providers/simple-query-service.js'; const logger = createLogger('GenerateTitle'); @@ -34,33 +35,6 @@ Rules: - No quotes, periods, or extra formatting - Capture the essence of the feature in a scannable way`; -async function extractTextFromStream( - stream: AsyncIterable<{ - type: string; - subtype?: string; - result?: string; - message?: { - content?: Array<{ type: string; text?: string }>; - }; - }> -): Promise { - let responseText = ''; - - for await (const msg of stream) { - if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text' && block.text) { - responseText += block.text; - } - } - } else if (msg.type === 'result' && msg.subtype === 'success') { - responseText = msg.result || responseText; - } - } - - return responseText; -} - export function createGenerateTitleHandler(): (req: Request, res: Response) => Promise { return async (req: Request, res: Response): Promise => { try { @@ -89,21 +63,19 @@ export function createGenerateTitleHandler(): (req: Request, res: Response) => P const userPrompt = `Generate a concise title for this feature:\n\n${trimmedDescription}`; - const stream = query({ - prompt: userPrompt, - options: { - model: CLAUDE_MODEL_MAP.haiku, - systemPrompt: SYSTEM_PROMPT, - maxTurns: 1, - allowedTools: [], - permissionMode: 'default', - }, + // Use simpleQuery - provider abstraction handles all the streaming/extraction + const result = await simpleQuery({ + prompt: `${SYSTEM_PROMPT}\n\n${userPrompt}`, + model: CLAUDE_MODEL_MAP.haiku, + cwd: process.cwd(), + maxTurns: 1, + allowedTools: [], }); - const title = await extractTextFromStream(stream); + const title = result.text; if (!title || title.trim().length === 0) { - logger.warn('Received empty response from Claude'); + logger.warn('Received empty response from AI'); const response: GenerateTitleErrorResponse = { success: false, error: 'Failed to generate title - empty response', diff --git a/apps/server/src/routes/github/routes/check-github-remote.ts b/apps/server/src/routes/github/routes/check-github-remote.ts index 34a07198..5efdb172 100644 --- a/apps/server/src/routes/github/routes/check-github-remote.ts +++ b/apps/server/src/routes/github/routes/check-github-remote.ts @@ -5,6 +5,43 @@ import type { Request, Response } from 'express'; import { execAsync, execEnv, getErrorMessage, logError } from './common.js'; +const GIT_REMOTE_ORIGIN_COMMAND = 'git remote get-url origin'; +const GH_REPO_VIEW_COMMAND = 'gh repo view --json name,owner'; +const GITHUB_REPO_URL_PREFIX = 'https://github.com/'; +const GITHUB_HTTPS_REMOTE_REGEX = /https:\/\/github\.com\/([^/]+)\/([^/.]+)/; +const GITHUB_SSH_REMOTE_REGEX = /git@github\.com:([^/]+)\/([^/.]+)/; + +interface GhRepoViewResponse { + name?: string; + owner?: { + login?: string; + }; +} + +async function resolveRepoFromGh(projectPath: string): Promise<{ + owner: string; + repo: string; +} | null> { + try { + const { stdout } = await execAsync(GH_REPO_VIEW_COMMAND, { + cwd: projectPath, + env: execEnv, + }); + + const data = JSON.parse(stdout) as GhRepoViewResponse; + const owner = typeof data.owner?.login === 'string' ? data.owner.login : null; + const repo = typeof data.name === 'string' ? data.name : null; + + if (!owner || !repo) { + return null; + } + + return { owner, repo }; + } catch { + return null; + } +} + export interface GitHubRemoteStatus { hasGitHubRemote: boolean; remoteUrl: string | null; @@ -21,19 +58,38 @@ export async function checkGitHubRemote(projectPath: string): Promise; @@ -45,6 +50,7 @@ interface GraphQLResponse { /** Timeout for GitHub API requests in milliseconds */ const GITHUB_API_TIMEOUT_MS = 30000; +const COMMENTS_PAGE_SIZE = 50; /** * Validate cursor format (GraphQL cursors are typically base64 strings) @@ -54,7 +60,7 @@ function isValidCursor(cursor: string): boolean { } /** - * Fetch comments for a specific issue using GitHub GraphQL API + * Fetch comments for a specific issue or pull request using GitHub GraphQL API */ async function fetchIssueComments( projectPath: string, @@ -70,24 +76,52 @@ async function fetchIssueComments( // Use GraphQL variables instead of string interpolation for safety const query = ` - query GetIssueComments($owner: String!, $repo: String!, $issueNumber: Int!, $cursor: String) { + query GetIssueComments( + $owner: String! + $repo: String! + $issueNumber: Int! + $cursor: String + $pageSize: Int! + ) { repository(owner: $owner, name: $repo) { - issue(number: $issueNumber) { - comments(first: 50, after: $cursor) { - totalCount - pageInfo { - hasNextPage - endCursor - } - nodes { - id - author { - login - avatarUrl + issueOrPullRequest(number: $issueNumber) { + __typename + ... on Issue { + comments(first: $pageSize, after: $cursor) { + totalCount + pageInfo { + hasNextPage + endCursor + } + nodes { + id + author { + login + avatarUrl + } + body + createdAt + updatedAt + } + } + } + ... on PullRequest { + comments(first: $pageSize, after: $cursor) { + totalCount + pageInfo { + hasNextPage + endCursor + } + nodes { + id + author { + login + avatarUrl + } + body + createdAt + updatedAt } - body - createdAt - updatedAt } } } @@ -99,6 +133,7 @@ async function fetchIssueComments( repo, issueNumber, cursor: cursor || null, + pageSize: COMMENTS_PAGE_SIZE, }; const requestBody = JSON.stringify({ query, variables }); @@ -140,10 +175,10 @@ async function fetchIssueComments( throw new Error(response.errors[0].message); } - const commentsData = response.data?.repository?.issue?.comments; + const commentsData = response.data?.repository?.issueOrPullRequest?.comments; if (!commentsData) { - throw new Error('Issue not found or no comments data available'); + throw new Error('Issue or pull request not found or no comments data available'); } const comments: GitHubComment[] = commentsData.nodes.map((node) => ({ diff --git a/apps/server/src/routes/github/routes/list-issues.ts b/apps/server/src/routes/github/routes/list-issues.ts index 9c0f8933..96c3c202 100644 --- a/apps/server/src/routes/github/routes/list-issues.ts +++ b/apps/server/src/routes/github/routes/list-issues.ts @@ -9,6 +9,17 @@ import { checkGitHubRemote } from './check-github-remote.js'; import { createLogger } from '@automaker/utils'; const logger = createLogger('ListIssues'); +const OPEN_ISSUES_LIMIT = 100; +const CLOSED_ISSUES_LIMIT = 50; +const ISSUE_LIST_FIELDS = 'number,title,state,author,createdAt,labels,url,body,assignees'; +const ISSUE_STATE_OPEN = 'open'; +const ISSUE_STATE_CLOSED = 'closed'; +const GH_ISSUE_LIST_COMMAND = 'gh issue list'; +const GH_STATE_FLAG = '--state'; +const GH_JSON_FLAG = '--json'; +const GH_LIMIT_FLAG = '--limit'; +const LINKED_PRS_BATCH_SIZE = 20; +const LINKED_PRS_TIMELINE_ITEMS = 10; export interface GitHubLabel { name: string; @@ -69,34 +80,68 @@ async function fetchLinkedPRs( // Build GraphQL query for batch fetching linked PRs // We fetch up to 20 issues at a time to avoid query limits - const batchSize = 20; - for (let i = 0; i < issueNumbers.length; i += batchSize) { - const batch = issueNumbers.slice(i, i + batchSize); + for (let i = 0; i < issueNumbers.length; i += LINKED_PRS_BATCH_SIZE) { + const batch = issueNumbers.slice(i, i + LINKED_PRS_BATCH_SIZE); const issueQueries = batch .map( (num, idx) => ` - issue${idx}: issue(number: ${num}) { - number - timelineItems(first: 10, itemTypes: [CROSS_REFERENCED_EVENT, CONNECTED_EVENT]) { - nodes { - ... on CrossReferencedEvent { - source { - ... on PullRequest { - number - title - state - url + issue${idx}: issueOrPullRequest(number: ${num}) { + ... on Issue { + number + timelineItems( + first: ${LINKED_PRS_TIMELINE_ITEMS} + itemTypes: [CROSS_REFERENCED_EVENT, CONNECTED_EVENT] + ) { + nodes { + ... on CrossReferencedEvent { + source { + ... on PullRequest { + number + title + state + url + } + } + } + ... on ConnectedEvent { + subject { + ... on PullRequest { + number + title + state + url + } } } } - ... on ConnectedEvent { - subject { - ... on PullRequest { - number - title - state - url + } + } + ... on PullRequest { + number + timelineItems( + first: ${LINKED_PRS_TIMELINE_ITEMS} + itemTypes: [CROSS_REFERENCED_EVENT, CONNECTED_EVENT] + ) { + nodes { + ... on CrossReferencedEvent { + source { + ... on PullRequest { + number + title + state + url + } + } + } + ... on ConnectedEvent { + subject { + ... on PullRequest { + number + title + state + url + } } } } @@ -213,16 +258,35 @@ export function createListIssuesHandler() { } // Fetch open and closed issues in parallel (now including assignees) + const repoQualifier = + remoteStatus.owner && remoteStatus.repo ? `${remoteStatus.owner}/${remoteStatus.repo}` : ''; + const repoFlag = repoQualifier ? `-R ${repoQualifier}` : ''; const [openResult, closedResult] = await Promise.all([ execAsync( - 'gh issue list --state open --json number,title,state,author,createdAt,labels,url,body,assignees --limit 100', + [ + GH_ISSUE_LIST_COMMAND, + repoFlag, + `${GH_STATE_FLAG} ${ISSUE_STATE_OPEN}`, + `${GH_JSON_FLAG} ${ISSUE_LIST_FIELDS}`, + `${GH_LIMIT_FLAG} ${OPEN_ISSUES_LIMIT}`, + ] + .filter(Boolean) + .join(' '), { cwd: projectPath, env: execEnv, } ), execAsync( - 'gh issue list --state closed --json number,title,state,author,createdAt,labels,url,body,assignees --limit 50', + [ + GH_ISSUE_LIST_COMMAND, + repoFlag, + `${GH_STATE_FLAG} ${ISSUE_STATE_CLOSED}`, + `${GH_JSON_FLAG} ${ISSUE_LIST_FIELDS}`, + `${GH_LIMIT_FLAG} ${CLOSED_ISSUES_LIMIT}`, + ] + .filter(Boolean) + .join(' '), { cwd: projectPath, env: execEnv, diff --git a/apps/server/src/routes/github/routes/list-prs.ts b/apps/server/src/routes/github/routes/list-prs.ts index 87f42a38..b273fc0a 100644 --- a/apps/server/src/routes/github/routes/list-prs.ts +++ b/apps/server/src/routes/github/routes/list-prs.ts @@ -6,6 +6,17 @@ import type { Request, Response } from 'express'; import { execAsync, execEnv, getErrorMessage, logError } from './common.js'; import { checkGitHubRemote } from './check-github-remote.js'; +const OPEN_PRS_LIMIT = 100; +const MERGED_PRS_LIMIT = 50; +const PR_LIST_FIELDS = + 'number,title,state,author,createdAt,labels,url,isDraft,headRefName,reviewDecision,mergeable,body'; +const PR_STATE_OPEN = 'open'; +const PR_STATE_MERGED = 'merged'; +const GH_PR_LIST_COMMAND = 'gh pr list'; +const GH_STATE_FLAG = '--state'; +const GH_JSON_FLAG = '--json'; +const GH_LIMIT_FLAG = '--limit'; + export interface GitHubLabel { name: string; color: string; @@ -57,16 +68,36 @@ export function createListPRsHandler() { return; } + const repoQualifier = + remoteStatus.owner && remoteStatus.repo ? `${remoteStatus.owner}/${remoteStatus.repo}` : ''; + const repoFlag = repoQualifier ? `-R ${repoQualifier}` : ''; + const [openResult, mergedResult] = await Promise.all([ execAsync( - 'gh pr list --state open --json number,title,state,author,createdAt,labels,url,isDraft,headRefName,reviewDecision,mergeable,body --limit 100', + [ + GH_PR_LIST_COMMAND, + repoFlag, + `${GH_STATE_FLAG} ${PR_STATE_OPEN}`, + `${GH_JSON_FLAG} ${PR_LIST_FIELDS}`, + `${GH_LIMIT_FLAG} ${OPEN_PRS_LIMIT}`, + ] + .filter(Boolean) + .join(' '), { cwd: projectPath, env: execEnv, } ), execAsync( - 'gh pr list --state merged --json number,title,state,author,createdAt,labels,url,isDraft,headRefName,reviewDecision,mergeable,body --limit 50', + [ + GH_PR_LIST_COMMAND, + repoFlag, + `${GH_STATE_FLAG} ${PR_STATE_MERGED}`, + `${GH_JSON_FLAG} ${PR_LIST_FIELDS}`, + `${GH_LIMIT_FLAG} ${MERGED_PRS_LIMIT}`, + ] + .filter(Boolean) + .join(' '), { cwd: projectPath, env: execEnv, diff --git a/apps/server/src/routes/github/routes/validate-issue.ts b/apps/server/src/routes/github/routes/validate-issue.ts index 237036ae..14de437b 100644 --- a/apps/server/src/routes/github/routes/validate-issue.ts +++ b/apps/server/src/routes/github/routes/validate-issue.ts @@ -1,29 +1,33 @@ /** - * POST /validate-issue endpoint - Validate a GitHub issue using Claude SDK or Cursor (async) + * POST /validate-issue endpoint - Validate a GitHub issue using provider abstraction (async) * * Scans the codebase to determine if an issue is valid, invalid, or needs clarification. * Runs asynchronously and emits events for progress and completion. - * Supports both Claude models and Cursor models. + * Supports Claude, Codex, Cursor, and OpenCode models. */ import type { Request, Response } from 'express'; -import { query } from '@anthropic-ai/claude-agent-sdk'; import type { EventEmitter } from '../../../lib/events.js'; import type { IssueValidationResult, IssueValidationEvent, - ModelAlias, - CursorModelId, + ModelId, GitHubComment, LinkedPRInfo, ThinkingLevel, + ReasoningEffort, +} from '@automaker/types'; +import { + DEFAULT_PHASE_MODELS, + isClaudeModel, + isCodexModel, + isCursorModel, + isOpencodeModel, } from '@automaker/types'; -import { isCursorModel, DEFAULT_PHASE_MODELS, stripProviderPrefix } from '@automaker/types'; import { resolvePhaseModel } from '@automaker/model-resolver'; -import { createSuggestionsOptions } from '../../../lib/sdk-options.js'; import { extractJson } from '../../../lib/json-extractor.js'; import { writeValidation } from '../../../lib/validation-storage.js'; -import { ProviderFactory } from '../../../providers/provider-factory.js'; +import { streamingQuery } from '../../../providers/simple-query-service.js'; import { issueValidationSchema, ISSUE_VALIDATION_SYSTEM_PROMPT, @@ -41,9 +45,6 @@ import { import type { SettingsService } from '../../../services/settings-service.js'; import { getAutoLoadClaudeMdSetting } from '../../../lib/settings-helpers.js'; -/** Valid Claude model values for validation */ -const VALID_CLAUDE_MODELS: readonly ModelAlias[] = ['opus', 'sonnet', 'haiku'] as const; - /** * Request body for issue validation */ @@ -53,10 +54,12 @@ interface ValidateIssueRequestBody { issueTitle: string; issueBody: string; issueLabels?: string[]; - /** Model to use for validation (opus, sonnet, haiku, or cursor model IDs) */ - model?: ModelAlias | CursorModelId; - /** Thinking level for Claude models (ignored for Cursor models) */ + /** Model to use for validation (Claude alias or provider model ID) */ + model?: ModelId; + /** Thinking level for Claude models (ignored for non-Claude models) */ thinkingLevel?: ThinkingLevel; + /** Reasoning effort for Codex models (ignored for non-Codex models) */ + reasoningEffort?: ReasoningEffort; /** Comments to include in validation analysis */ comments?: GitHubComment[]; /** Linked pull requests for this issue */ @@ -68,7 +71,7 @@ interface ValidateIssueRequestBody { * * Emits events for start, progress, complete, and error. * Stores result on completion. - * Supports both Claude models (with structured output) and Cursor models (with JSON parsing). + * Supports Claude/Codex models (structured output) and Cursor/OpenCode models (JSON parsing). */ async function runValidation( projectPath: string, @@ -76,13 +79,14 @@ async function runValidation( issueTitle: string, issueBody: string, issueLabels: string[] | undefined, - model: ModelAlias | CursorModelId, + model: ModelId, events: EventEmitter, abortController: AbortController, settingsService?: SettingsService, comments?: ValidationComment[], linkedPRs?: ValidationLinkedPR[], - thinkingLevel?: ThinkingLevel + thinkingLevel?: ThinkingLevel, + reasoningEffort?: ReasoningEffort ): Promise { // Emit start event const startEvent: IssueValidationEvent = { @@ -102,7 +106,7 @@ async function runValidation( try { // Build the prompt (include comments and linked PRs if provided) - const prompt = buildValidationPrompt( + const basePrompt = buildValidationPrompt( issueNumber, issueTitle, issueBody, @@ -111,20 +115,15 @@ async function runValidation( linkedPRs ); - let validationResult: IssueValidationResult | null = null; let responseText = ''; - // Route to appropriate provider based on model - if (isCursorModel(model)) { - // Use Cursor provider for Cursor models - logger.info(`Using Cursor provider for validation with model: ${model}`); + // Determine if we should use structured output (Claude/Codex support it, Cursor/OpenCode don't) + const useStructuredOutput = isClaudeModel(model) || isCodexModel(model); - const provider = ProviderFactory.getProviderForModel(model); - // Strip provider prefix - providers expect bare model IDs - const bareModel = stripProviderPrefix(model); - - // For Cursor, include the system prompt and schema in the user prompt - const cursorPrompt = `${ISSUE_VALIDATION_SYSTEM_PROMPT} + // Build the final prompt - for Cursor, include system prompt and JSON schema instructions + let finalPrompt = basePrompt; + if (!useStructuredOutput) { + finalPrompt = `${ISSUE_VALIDATION_SYSTEM_PROMPT} CRITICAL INSTRUCTIONS: 1. DO NOT write any files. Return the JSON in your response only. @@ -135,121 +134,78 @@ ${JSON.stringify(issueValidationSchema, null, 2)} Your entire response should be valid JSON starting with { and ending with }. No text before or after. -${prompt}`; +${basePrompt}`; + } - for await (const msg of provider.executeQuery({ - prompt: cursorPrompt, - model: bareModel, - cwd: projectPath, - readOnly: true, // Issue validation only reads code, doesn't write - })) { - if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text' && block.text) { - responseText += block.text; + // Load autoLoadClaudeMd setting + const autoLoadClaudeMd = await getAutoLoadClaudeMdSetting( + projectPath, + settingsService, + '[ValidateIssue]' + ); - // Emit progress event - const progressEvent: IssueValidationEvent = { - type: 'issue_validation_progress', - issueNumber, - content: block.text, - projectPath, - }; - events.emit('issue-validation:event', progressEvent); - } - } - } else if (msg.type === 'result' && msg.subtype === 'success' && msg.result) { - // Use result if it's a final accumulated message - if (msg.result.length > responseText.length) { - responseText = msg.result; - } - } - } - - // Parse JSON from the response text using shared utility - if (responseText) { - validationResult = extractJson(responseText, { logger }); - } - } else { - // Use Claude SDK for Claude models - logger.info(`Using Claude provider for validation with model: ${model}`); - - // Load autoLoadClaudeMd setting - const autoLoadClaudeMd = await getAutoLoadClaudeMdSetting( - projectPath, - settingsService, - '[ValidateIssue]' - ); - - // Use thinkingLevel from request if provided, otherwise fall back to settings - let effectiveThinkingLevel: ThinkingLevel | undefined = thinkingLevel; + // Use request overrides if provided, otherwise fall back to settings + let effectiveThinkingLevel: ThinkingLevel | undefined = thinkingLevel; + let effectiveReasoningEffort: ReasoningEffort | undefined = reasoningEffort; + if (!effectiveThinkingLevel || !effectiveReasoningEffort) { + const settings = await settingsService?.getGlobalSettings(); + const phaseModelEntry = + settings?.phaseModels?.validationModel || DEFAULT_PHASE_MODELS.validationModel; + const resolved = resolvePhaseModel(phaseModelEntry); if (!effectiveThinkingLevel) { - const settings = await settingsService?.getGlobalSettings(); - const phaseModelEntry = - settings?.phaseModels?.validationModel || DEFAULT_PHASE_MODELS.validationModel; - const resolved = resolvePhaseModel(phaseModelEntry); effectiveThinkingLevel = resolved.thinkingLevel; } - - // Create SDK options with structured output and abort controller - const options = createSuggestionsOptions({ - cwd: projectPath, - model: model as ModelAlias, - systemPrompt: ISSUE_VALIDATION_SYSTEM_PROMPT, - abortController, - autoLoadClaudeMd, - thinkingLevel: effectiveThinkingLevel, - outputFormat: { - type: 'json_schema', - schema: issueValidationSchema as Record, - }, - }); - - // Execute the query - const stream = query({ prompt, options }); - - for await (const msg of stream) { - // Collect assistant text for debugging and emit progress - if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text') { - responseText += block.text; - - // Emit progress event - const progressEvent: IssueValidationEvent = { - type: 'issue_validation_progress', - issueNumber, - content: block.text, - projectPath, - }; - events.emit('issue-validation:event', progressEvent); - } - } - } - - // Extract structured output on success - if (msg.type === 'result' && msg.subtype === 'success') { - const resultMsg = msg as { structured_output?: IssueValidationResult }; - if (resultMsg.structured_output) { - validationResult = resultMsg.structured_output; - logger.debug('Received structured output:', validationResult); - } - } - - // Handle errors - if (msg.type === 'result') { - const resultMsg = msg as { subtype?: string }; - if (resultMsg.subtype === 'error_max_structured_output_retries') { - logger.error('Failed to produce valid structured output after retries'); - throw new Error('Could not produce valid validation output'); - } - } + if (!effectiveReasoningEffort && typeof phaseModelEntry !== 'string') { + effectiveReasoningEffort = phaseModelEntry.reasoningEffort; } } + logger.info(`Using model: ${model}`); + + // Use streamingQuery with event callbacks + const result = await streamingQuery({ + prompt: finalPrompt, + model: model as string, + cwd: projectPath, + systemPrompt: useStructuredOutput ? ISSUE_VALIDATION_SYSTEM_PROMPT : undefined, + abortController, + thinkingLevel: effectiveThinkingLevel, + reasoningEffort: effectiveReasoningEffort, + readOnly: true, // Issue validation only reads code, doesn't write + settingSources: autoLoadClaudeMd ? ['user', 'project', 'local'] : undefined, + outputFormat: useStructuredOutput + ? { + type: 'json_schema', + schema: issueValidationSchema as Record, + } + : undefined, + onText: (text) => { + responseText += text; + // Emit progress event + const progressEvent: IssueValidationEvent = { + type: 'issue_validation_progress', + issueNumber, + content: text, + projectPath, + }; + events.emit('issue-validation:event', progressEvent); + }, + }); + // Clear timeout clearTimeout(timeoutId); + // Get validation result from structured output or parse from text + let validationResult: IssueValidationResult | null = null; + + if (result.structured_output) { + validationResult = result.structured_output as unknown as IssueValidationResult; + logger.debug('Received structured output:', validationResult); + } else if (responseText) { + // Parse JSON from response text + validationResult = extractJson(responseText, { logger }); + } + // Require validation result if (!validationResult) { logger.error('No validation result received from AI provider'); @@ -299,7 +255,7 @@ ${prompt}`; /** * Creates the handler for validating GitHub issues against the codebase. * - * Uses Claude SDK with: + * Uses the provider abstraction with: * - Read-only tools (Read, Glob, Grep) for codebase analysis * - JSON schema structured output for reliable parsing * - System prompt guiding the validation process @@ -319,6 +275,7 @@ export function createValidateIssueHandler( issueLabels, model = 'opus', thinkingLevel, + reasoningEffort, comments: rawComments, linkedPRs: rawLinkedPRs, } = req.body as ValidateIssueRequestBody; @@ -366,14 +323,17 @@ export function createValidateIssueHandler( return; } - // Validate model parameter at runtime - accept Claude models or Cursor models - const isValidClaudeModel = VALID_CLAUDE_MODELS.includes(model as ModelAlias); - const isValidCursorModel = isCursorModel(model); + // Validate model parameter at runtime - accept any supported provider model + const isValidModel = + isClaudeModel(model) || + isCursorModel(model) || + isCodexModel(model) || + isOpencodeModel(model); - if (!isValidClaudeModel && !isValidCursorModel) { + if (!isValidModel) { res.status(400).json({ success: false, - error: `Invalid model. Must be one of: ${VALID_CLAUDE_MODELS.join(', ')}, or a Cursor model ID`, + error: 'Invalid model. Must be a Claude, Cursor, Codex, or OpenCode model ID (or alias).', }); return; } @@ -404,7 +364,8 @@ export function createValidateIssueHandler( settingsService, validationComments, validationLinkedPRs, - thinkingLevel + thinkingLevel, + reasoningEffort ) .catch(() => { // Error is already handled inside runValidation (event emitted) diff --git a/apps/server/src/routes/settings/routes/get-credentials.ts b/apps/server/src/routes/settings/routes/get-credentials.ts index be15b04b..140ccce4 100644 --- a/apps/server/src/routes/settings/routes/get-credentials.ts +++ b/apps/server/src/routes/settings/routes/get-credentials.ts @@ -5,7 +5,7 @@ * Each provider shows: `{ configured: boolean, masked: string }` * Masked shows first 4 and last 4 characters for verification. * - * Response: `{ "success": true, "credentials": { anthropic } }` + * Response: `{ "success": true, "credentials": { anthropic, google, openai } }` */ import type { Request, Response } from 'express'; diff --git a/apps/server/src/routes/settings/routes/update-credentials.ts b/apps/server/src/routes/settings/routes/update-credentials.ts index c08b2445..2b415830 100644 --- a/apps/server/src/routes/settings/routes/update-credentials.ts +++ b/apps/server/src/routes/settings/routes/update-credentials.ts @@ -1,7 +1,7 @@ /** * PUT /api/settings/credentials - Update API credentials * - * Updates API keys for Anthropic. Partial updates supported. + * Updates API keys for supported providers. Partial updates supported. * Returns masked credentials for verification without exposing full keys. * * Request body: `Partial` (usually just apiKeys) diff --git a/apps/server/src/routes/setup/routes/api-keys.ts b/apps/server/src/routes/setup/routes/api-keys.ts index 047b6455..ec870e7b 100644 --- a/apps/server/src/routes/setup/routes/api-keys.ts +++ b/apps/server/src/routes/setup/routes/api-keys.ts @@ -11,6 +11,7 @@ export function createApiKeysHandler() { res.json({ success: true, hasAnthropicKey: !!getApiKey('anthropic') || !!process.env.ANTHROPIC_API_KEY, + hasGoogleKey: !!getApiKey('google'), hasOpenaiKey: !!getApiKey('openai') || !!process.env.OPENAI_API_KEY, }); } catch (error) { diff --git a/apps/server/src/routes/setup/routes/store-api-key.ts b/apps/server/src/routes/setup/routes/store-api-key.ts index e77a697e..eae2e430 100644 --- a/apps/server/src/routes/setup/routes/store-api-key.ts +++ b/apps/server/src/routes/setup/routes/store-api-key.ts @@ -21,22 +21,25 @@ export function createStoreApiKeyHandler() { return; } - setApiKey(provider, apiKey); - - // Also set as environment variable and persist to .env - if (provider === 'anthropic' || provider === 'anthropic_oauth_token') { - // Both API key and OAuth token use ANTHROPIC_API_KEY - process.env.ANTHROPIC_API_KEY = apiKey; - await persistApiKeyToEnv('ANTHROPIC_API_KEY', apiKey); - logger.info('[Setup] Stored API key as ANTHROPIC_API_KEY'); - } else { + const providerEnvMap: Record = { + anthropic: 'ANTHROPIC_API_KEY', + anthropic_oauth_token: 'ANTHROPIC_API_KEY', + openai: 'OPENAI_API_KEY', + }; + const envKey = providerEnvMap[provider]; + if (!envKey) { res.status(400).json({ success: false, - error: `Unsupported provider: ${provider}. Only anthropic is supported.`, + error: `Unsupported provider: ${provider}. Only anthropic and openai are supported.`, }); return; } + setApiKey(provider, apiKey); + process.env[envKey] = apiKey; + await persistApiKeyToEnv(envKey, apiKey); + logger.info(`[Setup] Stored API key as ${envKey}`); + res.json({ success: true }); } catch (error) { logError(error, 'Store API key failed'); diff --git a/apps/server/src/routes/suggestions/generate-suggestions.ts b/apps/server/src/routes/suggestions/generate-suggestions.ts index 2cf7925f..0766c41b 100644 --- a/apps/server/src/routes/suggestions/generate-suggestions.ts +++ b/apps/server/src/routes/suggestions/generate-suggestions.ts @@ -5,19 +5,12 @@ * (AI Suggestions in the UI). Supports both Claude and Cursor models. */ -import { query } from '@anthropic-ai/claude-agent-sdk'; import type { EventEmitter } from '../../lib/events.js'; import { createLogger } from '@automaker/utils'; -import { - DEFAULT_PHASE_MODELS, - isCursorModel, - stripProviderPrefix, - type ThinkingLevel, -} from '@automaker/types'; +import { DEFAULT_PHASE_MODELS, isCursorModel, type ThinkingLevel } from '@automaker/types'; import { resolvePhaseModel } from '@automaker/model-resolver'; -import { createSuggestionsOptions } from '../../lib/sdk-options.js'; import { extractJsonWithArray } from '../../lib/json-extractor.js'; -import { ProviderFactory } from '../../providers/provider-factory.js'; +import { streamingQuery } from '../../providers/simple-query-service.js'; import { FeatureLoader } from '../../services/feature-loader.js'; import { getAppSpecPath } from '@automaker/platform'; import * as secureFs from '../../lib/secure-fs.js'; @@ -204,19 +197,14 @@ The response will be automatically formatted as structured JSON.`; logger.info('[Suggestions] Using model:', model); let responseText = ''; - let structuredOutput: { suggestions: Array> } | null = null; - // Route to appropriate provider based on model type - if (isCursorModel(model)) { - // Use Cursor provider for Cursor models - logger.info('[Suggestions] Using Cursor provider'); + // Determine if we should use structured output (Claude supports it, Cursor doesn't) + const useStructuredOutput = !isCursorModel(model); - const provider = ProviderFactory.getProviderForModel(model); - // Strip provider prefix - providers expect bare model IDs - const bareModel = stripProviderPrefix(model); - - // For Cursor, include the JSON schema in the prompt with clear instructions - const cursorPrompt = `${prompt} + // Build the final prompt - for Cursor, include JSON schema instructions + let finalPrompt = prompt; + if (!useStructuredOutput) { + finalPrompt = `${prompt} CRITICAL INSTRUCTIONS: 1. DO NOT write any files. Return the JSON in your response only. @@ -226,104 +214,60 @@ CRITICAL INSTRUCTIONS: ${JSON.stringify(suggestionsSchema, null, 2)} Your entire response should be valid JSON starting with { and ending with }. No text before or after.`; - - for await (const msg of provider.executeQuery({ - prompt: cursorPrompt, - model: bareModel, - cwd: projectPath, - maxTurns: 250, - allowedTools: ['Read', 'Glob', 'Grep'], - abortController, - readOnly: true, // Suggestions only reads code, doesn't write - })) { - if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text' && block.text) { - responseText += block.text; - events.emit('suggestions:event', { - type: 'suggestions_progress', - content: block.text, - }); - } else if (block.type === 'tool_use') { - events.emit('suggestions:event', { - type: 'suggestions_tool', - tool: block.name, - input: block.input, - }); - } - } - } else if (msg.type === 'result' && msg.subtype === 'success' && msg.result) { - // Use result if it's a final accumulated message (from Cursor provider) - logger.info('[Suggestions] Received result from Cursor, length:', msg.result.length); - logger.info('[Suggestions] Previous responseText length:', responseText.length); - if (msg.result.length > responseText.length) { - logger.info('[Suggestions] Using Cursor result (longer than accumulated text)'); - responseText = msg.result; - } else { - logger.info('[Suggestions] Keeping accumulated text (longer than Cursor result)'); - } - } - } - } else { - // Use Claude SDK for Claude models - logger.info('[Suggestions] Using Claude SDK'); - - const options = createSuggestionsOptions({ - cwd: projectPath, - abortController, - autoLoadClaudeMd, - model, // Pass the model from settings - thinkingLevel, // Pass thinking level for extended thinking - outputFormat: { - type: 'json_schema', - schema: suggestionsSchema, - }, - }); - - const stream = query({ prompt, options }); - - for await (const msg of stream) { - if (msg.type === 'assistant' && msg.message.content) { - for (const block of msg.message.content) { - if (block.type === 'text') { - responseText += block.text; - events.emit('suggestions:event', { - type: 'suggestions_progress', - content: block.text, - }); - } else if (block.type === 'tool_use') { - events.emit('suggestions:event', { - type: 'suggestions_tool', - tool: block.name, - input: block.input, - }); - } - } - } else if (msg.type === 'result' && msg.subtype === 'success') { - // Check for structured output - const resultMsg = msg as any; - if (resultMsg.structured_output) { - structuredOutput = resultMsg.structured_output as { - suggestions: Array>; - }; - logger.debug('Received structured output:', structuredOutput); - } - } else if (msg.type === 'result') { - const resultMsg = msg as any; - if (resultMsg.subtype === 'error_max_structured_output_retries') { - logger.error('Failed to produce valid structured output after retries'); - throw new Error('Could not produce valid suggestions output'); - } else if (resultMsg.subtype === 'error_max_turns') { - logger.error('Hit max turns limit before completing suggestions generation'); - logger.warn(`Response text length: ${responseText.length} chars`); - // Still try to parse what we have - } - } - } } + // Use streamingQuery with event callbacks + const result = await streamingQuery({ + prompt: finalPrompt, + model, + cwd: projectPath, + maxTurns: 250, + allowedTools: ['Read', 'Glob', 'Grep'], + abortController, + thinkingLevel, + readOnly: true, // Suggestions only reads code, doesn't write + settingSources: autoLoadClaudeMd ? ['user', 'project', 'local'] : undefined, + outputFormat: useStructuredOutput + ? { + type: 'json_schema', + schema: suggestionsSchema, + } + : undefined, + onText: (text) => { + responseText += text; + events.emit('suggestions:event', { + type: 'suggestions_progress', + content: text, + }); + }, + onToolUse: (tool, input) => { + events.emit('suggestions:event', { + type: 'suggestions_tool', + tool, + input, + }); + }, + }); + // Use structured output if available, otherwise fall back to parsing text try { + let structuredOutput: { suggestions: Array> } | null = null; + + if (result.structured_output) { + structuredOutput = result.structured_output as { + suggestions: Array>; + }; + logger.debug('Received structured output:', structuredOutput); + } else if (responseText) { + // Fallback: try to parse from text using shared extraction utility + logger.warn('No structured output received, attempting to parse from text'); + structuredOutput = extractJsonWithArray<{ suggestions: Array> }>( + responseText, + 'suggestions', + { logger } + ); + } + if (structuredOutput && structuredOutput.suggestions) { // Use structured output directly events.emit('suggestions:event', { @@ -334,24 +278,7 @@ Your entire response should be valid JSON starting with { and ending with }. No })), }); } else { - // Fallback: try to parse from text using shared extraction utility - logger.warn('No structured output received, attempting to parse from text'); - const parsed = extractJsonWithArray<{ suggestions: Array> }>( - responseText, - 'suggestions', - { logger } - ); - if (parsed && parsed.suggestions) { - events.emit('suggestions:event', { - type: 'suggestions_complete', - suggestions: parsed.suggestions.map((s: Record, i: number) => ({ - ...s, - id: s.id || `suggestion-${Date.now()}-${i}`, - })), - }); - } else { - throw new Error('No valid JSON found in response'); - } + throw new Error('No valid JSON found in response'); } } catch (error) { // Log the parsing error for debugging diff --git a/apps/server/src/services/auto-mode-service.ts b/apps/server/src/services/auto-mode-service.ts index b830a297..29caa4e1 100644 --- a/apps/server/src/services/auto-mode-service.ts +++ b/apps/server/src/services/auto-mode-service.ts @@ -10,15 +10,18 @@ */ import { ProviderFactory } from '../providers/provider-factory.js'; +import { simpleQuery } from '../providers/simple-query-service.js'; import type { ExecuteOptions, Feature, ModelProvider, PipelineStep, + FeatureStatusWithPipeline, + PipelineConfig, ThinkingLevel, PlanningMode, } from '@automaker/types'; -import { DEFAULT_PHASE_MODELS, stripProviderPrefix } from '@automaker/types'; +import { DEFAULT_PHASE_MODELS, isClaudeModel, stripProviderPrefix } from '@automaker/types'; import { buildPromptWithImages, classifyError, @@ -83,6 +86,26 @@ interface PlanSpec { tasks?: ParsedTask[]; } +/** + * Information about pipeline status when resuming a feature. + * Used to determine how to handle features stuck in pipeline execution. + * + * @property {boolean} isPipeline - Whether the feature is in a pipeline step + * @property {string | null} stepId - ID of the current pipeline step (e.g., 'step_123') + * @property {number} stepIndex - Index of the step in the sorted pipeline steps (-1 if not found) + * @property {number} totalSteps - Total number of steps in the pipeline + * @property {PipelineStep | null} step - The pipeline step configuration, or null if step not found + * @property {PipelineConfig | null} config - The full pipeline configuration, or null if no pipeline + */ +interface PipelineStatusInfo { + isPipeline: boolean; + stepId: string | null; + stepIndex: number; + totalSteps: number; + step: PipelineStep | null; + config: PipelineConfig | null; +} + /** * Parse tasks from generated spec content * Looks for the ```tasks code block and extracts task lines @@ -917,6 +940,25 @@ Complete the pipeline step instructions above. Review the previous work and appl throw new Error('already running'); } + // Load feature to check status + const feature = await this.loadFeature(projectPath, featureId); + if (!feature) { + throw new Error(`Feature ${featureId} not found`); + } + + // Check if feature is stuck in a pipeline step + const pipelineInfo = await this.detectPipelineStatus( + projectPath, + featureId, + (feature.status || '') as FeatureStatusWithPipeline + ); + + if (pipelineInfo.isPipeline) { + // Feature stuck in pipeline - use pipeline resume + return this.resumePipelineFeature(projectPath, feature, useWorktrees, pipelineInfo); + } + + // Normal resume flow for non-pipeline features // Check if context exists in .automaker directory const featureDir = getFeatureDir(projectPath, featureId); const contextPath = path.join(featureDir, 'agent-output.md'); @@ -936,11 +978,252 @@ Complete the pipeline step instructions above. Review the previous work and appl } // No context, start fresh - executeFeature will handle adding to runningFeatures - // Remove the temporary entry we added - this.runningFeatures.delete(featureId); return this.executeFeature(projectPath, featureId, useWorktrees, false); } + /** + * Resume a feature that crashed during pipeline execution. + * Handles multiple edge cases to ensure robust recovery: + * - No context file: Restart entire pipeline from beginning + * - Step deleted from config: Complete feature without remaining pipeline steps + * - Valid step exists: Resume from the crashed step and continue + * + * @param {string} projectPath - Absolute path to the project directory + * @param {Feature} feature - The feature object (already loaded to avoid redundant reads) + * @param {boolean} useWorktrees - Whether to use git worktrees for isolation + * @param {PipelineStatusInfo} pipelineInfo - Information about the pipeline status from detectPipelineStatus() + * @returns {Promise} Resolves when resume operation completes or throws on error + * @throws {Error} If pipeline config is null but stepIndex is valid (should never happen) + * @private + */ + private async resumePipelineFeature( + projectPath: string, + feature: Feature, + useWorktrees: boolean, + pipelineInfo: PipelineStatusInfo + ): Promise { + const featureId = feature.id; + console.log( + `[AutoMode] Resuming feature ${featureId} from pipeline step ${pipelineInfo.stepId}` + ); + + // Check for context file + const featureDir = getFeatureDir(projectPath, featureId); + const contextPath = path.join(featureDir, 'agent-output.md'); + + let hasContext = false; + try { + await secureFs.access(contextPath); + hasContext = true; + } catch { + // No context + } + + // Edge Case 1: No context file - restart entire pipeline from beginning + if (!hasContext) { + console.warn( + `[AutoMode] No context found for pipeline feature ${featureId}, restarting from beginning` + ); + + // Reset status to in_progress and start fresh + await this.updateFeatureStatus(projectPath, featureId, 'in_progress'); + + return this.executeFeature(projectPath, featureId, useWorktrees, false); + } + + // Edge Case 2: Step no longer exists in pipeline config + if (pipelineInfo.stepIndex === -1) { + console.warn( + `[AutoMode] Step ${pipelineInfo.stepId} no longer exists in pipeline, completing feature without pipeline` + ); + + const finalStatus = feature.skipTests ? 'waiting_approval' : 'verified'; + + await this.updateFeatureStatus(projectPath, featureId, finalStatus); + + this.emitAutoModeEvent('auto_mode_feature_complete', { + featureId, + passes: true, + message: + 'Pipeline step no longer exists - feature completed without remaining pipeline steps', + projectPath, + }); + + return; + } + + // Normal case: Valid pipeline step exists, has context + // Resume from the stuck step (re-execute the step that crashed) + if (!pipelineInfo.config) { + throw new Error('Pipeline config is null but stepIndex is valid - this should not happen'); + } + + return this.resumeFromPipelineStep( + projectPath, + feature, + useWorktrees, + pipelineInfo.stepIndex, + pipelineInfo.config + ); + } + + /** + * Resume pipeline execution from a specific step index. + * Re-executes the step that crashed (to handle partial completion), + * then continues executing all remaining pipeline steps in order. + * + * This method handles the complete pipeline resume workflow: + * - Validates feature and step index + * - Locates or creates git worktree if needed + * - Executes remaining steps starting from the crashed step + * - Updates feature status to verified/waiting_approval when complete + * - Emits progress events throughout execution + * + * @param {string} projectPath - Absolute path to the project directory + * @param {Feature} feature - The feature object (already loaded to avoid redundant reads) + * @param {boolean} useWorktrees - Whether to use git worktrees for isolation + * @param {number} startFromStepIndex - Zero-based index of the step to resume from + * @param {PipelineConfig} pipelineConfig - Pipeline config passed from detectPipelineStatus to avoid re-reading + * @returns {Promise} Resolves when pipeline execution completes successfully + * @throws {Error} If feature not found, step index invalid, or pipeline execution fails + * @private + */ + private async resumeFromPipelineStep( + projectPath: string, + feature: Feature, + useWorktrees: boolean, + startFromStepIndex: number, + pipelineConfig: PipelineConfig + ): Promise { + const featureId = feature.id; + + const sortedSteps = [...pipelineConfig.steps].sort((a, b) => a.order - b.order); + + // Validate step index + if (startFromStepIndex < 0 || startFromStepIndex >= sortedSteps.length) { + throw new Error(`Invalid step index: ${startFromStepIndex}`); + } + + // Get steps to execute (from startFromStepIndex onwards) + const stepsToExecute = sortedSteps.slice(startFromStepIndex); + + console.log( + `[AutoMode] Resuming pipeline for feature ${featureId} from step ${startFromStepIndex + 1}/${sortedSteps.length}` + ); + + // Add to running features immediately + const abortController = new AbortController(); + this.runningFeatures.set(featureId, { + featureId, + projectPath, + worktreePath: null, // Will be set below + branchName: feature.branchName ?? null, + abortController, + isAutoMode: false, + startTime: Date.now(), + }); + + try { + // Validate project path + validateWorkingDirectory(projectPath); + + // Derive workDir from feature.branchName + let worktreePath: string | null = null; + const branchName = feature.branchName; + + if (useWorktrees && branchName) { + worktreePath = await this.findExistingWorktreeForBranch(projectPath, branchName); + if (worktreePath) { + console.log(`[AutoMode] Using worktree for branch "${branchName}": ${worktreePath}`); + } else { + console.warn( + `[AutoMode] Worktree for branch "${branchName}" not found, using project path` + ); + } + } + + const workDir = worktreePath ? path.resolve(worktreePath) : path.resolve(projectPath); + validateWorkingDirectory(workDir); + + // Update running feature with worktree info + const runningFeature = this.runningFeatures.get(featureId); + if (runningFeature) { + runningFeature.worktreePath = worktreePath; + runningFeature.branchName = branchName ?? null; + } + + // Emit resume event + this.emitAutoModeEvent('auto_mode_feature_start', { + featureId, + projectPath, + feature: { + id: featureId, + title: feature.title || 'Resuming Pipeline', + description: feature.description, + }, + }); + + this.emitAutoModeEvent('auto_mode_progress', { + featureId, + content: `Resuming from pipeline step ${startFromStepIndex + 1}/${sortedSteps.length}`, + projectPath, + }); + + // Load autoLoadClaudeMd setting + const autoLoadClaudeMd = await getAutoLoadClaudeMdSetting( + projectPath, + this.settingsService, + '[AutoMode]' + ); + + // Execute remaining pipeline steps (starting from crashed step) + await this.executePipelineSteps( + projectPath, + featureId, + feature, + stepsToExecute, + workDir, + abortController, + autoLoadClaudeMd + ); + + // Determine final status + const finalStatus = feature.skipTests ? 'waiting_approval' : 'verified'; + await this.updateFeatureStatus(projectPath, featureId, finalStatus); + + console.log('[AutoMode] Pipeline resume completed successfully'); + + this.emitAutoModeEvent('auto_mode_feature_complete', { + featureId, + passes: true, + message: 'Pipeline resumed and completed successfully', + projectPath, + }); + } catch (error) { + const errorInfo = classifyError(error); + + if (errorInfo.isAbort) { + this.emitAutoModeEvent('auto_mode_feature_complete', { + featureId, + passes: false, + message: 'Pipeline resume stopped by user', + projectPath, + }); + } else { + console.error(`[AutoMode] Pipeline resume failed for feature ${featureId}:`, error); + await this.updateFeatureStatus(projectPath, featureId, 'backlog'); + this.emitAutoModeEvent('auto_mode_error', { + featureId, + error: errorInfo.message, + errorType: errorInfo.type, + projectPath, + }); + } + } finally { + this.runningFeatures.delete(featureId); + } + } + /** * Follow up on a feature with additional instructions */ @@ -2885,6 +3168,111 @@ Review the previous work and continue the implementation. If the feature appears }); } + /** + * Detect if a feature is stuck in a pipeline step and extract step information. + * Parses the feature status to determine if it's a pipeline status (e.g., 'pipeline_step_xyz'), + * loads the pipeline configuration, and validates that the step still exists. + * + * This method handles several scenarios: + * - Non-pipeline status: Returns default PipelineStatusInfo with isPipeline=false + * - Invalid pipeline status format: Returns isPipeline=true but null step info + * - Step deleted from config: Returns stepIndex=-1 to signal missing step + * - Valid pipeline step: Returns full step information and config + * + * @param {string} projectPath - Absolute path to the project directory + * @param {string} featureId - Unique identifier of the feature + * @param {FeatureStatusWithPipeline} currentStatus - Current feature status (may include pipeline step info) + * @returns {Promise} Information about the pipeline status and step + * @private + */ + private async detectPipelineStatus( + projectPath: string, + featureId: string, + currentStatus: FeatureStatusWithPipeline + ): Promise { + // Check if status is pipeline format using PipelineService + const isPipeline = pipelineService.isPipelineStatus(currentStatus); + + if (!isPipeline) { + return { + isPipeline: false, + stepId: null, + stepIndex: -1, + totalSteps: 0, + step: null, + config: null, + }; + } + + // Extract step ID using PipelineService + const stepId = pipelineService.getStepIdFromStatus(currentStatus); + + if (!stepId) { + console.warn( + `[AutoMode] Feature ${featureId} has invalid pipeline status format: ${currentStatus}` + ); + return { + isPipeline: true, + stepId: null, + stepIndex: -1, + totalSteps: 0, + step: null, + config: null, + }; + } + + // Load pipeline config + const config = await pipelineService.getPipelineConfig(projectPath); + + if (!config || config.steps.length === 0) { + // Pipeline config doesn't exist or empty - feature stuck with invalid pipeline status + console.warn( + `[AutoMode] Feature ${featureId} has pipeline status but no pipeline config exists` + ); + return { + isPipeline: true, + stepId, + stepIndex: -1, + totalSteps: 0, + step: null, + config: null, + }; + } + + // Find the step directly from config (already loaded, avoid redundant file read) + const sortedSteps = [...config.steps].sort((a, b) => a.order - b.order); + const stepIndex = sortedSteps.findIndex((s) => s.id === stepId); + const step = stepIndex === -1 ? null : sortedSteps[stepIndex]; + + if (!step) { + // Step not found in current config - step was deleted/changed + console.warn( + `[AutoMode] Feature ${featureId} stuck in step ${stepId} which no longer exists in pipeline config` + ); + return { + isPipeline: true, + stepId, + stepIndex: -1, + totalSteps: sortedSteps.length, + step: null, + config, + }; + } + + console.log( + `[AutoMode] Detected pipeline status for feature ${featureId}: step ${stepIndex + 1}/${sortedSteps.length} (${step.name})` + ); + + return { + isPipeline: true, + stepId, + stepIndex, + totalSteps: sortedSteps.length, + step, + config, + }; + } + /** * Build a focused prompt for executing a single task. * Each task gets minimal context to keep the agent focused. @@ -3193,41 +3581,43 @@ IMPORTANT: Only include NON-OBVIOUS learnings with real reasoning. Skip trivial If nothing notable: {"learnings": []}`; try { - // Import query dynamically to avoid circular dependencies - const { query } = await import('@anthropic-ai/claude-agent-sdk'); - // Get model from phase settings const settings = await this.settingsService?.getGlobalSettings(); const phaseModelEntry = settings?.phaseModels?.memoryExtractionModel || DEFAULT_PHASE_MODELS.memoryExtractionModel; const { model } = resolvePhaseModel(phaseModelEntry); + const hasClaudeKey = Boolean(process.env.ANTHROPIC_API_KEY); + let resolvedModel = model; - const stream = query({ - prompt: userPrompt, - options: { - model, - maxTurns: 1, - allowedTools: [], - permissionMode: 'acceptEdits', - systemPrompt: - 'You are a JSON extraction assistant. You MUST respond with ONLY valid JSON, no explanations, no markdown, no other text. Extract learnings from the provided implementation context and return them as JSON.', - }, - }); - - // Extract text from stream - let responseText = ''; - for await (const msg of stream) { - if (msg.type === 'assistant' && msg.message?.content) { - for (const block of msg.message.content) { - if (block.type === 'text' && block.text) { - responseText += block.text; - } - } - } else if (msg.type === 'result' && msg.subtype === 'success') { - responseText = msg.result || responseText; + if (isClaudeModel(model) && !hasClaudeKey) { + const fallbackModel = feature.model + ? resolveModelString(feature.model, DEFAULT_MODELS.claude) + : null; + if (fallbackModel && !isClaudeModel(fallbackModel)) { + console.log( + `[AutoMode] Claude not configured for memory extraction; using feature model "${fallbackModel}".` + ); + resolvedModel = fallbackModel; + } else { + console.log( + '[AutoMode] Claude not configured for memory extraction; skipping learning extraction.' + ); + return; } } + const result = await simpleQuery({ + prompt: userPrompt, + model: resolvedModel, + cwd: projectPath, + maxTurns: 1, + allowedTools: [], + systemPrompt: + 'You are a JSON extraction assistant. You MUST respond with ONLY valid JSON, no explanations, no markdown, no other text. Extract learnings from the provided implementation context and return them as JSON.', + }); + + const responseText = result.text; + console.log(`[AutoMode] Learning extraction response: ${responseText.length} chars`); console.log(`[AutoMode] Response preview: ${responseText.substring(0, 300)}`); diff --git a/apps/server/src/services/settings-service.ts b/apps/server/src/services/settings-service.ts index f1dfd45c..5f57ad83 100644 --- a/apps/server/src/services/settings-service.ts +++ b/apps/server/src/services/settings-service.ts @@ -431,6 +431,8 @@ export class SettingsService { */ async getMaskedCredentials(): Promise<{ anthropic: { configured: boolean; masked: string }; + google: { configured: boolean; masked: string }; + openai: { configured: boolean; masked: string }; }> { const credentials = await this.getCredentials(); @@ -444,6 +446,14 @@ export class SettingsService { configured: !!credentials.apiKeys.anthropic, masked: maskKey(credentials.apiKeys.anthropic), }, + google: { + configured: !!credentials.apiKeys.google, + masked: maskKey(credentials.apiKeys.google), + }, + openai: { + configured: !!credentials.apiKeys.openai, + masked: maskKey(credentials.apiKeys.openai), + }, }; } diff --git a/apps/server/tests/unit/lib/enhancement-prompts.test.ts b/apps/server/tests/unit/lib/enhancement-prompts.test.ts index ab139861..13d61555 100644 --- a/apps/server/tests/unit/lib/enhancement-prompts.test.ts +++ b/apps/server/tests/unit/lib/enhancement-prompts.test.ts @@ -17,6 +17,14 @@ import { type EnhancementMode, } from '@/lib/enhancement-prompts.js'; +const ENHANCEMENT_MODES: EnhancementMode[] = [ + 'improve', + 'technical', + 'simplify', + 'acceptance', + 'ux-reviewer', +]; + describe('enhancement-prompts.ts', () => { describe('System Prompt Constants', () => { it('should have non-empty improve system prompt', () => { @@ -184,8 +192,7 @@ describe('enhancement-prompts.ts', () => { }); it('should work with all enhancement modes', () => { - const modes: EnhancementMode[] = ['improve', 'technical', 'simplify', 'acceptance']; - modes.forEach((mode) => { + ENHANCEMENT_MODES.forEach((mode) => { const prompt = buildUserPrompt(mode, testText); expect(prompt).toContain(testText); expect(prompt.length).toBeGreaterThan(100); @@ -205,6 +212,7 @@ describe('enhancement-prompts.ts', () => { expect(isValidEnhancementMode('technical')).toBe(true); expect(isValidEnhancementMode('simplify')).toBe(true); expect(isValidEnhancementMode('acceptance')).toBe(true); + expect(isValidEnhancementMode('ux-reviewer')).toBe(true); }); it('should return false for invalid modes', () => { @@ -216,13 +224,12 @@ describe('enhancement-prompts.ts', () => { }); describe('getAvailableEnhancementModes', () => { - it('should return all four enhancement modes', () => { + it('should return all enhancement modes', () => { const modes = getAvailableEnhancementModes(); - expect(modes).toHaveLength(4); - expect(modes).toContain('improve'); - expect(modes).toContain('technical'); - expect(modes).toContain('simplify'); - expect(modes).toContain('acceptance'); + expect(modes).toHaveLength(ENHANCEMENT_MODES.length); + ENHANCEMENT_MODES.forEach((mode) => { + expect(modes).toContain(mode); + }); }); it('should return an array', () => { diff --git a/apps/server/tests/unit/providers/codex-provider.test.ts b/apps/server/tests/unit/providers/codex-provider.test.ts index ada1aae1..6ca69d86 100644 --- a/apps/server/tests/unit/providers/codex-provider.test.ts +++ b/apps/server/tests/unit/providers/codex-provider.test.ts @@ -257,7 +257,7 @@ describe('codex-provider.ts', () => { expect(results[1].result).toBe('Hello from SDK'); }); - it('uses the CLI when tools are requested even if an API key is present', async () => { + it('uses the SDK when API key is present, even for tool requests (to avoid OAuth issues)', async () => { process.env[OPENAI_API_KEY_ENV] = 'sk-test'; vi.mocked(spawnJSONLProcess).mockReturnValue((async function* () {})()); @@ -270,8 +270,8 @@ describe('codex-provider.ts', () => { }) ); - expect(codexRunMock).not.toHaveBeenCalled(); - expect(spawnJSONLProcess).toHaveBeenCalled(); + expect(codexRunMock).toHaveBeenCalled(); + expect(spawnJSONLProcess).not.toHaveBeenCalled(); }); it('falls back to CLI when no tools are requested and no API key is available', async () => { diff --git a/apps/server/tests/unit/routes/app-spec/common.test.ts b/apps/server/tests/unit/routes/app-spec/common.test.ts index aeaf8ea5..a348a2aa 100644 --- a/apps/server/tests/unit/routes/app-spec/common.test.ts +++ b/apps/server/tests/unit/routes/app-spec/common.test.ts @@ -5,59 +5,61 @@ import { getSpecRegenerationStatus, } from '@/routes/app-spec/common.js'; +const TEST_PROJECT_PATH = '/tmp/automaker-test-project'; + describe('app-spec/common.ts', () => { beforeEach(() => { // Reset state before each test - setRunningState(false, null); + setRunningState(TEST_PROJECT_PATH, false, null); }); describe('setRunningState', () => { it('should set isRunning to true when running is true', () => { - setRunningState(true); - expect(getSpecRegenerationStatus().isRunning).toBe(true); + setRunningState(TEST_PROJECT_PATH, true); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).isRunning).toBe(true); }); it('should set isRunning to false when running is false', () => { - setRunningState(true); - setRunningState(false); - expect(getSpecRegenerationStatus().isRunning).toBe(false); + setRunningState(TEST_PROJECT_PATH, true); + setRunningState(TEST_PROJECT_PATH, false); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).isRunning).toBe(false); }); it('should set currentAbortController when provided', () => { const controller = new AbortController(); - setRunningState(true, controller); - expect(getSpecRegenerationStatus().currentAbortController).toBe(controller); + setRunningState(TEST_PROJECT_PATH, true, controller); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).currentAbortController).toBe(controller); }); it('should set currentAbortController to null when not provided', () => { const controller = new AbortController(); - setRunningState(true, controller); - setRunningState(false); - expect(getSpecRegenerationStatus().currentAbortController).toBe(null); + setRunningState(TEST_PROJECT_PATH, true, controller); + setRunningState(TEST_PROJECT_PATH, false); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).currentAbortController).toBe(null); }); - it('should set currentAbortController to null when explicitly passed null', () => { + it('should keep currentAbortController when explicitly passed null while running', () => { const controller = new AbortController(); - setRunningState(true, controller); - setRunningState(true, null); - expect(getSpecRegenerationStatus().currentAbortController).toBe(null); + setRunningState(TEST_PROJECT_PATH, true, controller); + setRunningState(TEST_PROJECT_PATH, true, null); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).currentAbortController).toBe(controller); }); it('should update state multiple times correctly', () => { const controller1 = new AbortController(); const controller2 = new AbortController(); - setRunningState(true, controller1); - expect(getSpecRegenerationStatus().isRunning).toBe(true); - expect(getSpecRegenerationStatus().currentAbortController).toBe(controller1); + setRunningState(TEST_PROJECT_PATH, true, controller1); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).isRunning).toBe(true); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).currentAbortController).toBe(controller1); - setRunningState(true, controller2); - expect(getSpecRegenerationStatus().isRunning).toBe(true); - expect(getSpecRegenerationStatus().currentAbortController).toBe(controller2); + setRunningState(TEST_PROJECT_PATH, true, controller2); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).isRunning).toBe(true); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).currentAbortController).toBe(controller2); - setRunningState(false, null); - expect(getSpecRegenerationStatus().isRunning).toBe(false); - expect(getSpecRegenerationStatus().currentAbortController).toBe(null); + setRunningState(TEST_PROJECT_PATH, false, null); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).isRunning).toBe(false); + expect(getSpecRegenerationStatus(TEST_PROJECT_PATH).currentAbortController).toBe(null); }); }); diff --git a/apps/server/tests/unit/services/dev-server-service.test.ts b/apps/server/tests/unit/services/dev-server-service.test.ts index b6bae863..03d3d01c 100644 --- a/apps/server/tests/unit/services/dev-server-service.test.ts +++ b/apps/server/tests/unit/services/dev-server-service.test.ts @@ -8,6 +8,7 @@ import fs from 'fs/promises'; vi.mock('child_process', () => ({ spawn: vi.fn(), execSync: vi.fn(), + execFile: vi.fn(), })); // Mock secure-fs diff --git a/apps/ui/eslint.config.mjs b/apps/ui/eslint.config.mjs index d7bc54d4..6db837e3 100644 --- a/apps/ui/eslint.config.mjs +++ b/apps/ui/eslint.config.mjs @@ -70,6 +70,8 @@ const eslintConfig = defineConfig([ AbortSignal: 'readonly', Audio: 'readonly', ScrollBehavior: 'readonly', + URL: 'readonly', + URLSearchParams: 'readonly', // Timers setTimeout: 'readonly', setInterval: 'readonly', diff --git a/apps/ui/package.json b/apps/ui/package.json index 167734d3..384dc581 100644 --- a/apps/ui/package.json +++ b/apps/ui/package.json @@ -1,6 +1,6 @@ { "name": "@automaker/ui", - "version": "0.9.0", + "version": "0.10.0", "description": "An autonomous AI development studio that helps you build software faster using AI-powered agents", "homepage": "https://github.com/AutoMaker-Org/automaker", "repository": { @@ -56,6 +56,7 @@ "@radix-ui/react-label": "2.1.8", "@radix-ui/react-popover": "1.1.15", "@radix-ui/react-radio-group": "1.3.8", + "@radix-ui/react-scroll-area": "^1.2.10", "@radix-ui/react-select": "2.2.6", "@radix-ui/react-slider": "1.3.6", "@radix-ui/react-slot": "1.2.4", diff --git a/apps/ui/src/components/layout/project-switcher/components/edit-project-dialog.tsx b/apps/ui/src/components/layout/project-switcher/components/edit-project-dialog.tsx new file mode 100644 index 00000000..31e39367 --- /dev/null +++ b/apps/ui/src/components/layout/project-switcher/components/edit-project-dialog.tsx @@ -0,0 +1,187 @@ +import { useState, useRef } from 'react'; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, +} from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Upload, X, ImageIcon } from 'lucide-react'; +import { useAppStore } from '@/store/app-store'; +import { getAuthenticatedImageUrl } from '@/lib/api-fetch'; +import { getHttpApiClient } from '@/lib/http-api-client'; +import type { Project } from '@/lib/electron'; +import { IconPicker } from './icon-picker'; + +interface EditProjectDialogProps { + project: Project; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +export function EditProjectDialog({ project, open, onOpenChange }: EditProjectDialogProps) { + const { setProjectName, setProjectIcon, setProjectCustomIcon } = useAppStore(); + const [name, setName] = useState(project.name); + const [icon, setIcon] = useState((project as any).icon || null); + const [customIconPath, setCustomIconPath] = useState( + (project as any).customIconPath || null + ); + const [isUploadingIcon, setIsUploadingIcon] = useState(false); + const fileInputRef = useRef(null); + + const handleSave = () => { + if (name.trim() !== project.name) { + setProjectName(project.id, name.trim()); + } + if (icon !== (project as any).icon) { + setProjectIcon(project.id, icon); + } + if (customIconPath !== (project as any).customIconPath) { + setProjectCustomIcon(project.id, customIconPath); + } + onOpenChange(false); + }; + + const handleCustomIconUpload = async (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + + // Validate file type + const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; + if (!validTypes.includes(file.type)) { + return; + } + + // Validate file size (max 2MB for icons) + if (file.size > 2 * 1024 * 1024) { + return; + } + + setIsUploadingIcon(true); + try { + // Convert to base64 + const reader = new FileReader(); + reader.onload = async () => { + const base64Data = reader.result as string; + const result = await getHttpApiClient().saveImageToTemp( + base64Data, + `project-icon-${file.name}`, + file.type, + project.path + ); + if (result.success && result.path) { + setCustomIconPath(result.path); + // Clear the Lucide icon when custom icon is set + setIcon(null); + } + setIsUploadingIcon(false); + }; + reader.readAsDataURL(file); + } catch { + setIsUploadingIcon(false); + } + }; + + const handleRemoveCustomIcon = () => { + setCustomIconPath(null); + if (fileInputRef.current) { + fileInputRef.current.value = ''; + } + }; + + return ( + + + + Edit Project + + +
+ {/* Project Name */} +
+ + setName(e.target.value)} + placeholder="Enter project name" + /> +
+ + {/* Icon Picker */} +
+ +

+ Choose a preset icon or upload a custom image +

+ + {/* Custom Icon Upload */} +
+
+ {customIconPath ? ( +
+ Custom project icon + +
+ ) : ( +
+ +
+ )} +
+ + +

+ PNG, JPG, GIF or WebP. Max 2MB. +

+
+
+
+ + {/* Preset Icon Picker - only show if no custom icon */} + {!customIconPath && } +
+
+ + + + + +
+
+ ); +} diff --git a/apps/ui/src/components/layout/project-switcher/components/icon-picker.tsx b/apps/ui/src/components/layout/project-switcher/components/icon-picker.tsx new file mode 100644 index 00000000..10947a51 --- /dev/null +++ b/apps/ui/src/components/layout/project-switcher/components/icon-picker.tsx @@ -0,0 +1,129 @@ +import { useState } from 'react'; +import { X, Search } from 'lucide-react'; +import * as LucideIcons from 'lucide-react'; +import { cn } from '@/lib/utils'; +import { Input } from '@/components/ui/input'; +import { ScrollArea } from '@/components/ui/scroll-area'; + +interface IconPickerProps { + selectedIcon: string | null; + onSelectIcon: (icon: string | null) => void; +} + +// Popular project-related icons +const POPULAR_ICONS = [ + 'Folder', + 'FolderOpen', + 'FolderCode', + 'FolderGit', + 'FolderKanban', + 'Package', + 'Box', + 'Boxes', + 'Code', + 'Code2', + 'Braces', + 'FileCode', + 'Terminal', + 'Globe', + 'Server', + 'Database', + 'Layout', + 'Layers', + 'Blocks', + 'Component', + 'Puzzle', + 'Cog', + 'Wrench', + 'Hammer', + 'Zap', + 'Rocket', + 'Sparkles', + 'Star', + 'Heart', + 'Shield', + 'Lock', + 'Key', + 'Cpu', + 'CircuitBoard', + 'Workflow', +]; + +export function IconPicker({ selectedIcon, onSelectIcon }: IconPickerProps) { + const [search, setSearch] = useState(''); + + const filteredIcons = POPULAR_ICONS.filter((icon) => + icon.toLowerCase().includes(search.toLowerCase()) + ); + + const getIconComponent = (iconName: string) => { + return (LucideIcons as Record>)[iconName]; + }; + + return ( +
+ {/* Search */} +
+ + setSearch(e.target.value)} + placeholder="Search icons..." + className="pl-9" + /> +
+ + {/* Selected Icon Display */} + {selectedIcon && ( +
+
+ {(() => { + const IconComponent = getIconComponent(selectedIcon); + return IconComponent ? : null; + })()} + {selectedIcon} +
+ +
+ )} + + {/* Icons Grid */} + +
+ {filteredIcons.map((iconName) => { + const IconComponent = getIconComponent(iconName); + if (!IconComponent) return null; + + const isSelected = selectedIcon === iconName; + + return ( + + ); + })} +
+
+
+ ); +} diff --git a/apps/ui/src/components/layout/project-switcher/components/index.ts b/apps/ui/src/components/layout/project-switcher/components/index.ts new file mode 100644 index 00000000..86073ca1 --- /dev/null +++ b/apps/ui/src/components/layout/project-switcher/components/index.ts @@ -0,0 +1,4 @@ +export { ProjectSwitcherItem } from './project-switcher-item'; +export { ProjectContextMenu } from './project-context-menu'; +export { EditProjectDialog } from './edit-project-dialog'; +export { IconPicker } from './icon-picker'; diff --git a/apps/ui/src/components/layout/project-switcher/components/project-context-menu.tsx b/apps/ui/src/components/layout/project-switcher/components/project-context-menu.tsx new file mode 100644 index 00000000..84b6ea9a --- /dev/null +++ b/apps/ui/src/components/layout/project-switcher/components/project-context-menu.tsx @@ -0,0 +1,103 @@ +import { useEffect, useRef } from 'react'; +import { Edit2, Trash2 } from 'lucide-react'; +import { cn } from '@/lib/utils'; +import { useAppStore } from '@/store/app-store'; +import type { Project } from '@/lib/electron'; + +interface ProjectContextMenuProps { + project: Project; + position: { x: number; y: number }; + onClose: () => void; + onEdit: (project: Project) => void; +} + +export function ProjectContextMenu({ + project, + position, + onClose, + onEdit, +}: ProjectContextMenuProps) { + const menuRef = useRef(null); + const { moveProjectToTrash } = useAppStore(); + + useEffect(() => { + const handleClickOutside = (event: MouseEvent) => { + if (menuRef.current && !menuRef.current.contains(event.target as Node)) { + onClose(); + } + }; + + const handleEscape = (event: KeyboardEvent) => { + if (event.key === 'Escape') { + onClose(); + } + }; + + document.addEventListener('mousedown', handleClickOutside); + document.addEventListener('keydown', handleEscape); + + return () => { + document.removeEventListener('mousedown', handleClickOutside); + document.removeEventListener('keydown', handleEscape); + }; + }, [onClose]); + + const handleEdit = () => { + onEdit(project); + }; + + const handleRemove = () => { + if (confirm(`Remove "${project.name}" from the project list?`)) { + moveProjectToTrash(project.id); + } + onClose(); + }; + + return ( +
+
+ + + +
+
+ ); +} diff --git a/apps/ui/src/components/layout/project-switcher/components/project-switcher-item.tsx b/apps/ui/src/components/layout/project-switcher/components/project-switcher-item.tsx new file mode 100644 index 00000000..b4434f8b --- /dev/null +++ b/apps/ui/src/components/layout/project-switcher/components/project-switcher-item.tsx @@ -0,0 +1,116 @@ +import { Folder, LucideIcon } from 'lucide-react'; +import * as LucideIcons from 'lucide-react'; +import { cn } from '@/lib/utils'; +import { getAuthenticatedImageUrl } from '@/lib/api-fetch'; +import type { Project } from '@/lib/electron'; + +interface ProjectSwitcherItemProps { + project: Project; + isActive: boolean; + hotkeyIndex?: number; // 0-9 for hotkeys 1-9, 0 + onClick: () => void; + onContextMenu: (event: React.MouseEvent) => void; +} + +export function ProjectSwitcherItem({ + project, + isActive, + hotkeyIndex, + onClick, + onContextMenu, +}: ProjectSwitcherItemProps) { + // Convert index to hotkey label: 0 -> "1", 1 -> "2", ..., 8 -> "9", 9 -> "0" + const hotkeyLabel = + hotkeyIndex !== undefined && hotkeyIndex >= 0 && hotkeyIndex <= 9 + ? hotkeyIndex === 9 + ? '0' + : String(hotkeyIndex + 1) + : undefined; + // Get the icon component from lucide-react + const getIconComponent = (): LucideIcon => { + if (project.icon && project.icon in LucideIcons) { + return (LucideIcons as Record)[project.icon]; + } + return Folder; + }; + + const IconComponent = getIconComponent(); + const hasCustomIcon = !!project.customIconPath; + + return ( + + ); +} diff --git a/apps/ui/src/components/layout/project-switcher/index.ts b/apps/ui/src/components/layout/project-switcher/index.ts new file mode 100644 index 00000000..f540a4f6 --- /dev/null +++ b/apps/ui/src/components/layout/project-switcher/index.ts @@ -0,0 +1 @@ +export { ProjectSwitcher } from './project-switcher'; diff --git a/apps/ui/src/components/layout/project-switcher/project-switcher.tsx b/apps/ui/src/components/layout/project-switcher/project-switcher.tsx new file mode 100644 index 00000000..e6080ab4 --- /dev/null +++ b/apps/ui/src/components/layout/project-switcher/project-switcher.tsx @@ -0,0 +1,317 @@ +import { useState, useCallback, useEffect } from 'react'; +import { Plus, Bug } from 'lucide-react'; +import { useNavigate } from '@tanstack/react-router'; +import { cn } from '@/lib/utils'; +import { useAppStore } from '@/store/app-store'; +import { useOSDetection } from '@/hooks/use-os-detection'; +import { ProjectSwitcherItem } from './components/project-switcher-item'; +import { ProjectContextMenu } from './components/project-context-menu'; +import { EditProjectDialog } from './components/edit-project-dialog'; +import { NewProjectModal } from '@/components/dialogs/new-project-modal'; +import { OnboardingDialog } from '@/components/layout/sidebar/dialogs'; +import { useProjectCreation, useProjectTheme } from '@/components/layout/sidebar/hooks'; +import type { Project } from '@/lib/electron'; +import { getElectronAPI } from '@/lib/electron'; + +function getOSAbbreviation(os: string): string { + switch (os) { + case 'mac': + return 'M'; + case 'windows': + return 'W'; + case 'linux': + return 'L'; + default: + return '?'; + } +} + +export function ProjectSwitcher() { + const navigate = useNavigate(); + const { + projects, + currentProject, + setCurrentProject, + trashedProjects, + upsertAndSetCurrentProject, + } = useAppStore(); + const [contextMenuProject, setContextMenuProject] = useState(null); + const [contextMenuPosition, setContextMenuPosition] = useState<{ x: number; y: number } | null>( + null + ); + const [editDialogProject, setEditDialogProject] = useState(null); + + // Version info + const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : '0.0.0'; + const { os } = useOSDetection(); + const appMode = import.meta.env.VITE_APP_MODE || '?'; + const versionSuffix = `${getOSAbbreviation(os)}${appMode}`; + + // Get global theme for project creation + const { globalTheme } = useProjectTheme(); + + // Project creation state and handlers + const { + showNewProjectModal, + setShowNewProjectModal, + isCreatingProject, + showOnboardingDialog, + setShowOnboardingDialog, + newProjectName, + handleCreateBlankProject, + handleCreateFromTemplate, + handleCreateFromCustomUrl, + } = useProjectCreation({ + trashedProjects, + currentProject, + globalTheme, + upsertAndSetCurrentProject, + }); + + const handleContextMenu = (project: Project, event: React.MouseEvent) => { + event.preventDefault(); + setContextMenuProject(project); + setContextMenuPosition({ x: event.clientX, y: event.clientY }); + }; + + const handleCloseContextMenu = () => { + setContextMenuProject(null); + setContextMenuPosition(null); + }; + + const handleEditProject = (project: Project) => { + setEditDialogProject(project); + handleCloseContextMenu(); + }; + + const handleProjectClick = useCallback( + (project: Project) => { + setCurrentProject(project); + // Navigate to board view when switching projects + navigate({ to: '/board' }); + }, + [setCurrentProject, navigate] + ); + + const handleNewProject = () => { + // Open the new project modal + setShowNewProjectModal(true); + }; + + const handleOnboardingSkip = () => { + setShowOnboardingDialog(false); + navigate({ to: '/board' }); + }; + + const handleBugReportClick = useCallback(() => { + const api = getElectronAPI(); + api.openExternalLink('https://github.com/AutoMaker-Org/automaker/issues'); + }, []); + + // Keyboard shortcuts for project switching (1-9, 0) + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + // Ignore if user is typing in an input, textarea, or contenteditable + const target = event.target as HTMLElement; + if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) { + return; + } + + // Ignore if modifier keys are pressed (except for standalone number keys) + if (event.ctrlKey || event.metaKey || event.altKey) { + return; + } + + // Map key to project index: "1" -> 0, "2" -> 1, ..., "9" -> 8, "0" -> 9 + const key = event.key; + let projectIndex: number | null = null; + + if (key >= '1' && key <= '9') { + projectIndex = parseInt(key, 10) - 1; // "1" -> 0, "9" -> 8 + } else if (key === '0') { + projectIndex = 9; // "0" -> 9 + } + + if (projectIndex !== null && projectIndex < projects.length) { + const targetProject = projects[projectIndex]; + if (targetProject && targetProject.id !== currentProject?.id) { + handleProjectClick(targetProject); + } + } + }; + + window.addEventListener('keydown', handleKeyDown); + return () => window.removeEventListener('keydown', handleKeyDown); + }, [projects, currentProject, handleProjectClick]); + + return ( + <> + + + {/* Context Menu */} + {contextMenuProject && contextMenuPosition && ( + + )} + + {/* Edit Project Dialog */} + {editDialogProject && ( + !open && setEditDialogProject(null)} + /> + )} + + {/* New Project Modal */} + + + {/* Onboarding Dialog */} + + + ); +} diff --git a/apps/ui/src/components/layout/sidebar.tsx b/apps/ui/src/components/layout/sidebar.tsx index be547e04..92e804ce 100644 --- a/apps/ui/src/components/layout/sidebar.tsx +++ b/apps/ui/src/components/layout/sidebar.tsx @@ -18,7 +18,6 @@ import { CollapseToggleButton, SidebarHeader, SidebarNavigation, - ProjectSelectorWithOptions, SidebarFooter, } from './sidebar/components'; import { TrashDialog, OnboardingDialog } from './sidebar/dialogs'; @@ -64,9 +63,6 @@ export function Sidebar() { // Get customizable keyboard shortcuts const shortcuts = useKeyboardShortcutsConfig(); - // State for project picker (needed for keyboard shortcuts) - const [isProjectPickerOpen, setIsProjectPickerOpen] = useState(false); - // State for delete project confirmation dialog const [showDeleteProjectDialog, setShowDeleteProjectDialog] = useState(false); @@ -240,7 +236,6 @@ export function Sidebar() { navigate, toggleSidebar, handleOpenFolder, - setIsProjectPickerOpen, cyclePrevProject, cycleNextProject, unviewedValidationsCount, @@ -287,14 +282,7 @@ export function Sidebar() { />
- - - + void; + currentProject: Project | null; } -export function SidebarHeader({ sidebarOpen, navigate }: SidebarHeaderProps) { - return ( - <> - {/* Logo */} -
- - {/* Bug Report Button - Inside logo container when expanded */} - {sidebarOpen && } -
+export function SidebarHeader({ sidebarOpen, currentProject }: SidebarHeaderProps) { + // Get the icon component from lucide-react + const getIconComponent = (): LucideIcon => { + if (currentProject?.icon && currentProject.icon in LucideIcons) { + return (LucideIcons as Record)[currentProject.icon]; + } + return Folder; + }; - {/* Bug Report Button - Collapsed sidebar version */} - {!sidebarOpen && ( -
- + const IconComponent = getIconComponent(); + const hasCustomIcon = !!currentProject?.customIconPath; + + return ( +
+ {/* Project name and icon display */} + {currentProject && ( +
+ {/* Project Icon */} +
+ {hasCustomIcon ? ( + {currentProject.name} + ) : ( +
+ +
+ )} +
+ + {/* Project Name - only show when sidebar is open */} + {sidebarOpen && ( +
+

+ {currentProject.name} +

+
+ )}
)} - +
); } diff --git a/apps/ui/src/components/layout/sidebar/hooks/use-navigation.ts b/apps/ui/src/components/layout/sidebar/hooks/use-navigation.ts index 085606ae..110fa26c 100644 --- a/apps/ui/src/components/layout/sidebar/hooks/use-navigation.ts +++ b/apps/ui/src/components/layout/sidebar/hooks/use-navigation.ts @@ -45,7 +45,6 @@ interface UseNavigationProps { navigate: (opts: NavigateOptions) => void; toggleSidebar: () => void; handleOpenFolder: () => void; - setIsProjectPickerOpen: (value: boolean | ((prev: boolean) => boolean)) => void; cyclePrevProject: () => void; cycleNextProject: () => void; /** Count of unviewed validations to show on GitHub Issues nav item */ @@ -65,7 +64,6 @@ export function useNavigation({ navigate, toggleSidebar, handleOpenFolder, - setIsProjectPickerOpen, cyclePrevProject, cycleNextProject, unviewedValidationsCount, @@ -230,15 +228,6 @@ export function useNavigation({ description: 'Open folder selection dialog', }); - // Project picker shortcut - only when we have projects - if (projects.length > 0) { - shortcutsList.push({ - key: shortcuts.projectPicker, - action: () => setIsProjectPickerOpen((prev) => !prev), - description: 'Toggle project picker', - }); - } - // Project cycling shortcuts - only when we have project history if (projectHistory.length > 1) { shortcutsList.push({ @@ -288,7 +277,6 @@ export function useNavigation({ cyclePrevProject, cycleNextProject, navSections, - setIsProjectPickerOpen, ]); return { diff --git a/apps/ui/src/components/shared/use-model-override.ts b/apps/ui/src/components/shared/use-model-override.ts index 82e6685a..1a3efe2a 100644 --- a/apps/ui/src/components/shared/use-model-override.ts +++ b/apps/ui/src/components/shared/use-model-override.ts @@ -1,6 +1,6 @@ import { useState, useCallback, useMemo } from 'react'; import { useAppStore } from '@/store/app-store'; -import type { ModelAlias, CursorModelId, PhaseModelKey, PhaseModelEntry } from '@automaker/types'; +import type { ModelId, PhaseModelKey, PhaseModelEntry } from '@automaker/types'; import { DEFAULT_PHASE_MODELS } from '@automaker/types'; export interface UseModelOverrideOptions { @@ -14,7 +14,7 @@ export interface UseModelOverrideResult { /** The effective model entry (override or global default) */ effectiveModelEntry: PhaseModelEntry; /** The effective model string (for backward compatibility with APIs that only accept strings) */ - effectiveModel: ModelAlias | CursorModelId; + effectiveModel: ModelId; /** Whether the model is currently overridden */ isOverridden: boolean; /** Set a model override */ @@ -32,7 +32,7 @@ export interface UseModelOverrideResult { */ function normalizeEntry(entry: PhaseModelEntry | string): PhaseModelEntry { if (typeof entry === 'string') { - return { model: entry as ModelAlias | CursorModelId }; + return { model: entry as ModelId }; } return entry; } @@ -40,9 +40,9 @@ function normalizeEntry(entry: PhaseModelEntry | string): PhaseModelEntry { /** * Extract model string from PhaseModelEntry or string */ -function extractModel(entry: PhaseModelEntry | string): ModelAlias | CursorModelId { +function extractModel(entry: PhaseModelEntry | string): ModelId { if (typeof entry === 'string') { - return entry as ModelAlias | CursorModelId; + return entry as ModelId; } return entry.model; } diff --git a/apps/ui/src/components/ui/scroll-area.tsx b/apps/ui/src/components/ui/scroll-area.tsx new file mode 100644 index 00000000..d3dd5cd2 --- /dev/null +++ b/apps/ui/src/components/ui/scroll-area.tsx @@ -0,0 +1,73 @@ +import * as React from 'react'; +import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area'; + +import { cn } from '@/lib/utils'; + +// Type-safe wrappers for Radix UI primitives (React 19 compatibility) +const ScrollAreaRootPrimitive = ScrollAreaPrimitive.Root as React.ForwardRefExoticComponent< + React.ComponentPropsWithoutRef & { + children?: React.ReactNode; + className?: string; + } & React.RefAttributes +>; + +const ScrollAreaViewportPrimitive = ScrollAreaPrimitive.Viewport as React.ForwardRefExoticComponent< + React.ComponentPropsWithoutRef & { + children?: React.ReactNode; + className?: string; + } & React.RefAttributes +>; + +const ScrollAreaScrollbarPrimitive = + ScrollAreaPrimitive.Scrollbar as React.ForwardRefExoticComponent< + React.ComponentPropsWithoutRef & { + children?: React.ReactNode; + className?: string; + } & React.RefAttributes + >; + +const ScrollAreaThumbPrimitive = ScrollAreaPrimitive.Thumb as React.ForwardRefExoticComponent< + React.ComponentPropsWithoutRef & { + className?: string; + } & React.RefAttributes +>; + +const ScrollArea = React.forwardRef< + HTMLDivElement, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + {children} + + + + +)); +ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName; + +const ScrollBar = React.forwardRef< + HTMLDivElement, + React.ComponentPropsWithoutRef +>(({ className, orientation = 'vertical', ...props }, ref) => ( + + + +)); +ScrollBar.displayName = ScrollAreaPrimitive.Scrollbar.displayName; + +export { ScrollArea, ScrollBar }; diff --git a/apps/ui/src/components/views/board-view.tsx b/apps/ui/src/components/views/board-view.tsx index 6eef8bdf..d2df1f40 100644 --- a/apps/ui/src/components/views/board-view.tsx +++ b/apps/ui/src/components/views/board-view.tsx @@ -426,6 +426,31 @@ export function BoardView() { const selectedWorktreeBranch = currentWorktreeBranch || worktrees.find((w) => w.isMain)?.branch || 'main'; + // Helper function to add and select a worktree + const addAndSelectWorktree = useCallback( + (worktreeResult: { path: string; branch: string }) => { + if (!currentProject) return; + + const currentWorktrees = getWorktrees(currentProject.path); + const existingWorktree = currentWorktrees.find((w) => w.branch === worktreeResult.branch); + + // Only add if it doesn't already exist (to avoid duplicates) + if (!existingWorktree) { + const newWorktreeInfo = { + path: worktreeResult.path, + branch: worktreeResult.branch, + isMain: false, + isCurrent: false, + hasWorktree: true, + }; + setWorktrees(currentProject.path, [...currentWorktrees, newWorktreeInfo]); + } + // Select the worktree (whether it existed or was just added) + setCurrentWorktree(currentProject.path, worktreeResult.path, worktreeResult.branch); + }, + [currentProject, getWorktrees, setWorktrees, setCurrentWorktree] + ); + // Extract all action handlers into a hook const { handleAddFeature, @@ -471,43 +496,90 @@ export function BoardView() { outputFeature, projectPath: currentProject?.path || null, onWorktreeCreated: () => setWorktreeRefreshKey((k) => k + 1), - onWorktreeAutoSelect: (newWorktree) => { - if (!currentProject) return; - // Check if worktree already exists in the store (by branch name) - const currentWorktrees = getWorktrees(currentProject.path); - const existingWorktree = currentWorktrees.find((w) => w.branch === newWorktree.branch); - - // Only add if it doesn't already exist (to avoid duplicates) - if (!existingWorktree) { - const newWorktreeInfo = { - path: newWorktree.path, - branch: newWorktree.branch, - isMain: false, - isCurrent: false, - hasWorktree: true, - }; - setWorktrees(currentProject.path, [...currentWorktrees, newWorktreeInfo]); - } - // Select the worktree (whether it existed or was just added) - setCurrentWorktree(currentProject.path, newWorktree.path, newWorktree.branch); - }, + onWorktreeAutoSelect: addAndSelectWorktree, currentWorktreeBranch, }); // Handler for bulk updating multiple features const handleBulkUpdate = useCallback( - async (updates: Partial) => { + async (updates: Partial, workMode: 'current' | 'auto' | 'custom') => { if (!currentProject || selectedFeatureIds.size === 0) return; try { + // Determine final branch name based on work mode: + // - 'current': Empty string to clear branch assignment (work on main/current branch) + // - 'auto': Auto-generate branch name based on current branch + // - 'custom': Use the provided branch name + let finalBranchName: string | undefined; + + if (workMode === 'current') { + // Empty string clears the branch assignment, moving features to main/current branch + finalBranchName = ''; + } else if (workMode === 'auto') { + // Auto-generate a branch name based on current branch and timestamp + const baseBranch = + currentWorktreeBranch || getPrimaryWorktreeBranch(currentProject.path) || 'main'; + const timestamp = Date.now(); + const randomSuffix = Math.random().toString(36).substring(2, 6); + finalBranchName = `feature/${baseBranch}-${timestamp}-${randomSuffix}`; + } else { + // Custom mode - use provided branch name + finalBranchName = updates.branchName || undefined; + } + + // Create worktree for 'auto' or 'custom' modes when we have a branch name + if ((workMode === 'auto' || workMode === 'custom') && finalBranchName) { + try { + const electronApi = getElectronAPI(); + if (electronApi?.worktree?.create) { + const result = await electronApi.worktree.create( + currentProject.path, + finalBranchName + ); + if (result.success && result.worktree) { + logger.info( + `Worktree for branch "${finalBranchName}" ${ + result.worktree?.isNew ? 'created' : 'already exists' + }` + ); + // Auto-select the worktree when creating/using it for bulk update + addAndSelectWorktree(result.worktree); + // Refresh worktree list in UI + setWorktreeRefreshKey((k) => k + 1); + } else if (!result.success) { + logger.error( + `Failed to create worktree for branch "${finalBranchName}":`, + result.error + ); + toast.error('Failed to create worktree', { + description: result.error || 'An error occurred', + }); + return; // Don't proceed with update if worktree creation failed + } + } + } catch (error) { + logger.error('Error creating worktree:', error); + toast.error('Failed to create worktree', { + description: error instanceof Error ? error.message : 'An error occurred', + }); + return; // Don't proceed with update if worktree creation failed + } + } + + // Use the final branch name in updates + const finalUpdates = { + ...updates, + branchName: finalBranchName, + }; + const api = getHttpApiClient(); const featureIds = Array.from(selectedFeatureIds); - const result = await api.features.bulkUpdate(currentProject.path, featureIds, updates); + const result = await api.features.bulkUpdate(currentProject.path, featureIds, finalUpdates); if (result.success) { // Update local state featureIds.forEach((featureId) => { - updateFeature(featureId, updates); + updateFeature(featureId, finalUpdates); }); toast.success(`Updated ${result.updatedCount} features`); exitSelectionMode(); @@ -521,7 +593,16 @@ export function BoardView() { toast.error('Failed to update features'); } }, - [currentProject, selectedFeatureIds, updateFeature, exitSelectionMode] + [ + currentProject, + selectedFeatureIds, + updateFeature, + exitSelectionMode, + currentWorktreeBranch, + getPrimaryWorktreeBranch, + addAndSelectWorktree, + setWorktreeRefreshKey, + ] ); // Handler for bulk deleting multiple features @@ -1385,6 +1466,9 @@ export function BoardView() { onClose={() => setShowMassEditDialog(false)} selectedFeatures={selectedFeatures} onApply={handleBulkUpdate} + branchSuggestions={branchSuggestions} + branchCardCounts={branchCardCounts} + currentBranch={currentWorktreeBranch || undefined} /> {/* Board Background Modal */} diff --git a/apps/ui/src/components/views/board-view/board-header.tsx b/apps/ui/src/components/views/board-view/board-header.tsx index 1cf48f67..8bc64c93 100644 --- a/apps/ui/src/components/views/board-view/board-header.tsx +++ b/apps/ui/src/components/views/board-view/board-header.tsx @@ -161,7 +161,7 @@ export function BoardHeader({
)} - {!isCurrentAutoTask && feature.status === 'in_progress' && ( - <> - {/* Approve Plan button - shows when plan is generated and waiting for approval */} - {feature.planSpec?.status === 'generated' && onApprovePlan && ( - - )} - {feature.skipTests && onManualVerify ? ( - - ) : onResume ? ( - - ) : null} - {onViewOutput && !feature.skipTests && ( - - )} - - )} + {!isCurrentAutoTask && + (feature.status === 'in_progress' || + (typeof feature.status === 'string' && feature.status.startsWith('pipeline_'))) && ( + <> + {/* Approve Plan button - shows when plan is generated and waiting for approval */} + {feature.planSpec?.status === 'generated' && onApprovePlan && ( + + )} + {feature.skipTests && onManualVerify ? ( + + ) : onResume ? ( + + ) : onVerify ? ( + + ) : null} + {onViewOutput && !feature.skipTests && ( + + )} + + )} {!isCurrentAutoTask && feature.status === 'verified' && ( <> {/* Logs button */} diff --git a/apps/ui/src/components/views/board-view/dialogs/add-feature-dialog.tsx b/apps/ui/src/components/views/board-view/dialogs/add-feature-dialog.tsx index 736f3c40..860488d2 100644 --- a/apps/ui/src/components/views/board-view/dialogs/add-feature-dialog.tsx +++ b/apps/ui/src/components/views/board-view/dialogs/add-feature-dialog.tsx @@ -21,7 +21,8 @@ import { FeatureTextFilePath as DescriptionTextFilePath, ImagePreviewMap, } from '@/components/ui/description-image-dropzone'; -import { Play, Cpu, FolderKanban } from 'lucide-react'; +import { Play, Cpu, FolderKanban, Settings2 } from 'lucide-react'; +import { useNavigate } from '@tanstack/react-router'; import { toast } from 'sonner'; import { cn } from '@/lib/utils'; import { modelSupportsThinking } from '@/lib/utils'; @@ -33,7 +34,7 @@ import { PlanningMode, Feature, } from '@/store/app-store'; -import type { ReasoningEffort, PhaseModelEntry } from '@automaker/types'; +import type { ReasoningEffort, PhaseModelEntry, AgentModel } from '@automaker/types'; import { supportsReasoningEffort, isClaudeModel } from '@automaker/types'; import { TestingTabContent, @@ -122,7 +123,7 @@ interface AddFeatureDialogProps { selectedNonMainWorktreeBranch?: string; /** * When true, forces the dialog to default to 'current' work mode (work on current branch). - * This is used when the "Use selected worktree branch" setting is disabled. + * This is used when the "Default to worktree mode" setting is disabled. */ forceCurrentBranchMode?: boolean; } @@ -152,6 +153,7 @@ export function AddFeatureDialog({ forceCurrentBranchMode, }: AddFeatureDialogProps) { const isSpawnMode = !!parentFeature; + const navigate = useNavigate(); const [workMode, setWorkMode] = useState('current'); // Form state @@ -187,7 +189,8 @@ export function AddFeatureDialog({ const [selectedAncestorIds, setSelectedAncestorIds] = useState>(new Set()); // Get defaults from store - const { defaultPlanningMode, defaultRequirePlanApproval, useWorktrees } = useAppStore(); + const { defaultPlanningMode, defaultRequirePlanApproval, useWorktrees, defaultFeatureModel } = + useAppStore(); // Track previous open state to detect when dialog opens const wasOpenRef = useRef(false); @@ -207,7 +210,7 @@ export function AddFeatureDialog({ ); setPlanningMode(defaultPlanningMode); setRequirePlanApproval(defaultRequirePlanApproval); - setModelEntry({ model: 'opus' }); + setModelEntry(defaultFeatureModel); // Initialize description history (empty for new feature) setDescriptionHistory([]); @@ -228,6 +231,7 @@ export function AddFeatureDialog({ defaultBranch, defaultPlanningMode, defaultRequirePlanApproval, + defaultFeatureModel, useWorktrees, selectedNonMainWorktreeBranch, forceCurrentBranchMode, @@ -318,7 +322,7 @@ export function AddFeatureDialog({ // When a non-main worktree is selected, use its branch name for custom mode setBranchName(selectedNonMainWorktreeBranch || ''); setPriority(2); - setModelEntry({ model: 'opus' }); + setModelEntry(defaultFeatureModel); setWorkMode( getDefaultWorkMode(useWorktrees, selectedNonMainWorktreeBranch, forceCurrentBranchMode) ); @@ -473,9 +477,31 @@ export function AddFeatureDialog({ {/* AI & Execution Section */}
-
- - AI & Execution +
+
+ + AI & Execution +
+ + + + + + +

Change default model and planning settings for new features

+
+
+
diff --git a/apps/ui/src/components/views/board-view/dialogs/backlog-plan-dialog.tsx b/apps/ui/src/components/views/board-view/dialogs/backlog-plan-dialog.tsx index c9fcd311..4f909e55 100644 --- a/apps/ui/src/components/views/board-view/dialogs/backlog-plan-dialog.tsx +++ b/apps/ui/src/components/views/board-view/dialogs/backlog-plan-dialog.tsx @@ -419,7 +419,7 @@ export function BacklogPlanDialog({ -
{renderContent()}
+
{renderContent()}
{mode === 'input' && ( diff --git a/apps/ui/src/components/views/board-view/dialogs/create-pr-dialog.tsx b/apps/ui/src/components/views/board-view/dialogs/create-pr-dialog.tsx index a8ba8ee5..3abbb75f 100644 --- a/apps/ui/src/components/views/board-view/dialogs/create-pr-dialog.tsx +++ b/apps/ui/src/components/views/board-view/dialogs/create-pr-dialog.tsx @@ -117,7 +117,7 @@ export function CreatePRDialog({ description: `PR already exists for ${result.result.branch}`, action: { label: 'View PR', - onClick: () => window.open(result.result!.prUrl!, '_blank'), + onClick: () => window.open(result.result!.prUrl!, '_blank', 'noopener,noreferrer'), }, }); } else { @@ -125,7 +125,7 @@ export function CreatePRDialog({ description: `PR created from ${result.result.branch}`, action: { label: 'View PR', - onClick: () => window.open(result.result!.prUrl!, '_blank'), + onClick: () => window.open(result.result!.prUrl!, '_blank', 'noopener,noreferrer'), }, }); } @@ -251,7 +251,10 @@ export function CreatePRDialog({

Your PR is ready for review

- @@ -277,7 +280,7 @@ export function CreatePRDialog({ + + +

Change default model and planning settings for new features

+
+ +
diff --git a/apps/ui/src/components/views/board-view/dialogs/mass-edit-dialog.tsx b/apps/ui/src/components/views/board-view/dialogs/mass-edit-dialog.tsx index 30042a4c..2be7d32f 100644 --- a/apps/ui/src/components/views/board-view/dialogs/mass-edit-dialog.tsx +++ b/apps/ui/src/components/views/board-view/dialogs/mass-edit-dialog.tsx @@ -13,7 +13,8 @@ import { Label } from '@/components/ui/label'; import { AlertCircle } from 'lucide-react'; import { modelSupportsThinking } from '@/lib/utils'; import { Feature, ModelAlias, ThinkingLevel, PlanningMode } from '@/store/app-store'; -import { TestingTabContent, PrioritySelect, PlanningModeSelect } from '../shared'; +import { TestingTabContent, PrioritySelect, PlanningModeSelect, WorkModeSelector } from '../shared'; +import type { WorkMode } from '../shared'; import { PhaseModelSelector } from '@/components/views/settings-view/model-defaults/phase-model-selector'; import { isCursorModel, isClaudeModel, type PhaseModelEntry } from '@automaker/types'; import { cn } from '@/lib/utils'; @@ -23,7 +24,10 @@ interface MassEditDialogProps { open: boolean; onClose: () => void; selectedFeatures: Feature[]; - onApply: (updates: Partial) => Promise; + onApply: (updates: Partial, workMode: WorkMode) => Promise; + branchSuggestions: string[]; + branchCardCounts?: Record; + currentBranch?: string; } interface ApplyState { @@ -33,6 +37,7 @@ interface ApplyState { requirePlanApproval: boolean; priority: boolean; skipTests: boolean; + branchName: boolean; } function getMixedValues(features: Feature[]): Record { @@ -47,6 +52,7 @@ function getMixedValues(features: Feature[]): Record { ), priority: !features.every((f) => f.priority === first.priority), skipTests: !features.every((f) => f.skipTests === first.skipTests), + branchName: !features.every((f) => f.branchName === first.branchName), }; } @@ -97,7 +103,15 @@ function FieldWrapper({ label, isMixed, willApply, onApplyChange, children }: Fi ); } -export function MassEditDialog({ open, onClose, selectedFeatures, onApply }: MassEditDialogProps) { +export function MassEditDialog({ + open, + onClose, + selectedFeatures, + onApply, + branchSuggestions, + branchCardCounts, + currentBranch, +}: MassEditDialogProps) { const [isApplying, setIsApplying] = useState(false); // Track which fields to apply @@ -108,6 +122,7 @@ export function MassEditDialog({ open, onClose, selectedFeatures, onApply }: Mas requirePlanApproval: false, priority: false, skipTests: false, + branchName: false, }); // Field values @@ -118,6 +133,18 @@ export function MassEditDialog({ open, onClose, selectedFeatures, onApply }: Mas const [priority, setPriority] = useState(2); const [skipTests, setSkipTests] = useState(false); + // Work mode and branch name state + const [workMode, setWorkMode] = useState(() => { + // Derive initial work mode from first selected feature's branchName + if (selectedFeatures.length > 0 && selectedFeatures[0].branchName) { + return 'custom'; + } + return 'current'; + }); + const [branchName, setBranchName] = useState(() => { + return getInitialValue(selectedFeatures, 'branchName', '') as string; + }); + // Calculate mixed values const mixedValues = useMemo(() => getMixedValues(selectedFeatures), [selectedFeatures]); @@ -131,6 +158,7 @@ export function MassEditDialog({ open, onClose, selectedFeatures, onApply }: Mas requirePlanApproval: false, priority: false, skipTests: false, + branchName: false, }); setModel(getInitialValue(selectedFeatures, 'model', 'sonnet') as ModelAlias); setThinkingLevel(getInitialValue(selectedFeatures, 'thinkingLevel', 'none') as ThinkingLevel); @@ -138,6 +166,10 @@ export function MassEditDialog({ open, onClose, selectedFeatures, onApply }: Mas setRequirePlanApproval(getInitialValue(selectedFeatures, 'requirePlanApproval', false)); setPriority(getInitialValue(selectedFeatures, 'priority', 2)); setSkipTests(getInitialValue(selectedFeatures, 'skipTests', false)); + // Reset work mode and branch name + const initialBranchName = getInitialValue(selectedFeatures, 'branchName', '') as string; + setBranchName(initialBranchName); + setWorkMode(initialBranchName ? 'custom' : 'current'); } }, [open, selectedFeatures]); @@ -150,6 +182,12 @@ export function MassEditDialog({ open, onClose, selectedFeatures, onApply }: Mas if (applyState.requirePlanApproval) updates.requirePlanApproval = requirePlanApproval; if (applyState.priority) updates.priority = priority; if (applyState.skipTests) updates.skipTests = skipTests; + if (applyState.branchName) { + // For 'current' mode, use empty string (work on current branch) + // For 'auto' mode, use empty string (will be auto-generated) + // For 'custom' mode, use the specified branch name + updates.branchName = workMode === 'custom' ? branchName : ''; + } if (Object.keys(updates).length === 0) { onClose(); @@ -158,7 +196,7 @@ export function MassEditDialog({ open, onClose, selectedFeatures, onApply }: Mas setIsApplying(true); try { - await onApply(updates); + await onApply(updates, workMode); onClose(); } finally { setIsApplying(false); @@ -293,6 +331,25 @@ export function MassEditDialog({ open, onClose, selectedFeatures, onApply }: Mas testIdPrefix="mass-edit" /> + + {/* Branch / Work Mode */} + setApplyState((prev) => ({ ...prev, branchName: apply }))} + > + +
diff --git a/apps/ui/src/components/views/board-view/dialogs/plan-settings-dialog.tsx b/apps/ui/src/components/views/board-view/dialogs/plan-settings-dialog.tsx index bd42cb1a..e7b58103 100644 --- a/apps/ui/src/components/views/board-view/dialogs/plan-settings-dialog.tsx +++ b/apps/ui/src/components/views/board-view/dialogs/plan-settings-dialog.tsx @@ -45,7 +45,7 @@ export function PlanSettingsDialog({ className="text-sm font-medium cursor-pointer flex items-center gap-2" > - Use selected worktree branch + Default to worktree mode

- When enabled, features created via the Plan dialog will be assigned to the currently - selected worktree branch. When disabled, features will be added to the main branch. + Planned features will automatically use isolated worktrees, keeping changes separate + from your main branch until you're ready to merge.

diff --git a/apps/ui/src/components/views/board-view/dialogs/worktree-settings-dialog.tsx b/apps/ui/src/components/views/board-view/dialogs/worktree-settings-dialog.tsx index da7cb134..c742e631 100644 --- a/apps/ui/src/components/views/board-view/dialogs/worktree-settings-dialog.tsx +++ b/apps/ui/src/components/views/board-view/dialogs/worktree-settings-dialog.tsx @@ -45,7 +45,7 @@ export function WorktreeSettingsDialog({ className="text-sm font-medium cursor-pointer flex items-center gap-2" > - Use selected worktree branch + Default to worktree mode

- When enabled, the Add Feature dialog will default to custom branch mode with the - currently selected worktree branch pre-filled. + New features will automatically use isolated worktrees, keeping changes separate + from your main branch until you're ready to merge.

diff --git a/apps/ui/src/components/views/board-view/hooks/use-board-effects.ts b/apps/ui/src/components/views/board-view/hooks/use-board-effects.ts index f481c2c2..1a7eda53 100644 --- a/apps/ui/src/components/views/board-view/hooks/use-board-effects.ts +++ b/apps/ui/src/components/views/board-view/hooks/use-board-effects.ts @@ -102,7 +102,10 @@ export function useBoardEffects({ const checkAllContexts = async () => { const featuresWithPotentialContext = features.filter( (f) => - f.status === 'in_progress' || f.status === 'waiting_approval' || f.status === 'verified' + f.status === 'in_progress' || + f.status === 'waiting_approval' || + f.status === 'verified' || + (typeof f.status === 'string' && f.status.startsWith('pipeline_')) ); const contextChecks = await Promise.all( featuresWithPotentialContext.map(async (f) => ({ diff --git a/apps/ui/src/components/views/board-view/worktree-panel/components/worktree-actions-dropdown.tsx b/apps/ui/src/components/views/board-view/worktree-panel/components/worktree-actions-dropdown.tsx index 7148983f..13fa8313 100644 --- a/apps/ui/src/components/views/board-view/worktree-panel/components/worktree-actions-dropdown.tsx +++ b/apps/ui/src/components/views/board-view/worktree-panel/components/worktree-actions-dropdown.tsx @@ -148,8 +148,12 @@ export function WorktreeActionsDropdown({ Dev Server Running (:{devServerInfo?.port}) - onOpenDevServerUrl(worktree)} className="text-xs"> - + onOpenDevServerUrl(worktree)} + className="text-xs" + aria-label={`Open dev server on port ${devServerInfo?.port} in browser`} + > + { - window.open(worktree.pr!.url, '_blank'); + window.open(worktree.pr!.url, '_blank', 'noopener,noreferrer'); }} className="text-xs" > diff --git a/apps/ui/src/components/views/board-view/worktree-panel/components/worktree-tab.tsx b/apps/ui/src/components/views/board-view/worktree-panel/components/worktree-tab.tsx index 3945cf47..5d73060e 100644 --- a/apps/ui/src/components/views/board-view/worktree-panel/components/worktree-tab.tsx +++ b/apps/ui/src/components/views/board-view/worktree-panel/components/worktree-tab.tsx @@ -298,20 +298,29 @@ export function WorktreeTab({ )} {isDevServerRunning && ( - + + + + + + +

Open dev server (:{devServerInfo?.port})

+
+
+
)} { const serverInfo = runningDevServers.get(getWorktreeKey(worktree)); - if (serverInfo) { - window.open(serverInfo.url, '_blank'); + if (!serverInfo) { + logger.warn('No dev server info found for worktree:', getWorktreeKey(worktree)); + toast.error('Dev server not found', { + description: 'The dev server may have stopped. Try starting it again.', + }); + return; + } + + try { + // Rewrite URL hostname to match the current browser's hostname. + // This ensures dev server URLs work when accessing Automaker from + // remote machines (e.g., 192.168.x.x or hostname.local instead of localhost). + const devServerUrl = new URL(serverInfo.url); + + // Security: Only allow http/https protocols to prevent potential attacks + // via data:, javascript:, file:, or other dangerous URL schemes + if (devServerUrl.protocol !== 'http:' && devServerUrl.protocol !== 'https:') { + logger.error('Invalid dev server URL protocol:', devServerUrl.protocol); + toast.error('Invalid dev server URL', { + description: 'The server returned an unsupported URL protocol.', + }); + return; + } + + devServerUrl.hostname = window.location.hostname; + window.open(devServerUrl.toString(), '_blank', 'noopener,noreferrer'); + } catch (error) { + logger.error('Failed to parse dev server URL:', error); + toast.error('Failed to open dev server', { + description: 'The server URL could not be processed. Please try again.', + }); } }, [runningDevServers, getWorktreeKey] diff --git a/apps/ui/src/components/views/github-issues-view/hooks/use-issue-validation.ts b/apps/ui/src/components/views/github-issues-view/hooks/use-issue-validation.ts index 7978e9fe..c09baab0 100644 --- a/apps/ui/src/components/views/github-issues-view/hooks/use-issue-validation.ts +++ b/apps/ui/src/components/views/github-issues-view/hooks/use-issue-validation.ts @@ -9,7 +9,7 @@ import { IssueValidationEvent, StoredValidation, } from '@/lib/electron'; -import type { LinkedPRInfo, PhaseModelEntry, ModelAlias, CursorModelId } from '@automaker/types'; +import type { LinkedPRInfo, PhaseModelEntry, ModelId } from '@automaker/types'; import { useAppStore } from '@/store/app-store'; import { toast } from 'sonner'; import { isValidationStale } from '../utils'; @@ -19,12 +19,10 @@ const logger = createLogger('IssueValidation'); /** * Extract model string from PhaseModelEntry or string (handles both formats) */ -function extractModel( - entry: PhaseModelEntry | string | undefined -): ModelAlias | CursorModelId | undefined { +function extractModel(entry: PhaseModelEntry | string | undefined): ModelId | undefined { if (!entry) return undefined; if (typeof entry === 'string') { - return entry as ModelAlias | CursorModelId; + return entry as ModelId; } return entry.model; } @@ -228,8 +226,8 @@ export function useIssueValidation({ issue: GitHubIssue, options: { forceRevalidate?: boolean; - model?: string | PhaseModelEntry; // Accept either string (backward compat) or PhaseModelEntry - modelEntry?: PhaseModelEntry; // New preferred way to pass model with thinking level + model?: ModelId | PhaseModelEntry; // Accept either model ID (backward compat) or PhaseModelEntry + modelEntry?: PhaseModelEntry; // New preferred way to pass model with thinking/reasoning comments?: GitHubComment[]; linkedPRs?: LinkedPRInfo[]; } = {} @@ -267,15 +265,16 @@ export function useIssueValidation({ ? modelEntry : model ? typeof model === 'string' - ? { model: model as ModelAlias | CursorModelId } + ? { model: model as ModelId } : model : phaseModels.validationModel; const normalizedEntry = typeof effectiveModelEntry === 'string' - ? { model: effectiveModelEntry as ModelAlias | CursorModelId } + ? { model: effectiveModelEntry as ModelId } : effectiveModelEntry; const modelToUse = normalizedEntry.model; const thinkingLevelToUse = normalizedEntry.thinkingLevel; + const reasoningEffortToUse = normalizedEntry.reasoningEffort; try { const api = getElectronAPI(); @@ -292,7 +291,8 @@ export function useIssueValidation({ currentProject.path, validationInput, modelToUse, - thinkingLevelToUse + thinkingLevelToUse, + reasoningEffortToUse ); if (!result.success) { diff --git a/apps/ui/src/components/views/github-issues-view/types.ts b/apps/ui/src/components/views/github-issues-view/types.ts index 466859a9..7ea799d9 100644 --- a/apps/ui/src/components/views/github-issues-view/types.ts +++ b/apps/ui/src/components/views/github-issues-view/types.ts @@ -1,5 +1,5 @@ import type { GitHubIssue, StoredValidation, GitHubComment } from '@/lib/electron'; -import type { ModelAlias, CursorModelId, LinkedPRInfo, PhaseModelEntry } from '@automaker/types'; +import type { ModelId, LinkedPRInfo, PhaseModelEntry } from '@automaker/types'; export interface IssueRowProps { issue: GitHubIssue; @@ -37,7 +37,7 @@ export interface IssueDetailPanelProps { /** Model override state */ modelOverride: { effectiveModelEntry: PhaseModelEntry; - effectiveModel: ModelAlias | CursorModelId; + effectiveModel: ModelId; isOverridden: boolean; setOverride: (entry: PhaseModelEntry | null) => void; }; diff --git a/apps/ui/src/components/views/settings-view.tsx b/apps/ui/src/components/views/settings-view.tsx index 23e7e890..353bcf85 100644 --- a/apps/ui/src/components/views/settings-view.tsx +++ b/apps/ui/src/components/views/settings-view.tsx @@ -1,6 +1,6 @@ import { useState, useEffect } from 'react'; +import { useSearch } from '@tanstack/react-router'; import { useAppStore } from '@/store/app-store'; -import { useSetupStore } from '@/store/setup-store'; import { useSettingsView, type SettingsViewId } from './settings-view/hooks'; import { NAV_ITEMS } from './settings-view/config/navigation'; @@ -56,6 +56,8 @@ export function SettingsView() { setDefaultPlanningMode, defaultRequirePlanApproval, setDefaultRequirePlanApproval, + defaultFeatureModel, + setDefaultFeatureModel, autoLoadClaudeMd, setAutoLoadClaudeMd, promptCustomization, @@ -72,6 +74,8 @@ export function SettingsView() { name: project.name, path: project.path, theme: project.theme as Theme | undefined, + icon: project.icon, + customIconPath: project.customIconPath, }; }; @@ -91,8 +95,11 @@ export function SettingsView() { } }; + // Get initial view from URL search params + const { view: initialView } = useSearch({ from: '/settings' }); + // Use settings view navigation hook - const { activeView, navigateTo } = useSettingsView(); + const { activeView, navigateTo } = useSettingsView({ initialView }); // Handle navigation - if navigating to 'providers', default to 'claude-provider' const handleNavigate = (viewId: SettingsViewId) => { @@ -185,12 +192,14 @@ export function SettingsView() { defaultPlanningMode={defaultPlanningMode} defaultRequirePlanApproval={defaultRequirePlanApproval} enableAiCommitMessages={enableAiCommitMessages} + defaultFeatureModel={defaultFeatureModel} onDefaultSkipTestsChange={setDefaultSkipTests} onEnableDependencyBlockingChange={setEnableDependencyBlocking} onSkipVerificationInAutoModeChange={setSkipVerificationInAutoMode} onDefaultPlanningModeChange={setDefaultPlanningMode} onDefaultRequirePlanApprovalChange={setDefaultRequirePlanApproval} onEnableAiCommitMessagesChange={setEnableAiCommitMessages} + onDefaultFeatureModelChange={setDefaultFeatureModel} /> ); case 'worktrees': diff --git a/apps/ui/src/components/views/settings-view/appearance/appearance-section.tsx b/apps/ui/src/components/views/settings-view/appearance/appearance-section.tsx index 7f9ce3a6..003501f9 100644 --- a/apps/ui/src/components/views/settings-view/appearance/appearance-section.tsx +++ b/apps/ui/src/components/views/settings-view/appearance/appearance-section.tsx @@ -1,8 +1,14 @@ -import { useState } from 'react'; +import { useState, useRef, useEffect } from 'react'; import { Label } from '@/components/ui/label'; -import { Palette, Moon, Sun } from 'lucide-react'; +import { Input } from '@/components/ui/input'; +import { Button } from '@/components/ui/button'; +import { Palette, Moon, Sun, Upload, X, ImageIcon } from 'lucide-react'; import { darkThemes, lightThemes } from '@/config/theme-options'; import { cn } from '@/lib/utils'; +import { useAppStore } from '@/store/app-store'; +import { IconPicker } from '@/components/layout/project-switcher/components/icon-picker'; +import { getAuthenticatedImageUrl } from '@/lib/api-fetch'; +import { getHttpApiClient } from '@/lib/http-api-client'; import type { Theme, Project } from '../shared/types'; interface AppearanceSectionProps { @@ -16,10 +22,97 @@ export function AppearanceSection({ currentProject, onThemeChange, }: AppearanceSectionProps) { + const { setProjectIcon, setProjectName, setProjectCustomIcon } = useAppStore(); const [activeTab, setActiveTab] = useState<'dark' | 'light'>('dark'); + const [projectName, setProjectNameLocal] = useState(currentProject?.name || ''); + const [projectIcon, setProjectIconLocal] = useState(currentProject?.icon || null); + const [customIconPath, setCustomIconPathLocal] = useState( + currentProject?.customIconPath || null + ); + const [isUploadingIcon, setIsUploadingIcon] = useState(false); + const fileInputRef = useRef(null); + + // Sync local state when currentProject changes + useEffect(() => { + setProjectNameLocal(currentProject?.name || ''); + setProjectIconLocal(currentProject?.icon || null); + setCustomIconPathLocal(currentProject?.customIconPath || null); + }, [currentProject]); const themesToShow = activeTab === 'dark' ? darkThemes : lightThemes; + // Auto-save when values change + const handleNameChange = (name: string) => { + setProjectNameLocal(name); + if (currentProject && name.trim() && name.trim() !== currentProject.name) { + setProjectName(currentProject.id, name.trim()); + } + }; + + const handleIconChange = (icon: string | null) => { + setProjectIconLocal(icon); + if (currentProject) { + setProjectIcon(currentProject.id, icon); + } + }; + + const handleCustomIconChange = (path: string | null) => { + setCustomIconPathLocal(path); + if (currentProject) { + setProjectCustomIcon(currentProject.id, path); + // Clear Lucide icon when custom icon is set + if (path) { + setProjectIconLocal(null); + setProjectIcon(currentProject.id, null); + } + } + }; + + const handleCustomIconUpload = async (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file || !currentProject) return; + + // Validate file type + const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; + if (!validTypes.includes(file.type)) { + return; + } + + // Validate file size (max 2MB for icons) + if (file.size > 2 * 1024 * 1024) { + return; + } + + setIsUploadingIcon(true); + try { + // Convert to base64 + const reader = new FileReader(); + reader.onload = async () => { + const base64Data = reader.result as string; + const result = await getHttpApiClient().saveImageToTemp( + base64Data, + `project-icon-${file.name}`, + file.type, + currentProject.path + ); + if (result.success && result.path) { + handleCustomIconChange(result.path); + } + setIsUploadingIcon(false); + }; + reader.readAsDataURL(file); + } catch { + setIsUploadingIcon(false); + } + }; + + const handleRemoveCustomIcon = () => { + handleCustomIconChange(null); + if (fileInputRef.current) { + fileInputRef.current.value = ''; + } + }; + return (
-
+
+ {/* Project Details Section */} + {currentProject && ( +
+
+
+ + handleNameChange(e.target.value)} + placeholder="Enter project name" + /> +
+ +
+ +

+ Choose a preset icon or upload a custom image +

+ + {/* Custom Icon Upload */} +
+
+ {customIconPath ? ( +
+ Custom project icon + +
+ ) : ( +
+ +
+ )} +
+ + +

+ PNG, JPG, GIF or WebP. Max 2MB. +

+
+
+
+ + {/* Preset Icon Picker - only show if no custom icon */} + {!customIconPath && ( + + )} +
+
+
+ )} + + {/* Theme Section */}