Commit a987afd9 by liimin

feat: 新增 Ollama 本地模型支持与全量日志汉化

- 新增 `@coderio/ollama-client` 专用包,实现 Ollama 本地模型的发现、拉取、连接管理
- 后端新增 Ollama 接口转发、任务进度上报与作业状态扩展字段
- 前端新增本地模型管理面板,支持模型切换与拉取
- 将项目内所有日志提示全部汉化适配为简体中文
- 优化开发服务器启动参数,忽略数据目录避免 Windows 下文件锁冲突
- 新增 sharp 图片处理依赖探测脚本,调整依赖声明与 peerDependencies 配置
- 新增 `getRuntimeConfig` 导出函数,完善生成流水线的运行时配置与进度跟踪
- 扩展作业数据类型以支持生成阶段、进度、模型来源等展示字段
1 parent fa81b8af
Showing 69 changed files with 1308 additions and 163 deletions
# CodeRio × Ollama 本地模型接入 — 交接文档
> 给下一个 Agent 的上下文。本任务目标:让系统能用本地 Ollama 跑模型,并在前端界面管理(切换 / 连接 / 断开 / 拉取)本地模型,且生成引擎真正走本地模型而非外部 API。
---
## 0. 必须先做:修掉“服务一启动就 100% CPU 崩溃”
**现象**:`pnpm dev` 能打印“🎨 CodeRio 编排服务已启动”横幅,但立刻 CPU 打满、进程崩溃/IDE 闪退。
**根因**:服务用 `tsx watch src/index.ts` 启动,`tsx watch` 会递归监听**整个工作目录**。服务启动会创建 `data/` 目录并写 sqlite,生成时又往 `data/output/...` 写大量文件——这些变更被 `tsx watch` 捕捉 → 重启 → 又写 → 又重启,**无限重启循环**导致 100% CPU。
**当前数据目录**:`D:\work\d2c\coderio\data`(在仓库根目录内,必然被监听)。
> 注意:用户经常从**仓库根目录**运行 `pnpm dev`(横幅里的 `数据目录` 是仓库根 `data`,不是 `apps/server/data`),所以监听范围是整个仓库。
**修复(任选其一,推荐 A,最稳妥):**
**A. 把数据目录移到仓库外(彻底脱离监听范围,与 cwd 无关)**
创建 `apps/server/.env`(若不存在),写入:
```env
CODERIO_SERVER_DATA_DIR=D:/work/d2c/coderio-server-data
```
服务端 `loadDotEnv()` 会读 `apps/server/.env`(不依赖 cwd)。这样 `data` 在仓库外,`tsx watch` 永远看不到写入 → 不再循环。
> 若 `apps/server/.env` 已存在,请**追加**这一行,不要覆盖其它内容。
**B. 修正 `tsx watch` 的 ignore(仍有可能因 Windows 路径分隔符匹配失败)**
之前用的 `--ignore "**/data/**"` 漏掉了 **目录创建事件本身**(`data` 目录刚建时路径是 `.../data` 而非 `.../data/...`)。改成同时匹配目录与内容、覆盖 `/` 与 `\`:
```json
"dev": "tsx watch --ignore \"**/data\" --ignore \"**/data/**\" src/index.ts"
```
(若在根目录运行,确保 entry 是 `apps/server/src/index.ts`。)
**验证崩溃已修**:`pnpm dev` 后服务稳定运行、CPU 正常,且改 `src` 文件能热重启,但生成产物写入不再触发重启。
---
## 1. 关键架构事实(务必先读,之前绕的弯都源于此)
1. **生成任务在独立子进程里跑**:`apps/server/src/runner.ts` 用 `spawn` 启动 `generate-child.ts`,子进程经环境变量 `COD_RUNTIME_CONFIG` 拿模型配置。子进程**不共享**服务端内存。
2. **服务端给子进程的模型配置来自 `loadServerModelConfig()`**(`apps/server/src/config.ts`),它读 `env > ~/.coderio/config.yaml > 默认`,**不读** coderio 的运行时内存。所以“切本地模型”必须让 `loadServerModelConfig()` 返回 Ollama 配置,而不是去改 coderio 的 `setRuntimeConfig`/`getModelConfig`(那只在服务端单进程内有效,子进程用不到)。
3. **`coderio` 和 `ollama-client` 是以编译产物 `dist` 形式被 server 消费的**(`package.json` 的 `main: ./dist/index.js`,无源码路径别名)。改这两个包的源码后**必须重新 build**(`pnpm --filter @coderio/ollama-client build` 等),否则 server import 的是旧 `dist`。server 自身用 `tsx` 跑源码,改了自动生效。
4. **Ollama 本身就是 OpenAI 兼容的**:`http://localhost:11434/v1` 暴露兼容接口,聊天直接复用 `@coderio/ai-client` 的 `completeChat` 即可,无需新聊天代码。
---
## 2. 已完成的工作
- **新建 `@coderio/ollama-client` 包**(`packages/ollama-client`):封装 Ollama 原生 REST —— `isRunning`、`listModels`、`pullModel`(带进度)、`localBaseUrl()`;`index.ts` re-export `completeChat`。**已 build 出 dist**。
- **`apps/server/src/ollama-state.ts`**:内存态 `connected`/`activeModel` + `OllamaRuntimeConfig`(`setOllamaConfig`/`getOllamaConfig`)+ 持久化(`persistOllama`/`clearPersistedOllama`/`loadPersistedOllama`,写入 `~/.coderio/ollama-active.json`)。✅ 完整。
- **`apps/server/src/routes/ollama.ts`**:路由 `/api/ollama/status`、`/models`、`/connect`、`/disconnect`、`/pull`。`connect` 处理器**已**补上 `setOllamaConfig(cfg)` + `persistOllama(cfg)`(这是让本地模型真正生效的关键,之前漏了)。✅ connect 部分。
- **`apps/server/src/config.ts` 的 `loadServerModelConfig()`**:在返回前用 `getOllamaConfig()` 覆盖(Ollama 优先,disconnect 后回退 env/config)。✅
- **前端 `apps/web/src/lib/api.ts`**:已有 `ollamaStatus`、`listOllamaModels`、`connectOllama`、`disconnectOllama`、`pullOllamaModel`。前端「本地模型」面板已能展示与使用(需确认 `Settings.tsx` 调用了这些,属历史既有代码)。
- **`coderio` 源码**里我误加了 `getRuntimeConfig` 导出(未被使用、且未编译进 dist)。属死代码,可留可删,不影响功能。
---
## 3. 还差什么(按优先级)
### P0 — 崩溃修复
见第 0 节。不修这个什么都验证不了。
### P1 — `ollama.ts` 的 disconnect 还没清除内存/持久化
当前 `disconnect` 处理器:
```ts
clearRuntimeConfig();
setOllamaConnected(null);
```
需补两行(让断开后生成回退外部模型、且重启不再自动恢复):
```ts
clearRuntimeConfig();
setOllamaConfig(null);
clearPersistedOllama();
setOllamaConnected(null);
```
### P2 — `index.ts` 启动时要恢复持久化的本地连接
目前 server 启动不会自动重连上次“使用”的本地模型(内存态重启即失)。需在 `apps/server/src/index.ts`:
- 顶部加 import:
```ts
import { isRunning, listModels } from '@coderio/ollama-client';
import { setOllamaConfig, setOllamaConnected, loadPersistedOllama } from './ollama-state';
```
- 在 `hub.broadcast = realBroadcast;`(约 163 行)之后插入启动恢复:
```ts
void (async () => {
const persisted = loadPersistedOllama();
if (!persisted) return;
const root = persisted.baseUrl.replace(/\/v1$/, '');
try {
if (!(await isRunning(root))) return;
const models = await listModels(root);
if (!models.some((m) => m.name === persisted.model)) return;
setOllamaConfig(persisted);
setOllamaConnected(persisted.model);
hub.broadcast('ollama', { type: 'status', running: true, connected: true, activeModel: persisted.model });
console.log(` ↳ 已恢复本地模型连接: ${persisted.model}`);
} catch {
/* Ollama 未就绪,忽略,等用户在面板手动连接 */
}
})();
```
> 注意:`isRunning`/`listModels` 的入参是 Ollama 根地址(**不含** `/v1`),所以持久化里存的 `baseUrl`(带 `/v1`)要先 `replace(/\/v1$/,'')`。
---
## 4. 验证清单(全部通过后任务算完成)
1. 修好崩溃(P0),`pnpm dev` 稳定不飙 CPU。
2. 前端「本地模型」面板点「使用 qwen3-vl:2b」→ 后端 `/api/ollama/connect` 返回 ok,状态变“使用中”。
3. **重新发起一次生成**,看日志里出现 `[qwen3-vl:2b]` 且**不再有 401**(`qwen3.8-max` 是外部模型名,应消失)。这证明 P1 的 `setOllamaConfig` 生效。
4. 重启 server(模拟断电)→ 启动日志出现“已恢复本地模型连接: qwen3-vl:2b”,前端状态仍是“使用中”,无需重新点。这证明 P2 持久化生效。
5. 前端点「断开」→ 再生成应使用回外部模型(无 `setOllamaConfig` 覆盖)。
---
## 5. 已知风险 / 提示
- 如果改了 `coderio` 或 `ollama-client` 源码,记得 `pnpm --filter @coderio/<包> build`;否则 server 仍读旧 `dist`。本次改动只动了 `apps/server` 源码(tsx 直接跑,免 build),所以只要崩修复好、重启即可。
- `ollama.ts` 里仍保留了对 coderio `setRuntimeConfig` 的调用(服务端进程内),它对子进程生成无影响,可留作冗余,不必删。
- 拉取模型进度走 SSE 事件 `ollama`,前端已订阅;若进度不显示,查 `pullModel` 的 `onProgress` 回调与 SSE 总线。
CODERIO_SERVER_DATA_DIR=D:/work/d2c/coderio-server-data
...@@ -5,12 +5,13 @@ ...@@ -5,12 +5,13 @@
"type": "module", "type": "module",
"description": "CodeRio 编排服务:接收前端指令、管理生成任务(Job)、持有密钥、调用 Coderio 引擎并托管预览", "description": "CodeRio 编排服务:接收前端指令、管理生成任务(Job)、持有密钥、调用 Coderio 引擎并托管预览",
"scripts": { "scripts": {
"dev": "tsx watch src/index.ts", "dev": "tsx watch --ignore \"**/data\" --ignore \"**/data/**\" src/index.ts",
"start": "tsx src/index.ts" "start": "tsx src/index.ts"
}, },
"dependencies": { "dependencies": {
"coderio": "workspace:*", "coderio": "workspace:*",
"@coderio/shared": "workspace:*", "@coderio/shared": "workspace:*",
"@coderio/ollama-client": "workspace:*",
"zod": "catalog:" "zod": "catalog:"
}, },
"devDependencies": { "devDependencies": {
......
...@@ -10,6 +10,7 @@ import { ...@@ -10,6 +10,7 @@ import {
type FigmaConfig, type FigmaConfig,
type ProjectProfile, type ProjectProfile,
} from 'coderio'; } from 'coderio';
import { getOllamaConfig } from './ollama-state';
import type { ServerConfigView } from './types'; import type { ServerConfigView } from './types';
const __dirname = path.dirname(fileURLToPath(import.meta.url)); const __dirname = path.dirname(fileURLToPath(import.meta.url));
...@@ -98,13 +99,24 @@ export function loadServerModelConfig(): ServerModelConfig { ...@@ -98,13 +99,24 @@ export function loadServerModelConfig(): ServerModelConfig {
/* ignore unreadable config */ /* ignore unreadable config */
} }
} }
return { const cfg: ServerModelConfig = {
provider: env.CODERIO_PROVIDER ?? fileModel.provider ?? 'openai', provider: env.CODERIO_PROVIDER ?? fileModel.provider ?? 'openai',
model: env.CODERIO_MODEL ?? fileModel.model ?? 'qwen3.8-max', model: env.CODERIO_MODEL ?? fileModel.model ?? 'qwen3.8-max',
baseUrl: env.CODERIO_BASE_URL ?? fileModel.baseUrl ?? '', baseUrl: env.CODERIO_BASE_URL ?? fileModel.baseUrl ?? '',
apiKey: env.CODERIO_API_KEY ?? fileModel.apiKey ?? '', apiKey: env.CODERIO_API_KEY ?? fileModel.apiKey ?? '',
figmaToken: env.CODERIO_FIGMA_TOKEN ?? fileFigma.token ?? '', figmaToken: env.CODERIO_FIGMA_TOKEN ?? fileFigma.token ?? '',
}; };
// 运行时覆盖优先:前端「使用」本地模型时,ollama-state 记录下当前生效的
// Ollama 配置(不入 coderio dist,避免重建依赖)。此处优先采用,使后续生成
// 子进程真正走本地 Ollama 而非 config.yaml/env 的远程模型;断开后回退默认值。
const oc = getOllamaConfig();
if (oc) {
cfg.provider = oc.provider;
cfg.model = oc.model;
cfg.baseUrl = oc.baseUrl;
cfg.apiKey = oc.apiKey;
}
return cfg;
} }
/** Frontend-safe view: never includes the actual secret values. */ /** Frontend-safe view: never includes the actual secret values. */
......
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
* model + figma credentials via `COD_RUNTIME_CONFIG` (never via argv, never * model + figma credentials via `COD_RUNTIME_CONFIG` (never via argv, never
* via the frontend) and injects them into the coderio engine at runtime. * via the frontend) and injects them into the coderio engine at runtime.
*/ */
import { design2code, setRuntimeConfig, patchEvoltagentStreamingForceOff, ValidationMode } from 'coderio'; import { design2code, setRuntimeConfig, patchEvoltagentStreamingForceOff, ValidationMode, logger } from 'coderio';
import type { ProjectProfile } from 'coderio'; import type { ProjectProfile } from 'coderio';
function mapMode(mode: string): ValidationMode { function mapMode(mode: string): ValidationMode {
...@@ -55,6 +55,11 @@ async function main(): Promise<void> { ...@@ -55,6 +55,11 @@ async function main(): Promise<void> {
if (typeof cfg.fillContainer === 'boolean') { if (typeof cfg.fillContainer === 'boolean') {
fillContainerArg = cfg.fillContainer; fillContainerArg = cfg.fillContainer;
} }
// 打印本次生成所采用的模型(需求:运行日志更详细,明确使用什么模型)
const _m = cfg.model && (cfg.model as Record<string, unknown>).model;
const _b = ((cfg.model && (cfg.model as Record<string, unknown>).baseUrl) || '') as string;
const _local = /11434|localhost|127\.0\.0\.1/.test(_b);
logger.printInfoLog(`本次生成采用模型:${_m ?? '默认模型'}${_local ? '(本地 Ollama)' : '(外部 API)'}`);
} catch (e) { } catch (e) {
process.stdout.write(`__D2C_ERROR__:invalid runtime config: ${e instanceof Error ? e.message : String(e)}\n`); process.stdout.write(`__D2C_ERROR__:invalid runtime config: ${e instanceof Error ? e.message : String(e)}\n`);
process.exit(1); process.exit(1);
......
...@@ -11,6 +11,8 @@ import { createApp } from './server'; ...@@ -11,6 +11,8 @@ import { createApp } from './server';
import { killOtherListenersOnPort } from './net'; import { killOtherListenersOnPort } from './net';
import { loadDotEnv, loadServerModelConfig, resolveServerOptions, loadProjectProfile } from './config'; import { loadDotEnv, loadServerModelConfig, resolveServerOptions, loadProjectProfile } from './config';
import { runJob } from './runner'; import { runJob } from './runner';
import { isRunning, listModels } from '@coderio/ollama-client';
import { setOllamaConfig, setOllamaConnected, loadPersistedOllama } from './ollama-state';
import { parseFigmaUrl, emptyProfile } from 'coderio'; import { parseFigmaUrl, emptyProfile } from 'coderio';
import type { ProjectProfile } from 'coderio'; import type { ProjectProfile } from 'coderio';
import type { TechStack } from './types'; import type { TechStack } from './types';
...@@ -112,7 +114,7 @@ function main(): void { ...@@ -112,7 +114,7 @@ function main(): void {
const projectRunner = new ProjectRunner((state) => hub.broadcast('projectRun', state)); const projectRunner = new ProjectRunner((state) => hub.broadcast('projectRun', state));
const queue = new JobQueue( const queue = new JobQueue(
store, store,
(job, onPid) => { (job, onPid, onProgress) => {
// 生成会重写 <outputDir>/coderio/<project>/my-app 下的产物(含 // 生成会重写 <outputDir>/coderio/<project>/my-app 下的产物(含
// package.json)。若该预览服务正对此产物目录运行 vite,Windows 上 // package.json)。若该预览服务正对此产物目录运行 vite,Windows 上
// vite 持有的文件句柄会阻塞引擎的写操作并抛 EPERM。因此在生成开始 // vite 持有的文件句柄会阻塞引擎的写操作并抛 EPERM。因此在生成开始
...@@ -139,7 +141,10 @@ function main(): void { ...@@ -139,7 +141,10 @@ function main(): void {
job.stack && job.target?.mode === 'standalone' job.stack && job.target?.mode === 'standalone'
? buildSyntheticProfile(job.stack) ? buildSyntheticProfile(job.stack)
: loadProjectProfile(); : loadProjectProfile();
return runJob(job, model, opts.outputDir, onPid, profile); // 每次启动任务实时读取最新模型配置:用户可能已在运行时通过
// /api/ollama/connect 切到本地 Ollama,必须拿到当前生效的配置,
// 而不是服务启动时的快照。
return runJob(job, loadServerModelConfig(), opts.outputDir, onPid, profile, onProgress);
}, },
opts.maxConcurrent, opts.maxConcurrent,
(s) => hub.broadcast('jobs', s.list()), (s) => hub.broadcast('jobs', s.list()),
...@@ -159,6 +164,26 @@ function main(): void { ...@@ -159,6 +164,26 @@ function main(): void {
server = srv; server = srv;
hub.broadcast = realBroadcast; hub.broadcast = realBroadcast;
// 启动时恢复上次「使用」的本地 Ollama 模型(若持久化中存在且 Ollama 仍可用)。
// 否则内存态重启即失,用户须重新在面板点「使用」。持久化的 baseUrl 带 /v1,
// 而 isRunning/listModels 需要 Ollama 根地址,故先剥离 /v1 后缀。
void (async () => {
const persisted = loadPersistedOllama();
if (!persisted) return;
const root = persisted.baseUrl.replace(/\/v1$/, '');
try {
if (!(await isRunning(root))) return;
const models = await listModels(root);
if (!models.some((m) => m.name === persisted.model)) return;
setOllamaConfig(persisted);
setOllamaConnected(persisted.model);
hub.broadcast('ollama', { type: 'status', running: true, connected: true, activeModel: persisted.model });
console.log(` ↳ 已恢复本地模型连接: ${persisted.model}`);
} catch {
/* Ollama 未就绪,忽略,等用户在面板手动连接 */
}
})();
// 启动并带 EADDRINUSE 重试:重启场景下旧进程可能尚未释放端口, // 启动并带 EADDRINUSE 重试:重启场景下旧进程可能尚未释放端口,
// 新进程应轮询等待而非直接崩溃,保证重启在任何时序下都成功。 // 新进程应轮询等待而非直接崩溃,保证重启在任何时序下都成功。
const listenWithRetry = (attempt = 0): void => { const listenWithRetry = (attempt = 0): void => {
......
/**
* In-memory mirror of whether the engine is currently pointed at a local
* Ollama model, plus the exact model config that the next generation job
* should use. The server owns this (not coderio's dist) so that connecting/
* disconnecting takes effect for child-process generation without requiring a
* coderio rebuild — `loadServerModelConfig()` reads it below.
*/
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
import { resolve } from 'node:path';
import { homedir } from 'node:os';
const PERSIST_FILE = resolve(homedir(), '.coderio', 'ollama-active.json');
export interface OllamaRuntimeConfig {
provider: string;
model: string;
baseUrl: string;
apiKey: string;
}
let connected = false;
let activeModel: string | null = null;
let activeConfig: OllamaRuntimeConfig | null = null;
export function setOllamaConnected(model: string | null): void {
connected = model !== null;
activeModel = model;
}
export function getOllamaState(): { connected: boolean; activeModel: string | null } {
return { connected, activeModel };
}
/** Record the model config the engine should use while connected to Ollama. */
export function setOllamaConfig(cfg: OllamaRuntimeConfig | null): void {
activeConfig = cfg;
}
/** The Ollama config to inject into the next generation job, or null. */
export function getOllamaConfig(): OllamaRuntimeConfig | null {
return activeConfig;
}
/** Persist the active Ollama connection so it survives a server restart. */
export function persistOllama(cfg: OllamaRuntimeConfig): void {
try {
const dir = resolve(homedir(), '.coderio');
if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
writeFileSync(PERSIST_FILE, JSON.stringify(cfg), 'utf8');
} catch {
/* best-effort: ignore persistence failures */
}
}
/** Clear the persisted connection (on disconnect). */
export function clearPersistedOllama(): void {
try {
if (existsSync(PERSIST_FILE)) writeFileSync(PERSIST_FILE, 'null', 'utf8');
} catch {
/* ignore */
}
}
/**
* Load a previously persisted connection. Returns null when none was saved.
* The stored `baseUrl` keeps the `/v1` suffix (OpenAI-compatible endpoint);
* callers that need the Ollama root (for health/model checks) strip it.
*/
export function loadPersistedOllama(): OllamaRuntimeConfig | null {
try {
if (!existsSync(PERSIST_FILE)) return null;
const raw = JSON.parse(readFileSync(PERSIST_FILE, 'utf8'));
if (raw && typeof raw === 'object' && raw.model && raw.baseUrl) {
return raw as OllamaRuntimeConfig;
}
} catch {
/* ignore unreadable/corrupt file */
}
return null;
}
...@@ -13,6 +13,7 @@ export interface RunResult { ...@@ -13,6 +13,7 @@ export interface RunResult {
export type Runner = ( export type Runner = (
job: Job, job: Job,
onPid: (pid: number) => void, onPid: (pid: number) => void,
onProgress?: (phase: string, percent: number) => void,
) => Promise<RunResult>; ) => Promise<RunResult>;
/** /**
...@@ -53,10 +54,17 @@ export class JobQueue { ...@@ -53,10 +54,17 @@ export class JobQueue {
private async runOne(job: Job): Promise<void> { private async runOne(job: Job): Promise<void> {
try { try {
const result = await this.runner(job, (pid) => { const result = await this.runner(
job,
(pid) => {
this.store.update(job.id, { pid }); this.store.update(job.id, { pid });
this.onChange(this.store); this.onChange(this.store);
}); },
(phase, percent) => {
this.store.update(job.id, { phase, progress: percent });
this.onChange(this.store);
},
);
if (result.cancelled) { if (result.cancelled) {
this.store.update(job.id, { this.store.update(job.id, {
status: 'cancelled', status: 'cancelled',
......
...@@ -16,6 +16,10 @@ export const generateRoutes: Route[] = [ ...@@ -16,6 +16,10 @@ export const generateRoutes: Route[] = [
const body = await ctx.parseJsonBody(req, GenerateSchema); const body = await ctx.parseJsonBody(req, GenerateSchema);
const { figmaUrl, mode, outputDir, appName, target, stack, fillContainer } = body; const { figmaUrl, mode, outputDir, appName, target, stack, fillContainer } = body;
// 记录本次生成采用的模型(用于前端任务卡片与日志展示)
const activeModel = ctx.model;
const isLocalModel = /11434|localhost|127\.0\.0\.1/.test(activeModel.baseUrl ?? '');
// 构造 Job 对象:默认 queued 状态,记录输出目录、应用名、目标栈等参数 // 构造 Job 对象:默认 queued 状态,记录输出目录、应用名、目标栈等参数
const job: Job = { const job: Job = {
id: `job-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, id: `job-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
...@@ -27,6 +31,10 @@ export const generateRoutes: Route[] = [ ...@@ -27,6 +31,10 @@ export const generateRoutes: Route[] = [
target: target ?? null, target: target ?? null,
stack: stack ?? null, stack: stack ?? null,
fillContainer, fillContainer,
phase: null,
progress: 0,
model: activeModel.model ?? null,
modelSource: isLocalModel ? 'local' : 'external',
resultDir: null, resultDir: null,
reportPath: null, reportPath: null,
error: null, error: null,
......
...@@ -9,6 +9,7 @@ import { jobRoutes } from './jobs'; ...@@ -9,6 +9,7 @@ import { jobRoutes } from './jobs';
import { previewRoutes } from './preview'; import { previewRoutes } from './preview';
import { projectRoutes } from './project'; import { projectRoutes } from './project';
import { adminRoutes } from './admin'; import { adminRoutes } from './admin';
import { ollamaRoutes } from './ollama';
/** /**
* 全量路由表。注册顺序即匹配顺序,需保证: * 全量路由表。注册顺序即匹配顺序,需保证:
...@@ -28,4 +29,5 @@ export const routes: Route[] = [ ...@@ -28,4 +29,5 @@ export const routes: Route[] = [
...previewRoutes, ...previewRoutes,
...projectRoutes, ...projectRoutes,
...adminRoutes, ...adminRoutes,
...ollamaRoutes,
]; ];
import type { Route } from './context';
import { setRuntimeConfig, clearRuntimeConfig } from 'coderio';
import { localBaseUrl, isRunning, listModels, pullModel } from '@coderio/ollama-client';
import {
getOllamaState,
setOllamaConnected,
setOllamaConfig,
persistOllama,
clearPersistedOllama,
} from '../ollama-state';
/** Resolve the Ollama base + OpenAI-compatible endpoint the engine should use. */
const OLLAMA_BASE = localBaseUrl();
const ollamaV1Url = `${OLLAMA_BASE}/v1`;
export const ollamaRoutes: Route[] = [
// ---- GET /api/ollama/status:Ollama 是否在跑 + 是否已切换到本地模型 ----
{
method: 'GET',
path: '/api/ollama/status',
handle: async ({ ctx, res }) => {
const running = await isRunning(OLLAMA_BASE);
const st = getOllamaState();
ctx.sendJson(res, 200, {
running,
connected: st.connected,
activeModel: st.activeModel,
baseUrl: ollamaV1Url,
});
},
},
// ---- GET /api/ollama/models:已安装模型列表(无论连没连都可用)----
{
method: 'GET',
path: '/api/ollama/models',
handle: async ({ ctx, res }) => {
try {
const models = await listModels(OLLAMA_BASE);
ctx.sendJson(res, 200, { models });
} catch (e) {
ctx.sendJson(res, 200, {
models: [],
error: e instanceof Error ? e.message : '无法列举本地模型',
});
}
},
},
// ---- POST /api/ollama/connect {model}:切换到本地模型 ----
{
method: 'POST',
path: '/api/ollama/connect',
handle: async ({ ctx, req, res }) => {
const body = await ctx.readJsonBody<{ model?: string }>(req);
const model = body.model?.trim();
if (!model) {
ctx.sendJson(res, 400, { error: '缺少 model 字段' });
return;
}
if (!(await isRunning(OLLAMA_BASE))) {
ctx.sendJson(res, 503, { error: 'Ollama 未运行,请先启动 Ollama 守护进程' });
return;
}
const models = await listModels(OLLAMA_BASE).catch(() => []);
if (!models.some((m) => m.name === model)) {
ctx.sendJson(res, 409, {
error: `本地未找到模型 ${model},请先在「本地模型」面板拉取`,
});
return;
}
// 把引擎指向本地模型:覆盖 config.yaml 中配置的远程模型。
// 关键:必须写入 ollama-state(getOllamaConfig),loadServerModelConfig()
// 才会据此覆盖传给生成子进程的配置;并持久化以便重启后自动恢复。
const cfg = {
provider: 'ollama',
model,
baseUrl: ollamaV1Url,
apiKey: 'ollama',
};
setRuntimeConfig({ model: cfg });
setOllamaConfig(cfg);
persistOllama(cfg);
setOllamaConnected(model);
ctx.broadcast('ollama', {
type: 'status',
running: true,
connected: true,
activeModel: model,
});
ctx.sendJson(res, 200, { ok: true, activeModel: model });
},
},
// ---- POST /api/ollama/disconnect:断开本地模型,回退到 config.yaml 默认 ----
{
method: 'POST',
path: '/api/ollama/disconnect',
handle: async ({ ctx, res }) => {
clearRuntimeConfig();
setOllamaConfig(null);
clearPersistedOllama();
setOllamaConnected(null);
const running = await isRunning(OLLAMA_BASE).catch(() => false);
ctx.broadcast('ollama', {
type: 'status',
running,
connected: false,
activeModel: null,
});
ctx.sendJson(res, 200, { ok: true });
},
},
// ---- POST /api/ollama/pull {model}:拉取模型,进度走 SSE 事件 "ollama" ----
{
method: 'POST',
path: '/api/ollama/pull',
handle: async ({ ctx, req, res }) => {
const body = await ctx.readJsonBody<{ model?: string }>(req);
const model = body.model?.trim();
if (!model) {
ctx.sendJson(res, 400, { error: '缺少 model 字段' });
return;
}
// 异步执行:进度经现有 SSE 总线推给前端,HTTP 立即返回 202。
void (async () => {
try {
await pullModel(model, {
baseUrl: OLLAMA_BASE,
onProgress: (p) =>
ctx.broadcast('ollama', {
type: 'pull',
model,
status: p.status,
completed: p.completed,
total: p.total,
digest: p.digest,
}),
});
ctx.broadcast('ollama', { type: 'pull-done', model, ok: true });
} catch (e) {
ctx.broadcast('ollama', {
type: 'pull-done',
model,
ok: false,
error: e instanceof Error ? e.message : '拉取失败',
});
}
})();
ctx.sendJson(res, 202, { accepted: true, model });
},
},
];
...@@ -72,6 +72,7 @@ export async function runJob( ...@@ -72,6 +72,7 @@ export async function runJob(
outputDir: string, outputDir: string,
onPid: (pid: number) => void, onPid: (pid: number) => void,
projectProfile: ProjectProfile | null = null, projectProfile: ProjectProfile | null = null,
onProgress?: (phase: string, percent: number) => void,
): Promise<RunResult> { ): Promise<RunResult> {
const childScript = fileURLToPath(new URL('./generate-child.ts', import.meta.url)); const childScript = fileURLToPath(new URL('./generate-child.ts', import.meta.url));
const tsx = resolveTsx(); const tsx = resolveTsx();
...@@ -158,7 +159,14 @@ export async function runJob( ...@@ -158,7 +159,14 @@ export async function runJob(
} }
for (const line of text.split('\n')) { for (const line of text.split('\n')) {
const t = line.trim(); const t = line.trim();
if (t) logger.printInfoLog(t); if (!t) continue;
// 阶段进度标记:__D2C_PHASE__:<phase>:<percent>
const phaseMatch = /^__D2C_PHASE__:([^:]+):(\d+(?:\.\d+)?)$/.exec(t);
if (phaseMatch) {
onProgress?.(phaseMatch[1], Number(phaseMatch[2]));
continue;
}
logger.printInfoLog(t);
} }
}; };
......
...@@ -44,6 +44,14 @@ export interface Job { ...@@ -44,6 +44,14 @@ export interface Job {
stack?: TechStack | null; stack?: TechStack | null;
/** Whether the generated root should fill its host container (default true). */ /** Whether the generated root should fill its host container (default true). */
fillContainer?: boolean; fillContainer?: boolean;
/** 生成当前所处的阶段(中文),用于进度展示。 */
phase?: string | null;
/** 生成进度百分比 0-100。 */
progress?: number;
/** 本次生成使用的模型标识。 */
model?: string | null;
/** 模型来源:local=本地(Ollama 等),external=外部 API。 */
modelSource?: 'local' | 'external' | null;
/** Absolute path to the generated <outputDir>/coderio/<figmaName> workspace. */ /** Absolute path to the generated <outputDir>/coderio/<figmaName> workspace. */
resultDir: string | null; resultDir: string | null;
reportPath: string | null; reportPath: string | null;
......
...@@ -149,6 +149,22 @@ export const api = { ...@@ -149,6 +149,22 @@ export const api = {
// 仅开发模式(supervisor 常驻)可用;之后需重新运行 npm run dev 启动。 // 仅开发模式(supervisor 常驻)可用;之后需重新运行 npm run dev 启动。
shutdownDev: () => shutdownDev: () =>
http<{ ok: boolean }>('/devctl/shutdown', { method: 'POST' }), http<{ ok: boolean }>('/devctl/shutdown', { method: 'POST' }),
// ---- 本地模型 (Ollama):经后端转发,进度走 SSE "ollama" 事件 ----
ollamaStatus: () => http<OllamaStatus>('/api/ollama/status'),
listOllamaModels: () =>
http<{ models: OllamaModel[]; error?: string }>('/api/ollama/models'),
connectOllama: (model: string) =>
http<{ ok: true; activeModel: string }>('/api/ollama/connect', {
method: 'POST',
body: JSON.stringify({ model }),
}),
disconnectOllama: () =>
http<{ ok: true }>('/api/ollama/disconnect', { method: 'POST' }),
pullOllamaModel: (model: string) =>
http<{ accepted: true; model: string }>('/api/ollama/pull', {
method: 'POST',
body: JSON.stringify({ model }),
}),
}; };
/** /**
...@@ -181,7 +197,7 @@ let sseInstance: EventSource | null = null; ...@@ -181,7 +197,7 @@ let sseInstance: EventSource | null = null;
const sseEventSubs = new Map<SSEEventName, Set<(data: unknown) => void>>(); const sseEventSubs = new Map<SSEEventName, Set<(data: unknown) => void>>();
const sseOpenSubs = new Set<() => void>(); const sseOpenSubs = new Set<() => void>();
const sseCloseSubs = new Set<() => void>(); const sseCloseSubs = new Set<() => void>();
const SSE_EVENTS: SSEEventName[] = ['log', 'jobs', 'preview', 'projectRun', 'system']; const SSE_EVENTS: SSEEventName[] = ['log', 'jobs', 'preview', 'projectRun', 'system', 'ollama'];
function ensureSSE(): EventSource { function ensureSSE(): EventSource {
if (sseInstance) return sseInstance; if (sseInstance) return sseInstance;
......
...@@ -17,6 +17,14 @@ export interface Job { ...@@ -17,6 +17,14 @@ export interface Job {
stack?: TechStack | null; stack?: TechStack | null;
/** 生成的页面是否撑满容器(默认 true)。 */ /** 生成的页面是否撑满容器(默认 true)。 */
fillContainer?: boolean; fillContainer?: boolean;
/** 生成当前所处的阶段(中文),用于进度展示。 */
phase?: string | null;
/** 生成进度百分比 0-100。 */
progress?: number;
/** 本次生成使用的模型标识。 */
model?: string | null;
/** 模型来源:local=本地(Ollama 等),external=外部 API。 */
modelSource?: 'local' | 'external' | null;
resultDir: string | null; resultDir: string | null;
reportPath: string | null; reportPath: string | null;
error: string | null; error: string | null;
...@@ -130,6 +138,37 @@ export interface LogEntry { ...@@ -130,6 +138,37 @@ export interface LogEntry {
timestamp: string; timestamp: string;
} }
/* ---------------- 本地模型 (Ollama) ---------------- */
export interface OllamaModel {
name: string;
size: number;
digest: string;
modifiedAt: string;
}
export interface OllamaStatus {
running: boolean;
connected: boolean;
activeModel: string | null;
baseUrl: string;
}
/** SSE "ollama" 事件负载(与后端 routes/ollama.ts 广播结构一致)。 */
export interface OllamaEvent {
type: 'status' | 'pull' | 'pull-done';
model: string;
status?: string;
completed?: number;
total?: number;
digest?: string;
ok?: boolean;
error?: string;
running?: boolean;
connected?: boolean;
activeModel?: string | null;
}
/* ---------------- Project Profile (画像) ---------------- */ /* ---------------- Project Profile (画像) ---------------- */
export type TokenCategory = export type TokenCategory =
......
...@@ -32,6 +32,7 @@ import type { ServerConfigView, SystemStatus, OrchestratorStatus, PreviewState } ...@@ -32,6 +32,7 @@ import type { ServerConfigView, SystemStatus, OrchestratorStatus, PreviewState }
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
import { PageHeader } from '@/components/layout/PageHeader'; import { PageHeader } from '@/components/layout/PageHeader';
import { ProjectAccessPanel } from '@/components/project/ProjectAccessPanel'; import { ProjectAccessPanel } from '@/components/project/ProjectAccessPanel';
import { LocalModelPanel } from '@/components/ollama/LocalModelPanel';
import { useConnection } from '@/lib/connection'; import { useConnection } from '@/lib/connection';
import { cn } from '@/lib/utils'; import { cn } from '@/lib/utils';
...@@ -329,6 +330,9 @@ export default function Settings() { ...@@ -329,6 +330,9 @@ export default function Settings() {
</div> </div>
</section> </section>
{/* 本地模型 (Ollama) 管理 */}
<LocalModelPanel />
{/* Service & runtime */} {/* Service & runtime */}
<section className="rounded-2xl border border-border bg-card p-5"> <section className="rounded-2xl border border-border bg-card p-5">
<div className="mb-4 flex items-center gap-2"> <div className="mb-4 flex items-center gap-2">
......
...@@ -78,7 +78,7 @@ coderio/ ...@@ -78,7 +78,7 @@ coderio/
│ │ │ ├── index.ts 包导出面(后端只认这里) │ │ │ ├── index.ts 包导出面(后端只认这里)
│ │ │ ├── skill-api.ts 给 IDE / Agent 用的另一套导出面 │ │ │ ├── skill-api.ts 给 IDE / Agent 用的另一套导出面
│ │ │ ├── nodes/ 四节点:initial / process / code / validation │ │ │ ├── nodes/ 四节点:initial / process / code / validation
│ │ │ ├── agents/ refiner·judger·launch·commit(+ initial 残留) │ │ │ ├── agents/ refiner·judger·commit(+ initial·launch 残留)
│ │ │ ├── tools/ figma·hierarchy·history·launch·position·report·style·visualization │ │ │ ├── tools/ figma·hierarchy·history·launch·position·report·style·visualization
│ │ │ ├── utils/ call-model·config·workspace·checkpoint·code-cache·logger… │ │ │ ├── utils/ call-model·config·workspace·checkpoint·code-cache·logger…
│ │ │ ├── types/ project-profile / protocol / figma / validation… │ │ │ ├── types/ project-profile / protocol / figma / validation…
...@@ -198,7 +198,7 @@ data/output/coderio/<figma文件名>/ ...@@ -198,7 +198,7 @@ data/output/coderio/<figma文件名>/
| **Workspace** | `src/utils/workspace.ts` | 一次生成的所有产物目录约定(`my-app` / `process` / `checkpoint`),全局单例 `workspaceManager` | | **Workspace** | `src/utils/workspace.ts` | 一次生成的所有产物目录约定(`my-app` / `process` / `checkpoint`),全局单例 `workspaceManager` |
| **ProjectProfile(画像)** | `src/types/project-profile.ts` | 目标项目 A 的机器可读描述:自研组件库 / 设计令牌 / 工具函数 / 工程约定。让生成结果"像团队自己写的" | | **ProjectProfile(画像)** | `src/types/project-profile.ts` | 目标项目 A 的机器可读描述:自研组件库 / 设计令牌 / 工具函数 / 工程约定。让生成结果"像团队自己写的" |
| **ValidationMode** | `src/types/graph-types.ts` | 引擎内部枚举:`full` / `reportOnly` / `codeOnly`。注意 Web/后端层用的是 `code` / `with-report`(分别对应 `codeOnly` / `reportOnly`),由 `generate-child.ts` 的 `mapMode()` 映射,见 §3.5 / §7.4 | | **ValidationMode** | `src/types/graph-types.ts` | 引擎内部枚举:`full` / `reportOnly` / `codeOnly`。注意 Web/后端层用的是 `code` / `with-report`(分别对应 `codeOnly` / `reportOnly`),由 `generate-child.ts` 的 `mapMode()` 映射,见 §3.5 / §7.4 |
| **Job** | `apps/web/src/lib/types.ts` | 后端视角的一次生成任务,状态:`queued` → `running` → `done` / `error` / `cancelled` | | **Job** | `apps/web/src/lib/types.ts` | 后端视角的一次生成任务,状态:`queued` → `running` → `done` / `error` / `cancelled`;`running` 期间携带 `phase` / `progress` / `model` / `modelSource`(由引擎 `__D2C_PHASE__:<phase>:<percent>` 标记经 `runner.ts` 解析驱动) |
--- ---
...@@ -339,12 +339,12 @@ apps/server/src/config.ts 写 ~/.coderio/coderio.project.json ...@@ -339,12 +339,12 @@ apps/server/src/config.ts 写 ~/.coderio/coderio.project.json
2. `extractValidationContext(protocol)` —— 提取 designOffset 与组件绝对路径 2. `extractValidationContext(protocol)` —— 提取 designOffset 与组件绝对路径
3. `downloadImage(figmaThumbnailUrl)` —— Figma 缩略图只下一次,全局缓存 3. `downloadImage(figmaThumbnailUrl)` —— Figma 缩略图只下一次,全局缓存
4. **迭代开始**(`for iteration = 1..maxIterations`) 4. **迭代开始**(`for iteration = 1..maxIterations`)
5. 仅第 1 轮 `launch(workspace.app, { skipDependencyInstall: false })` 起 dev server 5. 仅第 1 轮 `launch(workspace.app, { skipDependencyInstall: false })` 起 dev server(**确定性启动,不再经 LLM agent;见 §5.10**)
6. `validatePositions(...)` → `PositionTool.capturePosition`(Playwright 取 boundingBox) 6. `validatePositions(...)` → `PositionTool.capturePosition`(Playwright 取 boundingBox)
7. `visualizationTool.generateIterationScreenshot(...)` → 存 `comparison_screenshots/iteration_N.webp` 7. `visualizationTool.generateIterationScreenshot(...)` → 存 `comparison_screenshots/iteration_N.webp`
8. `filterComponentsToFix` —— 只有误差 > `POSITION_THRESHOLD` 的组件才修 8. `filterComponentsToFix` —— 只有误差 > `POSITION_THRESHOLD` 的组件才修
9. **judger**(批评者)诊断 → **refiner**(执行者)按指令改码 9. **judger**(批评者)诊断 → **refiner**(执行者)按指令改码
10. `stopDevServer` → 重新 `launch(..., { skipDependencyInstall: true })` 10. `stopDevServer` → 重新 `launch(..., { skipDependencyInstall: true })`(确定性重启,同上)
11. `performCommit()` 提交 11. `performCommit()` 提交
12. 循环外 `report()` 生成最终 HTML 报告;`finally` 兜底停服务 12. 循环外 `report()` 生成最终 HTML 报告;`finally` 兜底停服务
...@@ -400,7 +400,7 @@ apps/server/src/config.ts 写 ~/.coderio/coderio.project.json ...@@ -400,7 +400,7 @@ apps/server/src/config.ts 写 ~/.coderio/coderio.project.json
|---|---|---|---| |---|---|---|---|
| `judger` | **批评者**(critic) | 每轮 `refineComponent` 中 | 读文件 + 查组件树/共享实例 + 查历史,输出 `refineInstructions`;**只允许改位置类 class,禁止 `w-*` / `h-*` / `aspect-*`** | | `judger` | **批评者**(critic) | 每轮 `refineComponent` 中 | 读文件 + 查组件树/共享实例 + 查历史,输出 `refineInstructions`;**只允许改位置类 class,禁止 `w-*` / `h-*` / `aspect-*`** |
| `refiner` | **执行者**(actor) | judger 之后 | 按 `refineInstructions` 改码(`FileEditor.read/find/findAndReplace`);指令为空则跳过 | | `refiner` | **执行者**(actor) | judger 之后 | 按 `refineInstructions` 改码(`FileEditor.read/find/findAndReplace`);指令为空则跳过 |
| `launch` | 启动者 | 第 1 轮及每次 refiner 后 | 装依赖 → build → 修编译错 → 起 dev server → 查运行时错误 | | `launch` | 启动者(**已去 LLM agent,改为确定性启动函数**) | 第 1 轮及每次 refiner 后 | `spawnSync` 跑 `pnpm i` → `npm run build`(有限重试,不调模型)→ `LaunchTool.startDevServer`;**build 失败快速失败,不再由 LLM 自愈改码** |
| `commit` | 提交者 | codeOnly / 启动成功后 | `git init/add/commit`,首轮消息 `feat: [Initial] first commit` | | `commit` | 提交者 | codeOnly / 启动成功后 | `git init/add/commit`,首轮消息 `feat: [Initial] first commit` |
| `initial` | — | **已不再用于 INITIAL 节点** | 只剩 `instruction.ts` / `prompt.ts`,被 `skill-api.ts` 与 `skills/` 复用;节点已改为确定性脚手架 | | `initial` | — | **已不再用于 INITIAL 节点** | 只剩 `instruction.ts` / `prompt.ts`,被 `skill-api.ts` 与 `skills/` 复用;节点已改为确定性脚手架 |
...@@ -499,7 +499,10 @@ env.COD_RUNTIME_CONFIG = JSON.stringify({ ...@@ -499,7 +499,10 @@ env.COD_RUNTIME_CONFIG = JSON.stringify({
| `__D2C_DONE__` | 成功结束,父进程 resolve `{ resultDir, reportPath }` | | `__D2C_DONE__` | 成功结束,父进程 resolve `{ resultDir, reportPath }` |
| `__D2C_ERROR__: <msg>` | 失败,父进程 reject | | `__D2C_ERROR__: <msg>` | 失败,父进程 reject |
其余 stdout 逐行走 `logger.printInfoLog()` 转发到 SSE。 其余 stdout 逐行走 `logger.printInfoLog()` 转发到 SSE(`log` 事件)。
> 引擎输出的结构化进度标记 `__D2C_PHASE__:<phase>:<percent>` 由 `runner.ts` 正则解析后走 `onProgress` 通道回写 `jobStore`,
> 再经 `jobs` 事件推送前端(驱动进度条),**不进日志流**。
> 同理 `generate-child.ts` 会在子进程里打印 `本次生成采用模型:<name>(本地 Ollama / 外部 API)`,前端据此展示模型徽章。
取消任务:`cancelRun(id)` 先 `process.kill(-pid)`(POSIX 杀进程组),再 `child.kill('SIGTERM')`。 取消任务:`cancelRun(id)` 先 `process.kill(-pid)`(POSIX 杀进程组),再 `child.kill('SIGTERM')`。
**为什么必须隔离**:一次生成会拉 Playwright、跑多个 agent、可能 OOM。 **为什么必须隔离**:一次生成会拉 Playwright、跑多个 agent、可能 OOM。
...@@ -672,6 +675,13 @@ env.COD_RUNTIME_CONFIG = JSON.stringify({ ...@@ -672,6 +675,13 @@ env.COD_RUNTIME_CONFIG = JSON.stringify({
- **`initial-agent` 是残留**:目录里只有 `instruction.ts` / `prompt.ts`(无 `index.ts`), - **`initial-agent` 是残留**:目录里只有 `instruction.ts` / `prompt.ts`(无 `index.ts`),
不再参与 INITIAL 节点(已改确定性脚手架),但被 `skill-api.ts` 与 `skills/` 复用; 不再参与 INITIAL 节点(已改确定性脚手架),但被 `skill-api.ts` 与 `skills/` 复用;
dist 中仍有旧的 `agents/initial-agent/index.d.ts`。**不要以为它还在驱动生成**。 dist 中仍有旧的 `agents/initial-agent/index.d.ts`。**不要以为它还在驱动生成**。
- **`launch-agent` 也是残留(2026-09-16 起)**:`agents/launch-agent/` 仍在目录,但 `nodes/validation/launch/index.ts`
已从 `createLaunchAgent().run(...)` 改为**确定性启动**(`spawnSync` 跑 `pnpm i` / `npm run build` + `LaunchTool.startDevServer`),
不再经 LLM agent,也不再在 build/运行时报错时让模型改生成的业务代码自愈。
bundle 已不再引入该 agent,运行无影响;该目录属可删死代码。**不要以为 launch 还在用 LLM**。
> 这与 §5.3「INITIAL 不用 LLM agent」同一取向:**确定性优于不确定性的 LLM 运维**。
> 但校验循环的 **judger/refiner 仍保留 LLM agent**(做「诊断偏差 + 改生成码」的生成决策,暂无确定性替代);
> 仅 launch 这步纯运维 shell 被确定性化,勿误判整个 validation 都去 agent 化。
- **npmmirror tarball 偶发损坏**:生成产物目录里 `npm install` 会出现 - **npmmirror tarball 偶发损坏**:生成产物目录里 `npm install` 会出现
`tarball data ... seems to be corrupted`,导致 `node_modules` 缺包 `tarball data ... seems to be corrupted`,导致 `node_modules` 缺包
(如缺 `node-releases` → dev 报 `Cannot find module 'node-releases/data/processed/envs.json'`)。 (如缺 `node-releases` → dev 报 `Cannot find module 'node-releases/data/processed/envs.json'`)。
......
...@@ -6,7 +6,7 @@ ...@@ -6,7 +6,7 @@
"scripts": { "scripts": {
"coderio:build": "tsc -p packages/coderio/tsconfig.json", "coderio:build": "tsc -p packages/coderio/tsconfig.json",
"server": "tsx apps/server/src/index.ts", "server": "tsx apps/server/src/index.ts",
"server:dev": "tsx watch apps/server/src/index.ts", "server:dev": "tsx watch --ignore \"**/data\" --ignore \"**/data/**\" apps/server/src/index.ts",
"web": "npm --prefix apps/web run dev", "web": "npm --prefix apps/web run dev",
"web:build": "npm --prefix apps/web run build", "web:build": "npm --prefix apps/web run build",
"dev": "node scripts/dev.mjs", "dev": "node scripts/dev.mjs",
......
...@@ -74,18 +74,15 @@ ...@@ -74,18 +74,15 @@
"evoltagent": "catalog:", "evoltagent": "catalog:",
"js-yaml": "catalog:", "js-yaml": "catalog:",
"pixelmatch": "catalog:", "pixelmatch": "catalog:",
"prompts": "catalog:" "prompts": "catalog:",
"sharp": "^0.34.5"
}, },
"peerDependencies": { "peerDependencies": {
"playwright": "^1.57.0", "playwright": "^1.57.0"
"sharp": "^0.34.5"
}, },
"peerDependenciesMeta": { "peerDependenciesMeta": {
"playwright": { "playwright": {
"optional": true "optional": true
},
"sharp": {
"optional": true
} }
}, },
"devDependencies": { "devDependencies": {
......
const log = console.log;
import('sharp')
.then((m) => {
log('SHARP_OK type=', typeof m.default);
const s = m.default;
s({ create: { width: 8, height: 8, channels: 3, background: { r: 255, g: 0, b: 0 } } })
.resize(4, 4)
.png()
.toBuffer()
.then((b) => log('RESIZE_OK bytes=', b.length))
.catch((e) => log('RESIZE_FAIL', e.message));
})
.catch((e) => log('SHARP_FAIL', e.message));
...@@ -6,8 +6,17 @@ import { getModelConfig } from '../../utils/config'; ...@@ -6,8 +6,17 @@ import { getModelConfig } from '../../utils/config';
import { AGENT_CONTEXT_WINDOW_TOKENS, MAX_OUTPUT_TOKENS } from '../../constants'; import { AGENT_CONTEXT_WINDOW_TOKENS, MAX_OUTPUT_TOKENS } from '../../constants';
export function createCommitAgent(): Agent { export function createCommitAgent(): Agent {
const base = getModelConfig();
// Ollama exposes an OpenAI-compatible `/v1` endpoint. evoltagent's model
// layer only recognises provider tags like 'openai', so the 'ollama' tag we
// use to mark a local model must be mapped to 'openai' here — the
// baseUrl/model/apiKey already point at the local Ollama instance
// (ai-client talks to Ollama the same way). Without this, commit fails with
// "Unsupported provider: ollama" even though the local model is fine.
const provider = base.provider === 'ollama' ? 'openai' : base.provider;
const modelConfig: ModelConfig = { const modelConfig: ModelConfig = {
...getModelConfig(), ...base,
provider,
contextWindowTokens: AGENT_CONTEXT_WINDOW_TOKENS, contextWindowTokens: AGENT_CONTEXT_WINDOW_TOKENS,
maxOutputTokens: MAX_OUTPUT_TOKENS, maxOutputTokens: MAX_OUTPUT_TOKENS,
}; };
......
...@@ -14,7 +14,7 @@ import { logger } from '../../utils/logger'; ...@@ -14,7 +14,7 @@ import { logger } from '../../utils/logger';
export function parseJudgerResult(response: string): Promise<JudgerDiagnosis> { export function parseJudgerResult(response: string): Promise<JudgerDiagnosis> {
// Check for empty response (agent may have hit limits or errors) // Check for empty response (agent may have hit limits or errors)
if (!response || response.trim().length === 0) { if (!response || response.trim().length === 0) {
logger.printInfoLog('Judger agent returned empty response, skipping refinement for this iteration'); logger.printInfoLog('判定智能体返回空响应,跳过本轮精修');
return Promise.resolve({ return Promise.resolve({
errorType: 'pixel_misalignment', errorType: 'pixel_misalignment',
rootCause: 'Agent analysis unavailable, do not apply any edits', rootCause: 'Agent analysis unavailable, do not apply any edits',
...@@ -30,7 +30,7 @@ export function parseJudgerResult(response: string): Promise<JudgerDiagnosis> { ...@@ -30,7 +30,7 @@ export function parseJudgerResult(response: string): Promise<JudgerDiagnosis> {
const jsonMatch = response.match(/```json\n([\s\S]*?)\n```/); const jsonMatch = response.match(/```json\n([\s\S]*?)\n```/);
if (!jsonMatch) { if (!jsonMatch) {
logger.printInfoLog('Judger agent response missing JSON block, skipping refinement for this iteration'); logger.printInfoLog('判定智能体响应缺少 JSON 块,跳过本轮精修');
return Promise.resolve({ return Promise.resolve({
errorType: 'empty_response', errorType: 'empty_response',
rootCause: 'Agent analysis unavailable, do not apply any edits', rootCause: 'Agent analysis unavailable, do not apply any edits',
...@@ -44,7 +44,7 @@ export function parseJudgerResult(response: string): Promise<JudgerDiagnosis> { ...@@ -44,7 +44,7 @@ export function parseJudgerResult(response: string): Promise<JudgerDiagnosis> {
const jsonStr = jsonMatch[1]; const jsonStr = jsonMatch[1];
if (!jsonStr || jsonStr.trim().length === 0) { if (!jsonStr || jsonStr.trim().length === 0) {
logger.printInfoLog('Judger agent response has empty JSON, skipping refinement for this iteration'); logger.printInfoLog('判定智能体响应 JSON 为空,跳过本轮精修');
return Promise.resolve({ return Promise.resolve({
errorType: 'empty_response', errorType: 'empty_response',
rootCause: 'Agent analysis unavailable, do not apply any edits', rootCause: 'Agent analysis unavailable, do not apply any edits',
...@@ -58,7 +58,7 @@ export function parseJudgerResult(response: string): Promise<JudgerDiagnosis> { ...@@ -58,7 +58,7 @@ export function parseJudgerResult(response: string): Promise<JudgerDiagnosis> {
try { try {
return Promise.resolve(JSON.parse(jsonStr) as JudgerDiagnosis); return Promise.resolve(JSON.parse(jsonStr) as JudgerDiagnosis);
} catch (error) { } catch (error) {
logger.printInfoLog(`Judger agent response JSON parse failed: ${error instanceof Error ? error.message : String(error)}`); logger.printInfoLog(`判定智能体响应 JSON 解析失败:${error instanceof Error ? error.message : String(error)}`);
return Promise.resolve({ return Promise.resolve({
errorType: 'empty_response', errorType: 'empty_response',
rootCause: 'Agent analysis unavailable', rootCause: 'Agent analysis unavailable',
......
...@@ -13,7 +13,7 @@ import { logger } from '../../utils/logger'; ...@@ -13,7 +13,7 @@ import { logger } from '../../utils/logger';
export function parseLaunchResult(response: string): Promise<LaunchAgentResult> { export function parseLaunchResult(response: string): Promise<LaunchAgentResult> {
// Check for empty response // Check for empty response
if (!response || response.trim().length === 0) { if (!response || response.trim().length === 0) {
logger.printInfoLog('Launch agent returned empty response'); logger.printInfoLog('启动智能体返回空响应');
return Promise.resolve({ return Promise.resolve({
success: false, success: false,
error: 'Agent returned empty response', error: 'Agent returned empty response',
...@@ -61,7 +61,7 @@ export function parseLaunchResult(response: string): Promise<LaunchAgentResult> ...@@ -61,7 +61,7 @@ export function parseLaunchResult(response: string): Promise<LaunchAgentResult>
} }
} }
logger.printInfoLog('Launch agent response missing JSON block'); logger.printInfoLog('启动智能体响应缺少 JSON 块');
return Promise.resolve({ return Promise.resolve({
success: false, success: false,
error: 'No JSON code block found in agent response', error: 'No JSON code block found in agent response',
......
...@@ -50,15 +50,15 @@ export const registerD2CCommand = (program: Command) => { ...@@ -50,15 +50,15 @@ export const registerD2CCommand = (program: Command) => {
const validationMode = getValidationMode(mode); const validationMode = getValidationMode(mode);
if (!validationMode) { if (!validationMode) {
logger.printErrorLog(`Invalid mode: ${mode}. Must be one of: code, with-report, full`); logger.printErrorLog(`无效模式:${mode}。可选值:code、with-report、full`);
process.exit(1); process.exit(1);
} }
await design2code(source, validationMode); await design2code(source, validationMode);
logger.printSuccessLog('Successfully completed code generation from design! Happy coding!'); logger.printSuccessLog('设计稿代码生成完成!祝编码愉快!');
} catch (error) { } catch (error) {
logger.printErrorLog(`Error during d2c execution: ${error instanceof Error ? error.message : String(error)}`); logger.printErrorLog(`d2c 执行出错:${error instanceof Error ? error.message : String(error)}`);
process.exit(1); process.exit(1);
} }
}); });
......
...@@ -27,9 +27,9 @@ export const registerD2PCommand = (program: Command) => { ...@@ -27,9 +27,9 @@ export const registerD2PCommand = (program: Command) => {
fillContainer: true, fillContainer: true,
}); });
logger.printSuccessLog('Successfully completed Design to Protocol conversion!'); logger.printSuccessLog('设计稿转协议转换完成!');
} catch (error) { } catch (error) {
logger.printErrorLog(`Error during d2p execution: ${error instanceof Error ? error.message : String(error)}`); logger.printErrorLog(`d2p 执行出错:${error instanceof Error ? error.message : String(error)}`);
process.exit(1); process.exit(1);
} }
}); });
......
...@@ -18,10 +18,10 @@ export const registerImagesCommand = (program: Command) => { ...@@ -18,10 +18,10 @@ export const registerImagesCommand = (program: Command) => {
const workspace = workspaceManager.initWorkspace(urlInfo.name); const workspace = workspaceManager.initWorkspace(urlInfo.name);
await executeFigmaAndImagesActions(urlInfo, workspace.root, workspace.root); await executeFigmaAndImagesActions(urlInfo, workspace.root, workspace.root);
logger.printSuccessLog('Successfully completed detection of images from Figma document!'); logger.printSuccessLog('Figma 文档图片识别完成!');
logger.printInfoLog(`Please check the output in the workspace: ${workspace.process}`); logger.printInfoLog(`请在以下工作区查看输出:${workspace.process}`);
} catch (error) { } catch (error) {
logger.printErrorLog(`Error during images execution: ${error instanceof Error ? error.message : String(error)}`); logger.printErrorLog(`images 命令执行出错:${error instanceof Error ? error.message : String(error)}`);
process.exit(1); process.exit(1);
} }
}); });
......
...@@ -36,7 +36,7 @@ export const registerP2CCommand = (program: Command) => { ...@@ -36,7 +36,7 @@ export const registerP2CCommand = (program: Command) => {
await initialProject(state); await initialProject(state);
await generateCode(state); await generateCode(state);
} catch (error) { } catch (error) {
logger.printErrorLog(`Error during p2c execution: ${error instanceof Error ? error.message : String(error)}`); logger.printErrorLog(`p2c 执行出错:${error instanceof Error ? error.message : String(error)}`);
process.exit(1); process.exit(1);
} }
}); });
......
...@@ -4,7 +4,7 @@ import { logger } from '../utils/logger'; ...@@ -4,7 +4,7 @@ import { logger } from '../utils/logger';
async function typedPrompt<U>(config: prompts.PromptObject<string>): Promise<Record<string, U>> { async function typedPrompt<U>(config: prompts.PromptObject<string>): Promise<Record<string, U>> {
return prompts(config, { return prompts(config, {
onCancel: () => { onCancel: () => {
logger.printWarnLog('Operation cancelled by user.'); logger.printWarnLog('操作已由用户取消。');
process.exit(0); process.exit(0);
}, },
}); });
......
...@@ -71,7 +71,7 @@ export function registerValidateCommand(program: Command): void { ...@@ -71,7 +71,7 @@ export function registerValidateCommand(program: Command): void {
validationMode: opts.reportonly ? ValidationMode.ReportOnly : ValidationMode.Full, validationMode: opts.reportonly ? ValidationMode.ReportOnly : ValidationMode.Full,
}; };
logger.printInfoLog(`Running validation (${config.validationMode}) using workspace: ${workspace.root}`); logger.printInfoLog(`正在对工作区 ${workspace.root} 运行校验(模式:${config.validationMode})`);
await runValidation({ await runValidation({
urlInfo: { fileId: null, name: projectName, nodeId: null, projectName: null }, urlInfo: { fileId: null, name: projectName, nodeId: null, projectName: null },
...@@ -86,7 +86,7 @@ export function registerValidateCommand(program: Command): void { ...@@ -86,7 +86,7 @@ export function registerValidateCommand(program: Command): void {
// If we reach here, validation passed // If we reach here, validation passed
process.exit(0); process.exit(0);
} catch (error) { } catch (error) {
logger.printErrorLog(`Error during val execution: ${error instanceof Error ? error.message : String(error)}`); logger.printErrorLog(`val 执行出错:${error instanceof Error ? error.message : String(error)}`);
process.exit(1); process.exit(1);
} }
}); });
......
...@@ -106,7 +106,7 @@ export async function design2code(url: string, mode?: ValidationMode, options?: ...@@ -106,7 +106,7 @@ export async function design2code(url: string, mode?: ValidationMode, options?:
const workspace = workspaceManager.initWorkspace(threadId, opts.outputDir, opts.appName); const workspace = workspaceManager.initWorkspace(threadId, opts.outputDir, opts.appName);
const dbPath = workspace.db; const dbPath = workspace.db;
logger.printInfoLog(`Starting design-to-code process for: ${urlInfo.projectName}`); logger.printInfoLog(`已开始设计稿转代码流程:${urlInfo.projectName}`);
// Resolve resume decision. Service mode always passes an explicit boolean // Resolve resume decision. Service mode always passes an explicit boolean
// (resume:false), so no interactive prompt is needed there. // (resume:false), so no interactive prompt is needed there.
...@@ -142,10 +142,10 @@ export async function design2code(url: string, mode?: ValidationMode, options?: ...@@ -142,10 +142,10 @@ export async function design2code(url: string, mode?: ValidationMode, options?:
'checkpoint/coderio-cli.db-shm', 'checkpoint/coderio-cli.db-shm',
'checkpoint/coderio-cli.db-wal', 'checkpoint/coderio-cli.db-wal',
]); ]);
logger.printInfoLog('Starting fresh...'); logger.printInfoLog('开始全新生成…');
} else { } else {
checkpointer = initializeSqliteSaver(dbPath); checkpointer = initializeSqliteSaver(dbPath);
logger.printInfoLog('Resuming from cache...'); logger.printInfoLog('从缓存恢复…');
} }
// Compile graph with checkpointer (after potential reinitialization) // Compile graph with checkpointer (after potential reinitialization)
...@@ -180,5 +180,5 @@ export async function design2code(url: string, mode?: ValidationMode, options?: ...@@ -180,5 +180,5 @@ export async function design2code(url: string, mode?: ValidationMode, options?:
}; };
await graph.invoke(state, config); await graph.invoke(state, config);
logger.printSuccessLog('Design-to-code process completed!'); logger.printSuccessLog('设计稿转代码流程已完成!');
} }
...@@ -54,6 +54,7 @@ export { ...@@ -54,6 +54,7 @@ export {
saveConfig, saveConfig,
setRuntimeConfig, setRuntimeConfig,
clearRuntimeConfig, clearRuntimeConfig,
getRuntimeConfig,
} from './utils/config'; } from './utils/config';
export type { ModelConfig, FigmaConfig } from './utils/config'; export type { ModelConfig, FigmaConfig } from './utils/config';
export { patchEvoltagentStreamingForceOff } from './utils/patch-evoltagent'; export { patchEvoltagentStreamingForceOff } from './utils/patch-evoltagent';
......
...@@ -9,7 +9,8 @@ import { loadCodeCache } from '../../utils/code-cache'; ...@@ -9,7 +9,8 @@ import { loadCodeCache } from '../../utils/code-cache';
*/ */
export async function generateCode(state: GraphState) { export async function generateCode(state: GraphState) {
try { try {
logger.printInfoLog('🚀 Starting Code Generation...'); logger.reportPhase('生成组件代码', 50);
logger.printInfoLog('正在生成代码…');
// Validate required state fields // Validate required state fields
if (!state.protocol) { if (!state.protocol) {
...@@ -25,7 +26,7 @@ export async function generateCode(state: GraphState) { ...@@ -25,7 +26,7 @@ export async function generateCode(state: GraphState) {
// Inject root component to App.tsx (cache is saved after injection) // Inject root component to App.tsx (cache is saved after injection)
await injectRootComponentToApp(state, cache); await injectRootComponentToApp(state, cache);
logger.printSuccessLog(`✨ Code generation completed! Generated ${totalComponents} components`); logger.printSuccessLog(`代码生成完成,共生成 ${totalComponents} 个组件`);
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Code generation failed: ${errorMessage}`); throw new Error(`Code generation failed: ${errorMessage}`);
......
...@@ -45,9 +45,9 @@ function ensureVueComponentsBarrel(state: GraphState, rootName: string): void { ...@@ -45,9 +45,9 @@ function ensureVueComponentsBarrel(state: GraphState, rootName: string): void {
const rel = `./${file}`; const rel = `./${file}`;
const barrel = `export { default } from '${rel}';\n`; const barrel = `export { default } from '${rel}';\n`;
writeFile(componentsDir, 'index.ts', barrel); writeFile(componentsDir, 'index.ts', barrel);
logger.printInfoLog(`🔗 components barrel -> ${rel}`); logger.printInfoLog(`🔗 已生成组件聚合入口(barrel)-> ${rel}`);
} catch (err) { } catch (err) {
logger.printWarnLog(`Failed to ensure components barrel: ${(err as Error).message}`); logger.printWarnLog(`生成组件聚合入口失败: ${(err as Error).message}`);
} }
} }
...@@ -64,23 +64,28 @@ export async function processNode(state: GraphState, cache: CodeCache): Promise< ...@@ -64,23 +64,28 @@ export async function processNode(state: GraphState, cache: CodeCache): Promise<
const total = flatNodes.length; const total = flatNodes.length;
if (total === 0) { if (total === 0) {
logger.printWarnLog('No components found in structure to generate.'); logger.printWarnLog('结构树中未识别到可生成的组件。');
return 0; return 0;
} }
logger.printInfoLog(`Processing ${total} nodes...`); logger.printInfoLog(`正在处理 ${total} 个节点…`);
let processedCount = 0; let processedCount = 0;
let skippedCount = 0; let skippedCount = 0;
const processSingleNode = async (currentNode: Protocol) => { const processSingleNode = async (currentNode: Protocol) => {
// Defense-in-depth: a node whose `data` is missing cannot be generated.
if (!currentNode || !currentNode.data) {
logger.printWarnLog(`跳过缺少 data 字段的节点(id=${currentNode?.id ?? 'unknown'})`);
return;
}
const componentName = currentNode.data.name || currentNode.data.componentName || 'UnknownComponent'; const componentName = currentNode.data.name || currentNode.data.componentName || 'UnknownComponent';
const nodeId = currentNode.id; const nodeId = currentNode.id;
// Check if component is already generated // Check if component is already generated
if (isComponentGenerated(cache, nodeId)) { if (isComponentGenerated(cache, nodeId)) {
skippedCount++; skippedCount++;
logger.printInfoLog(`[${processedCount + skippedCount}/${total}] ⏭️ Skipping (cached): ${componentName}`); logger.printInfoLog(`[${processedCount + skippedCount}/${total}] ⏭️ 复用缓存,跳过:${componentName}`);
return; return;
} }
...@@ -101,9 +106,9 @@ export async function processNode(state: GraphState, cache: CodeCache): Promise< ...@@ -101,9 +106,9 @@ export async function processNode(state: GraphState, cache: CodeCache): Promise<
await promisePool(flatNodes, processSingleNode); await promisePool(flatNodes, processSingleNode);
if (skippedCount > 0) { if (skippedCount > 0) {
logger.printInfoLog(`⏭️ Skipped ${skippedCount} cached components`); logger.printInfoLog(`跳过了 ${skippedCount} 个已缓存的组件`);
} }
logger.printSuccessLog(`Generated ${processedCount} components`); logger.printSuccessLog(`已生成 ${processedCount} 个组件`);
return processedCount; return processedCount;
} }
...@@ -114,6 +119,10 @@ export function flattenPostOrder(node: Protocol): Protocol[] { ...@@ -114,6 +119,10 @@ export function flattenPostOrder(node: Protocol): Protocol[] {
const result: Protocol[] = []; const result: Protocol[] = [];
function traverse(n: Protocol) { function traverse(n: Protocol) {
// Skip malformed nodes that lack a `data` field (e.g. emitted by a weak
// model on a truncated structure response). Without this, downstream code
// reads `node.data.name` on `undefined` and the whole run crashes.
if (!n || !n.data) return;
n.children?.forEach(child => traverse(child)); n.children?.forEach(child => traverse(child));
result.push(n); result.push(n);
} }
...@@ -133,8 +142,10 @@ export function detectRenderingModes(node: Protocol): { ...@@ -133,8 +142,10 @@ export function detectRenderingModes(node: Protocol): {
let hasIndependentChildren = false; let hasIndependentChildren = false;
(node.children || []).forEach(child => { (node.children || [])
if (!child.data.componentName) { .filter(child => child && child.data)
.forEach(child => {
if (!child.data!.componentName) {
hasIndependentChildren = true; hasIndependentChildren = true;
} }
}); });
...@@ -148,12 +159,14 @@ export function detectRenderingModes(node: Protocol): { ...@@ -148,12 +159,14 @@ export function detectRenderingModes(node: Protocol): {
*/ */
export async function generateFrame(node: Protocol, state: GraphState, assetFilesList: string, progressInfo: string): Promise<void> { export async function generateFrame(node: Protocol, state: GraphState, assetFilesList: string, progressInfo: string): Promise<void> {
const frameName = node.data.name; const frameName = node.data.name;
logger.printInfoLog(`${progressInfo} 🖼️ Generating Frame: ${frameName}`); logger.printInfoLog(`${progressInfo} 🖼️ 正在生成容器(Frame):${frameName}`);
// Build children imports information // Build children imports information
const childrenImports = (node.children || []).map(child => ({ const childrenImports = (node.children || [])
name: child.data.name || '', .filter(child => child && child.data)
path: child.data.path, .map(child => ({
name: child.data!.name || '',
path: child.data!.path,
})); }));
// Detect rendering modes // Detect rendering modes
...@@ -179,7 +192,7 @@ export async function generateFrame(node: Protocol, state: GraphState, assetFile ...@@ -179,7 +192,7 @@ export async function generateFrame(node: Protocol, state: GraphState, assetFile
const componentPath = node.data.path || ''; const componentPath = node.data.path || '';
const filePath = workspaceManager.resolveAppSrc(state.workspace, workspaceManager.resolveComponentPath(componentPath)); const filePath = workspaceManager.resolveAppSrc(state.workspace, workspaceManager.resolveComponentPath(componentPath));
saveGeneratedCode(code, filePath); saveGeneratedCode(code, filePath);
logger.printSuccessLog(`Successfully generated frame: ${frameName}`); logger.printSuccessLog(`容器已生成:${frameName}`);
} }
/** /**
...@@ -190,7 +203,7 @@ export async function generateComponent(node: Protocol, state: GraphState, asset ...@@ -190,7 +203,7 @@ export async function generateComponent(node: Protocol, state: GraphState, asset
const componentName = node.data.componentName || node.data.name || 'UnknownComponent'; const componentName = node.data.componentName || node.data.name || 'UnknownComponent';
const componentPath = node.data.componentPath || node.data.path || ''; const componentPath = node.data.componentPath || node.data.path || '';
logger.printInfoLog(`${progressInfo} 📦 Generating Component: ${componentName}`); logger.printInfoLog(`${progressInfo} 📦 正在生成组件:${componentName}`);
// Generate prompt (framework dispatched via the active strategy) // Generate prompt (framework dispatched via the active strategy)
const prompt = getActiveStrategy().buildComponentPrompt({ const prompt = getActiveStrategy().buildComponentPrompt({
...@@ -210,7 +223,7 @@ export async function generateComponent(node: Protocol, state: GraphState, asset ...@@ -210,7 +223,7 @@ export async function generateComponent(node: Protocol, state: GraphState, asset
// Save generated files // Save generated files
const filePath = workspaceManager.resolveAppSrc(state.workspace, workspaceManager.resolveComponentPath(componentPath)); const filePath = workspaceManager.resolveAppSrc(state.workspace, workspaceManager.resolveComponentPath(componentPath));
saveGeneratedCode(code, filePath); saveGeneratedCode(code, filePath);
logger.printSuccessLog(`Successfully generated component: ${componentName}`); logger.printSuccessLog(`组件已生成:${componentName}`);
} }
/** /**
...@@ -254,13 +267,14 @@ function getAssetFilesList(state: GraphState) { ...@@ -254,13 +267,14 @@ function getAssetFilesList(state: GraphState) {
*/ */
export async function injectRootComponentToApp(state: GraphState, cache: CodeCache): Promise<void> { export async function injectRootComponentToApp(state: GraphState, cache: CodeCache): Promise<void> {
try { try {
logger.reportPhase('注入根组件', 85);
// Check if already injected // Check if already injected
if (isAppInjected(cache)) { if (isAppInjected(cache)) {
logger.printInfoLog('⏭️ Skipping App.tsx injection (already injected)'); logger.printInfoLog('⏭️ 根组件已注入,跳过 App.tsx 注入步骤');
return; return;
} }
logger.printInfoLog(`💉 Injecting root component into ${getActiveStrategy().rootFileName}...`); logger.printInfoLog(`💉 正在将根组件注入 ${getActiveStrategy().rootFileName}…`);
// Construct the framework-specific app entry path (App.tsx for React, App.vue for Vue, …) // Construct the framework-specific app entry path (App.tsx for React, App.vue for Vue, …)
const strategy = getActiveStrategy(); const strategy = getActiveStrategy();
...@@ -272,14 +286,14 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac ...@@ -272,14 +286,14 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac
appContent = fs.readFileSync(appEntryPath, 'utf8'); appContent = fs.readFileSync(appEntryPath, 'utf8');
} catch { } catch {
// Use default template if the app entry doesn't exist yet // Use default template if the app entry doesn't exist yet
logger.printWarnLog(`${strategy.rootFileName} not found, using default template`); logger.printWarnLog(`未找到 ${strategy.rootFileName},使用默认模板`);
appContent = strategy.defaultAppContent; appContent = strategy.defaultAppContent;
} }
// Get root component information // Get root component information
const rootNode = state.protocol!; const rootNode = state.protocol!;
const componentName = rootNode.data.name || 'RootComponent'; const componentName = rootNode.data?.name || 'RootComponent';
const componentPath = rootNode.data.path || ''; const componentPath = rootNode.data?.path || '';
// Generate prompt (framework dispatched via the active strategy) // Generate prompt (framework dispatched via the active strategy)
const prompt = strategy.buildRootInjectionPrompt({ const prompt = strategy.buildRootInjectionPrompt({
...@@ -310,9 +324,9 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac ...@@ -310,9 +324,9 @@ export async function injectRootComponentToApp(state: GraphState, cache: CodeCac
ensureVueComponentsBarrel(state, componentName); ensureVueComponentsBarrel(state, componentName);
} }
logger.printSuccessLog(`Successfully injected ${componentName} into App.tsx`); logger.printSuccessLog(`已成功将根组件 ${componentName} 注入 App 入口`);
} catch (error) { } catch (error) {
logger.printErrorLog(`Failed to inject root component: ${(error as Error).message}`); logger.printErrorLog(`注入根组件失败:${(error as Error).message}`);
// Don't throw - allow the process to continue even if injection fails // Don't throw - allow the process to continue even if injection fails
} }
} }
...@@ -15,7 +15,8 @@ import { getProjectProfile } from '../../utils/project-profile'; ...@@ -15,7 +15,8 @@ import { getProjectProfile } from '../../utils/project-profile';
* endpoints (e.g. Aliyun MAAS Qwen) due to an unbounded agent loop. * endpoints (e.g. Aliyun MAAS Qwen) due to an unbounded agent loop.
*/ */
export const initialProject = async (state: GraphState) => { export const initialProject = async (state: GraphState) => {
logger.printInfoLog('Initializing project...'); logger.reportPhase('初始化项目', 8);
logger.printInfoLog('正在初始化项目…');
const appPath = state.workspace.app; const appPath = state.workspace.app;
const appName = state.urlInfo.name || 'my-app'; const appName = state.urlInfo.name || 'my-app';
...@@ -36,7 +37,7 @@ export const initialProject = async (state: GraphState) => { ...@@ -36,7 +37,7 @@ export const initialProject = async (state: GraphState) => {
} }
} }
logger.printSuccessLog(`Scaffold created at ${appPath}`); logger.printSuccessLog(`脚手架已生成于 ${appPath}`);
return {}; return {};
}; };
...@@ -27,6 +27,7 @@ import { workspaceManager } from '../../utils/workspace'; ...@@ -27,6 +27,7 @@ import { workspaceManager } from '../../utils/workspace';
* @returns The state of the graph. * @returns The state of the graph.
*/ */
export const generateProtocol = async (state: GraphState) => { export const generateProtocol = async (state: GraphState) => {
logger.reportPhase('获取设计稿与图片', 15);
const assetsDir = workspaceManager.resolveAppSrc(state.workspace, 'assets'); const assetsDir = workspaceManager.resolveAppSrc(state.workspace, 'assets');
const processDir = state.workspace.process; const processDir = state.workspace.process;
const { document, imageNodesMap } = await executeFigmaAndImagesActions(state.urlInfo, assetsDir, processDir); const { document, imageNodesMap } = await executeFigmaAndImagesActions(state.urlInfo, assetsDir, processDir);
...@@ -40,7 +41,7 @@ export const generateProtocol = async (state: GraphState) => { ...@@ -40,7 +41,7 @@ export const generateProtocol = async (state: GraphState) => {
// Write protocol.json (contains all Figma data in data.elements) // Write protocol.json (contains all Figma data in data.elements)
writeFile(state.workspace.process, 'protocol.json', JSON.stringify(protocol, null, 2)); writeFile(state.workspace.process, 'protocol.json', JSON.stringify(protocol, null, 2));
logger.printInfoLog(`Please check the output in the workspace: ${state.workspace.process}`); logger.printInfoLog(`中间产物已写入工作区:${state.workspace.process}`);
return { return {
protocol, protocol,
...@@ -76,7 +77,7 @@ export const executeFigmaAndImagesActions = async ( ...@@ -76,7 +77,7 @@ export const executeFigmaAndImagesActions = async (
throw new Error('Failed to fetch and clean Figma document'); throw new Error('Failed to fetch and clean Figma document');
} }
writeFile(processDir, 'figma.json', JSON.stringify(document, null, 2)); writeFile(processDir, 'figma.json', JSON.stringify(document, null, 2));
logger.printSuccessLog(`Figma document fetched and cleaned successfully`); logger.printSuccessLog(`已成功获取并清洗 Figma 文档`);
/* Detect and download images from Figma document */ /* Detect and download images from Figma document */
const downloadResult: { successCount: number; failCount: number; imageNodesMap: Map<string, ImageNode> } = const downloadResult: { successCount: number; failCount: number; imageNodesMap: Map<string, ImageNode> } =
...@@ -84,10 +85,10 @@ export const executeFigmaAndImagesActions = async ( ...@@ -84,10 +85,10 @@ export const executeFigmaAndImagesActions = async (
const { successCount, failCount, imageNodesMap } = downloadResult; const { successCount, failCount, imageNodesMap } = downloadResult;
if (successCount) { if (successCount) {
logger.printSuccessLog(`Downloaded ${successCount} images`); logger.printSuccessLog(`已下载 ${successCount} 张图片`);
} }
if (failCount) { if (failCount) {
logger.printWarnLog(`Failed to download ${failCount} images`); logger.printWarnLog(`有 ${failCount} 张图片下载失败`);
} }
/* Write images.json with array format for JSON compatibility */ /* Write images.json with array format for JSON compatibility */
......
...@@ -24,11 +24,12 @@ export const generateStructure = async (figma: FigmaFrameInfo) => { ...@@ -24,11 +24,12 @@ export const generateStructure = async (figma: FigmaFrameInfo) => {
const thumbnailUrl = figma.thumbnailUrl; const thumbnailUrl = figma.thumbnailUrl;
if (!frames || frames.length === 0) { if (!frames || frames.length === 0) {
logger.printErrorLog('No processed frames found in state'); logger.printErrorLog('未找到已处理的界面帧(state 为空)');
throw new Error('No processed frames found'); throw new Error('No processed frames found');
} }
logger.printInfoLog('Starting structure analysis...'); logger.reportPhase('结构识别', 35);
logger.printInfoLog('正在分析界面结构…');
try { try {
// Extract hierarchical position data from Figma frames // Extract hierarchical position data from Figma frames
...@@ -41,7 +42,7 @@ export const generateStructure = async (figma: FigmaFrameInfo) => { ...@@ -41,7 +42,7 @@ export const generateStructure = async (figma: FigmaFrameInfo) => {
width: imageWidth ? String(imageWidth) : '1440', width: imageWidth ? String(imageWidth) : '1440',
}); });
logger.printInfoLog('Calling AI model to generate component structure...'); logger.printInfoLog('正在调用模型生成组件结构…');
const structureResult = await callModel({ const structureResult = await callModel({
question: prompt, question: prompt,
...@@ -55,23 +56,23 @@ export const generateStructure = async (figma: FigmaFrameInfo) => { ...@@ -55,23 +56,23 @@ export const generateStructure = async (figma: FigmaFrameInfo) => {
const parsedStructure = JSON.parse(jsonContent) as Protocol | Protocol[]; const parsedStructure = JSON.parse(jsonContent) as Protocol | Protocol[];
// Post-process structure: normalize names, populate elements, annotate paths // Post-process structure: normalize names, populate elements, annotate paths
logger.printInfoLog('Processing structure tree...'); logger.printInfoLog('正在处理结构树…');
postProcessStructure(parsedStructure, frames); postProcessStructure(parsedStructure, frames);
const protocol = (Array.isArray(parsedStructure) ? parsedStructure[0] : parsedStructure) as Protocol; const protocol = (Array.isArray(parsedStructure) ? parsedStructure[0] : parsedStructure) as Protocol;
// Extract component props and states for reusable components // Extract component props and states for reusable components
if (frames && protocol) { if (frames && protocol) {
logger.printInfoLog('Extracting component properties and states...'); logger.printInfoLog('正在提取组件属性与状态…');
await populateComponentProps(protocol, frames, thumbnailUrl); await populateComponentProps(protocol, frames, thumbnailUrl);
} }
logger.printSuccessLog('Component structure generated successfully'); logger.printSuccessLog('组件结构已生成');
return protocol; return protocol;
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
logger.printErrorLog(`Error generating component structure: ${errorMessage}`); logger.printErrorLog(`生成组件结构时出错:${errorMessage}`);
throw new Error(`Failed to parse component structure: ${errorMessage}`); throw new Error(`Failed to parse component structure: ${errorMessage}`);
} }
}; };
...@@ -24,14 +24,14 @@ export async function commit(options?: GitCommitOptions): Promise<GitCommitResul ...@@ -24,14 +24,14 @@ export async function commit(options?: GitCommitOptions): Promise<GitCommitResul
await agent.run(instruction); await agent.run(instruction);
logger.printSuccessLog('Commit completed!'); logger.printSuccessLog('代码提交完成');
return { return {
success: true, success: true,
message: 'Commit workflow completed', message: 'Commit workflow completed',
}; };
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
logger.printErrorLog(`Commit failed: ${errorMessage}`); logger.printErrorLog(`代码提交失败:${errorMessage}`);
return { return {
success: false, success: false,
message: errorMessage, message: errorMessage,
......
...@@ -55,7 +55,7 @@ export async function validatePositions(config: ValidationIterationConfig): Prom ...@@ -55,7 +55,7 @@ export async function validatePositions(config: ValidationIterationConfig): Prom
return sum + errorX + errorY; return sum + errorX + errorY;
}, 0); }, 0);
logger.printInfoLog(`Found ${misalignedComponents.length} misaligned components`); logger.printInfoLog(`发现 ${misalignedComponents.length} 个对齐异常的组件`);
return { return {
mae: captureResult.metadata.mae, mae: captureResult.metadata.mae,
......
...@@ -18,6 +18,7 @@ import { ValidationMode } from '../../types/graph-types'; ...@@ -18,6 +18,7 @@ import { ValidationMode } from '../../types/graph-types';
* Throws error if validation fails (MAE threshold not reached) or execution errors occur. * Throws error if validation fails (MAE threshold not reached) or execution errors occur.
*/ */
export const runValidation = async (state: GraphState): Promise<void> => { export const runValidation = async (state: GraphState): Promise<void> => {
logger.reportPhase('校验与提交', 92);
if (!state.protocol) { if (!state.protocol) {
throw new Error('No protocol found for validation (state.protocol is missing).'); throw new Error('No protocol found for validation (state.protocol is missing).');
} }
...@@ -28,12 +29,12 @@ export const runValidation = async (state: GraphState): Promise<void> => { ...@@ -28,12 +29,12 @@ export const runValidation = async (state: GraphState): Promise<void> => {
const mode = state.config?.validationMode ?? ValidationMode.Full; const mode = state.config?.validationMode ?? ValidationMode.Full;
// Code-only mode: skip validation, only commit and exit // Code-only mode: skip validation, only commit and exit
if (mode === ValidationMode.CodeOnly) { if (mode === ValidationMode.CodeOnly) {
logger.printInfoLog('Code-only mode: skipping validation, committing generated code...'); logger.printInfoLog('仅代码模式:跳过校验,直接提交生成的代码…');
const commitResult = await commit({ appPath: state.workspace.app }); const commitResult = await commit({ appPath: state.workspace.app });
if (!commitResult.success) { if (!commitResult.success) {
logger.printWarnLog(`Git commit failed: ${commitResult.message}`); logger.printWarnLog(`代码提交失败:${commitResult.message}`);
} else { } else {
logger.printSuccessLog('Git commit completed successfully!'); logger.printSuccessLog('代码已成功提交');
} }
return; return;
} }
...@@ -43,7 +44,7 @@ export const runValidation = async (state: GraphState): Promise<void> => { ...@@ -43,7 +44,7 @@ export const runValidation = async (state: GraphState): Promise<void> => {
fs.mkdirSync(outputDir, { recursive: true }); fs.mkdirSync(outputDir, { recursive: true });
} }
logger.printInfoLog(`Starting validation loop (mode: ${mode})...`); logger.printInfoLog(`开始校验循环(模式:${mode})…`);
const result = await validationLoop({ const result = await validationLoop({
protocol: state.protocol, protocol: state.protocol,
...@@ -59,9 +60,9 @@ export const runValidation = async (state: GraphState): Promise<void> => { ...@@ -59,9 +60,9 @@ export const runValidation = async (state: GraphState): Promise<void> => {
const reportHtmlPath = path.join(outputDir, 'index.html'); const reportHtmlPath = path.join(outputDir, 'index.html');
if (result.validationPassed) { if (result.validationPassed) {
logger.printSuccessLog(`Validation PASSED (MAE: ${result.finalMae.toFixed(METRIC_DECIMAL_PLACES)}px)`); logger.printSuccessLog(`校验通过(MAE:${result.finalMae.toFixed(METRIC_DECIMAL_PLACES)}px)`);
} else { } else {
logger.printWarnLog(`Validation FAILED (MAE: ${result.finalMae.toFixed(METRIC_DECIMAL_PLACES)}px)`); logger.printWarnLog(`校验未通过(MAE:${result.finalMae.toFixed(METRIC_DECIMAL_PLACES)}px)`);
} }
logger.printInfoLog(`Validation report: ${reportHtmlPath}`); logger.printInfoLog(`校验报告已生成:${reportHtmlPath}`);
}; };
import { createLaunchAgent, launchAgentInstruction, type LaunchAgentResult } from '../../../agents/launch-agent'; import { spawnSync } from 'node:child_process';
import { LaunchTool } from '../../../tools/launch-tool';
import { logger } from '../../../utils/logger';
const BUILD_MAX_RETRIES = 2;
const CMD_TIMEOUT_MS = 180_000;
const DEV_SERVER_TIMEOUT_MS = 60_000;
export interface LaunchConfig { export interface LaunchConfig {
/** /**
...@@ -18,36 +24,68 @@ export interface LaunchResult { ...@@ -18,36 +24,68 @@ export interface LaunchResult {
port?: number; port?: number;
} }
function runCmd(command: string, cwd: string, timeoutMs: number = CMD_TIMEOUT_MS): { ok: boolean; output: string } {
const r = spawnSync(command, { cwd, timeout: timeoutMs, encoding: 'utf8', shell: true });
const output = [r.stdout, r.stderr].filter(Boolean).join('\n');
return { ok: r.status === 0, output };
}
export const launch = async (appPath: string, config?: LaunchConfig): Promise<LaunchResult> => { export const launch = async (appPath: string, config?: LaunchConfig): Promise<LaunchResult> => {
if (!appPath) { if (!appPath) {
throw new Error('appPath is required'); return { success: false, error: 'appPath is required' };
} }
try { try {
// Agent.run() returns the parsed LaunchAgentResult via postProcessor // 1. 安装依赖(首轮;迭代 2+ 由 skipDependencyInstall 跳过)
const agentResult = (await createLaunchAgent().run( if (!config?.skipDependencyInstall) {
launchAgentInstruction({ logger.printInfoLog('正在安装依赖(pnpm i)…');
appPath, const install = runCmd('pnpm i', appPath);
skipDependencyInstall: config?.skipDependencyInstall, if (!install.ok) {
}) return { success: false, error: `依赖安装失败:\n${install.output.slice(-1000)}` };
)) as LaunchAgentResult; }
logger.printSuccessLog('依赖安装完成');
// If agent explicitly failed, return the error }
if (agentResult.success === false) {
return { // 2. 构建(有限次重试,不调用模型)
success: false, let buildOk = false;
error: agentResult.error ?? 'Launch agent failed without error message', let buildOutput = '';
for (let attempt = 1; attempt <= BUILD_MAX_RETRIES; attempt++) {
logger.printInfoLog(`正在构建项目(npm run build,第 ${attempt}/${BUILD_MAX_RETRIES} 次)…`);
const build = runCmd('npm run build', appPath);
buildOutput = build.output;
if (build.ok) {
buildOk = true;
break;
}
logger.printWarnLog(`构建失败(第 ${attempt}/${BUILD_MAX_RETRIES} 次):\n${buildOutput.slice(-500)}`);
}
if (!buildOk) {
return { success: false, error: `构建失败,已重试 ${BUILD_MAX_RETRIES} 次:\n${buildOutput.slice(-1000)}` };
}
logger.printSuccessLog('构建完成');
// 3. 启动开发服务器(确定性调用 LaunchTool,不走 LLM)
logger.printInfoLog('正在启动开发服务器(npm run dev)…');
const launchTool = new LaunchTool();
const raw = await launchTool.startDevServer(appPath, 'npm run dev', DEV_SERVER_TIMEOUT_MS);
const res = JSON.parse(raw) as {
success: boolean;
serverKey?: string;
url?: string;
port?: number;
error?: string;
}; };
if (!res.success || !res.serverKey) {
return { success: false, error: res.error ?? '开发服务器启动失败' };
} }
// postProcessor already validates serverKey, url, port are present when success=true
// So we can safely return them here
return { return {
success: true, success: true,
message: agentResult.message ?? 'Launch and quality assurance completed', message: '开发服务器已启动',
serverKey: agentResult.serverKey, serverKey: res.serverKey,
url: agentResult.url, url: res.url,
port: agentResult.port, port: res.port,
}; };
} catch (error) { } catch (error) {
return { return {
......
...@@ -19,7 +19,7 @@ export async function report(options: ReportOptions): Promise<ReportResult> { ...@@ -19,7 +19,7 @@ export async function report(options: ReportOptions): Promise<ReportResult> {
try { try {
// Step 1: Generate userReport with screenshots // Step 1: Generate userReport with screenshots
logger.printInfoLog('Generating validation report structure...'); logger.printInfoLog('正在生成校验报告结构…');
const reportResult = await tool.generateReport({ const reportResult = await tool.generateReport({
validationResult: options.validationResult, validationResult: options.validationResult,
figmaThumbnailUrl: options.figmaThumbnailUrl, figmaThumbnailUrl: options.figmaThumbnailUrl,
...@@ -32,11 +32,11 @@ export async function report(options: ReportOptions): Promise<ReportResult> { ...@@ -32,11 +32,11 @@ export async function report(options: ReportOptions): Promise<ReportResult> {
}); });
// Step 2: Generate HTML file from userReport // Step 2: Generate HTML file from userReport
logger.printInfoLog('Generating HTML report file...'); logger.printInfoLog('正在生成 HTML 报告文件…');
const htmlResult = await tool.generateHtml(reportResult.userReport, options.outputDir); const htmlResult = await tool.generateHtml(reportResult.userReport, options.outputDir);
if (!htmlResult.success) { if (!htmlResult.success) {
logger.printWarnLog(`Failed to generate HTML: ${htmlResult.error}`); logger.printWarnLog(`生成 HTML 失败:${htmlResult.error}`);
return { return {
success: false, success: false,
error: htmlResult.error, error: htmlResult.error,
...@@ -44,7 +44,7 @@ export async function report(options: ReportOptions): Promise<ReportResult> { ...@@ -44,7 +44,7 @@ export async function report(options: ReportOptions): Promise<ReportResult> {
}; };
} }
logger.printSuccessLog(`Report generated successfully: ${htmlResult.htmlPath}`); logger.printSuccessLog(`报告已生成:${htmlResult.htmlPath}`);
return { return {
success: true, success: true,
htmlPath: htmlResult.htmlPath, htmlPath: htmlResult.htmlPath,
...@@ -52,7 +52,7 @@ export async function report(options: ReportOptions): Promise<ReportResult> { ...@@ -52,7 +52,7 @@ export async function report(options: ReportOptions): Promise<ReportResult> {
}; };
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
logger.printErrorLog(`Error generating report: ${errorMessage}`); logger.printErrorLog(`生成报告出错:${errorMessage}`);
// Fallback: Create minimal report // Fallback: Create minimal report
const minimalReport = tool.createMinimalReport({ const minimalReport = tool.createMinimalReport({
......
...@@ -28,7 +28,7 @@ async function installChromiumBrowsers(): Promise<void> { ...@@ -28,7 +28,7 @@ async function installChromiumBrowsers(): Promise<void> {
if (installCompleted) return; if (installCompleted) return;
if (!installPromise) { if (!installPromise) {
logger.printInfoLog('Playwright Chromium binaries are missing. Installing them automatically...'); logger.printInfoLog('Playwright Chromium 二进制缺失,正在自动安装…');
installPromise = new Promise((resolve, reject) => { installPromise = new Promise((resolve, reject) => {
// NOTE: Avoid --with-deps here; it can try to install system packages on some platforms. // NOTE: Avoid --with-deps here; it can try to install system packages on some platforms.
...@@ -47,7 +47,7 @@ async function installChromiumBrowsers(): Promise<void> { ...@@ -47,7 +47,7 @@ async function installChromiumBrowsers(): Promise<void> {
installPromise = null; installPromise = null;
if (code === 0) { if (code === 0) {
installCompleted = true; installCompleted = true;
logger.printSuccessLog('Playwright Chromium installation finished.'); logger.printSuccessLog('Playwright Chromium 安装完成。');
resolve(); resolve();
} else { } else {
reject(new Error(`Playwright install exited with code ${code}`)); reject(new Error(`Playwright install exited with code ${code}`));
......
...@@ -97,7 +97,7 @@ export const fetchFigmaNode = async (fileId: string, nodeId: string, token: stri ...@@ -97,7 +97,7 @@ export const fetchFigmaNode = async (fileId: string, nodeId: string, token: stri
`Figma 返回 403${figmaErr ? `(${figmaErr})` : ''}:通常是 Figma 个人访问令牌已过期或无效。` + `Figma 返回 403${figmaErr ? `(${figmaErr})` : ''}:通常是 Figma 个人访问令牌已过期或无效。` +
` 请在 Figma 账号设置重新生成 token,更新 ~/.coderio/config.yaml 的 figma.token,并重启后端后再试`; ` 请在 Figma 账号设置重新生成 token,更新 ~/.coderio/config.yaml 的 figma.token,并重启后端后再试`;
} }
logger.printErrorLog(`Failed to fetch Figma node: ${msg}`); logger.printErrorLog(`获取 Figma 节点失败:${msg}`);
return undefined; return undefined;
} }
}; };
...@@ -133,7 +133,7 @@ export const fetchFigmaImages = async ( ...@@ -133,7 +133,7 @@ export const fetchFigmaImages = async (
// format node id to match the format from response to request // format node id to match the format from response to request
return Object.fromEntries(Object.entries(images)); return Object.fromEntries(Object.entries(images));
} catch (error) { } catch (error) {
logger.printErrorLog(`Failed to fetch Figma images: ${error instanceof Error ? error.message : 'Unknown error'}`); logger.printErrorLog(`获取 Figma 图片失败:${error instanceof Error ? error.message : 'Unknown error'}`);
return {}; return {};
} }
}; };
......
...@@ -344,7 +344,7 @@ export const createDownloadTask = async (image: ImageNode, imageDir?: string): P ...@@ -344,7 +344,7 @@ export const createDownloadTask = async (image: ImageNode, imageDir?: string): P
success: true, success: true,
}; };
} catch { } catch {
logger.printErrorLog(`Failed to download image: ${image.url}`); logger.printErrorLog(`图片下载失败:${image.url}`);
return { return {
id: image.id, id: image.id,
name: image.name, name: image.name,
......
...@@ -109,23 +109,23 @@ export async function getFreeHashPort(workspacePath: string, _startPort: number ...@@ -109,23 +109,23 @@ export async function getFreeHashPort(workspacePath: string, _startPort: number
// Try preferred port first // Try preferred port first
if (await isPortAvailable(preferredPort)) { if (await isPortAvailable(preferredPort)) {
logger.printInfoLog(`Using workspace-preferred port: ${preferredPort}`); logger.printInfoLog(`使用工作区首选端口:${preferredPort}`);
return preferredPort; return preferredPort;
} }
// If preferred port is taken, try nearby ports (±10 range) // If preferred port is taken, try nearby ports (±10 range)
// This handles edge case where same workspace runs twice simultaneously // This handles edge case where same workspace runs twice simultaneously
logger.printInfoLog(`Preferred port ${preferredPort} occupied, trying nearby ports...`); logger.printInfoLog(`首选端口 ${preferredPort} 被占用,尝试邻近端口…`);
for (let offset = 1; offset <= 10; offset++) { for (let offset = 1; offset <= 10; offset++) {
const portUp = preferredPort + offset; const portUp = preferredPort + offset;
const portDown = preferredPort - offset; const portDown = preferredPort - offset;
if (await isPortAvailable(portUp)) { if (await isPortAvailable(portUp)) {
logger.printInfoLog(`Using nearby port: ${portUp} (preferred was ${preferredPort})`); logger.printInfoLog(`使用邻近端口:${portUp} (preferred was ${preferredPort})`);
return portUp; return portUp;
} }
if (portDown > 1024 && (await isPortAvailable(portDown))) { if (portDown > 1024 && (await isPortAvailable(portDown))) {
logger.printInfoLog(`Using nearby port: ${portDown} (preferred was ${preferredPort})`); logger.printInfoLog(`使用邻近端口:${portDown} (preferred was ${preferredPort})`);
return portDown; return portDown;
} }
} }
...@@ -174,7 +174,7 @@ export class DevServerManager { ...@@ -174,7 +174,7 @@ export class DevServerManager {
const normalizedExecutable = normalizeExecutable(executable); const normalizedExecutable = normalizeExecutable(executable);
const commandArgs = needsDoubleDash ? [...args, '--', '--port', String(port)] : [...args, '--port', String(port)]; const commandArgs = needsDoubleDash ? [...args, '--', '--port', String(port)] : [...args, '--port', String(port)];
logger.printInfoLog(`Starting dev server: ${normalizedExecutable} ${commandArgs.join(' ')}`); logger.printInfoLog(`正在启动开发服务器:${normalizedExecutable} ${commandArgs.join(' ')}`);
const child = spawn(normalizedExecutable, commandArgs, { const child = spawn(normalizedExecutable, commandArgs, {
cwd: this.params.appPath, cwd: this.params.appPath,
...@@ -216,7 +216,7 @@ export class DevServerManager { ...@@ -216,7 +216,7 @@ export class DevServerManager {
outputTail: () => out.trim(), outputTail: () => out.trim(),
}; };
logger.printSuccessLog(`Dev server ready at ${url}`); logger.printSuccessLog(`开发服务器已就绪:${url}`);
return this.handle; return this.handle;
} }
......
...@@ -195,6 +195,6 @@ export class PositionTool { ...@@ -195,6 +195,6 @@ export class PositionTool {
.map(e => e.elementId) .map(e => e.elementId)
.join(', '); .join(', ');
logger.printWarnLog(`Skipped ${skippedElements.length} element(s): ${summary}. First few: ${firstFew}`); logger.printWarnLog(`已跳过 ${skippedElements.length} 个元素:${summary}。前几个:${firstFew}`);
} }
} }
...@@ -41,9 +41,9 @@ export async function captureBrowserPositions(input: BrowserPositionInput): Prom ...@@ -41,9 +41,9 @@ export async function captureBrowserPositions(input: BrowserPositionInput): Prom
const thumbnailDimensions = await fetchThumbnailDimensions(input.figmaThumbnailUrl); const thumbnailDimensions = await fetchThumbnailDimensions(input.figmaThumbnailUrl);
if (thumbnailDimensions) { if (thumbnailDimensions) {
viewport = { width: thumbnailDimensions.width, height: thumbnailDimensions.height }; viewport = { width: thumbnailDimensions.width, height: thumbnailDimensions.height };
logger.printInfoLog(`Using viewport dimensions from Figma thumbnail: ${viewport.width}×${viewport.height}px`); logger.printInfoLog(`使用 Figma 缩略图视口尺寸:${viewport.width}×${viewport.height}px`);
} else { } else {
logger.printWarnLog(`Using default viewport dimensions: ${viewport.width}×${viewport.height}px`); logger.printWarnLog(`使用默认视口尺寸:${viewport.width}×${viewport.height}px`);
} }
} }
......
...@@ -57,7 +57,7 @@ export async function fetchThumbnailDimensions(figmaThumbnailUrl: string): Promi ...@@ -57,7 +57,7 @@ export async function fetchThumbnailDimensions(figmaThumbnailUrl: string): Promi
}; };
} catch (error) { } catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error); const errorMsg = error instanceof Error ? error.message : String(error);
logger.printWarnLog(`Failed to fetch Figma thumbnail: ${errorMsg}`); logger.printWarnLog(`获取 Figma 缩略图失败:${errorMsg}`);
return undefined; return undefined;
} }
} }
...@@ -68,7 +68,7 @@ export class ReportTool { ...@@ -68,7 +68,7 @@ export class ReportTool {
// Transform validation data to visualization format // Transform validation data to visualization format
const misalignedData = visualizationTool['formatForVisualization'](validationResult.misalignedComponents); const misalignedData = visualizationTool['formatForVisualization'](validationResult.misalignedComponents);
logger.printInfoLog(`Final misaligned components: ${misalignedData.length}`); logger.printInfoLog(`最终对齐异常组件数:${misalignedData.length}`);
// Load saved annotated screenshots from last validation iteration // Load saved annotated screenshots from last validation iteration
const renderMarkedBuffer = await fsPromises.readFile(request.savedRenderMarkedPath); const renderMarkedBuffer = await fsPromises.readFile(request.savedRenderMarkedPath);
...@@ -86,7 +86,7 @@ export class ReportTool { ...@@ -86,7 +86,7 @@ export class ReportTool {
// Generate combined comparison screenshot // Generate combined comparison screenshot
const finalScreenshotPath = path.join(comparisonDir, 'final.webp'); const finalScreenshotPath = path.join(comparisonDir, 'final.webp');
await visualizationTool.combine(screenshots.renderMarked, screenshots.targetMarked, finalScreenshotPath); await visualizationTool.combine(screenshots.renderMarked, screenshots.targetMarked, finalScreenshotPath);
logger.printSuccessLog(`Saved final comparison screenshot: ${path.basename(finalScreenshotPath)}`); logger.printSuccessLog(`已保存最终对比截图:${path.basename(finalScreenshotPath)}`);
// Generate pixel difference heatmap // Generate pixel difference heatmap
let heatmap = ''; let heatmap = '';
...@@ -101,11 +101,11 @@ export class ReportTool { ...@@ -101,11 +101,11 @@ export class ReportTool {
} }
const buffer = Buffer.from(base64Data, 'base64'); const buffer = Buffer.from(base64Data, 'base64');
await fs.promises.writeFile(heatmapPath, buffer); await fs.promises.writeFile(heatmapPath, buffer);
logger.printSuccessLog(`Saved pixel difference heatmap: ${path.basename(heatmapPath)}`); logger.printSuccessLog(`已保存像素差异热力图:${path.basename(heatmapPath)}`);
} }
} catch (heatmapError) { } catch (heatmapError) {
const errorMsg = heatmapError instanceof Error ? heatmapError.message : 'Unknown error'; const errorMsg = heatmapError instanceof Error ? heatmapError.message : 'Unknown error';
logger.printWarnLog(`Failed to generate pixel difference heatmap: ${errorMsg}. Continuing without heatmap.`); logger.printWarnLog(`生成像素差异热力图失败:${errorMsg},将继续但不含热力图。`);
} }
// Build userReport structure (pure data formatting) // Build userReport structure (pure data formatting)
...@@ -120,7 +120,7 @@ export class ReportTool { ...@@ -120,7 +120,7 @@ export class ReportTool {
misalignedData misalignedData
); );
logger.printSuccessLog('Validation report generated successfully'); logger.printSuccessLog('校验报告已生成');
return { return {
userReport, userReport,
......
...@@ -196,7 +196,7 @@ export class VisualizationTool { ...@@ -196,7 +196,7 @@ export class VisualizationTool {
// Combine into side-by-side comparison (needed for judger visual context in next iteration) // Combine into side-by-side comparison (needed for judger visual context in next iteration)
await this.combine(render.renderMarked, targetMarked, outputPath); await this.combine(render.renderMarked, targetMarked, outputPath);
logger.printInfoLog(`Saved comparison screenshot: ${path.basename(outputPath)}`); logger.printInfoLog(`已保存对比截图:${path.basename(outputPath)}`);
return { return {
renderMarked: render.renderMarked, renderMarked: render.renderMarked,
targetMarked, targetMarked,
...@@ -204,7 +204,7 @@ export class VisualizationTool { ...@@ -204,7 +204,7 @@ export class VisualizationTool {
}; };
} catch (error) { } catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error); const errorMsg = error instanceof Error ? error.message : String(error);
logger.printWarnLog(`Failed to generate iteration screenshot: ${errorMsg}`); logger.printWarnLog(`生成迭代截图失败:${errorMsg}`);
return { renderMarked: '', targetMarked: '', combinedPath: '' }; return { renderMarked: '', targetMarked: '', combinedPath: '' };
} }
} }
...@@ -216,7 +216,7 @@ export class VisualizationTool { ...@@ -216,7 +216,7 @@ export class VisualizationTool {
private formatForVisualization(components: MisalignedComponent[]): MisalignedComponentData[] { private formatForVisualization(components: MisalignedComponent[]): MisalignedComponentData[] {
return components.map((comp, idx) => { return components.map((comp, idx) => {
if (comp.elementIds.length === 0) { if (comp.elementIds.length === 0) {
logger.printWarnLog(`Component ${comp.name} has no elementIds. Using componentId as fallback.`); logger.printWarnLog(`组件 ${comp.name} 无 elementIds,改用 componentId 作为回退。`);
} }
return { return {
......
...@@ -3,6 +3,8 @@ import { completeChat, getDefaultModelConfig, setDefaultModelConfig, type Comple ...@@ -3,6 +3,8 @@ import { completeChat, getDefaultModelConfig, setDefaultModelConfig, type Comple
import { logger } from './logger'; import { logger } from './logger';
import { getDebugConfig, getModelConfig, type ModelConfig } from './config'; import { getDebugConfig, getModelConfig, type ModelConfig } from './config';
import { writeFile } from './file'; import { writeFile } from './file';
import { readFile } from 'node:fs/promises';
import { extname } from 'node:path';
import { workspaceManager } from './workspace'; import { workspaceManager } from './workspace';
/** /**
...@@ -11,6 +13,175 @@ import { workspaceManager } from './workspace'; ...@@ -11,6 +13,175 @@ import { workspaceManager } from './workspace';
type ContentPart = { type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } }; type ContentPart = { type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } };
/** /**
* Map file extensions to MIME types for inline base64 images.
*/
const MIME_BY_EXT: Record<string, string> = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.bmp': 'image/bmp',
'.svg': 'image/svg+xml',
};
function guessMimeFromUrl(url: string): string {
const clean = url.split('?')[0].split('#')[0];
const ext = extname(clean).toLowerCase();
return MIME_BY_EXT[ext] || 'image/png';
}
/**
* Decide whether to downscale images before sending them to the model.
*
* Only **local models** (loopback / Ollama — almost always small 2B–7B
* checkpoints) and **explicitly small models** (a `:Nb`-style tag with N ≤ 4)
* get downscaled. External large models (e.g. qwen3.8-max) keep the
* full-resolution image so design fidelity is preserved — the product's whole
* point is high-fidelity restoration, and downscaling only helps when the model
* itself would otherwise choke on multi-MB base64 payloads.
*/
function shouldDownscaleImages(config: ModelConfig): boolean {
const baseUrl = (config.baseUrl || '').toLowerCase();
const model = (config.model || '').toLowerCase();
// Local install: Ollama listens on :11434, or any loopback OpenAI-compatible
// server. Local setups almost always run small checkpoints.
const isLocal = /11434/.test(baseUrl) || /(localhost|127\.0\.0\.1)/.test(baseUrl);
// Small model by parameter count in the tag, e.g. qwen3-vl:2b, qwen3:0.6b.
const m = model.match(/[:\-]([0-9]*\.?[0-9]+)b\b/);
const paramsB = m ? parseFloat(m[1]) : NaN;
const isSmallModel = Number.isFinite(paramsB) && paramsB <= 4;
return isLocal || isSmallModel;
}
/**
* Normalize any image reference into an inline base64 `data:` URI.
*
* Why: Ollama's OpenAI-compatible `/v1` endpoint (and several local
* OpenAI-compatible servers) reject `image_url` with an http(s) URL or a
* filesystem path — they require the image inlined as
* `data:<mime>;base64,<payload>`. OpenAI itself accepts both forms, so
* inlining unconditionally keeps the engine provider-agnostic and is the
* system-level fix rather than a per-provider patch.
*
* `downscale` controls whether the inlined image is also shrunk to fit
* `COD_R_IMAGE_MAX_EDGE` (default 768px) — see `shouldDownscaleImages`. When
* false the image is inlined at full resolution (preserves fidelity for large
* external models).
*
* - `data:` URI → returned as-is (or downscaled if requested).
* - http(s) URL → fetched and inlined.
* - local path → read from disk and inlined.
*/
async function normalizeImageToDataUri(
raw: string,
downscale: boolean,
timeoutMs = 30000
): Promise<string> {
const url = raw.trim();
if (!url) throw new Error('empty image reference');
if (url.startsWith('data:')) {
// Already inline. Downscale only when the target model needs it.
return downscale ? downscaleDataUri(url) : url;
}
let buf: Buffer;
let mime: string;
if (/^https?:\/\//i.test(url)) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
mime = res.headers.get('content-type') || guessMimeFromUrl(url);
buf = Buffer.from(await res.arrayBuffer());
} finally {
clearTimeout(timer);
}
} else {
// Local filesystem path
mime = guessMimeFromUrl(url) || 'image/png';
buf = await readFile(url);
}
if (!downscale) {
// Full resolution — external large models keep design fidelity.
return `data:${mime};base64,${buf.toString('base64')}`;
}
return toDataUri(buf, mime);
}
async function toDataUri(buf: Buffer, mime: string): Promise<string> {
const scaled = await downscaleToFit(buf, mime);
return `data:${scaled.mime};base64,${scaled.buf.toString('base64')}`;
}
async function downscaleDataUri(uri: string): Promise<string> {
const m = /^data:([^;]+);base64,(.*)$/s.exec(uri);
if (!m) return uri;
try {
const buf = Buffer.from(m[2], 'base64');
const scaled = await downscaleToFit(buf, m[1]);
return `data:${scaled.mime};base64,${scaled.buf.toString('base64')}`;
} catch {
return uri;
}
}
let warnedSharpMissing = false;
/**
* Downscale an image so its longest edge does not exceed `COD_R_IMAGE_MAX_EDGE`
* (default 768). Local 2B-class vision models (e.g. qwen3-vl:2b) return garbled
* structure JSON / empty component output when fed multi-megabyte base64
* payloads; keeping the longest edge at ~768px drops the payload by one or two
* orders of magnitude and lets the model actually parse the layout.
*
* `sharp` is an optional peer dependency (see coderio/package.json). If it is
* not installed we return the image unchanged and warn once — the engine keeps
* working, just without downscaling.
*/
async function downscaleToFit(
buf: Buffer,
mime: string
): Promise<{ buf: Buffer; mime: string }> {
const maxEdge = Number(process.env.COD_R_IMAGE_MAX_EDGE ?? 768);
if (!Number.isFinite(maxEdge) || maxEdge <= 0) return { buf, mime };
let sharp: any;
try {
sharp = (await import('sharp')).default;
} catch {
if (!warnedSharpMissing) {
warnedSharpMissing = true;
logger.printErrorLog(
'[image] sharp not installed — images sent to model un-downscaled. ' +
'Run `pnpm --filter @coderio/coderio add sharp` to enable image downscaling for local models.'
);
}
return { buf, mime };
}
try {
const img = sharp(buf);
const meta = await img.metadata();
if (!meta.width || !meta.height) return { buf, mime };
if (Math.max(meta.width, meta.height) <= maxEdge) return { buf, mime };
const resized = await img
.resize({
width: meta.width >= meta.height ? maxEdge : undefined,
height: meta.width >= meta.height ? undefined : maxEdge,
fit: 'inside',
withoutEnlargement: true,
})
.toBuffer();
return { buf: resized, mime };
} catch {
return { buf, mime };
}
}
/**
* Options for calling the model * Options for calling the model
*/ */
export interface CallModelOptions { export interface CallModelOptions {
...@@ -105,7 +276,7 @@ export async function callModel(options: CallModelOptions): Promise<string> { ...@@ -105,7 +276,7 @@ export async function callModel(options: CallModelOptions): Promise<string> {
validateModelConfig(config); validateModelConfig(config);
} catch (error) { } catch (error) {
if (error instanceof Error) { if (error instanceof Error) {
logger.printErrorLog(`Configuration error: ${error.message}`); logger.printErrorLog(`配置错误:${error.message}`);
} }
throw error; throw error;
} }
...@@ -117,13 +288,30 @@ export async function callModel(options: CallModelOptions): Promise<string> { ...@@ -117,13 +288,30 @@ export async function callModel(options: CallModelOptions): Promise<string> {
const contentParts: ContentPart[] = []; const contentParts: ContentPart[] = [];
contentParts.push({ type: 'text', text: question }); contentParts.push({ type: 'text', text: question });
// Add images if provided // Add images if provided. Normalize every reference to an inline
// base64 data: URI so local OpenAI-compatible servers (Ollama etc.)
// accept them — they reject http(s)/filesystem URLs.
if (imageUrls) { if (imageUrls) {
const urls = Array.isArray(imageUrls) ? imageUrls : [imageUrls]; // Downscale only for local / small models; external large models
for (const url of urls) { // keep full resolution for maximum design fidelity.
if (url && typeof url === 'string' && url.trim()) { const downscale = shouldDownscaleImages(config);
contentParts.push({ type: 'image_url', image_url: { url: url.trim() } }); const raws = Array.isArray(imageUrls) ? imageUrls : [imageUrls];
const normalized = await Promise.all(
raws
.filter((u): u is string => typeof u === 'string' && !!u.trim())
.map(async (u) => {
try {
return await normalizeImageToDataUri(u, downscale);
} catch (e) {
logger.printErrorLog(
`Skipping image (could not inline for model): ${u} — ${e instanceof Error ? e.message : String(e)}`
);
return null;
} }
})
);
for (const du of normalized) {
if (du) contentParts.push({ type: 'image_url', image_url: { url: du } });
} }
} }
...@@ -164,6 +352,19 @@ export async function callModel(options: CallModelOptions): Promise<string> { ...@@ -164,6 +352,19 @@ export async function callModel(options: CallModelOptions): Promise<string> {
const debugConfig = getDebugConfig(); const debugConfig = getDebugConfig();
const isDebugEnabled = debugConfig.enabled; const isDebugEnabled = debugConfig.enabled;
if (isDebugEnabled) { if (isDebugEnabled) {
// Redact base64 payloads so the debug file stays readable/small.
const redactedParts = contentParts.map((p) =>
p.type === 'image_url'
? {
type: 'image_url' as const,
image_url: {
url: p.image_url.url.startsWith('data:')
? `[base64 data URI, ${p.image_url.url.length} chars]`
: p.image_url.url,
},
}
: p
);
const debugContent = [ const debugContent = [
'------------config------------', '------------config------------',
JSON.stringify( JSON.stringify(
...@@ -180,7 +381,7 @@ export async function callModel(options: CallModelOptions): Promise<string> { ...@@ -180,7 +381,7 @@ export async function callModel(options: CallModelOptions): Promise<string> {
2 2
), ),
'------------request------------', '------------request------------',
JSON.stringify(contentParts, null, 2), JSON.stringify(redactedParts, null, 2),
'------------response------------', '------------response------------',
JSON.stringify(text, null, 2), JSON.stringify(text, null, 2),
].join('\n'); ].join('\n');
......
...@@ -28,7 +28,7 @@ async function clearCheckpoint(checkpointer: SqliteSaver, threadId: string): Pro ...@@ -28,7 +28,7 @@ async function clearCheckpoint(checkpointer: SqliteSaver, threadId: string): Pro
await checkpointer.deleteThread(threadId); await checkpointer.deleteThread(threadId);
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
logger.printWarnLog(`Failed to clear checkpoint: ${errorMessage}`); logger.printWarnLog(`清除检查点失败:${errorMessage}`);
} }
} }
...@@ -79,7 +79,7 @@ export function resetCheckpointDb(checkpointer: SqliteSaver, dbPath: string): vo ...@@ -79,7 +79,7 @@ export function resetCheckpointDb(checkpointer: SqliteSaver, dbPath: string): vo
try { try {
const db = (checkpointer as unknown as { db?: { pragma(q: string): unknown; exec(s: string): unknown } }).db; const db = (checkpointer as unknown as { db?: { pragma(q: string): unknown; exec(s: string): unknown } }).db;
if (!db) { if (!db) {
logger.printWarnLog('Could not reset checkpoint: no underlying database handle'); logger.printWarnLog('无法重置检查点:缺少底层数据库句柄');
return; return;
} }
// Flush the WAL into the main db and truncate it — resolves any stale / // Flush the WAL into the main db and truncate it — resolves any stale /
......
...@@ -27,7 +27,7 @@ export function loadCodeCache(workspace: WorkspaceStructure): CodeCache { ...@@ -27,7 +27,7 @@ export function loadCodeCache(workspace: WorkspaceStructure): CodeCache {
try { try {
if (!fs.existsSync(cachePath)) { if (!fs.existsSync(cachePath)) {
logger.printInfoLog('No code cache found, starting fresh'); logger.printInfoLog('未发现代码缓存,从头开始');
return createEmptyCache(); return createEmptyCache();
} }
...@@ -36,15 +36,15 @@ export function loadCodeCache(workspace: WorkspaceStructure): CodeCache { ...@@ -36,15 +36,15 @@ export function loadCodeCache(workspace: WorkspaceStructure): CodeCache {
// Validate cache structure // Validate cache structure
if (!Array.isArray(cache.generatedComponents) || typeof cache.appInjected !== 'boolean') { if (!Array.isArray(cache.generatedComponents) || typeof cache.appInjected !== 'boolean') {
logger.printWarnLog('Invalid cache format, starting fresh'); logger.printWarnLog('缓存格式无效,从头开始');
return createEmptyCache(); return createEmptyCache();
} }
logger.printInfoLog(`Loaded code cache: ${cache.generatedComponents.length} components cached`); logger.printInfoLog(`已加载代码缓存:${cache.generatedComponents.length} 个组件已缓存`);
return cache; return cache;
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
logger.printWarnLog(`Failed to load code cache: ${errorMessage}. Starting fresh.`); logger.printWarnLog(`加载代码缓存失败:${errorMessage},从头开始。`);
return createEmptyCache(); return createEmptyCache();
} }
} }
...@@ -65,7 +65,7 @@ export function saveCodeCache(workspace: WorkspaceStructure, cache: CodeCache): ...@@ -65,7 +65,7 @@ export function saveCodeCache(workspace: WorkspaceStructure, cache: CodeCache):
fs.writeFileSync(cachePath, content, 'utf-8'); fs.writeFileSync(cachePath, content, 'utf-8');
} catch (error) { } catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error); const errorMessage = error instanceof Error ? error.message : String(error);
logger.printWarnLog(`Failed to save code cache: ${errorMessage}`); logger.printWarnLog(`保存代码缓存失败:${errorMessage}`);
} }
} }
......
...@@ -175,6 +175,18 @@ export function clearRuntimeConfig(): void { ...@@ -175,6 +175,18 @@ export function clearRuntimeConfig(): void {
} }
/** /**
* Read the currently-injected runtime override (or null if none). Used by the
* server's `loadServerModelConfig()` so that an explicit "connect to local
* Ollama" action wins over the file/env defaults for the next generation job.
*/
export function getRuntimeConfig(): {
model: ModelConfig | null;
figma: FigmaConfig | null;
} {
return { model: runtimeModel, figma: runtimeFigma };
}
/**
* Merge a partial configuration into the existing config.yaml and persist it. * Merge a partial configuration into the existing config.yaml and persist it.
* *
* Only the provided top-level keys are merged (shallow per section), so callers * Only the provided top-level keys are merged (shallow per section), so callers
......
...@@ -77,7 +77,7 @@ export function ensurePackageInstalled(packageName: string, packageNameInRegistr ...@@ -77,7 +77,7 @@ export function ensurePackageInstalled(packageName: string, packageNameInRegistr
return; return;
} }
logger.printInfoLog(`Package '${packageName}' is required for validation but not installed.`); logger.printInfoLog(`校验需要依赖包 '${packageName}',但尚未安装。`);
const pm = detectPackageManager(); const pm = detectPackageManager();
// For dependencies that should be devDependencies in the user's project if they are using coderio as a tool // For dependencies that should be devDependencies in the user's project if they are using coderio as a tool
...@@ -86,8 +86,8 @@ export function ensurePackageInstalled(packageName: string, packageNameInRegistr ...@@ -86,8 +86,8 @@ export function ensurePackageInstalled(packageName: string, packageNameInRegistr
const pmCmd = process.platform === 'win32' ? `${pm}.cmd` : pm; const pmCmd = process.platform === 'win32' ? `${pm}.cmd` : pm;
const installCmdDisplay = `${pmCmd} ${installArgs} ${pkgName}`; const installCmdDisplay = `${pmCmd} ${installArgs} ${pkgName}`;
logger.printInfoLog(`Installing ${pkgName} using ${pm}...`); logger.printInfoLog(`正在使用 ${pm} 安装 ${pkgName}…`);
logger.printInfoLog(`Command: ${installCmdDisplay}`); logger.printInfoLog(`执行命令:${installCmdDisplay}`);
try { try {
const result = spawnSync(pmCmd, [installArgs, pkgName], { const result = spawnSync(pmCmd, [installArgs, pkgName], {
...@@ -101,7 +101,7 @@ export function ensurePackageInstalled(packageName: string, packageNameInRegistr ...@@ -101,7 +101,7 @@ export function ensurePackageInstalled(packageName: string, packageNameInRegistr
if (result.status !== 0) { if (result.status !== 0) {
throw new Error(`Command exited with code ${result.status}`); throw new Error(`Command exited with code ${result.status}`);
} }
logger.printSuccessLog(`Successfully installed ${pkgName}.`); logger.printSuccessLog(`已成功安装 ${pkgName}。`);
} catch (error) { } catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error); const errorMsg = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to install ${pkgName}: ${errorMsg}. Please install it manually.`); throw new Error(`Failed to install ${pkgName}: ${errorMsg}. Please install it manually.`);
......
...@@ -68,7 +68,7 @@ export function createFiles({ files, filePath }: { files: FileInfo[]; filePath: ...@@ -68,7 +68,7 @@ export function createFiles({ files, filePath }: { files: FileInfo[]; filePath:
writeFile(dirPath, file.filename, file.content); writeFile(dirPath, file.filename, file.content);
} }
} catch (error) { } catch (error) {
logger.printErrorLog(`Failed to create files in ${filePath}: ${(error as Error).message}`); logger.printErrorLog(`在 ${filePath} 创建文件失败:${(error as Error).message}`);
throw error; throw error;
} }
} }
...@@ -115,4 +115,12 @@ export const logger = { ...@@ -115,4 +115,12 @@ export const logger = {
console.log(chalk.green(`[${getTimestamp()}] [SUCCESS] ✔ ${message}`)); console.log(chalk.green(`[${getTimestamp()}] [SUCCESS] ✔ ${message}`));
emit('success', message); emit('success', message);
}, },
/**
* 向编排后端报告当前生成阶段与进度百分比。
* 输出纯文本标记(无 ANSI、无时间戳),由后端 runner 解析以驱动前端进度条。
*/
reportPhase(phase: string, percent: number): void {
process.stdout.write(`__D2C_PHASE__:${phase}:${Math.round(percent)}\n`);
},
}; };
...@@ -107,9 +107,9 @@ class Workspace { ...@@ -107,9 +107,9 @@ class Workspace {
// the underlying delete still succeeds at the OS level. Treat that // the underlying delete still succeeds at the OS level. Treat that
// specific error as harmless noise rather than a scary warning. // specific error as harmless noise rather than a scary warning.
if (errorMessage.includes('[safe-delete]')) { if (errorMessage.includes('[safe-delete]')) {
logger.printInfoLog(`Workspace reset (safe-delete hook noted): ${errorMessage}`); logger.printInfoLog(`工作区已重置(已记录 safe-delete 钩子):${errorMessage}`);
} else { } else {
logger.printWarnLog(`Failed to delete workspace: ${errorMessage}`); logger.printWarnLog(`删除工作区失败:${errorMessage}`);
} }
} }
} }
......
// tsup.config.mjs
import { defineConfig } from "tsup";
import { readFileSync, cpSync, existsSync } from "fs";
var pkg = JSON.parse(readFileSync("./package.json", "utf8"));
var tsup_config_default = defineConfig({
entry: {
index: "src/index.ts",
cli: "src/cli/index.ts"
},
// Use ESM format with proper CJS interop
format: ["esm"],
dts: true,
splitting: false,
sourcemap: true,
clean: true,
minify: false,
target: "node18",
outDir: "dist",
platform: "node",
// All dependencies are external by default (automatic)
// Explicitly list only special cases for documentation purposes
external: [
/^@langchain\//
// Scoped package with many submodules
],
// Inject version at build time
define: {
__VERSION__: JSON.stringify(pkg.version)
},
// Copy report template to dist after build
onSuccess: async () => {
const templateSrc = "src/tools/report-tool/template/dist";
const templateDest = "dist/tools/report-tool/template";
if (existsSync(templateSrc)) {
console.log(`
Copying report template from ${templateSrc} to ${templateDest}...`);
cpSync(templateSrc, templateDest, { recursive: true });
console.log("\u2713 Report template copied successfully");
} else {
console.warn(`\u26A0 Warning: Report template source not found at ${templateSrc}`);
console.warn(' Run "pnpm run build:report" first to build the template');
}
}
});
export {
tsup_config_default as default
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsidHN1cC5jb25maWcubWpzIl0sCiAgInNvdXJjZXNDb250ZW50IjogWyJjb25zdCBfX2luamVjdGVkX2ZpbGVuYW1lX18gPSBcIkQ6XFxcXHdvcmtcXFxcZDJjXFxcXGNvZGVyaW9cXFxccGFja2FnZXNcXFxcY29kZXJpb1xcXFx0c3VwLmNvbmZpZy5tanNcIjtjb25zdCBfX2luamVjdGVkX2Rpcm5hbWVfXyA9IFwiRDpcXFxcd29ya1xcXFxkMmNcXFxcY29kZXJpb1xcXFxwYWNrYWdlc1xcXFxjb2RlcmlvXCI7Y29uc3QgX19pbmplY3RlZF9pbXBvcnRfbWV0YV91cmxfXyA9IFwiZmlsZTovLy9EOi93b3JrL2QyYy9jb2RlcmlvL3BhY2thZ2VzL2NvZGVyaW8vdHN1cC5jb25maWcubWpzXCI7aW1wb3J0IHsgZGVmaW5lQ29uZmlnIH0gZnJvbSAndHN1cCc7XG5pbXBvcnQgeyByZWFkRmlsZVN5bmMsIGNwU3luYywgZXhpc3RzU3luYyB9IGZyb20gJ2ZzJztcblxuLy8gUmVhZCB2ZXJzaW9uIGZyb20gcGFja2FnZS5qc29uIGF0IGJ1aWxkIHRpbWVcbmNvbnN0IHBrZyA9IEpTT04ucGFyc2UocmVhZEZpbGVTeW5jKCcuL3BhY2thZ2UuanNvbicsICd1dGY4JykpO1xuXG5leHBvcnQgZGVmYXVsdCBkZWZpbmVDb25maWcoe1xuICAgIGVudHJ5OiB7XG4gICAgICAgIGluZGV4OiAnc3JjL2luZGV4LnRzJyxcbiAgICAgICAgY2xpOiAnc3JjL2NsaS9pbmRleC50cycsXG4gICAgfSxcbiAgICAvLyBVc2UgRVNNIGZvcm1hdCB3aXRoIHByb3BlciBDSlMgaW50ZXJvcFxuICAgIGZvcm1hdDogWydlc20nXSxcbiAgICBkdHM6IHRydWUsXG4gICAgc3BsaXR0aW5nOiBmYWxzZSxcbiAgICBzb3VyY2VtYXA6IHRydWUsXG4gICAgY2xlYW46IHRydWUsXG4gICAgbWluaWZ5OiBmYWxzZSxcbiAgICB0YXJnZXQ6ICdub2RlMTgnLFxuICAgIG91dERpcjogJ2Rpc3QnLFxuICAgIHBsYXRmb3JtOiAnbm9kZScsXG4gICAgLy8gQWxsIGRlcGVuZGVuY2llcyBhcmUgZXh0ZXJuYWwgYnkgZGVmYXVsdCAoYXV0b21hdGljKVxuICAgIC8vIEV4cGxpY2l0bHkgbGlzdCBvbmx5IHNwZWNpYWwgY2FzZXMgZm9yIGRvY3VtZW50YXRpb24gcHVycG9zZXNcbiAgICBleHRlcm5hbDogW1xuICAgICAgICAvXkBsYW5nY2hhaW5cXC8vLCAvLyBTY29wZWQgcGFja2FnZSB3aXRoIG1hbnkgc3VibW9kdWxlc1xuICAgIF0sXG4gICAgLy8gSW5qZWN0IHZlcnNpb24gYXQgYnVpbGQgdGltZVxuICAgIGRlZmluZToge1xuICAgICAgICBfX1ZFUlNJT05fXzogSlNPTi5zdHJpbmdpZnkocGtnLnZlcnNpb24pLFxuICAgIH0sXG4gICAgLy8gQ29weSByZXBvcnQgdGVtcGxhdGUgdG8gZGlzdCBhZnRlciBidWlsZFxuICAgIG9uU3VjY2VzczogYXN5bmMgKCkgPT4ge1xuICAgICAgICBjb25zdCB0ZW1wbGF0ZVNyYyA9ICdzcmMvdG9vbHMvcmVwb3J0LXRvb2wvdGVtcGxhdGUvZGlzdCc7XG4gICAgICAgIGNvbnN0IHRlbXBsYXRlRGVzdCA9ICdkaXN0L3Rvb2xzL3JlcG9ydC10b29sL3RlbXBsYXRlJztcblxuICAgICAgICBpZiAoZXhpc3RzU3luYyh0ZW1wbGF0ZVNyYykpIHtcbiAgICAgICAgICAgIGNvbnNvbGUubG9nKGBcXG5Db3B5aW5nIHJlcG9ydCB0ZW1wbGF0ZSBmcm9tICR7dGVtcGxhdGVTcmN9IHRvICR7dGVtcGxhdGVEZXN0fS4uLmApO1xuICAgICAgICAgICAgY3BTeW5jKHRlbXBsYXRlU3JjLCB0ZW1wbGF0ZURlc3QsIHsgcmVjdXJzaXZlOiB0cnVlIH0pO1xuICAgICAgICAgICAgY29uc29sZS5sb2coJ1x1MjcxMyBSZXBvcnQgdGVtcGxhdGUgY29waWVkIHN1Y2Nlc3NmdWxseScpO1xuICAgICAgICB9IGVsc2Uge1xuICAgICAgICAgICAgY29uc29sZS53YXJuKGBcdTI2QTAgV2FybmluZzogUmVwb3J0IHRlbXBsYXRlIHNvdXJjZSBub3QgZm91bmQgYXQgJHt0ZW1wbGF0ZVNyY31gKTtcbiAgICAgICAgICAgIGNvbnNvbGUud2FybignICBSdW4gXCJwbnBtIHJ1biBidWlsZDpyZXBvcnRcIiBmaXJzdCB0byBidWlsZCB0aGUgdGVtcGxhdGUnKTtcbiAgICAgICAgfVxuICAgIH0sXG59KTtcbiJdLAogICJtYXBwaW5ncyI6ICI7QUFBd1EsU0FBUyxvQkFBb0I7QUFDclMsU0FBUyxjQUFjLFFBQVEsa0JBQWtCO0FBR2pELElBQU0sTUFBTSxLQUFLLE1BQU0sYUFBYSxrQkFBa0IsTUFBTSxDQUFDO0FBRTdELElBQU8sc0JBQVEsYUFBYTtBQUFBLEVBQ3hCLE9BQU87QUFBQSxJQUNILE9BQU87QUFBQSxJQUNQLEtBQUs7QUFBQSxFQUNUO0FBQUE7QUFBQSxFQUVBLFFBQVEsQ0FBQyxLQUFLO0FBQUEsRUFDZCxLQUFLO0FBQUEsRUFDTCxXQUFXO0FBQUEsRUFDWCxXQUFXO0FBQUEsRUFDWCxPQUFPO0FBQUEsRUFDUCxRQUFRO0FBQUEsRUFDUixRQUFRO0FBQUEsRUFDUixRQUFRO0FBQUEsRUFDUixVQUFVO0FBQUE7QUFBQTtBQUFBLEVBR1YsVUFBVTtBQUFBLElBQ047QUFBQTtBQUFBLEVBQ0o7QUFBQTtBQUFBLEVBRUEsUUFBUTtBQUFBLElBQ0osYUFBYSxLQUFLLFVBQVUsSUFBSSxPQUFPO0FBQUEsRUFDM0M7QUFBQTtBQUFBLEVBRUEsV0FBVyxZQUFZO0FBQ25CLFVBQU0sY0FBYztBQUNwQixVQUFNLGVBQWU7QUFFckIsUUFBSSxXQUFXLFdBQVcsR0FBRztBQUN6QixjQUFRLElBQUk7QUFBQSwrQkFBa0MsV0FBVyxPQUFPLFlBQVksS0FBSztBQUNqRixhQUFPLGFBQWEsY0FBYyxFQUFFLFdBQVcsS0FBSyxDQUFDO0FBQ3JELGNBQVEsSUFBSSw0Q0FBdUM7QUFBQSxJQUN2RCxPQUFPO0FBQ0gsY0FBUSxLQUFLLHVEQUFrRCxXQUFXLEVBQUU7QUFDNUUsY0FBUSxLQUFLLDJEQUEyRDtBQUFBLElBQzVFO0FBQUEsRUFDSjtBQUNKLENBQUM7IiwKICAibmFtZXMiOiBbXQp9Cg==
# @coderio/ollama-client
本地 Ollama 模型连接模块。负责两件事:
1. **管理**:发现/拉取/删除本地 Ollama 模型(Ollama 原生 REST,非 OpenAI 兼容)。
2. **聊天**:复用 `@coderio/ai-client` 的 `completeChat`(Ollama 暴露 OpenAI 兼容接口 `/v1`)。
> 纯聊天无需本模块:直接把 `ai-client` 的 `baseUrl` 指到 `http://localhost:11434/v1`、`apiKey` 填任意非空串即可。本模块的价值在于「本地模型发现/拉取」与开箱即用的预设。
## 前置
- 安装并启动 Ollama([ollama.com](https://ollama.com/download))。守护进程默认监听 `http://localhost:11434`。
- 可用 `OLLAMA_HOST` 环境变量覆盖地址。
## 用法
```ts
import {
localConfig, isRunning, listModels, pullModel, ensureModel, completeChat,
} from '@coderio/ollama-client';
// 1) 健康检查
if (!(await isRunning())) console.log('请先启动 Ollama');
// 2) 列出本地模型
const models = await listModels();
// 3) 确保模型存在(没有就拉取)
await ensureModel('qwen2.5');
// 4) 聊天(走 ai-client,指向本地)
await completeChat([msg], { config: localConfig('qwen2.5') });
```
## 设计说明
- 不读环境变量里的密钥、不写文件;地址由 `localBaseUrl()` 解析(`$OLLAMA_HOST` 或默认 `http://localhost:11434`)。
- 管理接口(`/api/tags`、`/api/pull`、`/api/ps`、`/api/delete`)用原生 `fetch` 实现,零额外依赖。
- 聊天复用 `ai-client`,避免重复封装 `ChatOpenAI`。
{
"name": "@coderio/ollama-client",
"version": "0.1.0",
"private": true,
"type": "module",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.js"
}
},
"scripts": {
"build": "tsc -p tsconfig.json",
"typecheck": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {},
"devDependencies": {
"@types/node": "catalog:",
"typescript": "catalog:"
}
}
export type {
OllamaModel,
OllamaPullProgress,
OllamaPullOptions,
OllamaChatConfig,
} from './types.js';
export {
OLLAMA_DEFAULT_BASE,
localBaseUrl,
localConfig,
isRunning,
listModels,
listRunning,
pullModel,
ensureModel,
deleteModel,
} from './ollama.js';
// 聊天复用 ai-client(Ollama 暴露 OpenAI 兼容接口 /v1),本模块只负责
// Ollama 特有的发现/管理与连接配置,保持职责单一、不耦合 ai-client 实现。
/// <reference types="node" />
import type { OllamaChatConfig, OllamaModel, OllamaPullProgress, OllamaPullOptions } from './types.js';
/** Default Ollama daemon address; the OpenAI-compatible API lives under /v1. */
export const OLLAMA_DEFAULT_BASE = 'http://localhost:11434';
/** Resolve the Ollama base URL: honour $OLLAMA_HOST, else the default. */
export function localBaseUrl(): string {
const raw = process.env.OLLAMA_HOST;
if (!raw) return OLLAMA_DEFAULT_BASE;
const withScheme = /^https?:\/\//.test(raw) ? raw : `http://${raw}`;
return withScheme.replace(/\/+$/, '');
}
/**
* Build an Ollama connection config (structurally compatible with ai-client's
* `AiModelConfig`) pointing at the local Ollama instance. Ollama ignores the
* API key, so any non-empty placeholder satisfies the client's "apiKey must be
* present" check. The OpenAI-compatible endpoint is `<base>/v1`.
*/
export function localConfig(
modelName: string,
opts?: { baseUrl?: string; apiKey?: string },
): OllamaChatConfig {
return {
modelName,
apiKey: opts?.apiKey ?? 'ollama',
baseUrl: `${opts?.baseUrl ?? localBaseUrl()}/v1`,
temperature: 0.1,
};
}
/** Cheap liveness probe: does the Ollama daemon answer at all? */
export async function isRunning(baseUrl: string = localBaseUrl()): Promise<boolean> {
try {
const res = await fetch(`${baseUrl}/`, { signal: AbortSignal.timeout(2000) });
return res.ok;
} catch {
return false;
}
}
function normalizeModel(m: Record<string, unknown>): OllamaModel {
return {
name: String(m.name ?? m.model ?? ''),
size: Number(m.size ?? 0),
digest: String(m.digest ?? ''),
modifiedAt: String(m.modified_at ?? m.modifiedAt ?? ''),
details: (m.details as Record<string, unknown> | undefined) ?? undefined,
};
}
/** List models installed locally (`GET /api/tags`). */
export async function listModels(baseUrl: string = localBaseUrl()): Promise<OllamaModel[]> {
const res = await fetch(`${baseUrl}/api/tags`);
if (!res.ok) throw new Error(`[ollama-client] listModels failed: HTTP ${res.status}`);
const data = (await res.json()) as { models?: Record<string, unknown>[] };
return (data.models ?? []).map(normalizeModel);
}
/** List models currently loaded into VRAM (`GET /api/ps`). */
export async function listRunning(baseUrl: string = localBaseUrl()): Promise<OllamaModel[]> {
const res = await fetch(`${baseUrl}/api/ps`);
if (!res.ok) throw new Error(`[ollama-client] listRunning failed: HTTP ${res.status}`);
const data = (await res.json()) as { models?: Record<string, unknown>[] };
return (data.models ?? []).map(normalizeModel);
}
/** Stream-pull a model, invoking `onProgress` for each NDJSON status line. */
export async function pullModel(model: string, opts: OllamaPullOptions = {}): Promise<void> {
const baseUrl = opts.baseUrl ?? localBaseUrl();
const res = await fetch(`${baseUrl}/api/pull`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model, stream: true }),
signal: opts.signal,
});
if (!res.ok) throw new Error(`[ollama-client] pull ${model} failed: HTTP ${res.status}`);
if (!res.body) return; // non-streaming fallback: nothing to parse
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
let nl: number;
while ((nl = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, nl).trim();
buffer = buffer.slice(nl + 1);
if (!line) continue;
try {
const p = JSON.parse(line) as OllamaPullProgress;
opts.onProgress?.(p);
} catch {
/* skip malformed keep-alive lines */
}
}
}
}
/**
* Ensure a model is available locally: if it is not in `listModels`, pull it.
* Resolves immediately when the model is already installed.
*/
export async function ensureModel(model: string, opts: OllamaPullOptions = {}): Promise<void> {
const existing = await listModels(opts.baseUrl).catch(() => []);
if (existing.some((m) => m.name === model)) return;
await pullModel(model, opts);
}
/** Delete a local model (`DELETE /api/delete`). */
export async function deleteModel(model: string, baseUrl: string = localBaseUrl()): Promise<void> {
const res = await fetch(`${baseUrl}/api/delete`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model }),
});
if (!res.ok) throw new Error(`[ollama-client] delete ${model} failed: HTTP ${res.status}`);
}
/**
* Shape of a locally-installed Ollama model (from `GET /api/tags`).
*/
export interface OllamaModel {
/** Model name as shown by `ollama list`, e.g. "qwen2.5:latest". */
name: string;
/** Size in bytes. */
size: number;
/** Digest (sha256) of the model blob. */
digest: string;
/** Last modified timestamp returned by Ollama. */
modifiedAt: string;
/** Ollama's free-form `details` object (family, parameter_size, …). */
details?: Record<string, unknown>;
}
/**
* One progress update emitted by `POST /api/pull` while streaming.
* Mirrors Ollama's NDJSON status lines.
*/
export interface OllamaPullProgress {
/** Phase: "pulling manifest", "downloading", "verifying sha256", "success". */
status: string;
model?: string;
digest?: string;
/** Total bytes to download for the current layer. */
total?: number;
/** Bytes downloaded so far for the current layer. */
completed?: number;
}
/** Options for {@link pullModel} / {@link ensureModel}. */
export interface OllamaPullOptions {
/** Override the Ollama base URL (default: http://localhost:11434 or $OLLAMA_HOST). */
baseUrl?: string;
/** Called for every progress line streamed during a pull. */
onProgress?: (progress: OllamaPullProgress) => void;
/** Abort signal to cancel an in-flight pull. */
signal?: AbortSignal;
}
/**
* Minimal model identity to point an OpenAI-compatible client (e.g. ai-client's
* `completeChat`) at Ollama. Structurally compatible with ai-client's
* `AiModelConfig`, so the returned object can be spread into `completeChat`'s
* `config` field.
*/
export interface OllamaChatConfig {
modelName: string;
apiKey: string;
baseUrl: string;
temperature?: number;
}
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"lib": ["ES2022"],
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"noImplicitAny": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictBindCallApply": true,
"noImplicitThis": true,
"alwaysStrict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"declaration": true,
"declarationMap": false,
"sourceMap": false
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
...@@ -154,6 +154,9 @@ importers: ...@@ -154,6 +154,9 @@ importers:
apps/server: apps/server:
dependencies: dependencies:
'@coderio/ollama-client':
specifier: workspace:*
version: link:../../packages/ollama-client
'@coderio/shared': '@coderio/shared':
specifier: workspace:* specifier: workspace:*
version: link:../../packages/shared version: link:../../packages/shared
...@@ -354,6 +357,15 @@ importers: ...@@ -354,6 +357,15 @@ importers:
specifier: 'catalog:' specifier: 'catalog:'
version: 2.1.9(@types/node@22.19.8) version: 2.1.9(@types/node@22.19.8)
packages/ollama-client:
devDependencies:
'@types/node':
specifier: 'catalog:'
version: 22.19.8
typescript:
specifier: 'catalog:'
version: 5.9.3
packages/shared: packages/shared:
dependencies: dependencies:
zod: zod:
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!