diff --git a/.changeset/i18n-localization-foundation.md b/.changeset/i18n-localization-foundation.md new file mode 100644 index 0000000000..5b2d8a4618 --- /dev/null +++ b/.changeset/i18n-localization-foundation.md @@ -0,0 +1,9 @@ +--- +"@runfusion/fusion": minor +--- + +Add a localization (i18n) foundation across the UI. Introduces react-i18next-backed translation for both the dashboard and the terminal UI, with English as the source language and Simplified Chinese, Traditional Chinese, French, and Spanish as target locales. + +- New `@fusion/i18n` package holding the authored catalogs and shared i18next configuration (namespace split, script-aware zh-CN/zh-TW fallback, plural setup). +- A `language` preference (`fusion settings`) and a Settings language switcher; the CLI resolves locale from `--lang`, settings, then environment. +- An `i18next-cli` workflow (`extract`/`sync`/`types`/`status`/`lint`) so adding a future language is a translate-only, near-zero-code operation. diff --git a/.gitignore b/.gitignore index 7362b6f83b..149f014bc0 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,10 @@ dist/ dist-electron/ *.tsbuildinfo +# Generated i18n catalogs synced into the dashboard tree from @fusion/i18n +# (authored source-of-truth lives in packages/i18n/locales/) +packages/dashboard/app/locales/ + # Desktop packaging artifacts *.dmg *.dmg.blockmap diff --git a/AGENTS.md b/AGENTS.md index 401c38436d..e876ae834d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -174,7 +174,7 @@ Scoped exception (FN-5819): shared-branch-group members (`branchContext.assignme - `./docs/soft-delete-verification-matrix.md` — mandatory soft-delete verification matrix. - `./docs/cli-reference.md` — CLI and terminal UI reference. - `./docs/contributing.md` — contributing conventions and release-adjacent context. -- `./docs/solutions/` — documented solutions to past problems (bugs, patterns, conventions), organized by category with YAML frontmatter (`module`, `tags`, `problem_type`). Relevant when implementing or debugging in documented areas. +- `./docs/solutions/` — documented solutions to past problems (bugs, architecture patterns, best practices, conventions), organized by category with YAML frontmatter (`category`, `module`, `tags`, `problem_type`, `applies_when`). Relevant when implementing or debugging in documented areas. - `./CONCEPTS.md` — shared domain vocabulary (entities, named processes, status concepts). Relevant when orienting to the codebase or discussing domain concepts. ### Lazy-Loaded Heavy Views diff --git a/CONCEPTS.md b/CONCEPTS.md index 081c76ab4f..8f4df9fce6 100644 --- a/CONCEPTS.md +++ b/CONCEPTS.md @@ -2,6 +2,20 @@ Shared domain vocabulary for this project — entities, named processes, and status concepts with project-specific meaning. Seeded with core domain vocabulary, then accretes as ce-compound and ce-compound-refresh process learnings; direct edits are fine. Glossary only, not a spec or catch-all. +## Settings & Localization + +### Surface +One of Fusion's user-facing frontends — the browser dashboard and the terminal TUI. Surfaces have independent runtimes and rendering stacks but are expected to share user-level state: a setting changed on one surface (theme, language) carries to the other. + +### Global Settings +User-level settings persisted server-side that apply across all Surfaces and all projects, as opposed to per-project settings. Values are validated at the write boundary — an invalid value is dropped rather than persisted — so every reader can trust what it loads. + +### Three-Tier Setting +The named persistence pattern for a user preference on the dashboard: a device-local cache for instant reads, a write-through to Global Settings so other Surfaces see it, and a hydrate-on-mount from the server when no local value exists. A local or in-flight user choice always wins over server hydration, and changes propagate to other open tabs. + +### Supported Locale +A language tag in the closed set Fusion ships translations for. Any external tag (browser, environment, flag) is normalized into this set or rejected — never passed through raw. Chinese tags route by script and region so Traditional-script users are never silently served Simplified, and the two Chinese variants never collapse into a generic base tag. + ## Missions ### Relationships diff --git a/README.es.md b/README.es.md new file mode 100644 index 0000000000..a69739fc7c --- /dev/null +++ b/README.es.md @@ -0,0 +1,469 @@ +
+ +Fusion + +# Fusion + +### De idea inicial a código en producción — automáticamente. + +**Orquestador de agentes multinodo** — tareas, agentes, misiones, git, archivos y worktrees, con cualquier modelo, local o en la nube. + +[**runfusion.ai →**](https://runfusion.ai) · [Docs](./docs/README.md) · [GitHub](https://github.com/Runfusion/Fusion) · [npm](https://www.npmjs.com/package/@runfusion/fusion) · [Discord](https://discord.gg/ksrfuy7WYR) + +[English](./README.md) · [简体中文](./README.zh-CN.md) · [繁體中文](./README.zh-TW.md) · [Français](./README.fr.md) · **Español** · [한국어](./README.ko.md) + +*Esta es una traducción automática; el README en inglés es el documento canónico.* + +[![License: MIT](https://img.shields.io/badge/license-MIT-3fb950.svg)](./LICENSE) +[![npm](https://img.shields.io/npm/v/@runfusion/fusion.svg?color=58a6ff)](https://www.npmjs.com/package/@runfusion/fusion) +[![Discord](https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white)](https://discord.gg/ksrfuy7WYR) +![Status](https://img.shields.io/badge/status-early%20preview-d29922.svg) +![Shipping](https://img.shields.io/badge/shipping-weekly-bc8cff.svg) + +
+ +Demo de Fusion: de idea inicial a código en producción + +
+
+ + + Panel de Fusion: columnas kanban de Planificación, Pendiente, En progreso, En revisión y Listo con tarjetas de tarea activas + + +
+ +--- + +## Todo tu entorno de desarrollo. En una sola pantalla. + +Describe una tarea en lenguaje natural. Un agente de planificación lee tu proyecto, comprende el contexto y escribe un plan completo en `PROMPT.md` — pasos, alcance de archivos, criterios de aceptación. Luego Fusion planifica, revisa, ejecuta y vuelve a revisar, en un worktree de git aislado, con una aprobación humana donde tú la necesites. + +Un tablero. Controlado desde cualquier lugar. Laptop, Mac mini, servidor Linux, VM en la nube, teléfono — todo conectado. + +> Como Trello, pero tus tareas son especificadas, ejecutadas y entregadas por IA. Construido sobre el gran trabajo de [dustinbyrne/kb](https://github.com/dustinbyrne/kb). + +--- + +## El flujo + +``` + ① Describir ② Planificación ③ El tablero ④ Worktree aislado + ───────────── ───────────── ───────────── ───────────────────── + "Agregar modo → El agente escribe → Plan → Revisión → → rama fusion/FN-123 + oscuro al PROMPT.md Ejecución → concurrente, cero + panel de (pasos, alcance, Revisión (por conflictos de + configuración" aceptación) paso, hasta archivos + terminar) +``` + +### Ve cada paso antes del merge + +
+ Detalle de tarea en Fusion: pasos del flujo visibles en una tarea en progreso con diffs y cambios de archivos +
+ +Cada tarea muestra su plan, sus revisiones, sus diffs y sus cambios de archivos en tiempo real. Entra a una tarea activa y ajusta la dirección, refina las restricciones, pausa o reescribe el prompt. + +--- + +## Qué lo hace diferente + +| | | +|---|---| +| 🧠 **Planificación con IA** | Describe una tarea en lenguaje natural. Los agentes de planificación la convierten en un plan `PROMPT.md` con pasos, alcance de archivos y criterios de aceptación. | +| 🔁 **Puertas de flujo** | Plan → Revisión → Ejecución → Revisión en cada paso. Las puertas previas al merge bloquean código deficiente; las posteriores ejecutan verificaciones informativas. | +| 🌳 **Aislamiento con worktrees** | Cada tarea corre en su propia rama y worktree (`fusion/{task-id}`). Tareas en paralelo. Cero conflictos. Delegación opcional a [worktrunk](https://github.com/max-sixty/worktrunk) mediante [`worktrunk.enabled`](./docs/settings-reference.md#worktree-backend-settings) (ver [abstracción WorktreeBackend](./docs/architecture.md#worktreebackend-abstraction)). | +| ⚡ **Merge inteligente** | ¿Pasa todas las puertas? Fusion hace squash-merge y avanza. Habilita aprobación manual en cualquier punto. | +| 🛰️ **Malla multinodo** | Laptop, Mac mini, servidor Linux, VM en la nube, teléfono — todos sincronizados. Escritorio, móvil, web. | +| 🧩 **Cualquier modelo** | Anthropic, OpenAI, Ollama y más. Local y en la nube coexisten. | +| 🏢 **Empresas de agentes** | Importa equipos predefinidos — más de 440 agentes en 16 empresas — y ejecútalos de forma autónoma durante semanas. | +| 📬 **Mensajería entre agentes** | Buzón incorporado entre agentes. Delega, aclara, coordina. | +| 🗨️ **Salas de chat multiagente** | Conversaciones grupales con alcance de proyecto donde varios miembros de la sala pueden responder: los miembros mencionados son respondedores directos, y miembros ambientales adicionales pueden responder hasta un límite. Actualmente **experimental** — habilita `chatRooms` en **Configuración → Funciones experimentales → Salas de chat**. ([Documentación de salas de chat](./docs/dashboard-guide.md#chat-rooms)) | +| 🗺️ **Misiones** | Planificación jerárquica (Misión → Hito → Slice → Característica → Tarea) con piloto automático y contratos de validación. | +| 🔬 **Investigación** | Ejecuciones de investigación delimitadas con búsqueda web, GitHub, documentación local y síntesis con LLM (además de soporte integrado en tiempo de ejecución para WebSearch/WebFetch en flujos de planificación y síntesis cuando está disponible). Convierte los hallazgos en tareas. ([Documentación](./docs/research.md)) | +| 🧪 **Automejora** | Los agentes reflexionan sobre su propio resultado y actualizan sus prompts a medida que aprenden tu base de código. | +| 🔓 **Código abierto. MIT.** | Sin dependencia de proveedor. Ejecútalo en tu propio hardware. Se actualiza semanalmente. | + +--- + +## Cómo funciona + +```mermaid +graph TD + H((Tú)) -->|idea inicial| T["Planificación
planificación automática"] + T --> TD["Pendiente
programado para ejecución"] + TD --> IP["En progreso
para cada paso:
planificar, revisar, ejecutar, revisar
"] + + subgraph IP["En progreso"] + direction TD + NS([Iniciar paso]) --> P[Planificar] + P --> R1{Revisar} + R1 -->|revisar| P + R1 -->|aprobar| E[Ejecutar] + E --> R2{Revisar} + R2 -->|revisar| E + R2 -->|siguiente paso| NS + R2 -->|repensar| P + end + + R2 -->|listo| IR["En revisión
listo para merge,
o completado automáticamente
"] + IR -->|squash merge directo
o PR mergeado| D["Listo"] + + style H fill:#161b22,stroke:#8b949e,color:#e6edf3 + style T fill:#2d2006,stroke:#d29922,color:#d29922 + style TD fill:#0d2044,stroke:#58a6ff,color:#58a6ff + style IP fill:#1a0d2e,stroke:#bc8cff,color:#bc8cff + style P fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style R1 fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style E fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style R2 fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style NS fill:#1a0d2e,stroke:#bc8cff,color:#bc8cff + style IR fill:#0d2d16,stroke:#3fb950,color:#3fb950 + style D fill:#1a1a1a,stroke:#8b949e,color:#8b949e +``` + +Las tareas con dependencias se procesan secuencialmente. Las tareas independientes se ejecutan en paralelo. Opcionalmente puedes requerir aprobación manual antes de que las tareas pasen de Planificación a Pendiente (configuración `requirePlanApproval`). + +--- + +## Multinodo. Un tablero. Todas las plataformas. + +
+ +Malla de Fusion: laptop, Mac mini, servidor Linux, VM en la nube, teléfono — todos sincronizados + +
+ +![macOS](https://img.shields.io/badge/macOS-000000?style=for-the-badge&logo=apple&logoColor=white) +![Windows](https://img.shields.io/badge/Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white) +![Linux](https://img.shields.io/badge/Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black) +![Web](https://img.shields.io/badge/Web-4285F4?style=for-the-badge&logo=googlechrome&logoColor=white) +![iOS](https://img.shields.io/badge/iOS-000000?style=for-the-badge&logo=apple&logoColor=white) +![Android](https://img.shields.io/badge/Android-3DDC84?style=for-the-badge&logo=android&logoColor=white) + +
+ +Laptop, Mac mini, servidor Linux, VM en la nube, teléfono — cada nodo es un par. El estado de tus tareas, agentes, registros y diffs permanecen sincronizados en toda la malla. El mismo Fusion se distribuye como: + +- 🖥️ **Aplicación de escritorio** — Electron para **macOS** (Intel + Apple Silicon), **Windows** 10/11 y **Linux** +- 📱 **Aplicación móvil** — Capacitor para **iOS/iPadOS** y **Android** ([MOBILE.md](./MOBILE.md)) +- 🌐 **Panel web** — cualquier navegador moderno, servido desde el daemon `fn dashboard` +- 🔌 **CLI** — binario `fn` + extensión para flujos de trabajo centrados en la terminal + +Inicia el daemon en cualquier nodo, conecta tus otros dispositivos y el tablero te sigue a todas partes. + +--- + +## Ejecuta una empresa de agentes + +
+ +Empresa de agentes Fusion: importa un equipo y ejecútalo de forma autónoma durante semanas + +
+ +Importa un equipo. Ejecútalo de forma autónoma durante semanas. **Más de 440 agentes en 16 empresas**, preparados para misiones, buzones y delegación entre agentes. + +```bash +npx companies.sh add paperclipai/companies/gstack +``` + +--- + +## Compatible con las herramientas que ya usas. + +Fusion se integra con las herramientas que ya conoces. **Hermes**, **Paperclip** y **OpenClaw** vienen como plugins de primera clase — enruta cualquier espacio de trabajo al entorno de ejecución que mejor se adapte a la tarea. Y cualquier empresa de agentes de Paperclip se importa con un solo comando. + +
+ Hermes +
+ +### [Hermes](https://hermes-agent.nousresearch.com) `experimental` + +Nous Research + +El agente autónomo de código abierto de **Nous Research**. Instala el plugin de Hermes y ejecuta agentes a través de Hermes para trabajos de larga duración con contexto creciente — enruta cualquier espacio de trabajo de Fusion hacia él. + +### OpenClaw `experimental` + +El soporte del entorno de ejecución de OpenClaw está disponible como plugin experimental (`fusion-plugin-openclaw-runtime`) para paridad en el descubrimiento y la configuración del entorno. Configura los agentes con `runtimeConfig.runtimeHint: "openclaw"` después de instalar el plugin. + +
+ +
+ Paperclip +
+ +### [Paperclip](https://paperclip.ing) `experimental` + +paperclip.ing + +El plano de control humano para la mano de obra de IA. Instala el plugin de Paperclip para ejecutar agentes a través de Paperclip dentro de Fusion. + +Fusion también soporta nativamente el estándar de empresa de agentes **[`companies.sh`](https://github.com/paperclipai/companies)**: importa un equipo predefinido — **más de 440 agentes en 16 empresas** — y déjalos coordinarse a través del buzón, las misiones y las puertas de flujo de Fusion durante semanas de trabajo autónomo. El mismo formato de empresa, los mismos agentes, las mismas habilidades que Paperclip. + +```bash +npx companies.sh add paperclipai/companies/gstack +``` + +
+ +> **Hermes**, **Paperclip** y **OpenClaw** son plugins de entorno de ejecución **experimentales** — las APIs y los formatos de comunicación pueden cambiar entre versiones menores. + +--- + +## Inicio rápido + +**Sin instalación, directo desde npm:** + +```bash +npx runfusion.ai +``` + +Esto lanza el panel. Los subcomandos se pasan directamente: `npx runfusion.ai task create "fix X"`, `npx runfusion.ai --help`, etc. (O de forma explícita: `npx @runfusion/fusion dashboard`.) + +**Instalador en una línea** (macOS y Linux — usa Homebrew automáticamente, recurre a npm como alternativa): + +```bash +curl -fsSL https://runfusion.ai/install.sh | sh +fusion dashboard +``` + +**Homebrew** (macOS y Linux): + +```bash +brew tap runfusion/fusion +brew install fusion +fusion dashboard # o: fn dashboard +``` + +O en una sola línea (añade el tap automáticamente): `brew install runfusion/fusion/fusion`. + +**npm global**: + +```bash +npm install -g @runfusion/fusion +fn dashboard # o: fusion dashboard +``` + +**Desde un clon** (para desarrollo): + +```bash +pnpm dev dashboard +``` + +Luego haz clic en la URL `Open:` que aparece en la terminal. Incorpora un token de portador +(`http://localhost:4040/?token=fn_...`) que el navegador guarda en +`localStorage` en la primera visita y reutiliza automáticamente. En el lado del +servidor, Fusion ahora persiste el token del panel/daemon en +`~/.fusion/settings.json` en la primera ejecución autenticada y lo reutiliza en +inicios posteriores a menos que lo sobreescribas (`--token`, `FUSION_DASHBOARD_TOKEN`, +`FUSION_DAEMON_TOKEN`) o deshabilites la autenticación con `--no-auth`. Consulta +[Referencia CLI → fn dashboard → Autenticación](./docs/cli-reference.md#fn-dashboard) +para conocer la precedencia completa y las opciones de restablecimiento/revocación. + +### Configuración inicial + +En el primer lanzamiento, Fusion abre el **asistente de incorporación** con tres pasos guiados: + +1. **Configuración de IA** — Usa una lista de proveedores simplificada para el inicio rápido (proveedores recomendados más los ya conectados), luego expande la **Configuración avanzada de proveedores** solo si necesitas proveedores adicionales o detalles de configuración. Solo necesitas un proveedor para comenzar. Las entradas de proveedor obsoletas de Google Gemini CLI / Antigravity están intencionalmente ocultas; las rutas de clave API de Google/Gemini, Google Generative AI, Vertex y Cloud Code permanecen disponibles. +2. **GitHub (Opcional)** — Conecta GitHub para importar issues y gestionar PRs +3. **Primera tarea** — Crea tu primera tarea o impórtala desde GitHub (si no hay ningún proyecto activo, la incorporación primero te pedirá que registres/selecciones un directorio de proyecto) + +El asistente se puede **descartar y no bloquea** — haz clic en **Omitir por ahora** para usar el panel de inmediato. Vuélvelo a activar más tarde desde **Configuración → Autenticación → Reabrir guía de incorporación**. + +### Móvil + +Para el flujo de trabajo con Capacitor + PWA, consulta [MOBILE.md](./MOBILE.md). + +--- + +## Documentación + +| Guía | Qué cubre | +|---|---| +| [Primeros pasos](./docs/getting-started.md) | Instalación e incorporación | +| [Guía del panel](./docs/dashboard-guide.md) | Vistas de tablero/lista, terminal, gestor de git | +| [Gestión de tareas](./docs/task-management.md) | Ciclo de vida de la tarea y comandos CLI | +| [Referencia CLI](./docs/cli-reference.md) | Referencia completa de comandos y daemon | +| [Referencia de configuración](./docs/settings-reference.md) | Opciones de configuración | +| [Arquitectura](./docs/architecture.md) | Funcionamiento interno del sistema | +| [Agentes](./docs/agents.md) | Gestión de agentes, creación, latido | +| [Pasos del flujo](./docs/workflow-steps.md) | Puertas de calidad, plantillas, fases | +| [Misiones](./docs/missions.md) | Jerarquía de misiones, planificación, piloto automático | +| [Multiproyecto](./docs/multi-project.md) | Registro central, modos de aislamiento | +| [Docker](./docs/docker.md) | Despliegue en contenedores | + +--- + +## Características principales + +- **Planificación con IA** — El agente de planificación genera un `PROMPT.md` detallado con pasos, alcance de archivos y criterios de aceptación +- **Ejecución paso a paso** — Ciclo Plan → Revisión → Ejecución → Revisión para cada paso de la tarea +- **Aislamiento con worktrees de git** — Cada tarea corre en su propio worktree (rama `fusion/{task-id}`) +- **Pasos del flujo** — Puertas de calidad configurables (previas al merge: bloquean el merge; posteriores al merge: informativas) +- **Integración con GitHub** — Importar issues, crear PRs, insignias en tiempo real de PR/issue +- **Panel** — Tablero kanban en tiempo real, gestión de agentes, terminal, gestor de git, planificador de misiones +- **Misiones** — Planificación jerárquica (Misión → Hito → Slice → Característica → Tarea) con piloto automático, contratos de validación, reintentos de corrección de características y semántica de entrega bloqueada +- **Multiproyecto** — Gestiona múltiples proyectos desde una sola instalación con aislamiento de proyectos +- **Mensajería entre agentes** — Sistema de mensajería integrado para la coordinación entre agentes y usuarios +- **Salas de chat (experimental)** — Chat grupal con alcance de proyecto donde los miembros mencionados se enrutan como respondedores directos y miembros ambientales adicionales pueden responder hasta un límite (habilitar en **Configuración → Funciones experimentales → Salas de chat**; detalles en [Guía del panel → Salas de chat](./docs/dashboard-guide.md#chat-rooms)) + +### Autenticación de proveedores + +Fusion soporta autenticación basada en OAuth para proveedores de IA configurados en **Configuración → Autenticación**. Para la mayoría de los proveedores OAuth, cuando se accede al panel desde un host que no es localhost (nodo remoto, host/IP de LAN o proxy inverso), las URLs de inicio de sesión del proveedor se reescriben para enrutar los callbacks de OAuth a través de un endpoint puente (`/api/auth/oauth-callback`) de modo que las redirecciones lleguen a la sesión de navegador activa. + +- **Anthropic (Claude)** — Usa un flujo de código de autorización pegado en Configuración/incorporación: inicia sesión y pega la URL de redirección final (o el código) de vuelta en Fusion para completar el inicio de sesión +- **OpenAI Codex** — Usa el mismo flujo de código de autorización pegado con validación segura de estado +- **Factory AI — mediante Droid CLI** *(opcional)* — requiere instalación local de Droid CLI + `droid auth login`; la detección sigue la ruta efectiva del binario en tiempo de ejecución (predeterminado `droid`, o `droidBinaryPath` del plugin cuando está configurado), luego habilita en **Configuración → Autenticación** y reinicia Fusion +- **llama.cpp — mediante servidor HTTP** *(opcional)* — configura la URL de tu servidor llama.cpp (predeterminado `http://127.0.0.1:8080`) y la clave API opcional, luego habilita en **Configuración → Autenticación** +- **Otros proveedores** — Autentícate mediante entrada de clave API en Configuración (incluidas la clave API de Google/Gemini, Google Generative AI, Vertex y los alias de Cloud Code) + +### Sistema de modelos + +Fusion usa una jerarquía de modelos de doble alcance con cinco canales independientes. La configuración global define los valores predeterminados de referencia; la configuración de proyecto proporciona sobreescrituras por proyecto. + +| Canal | Propósito | Claves de referencia global | Claves de sobreescritura por proyecto | +|------|---------|---------------------|----------------------| +| Executor | Agente de ejecución de tareas | `executionGlobalProvider` + `executionGlobalModelId` | `executionProvider` + `executionModelId` | +| Planning | Agente de planificación de tareas | `planningGlobalProvider` + `planningGlobalModelId` | `planningProvider` + `planningModelId` | +| Validator | Revisor de plan/código | `validatorGlobalProvider` + `validatorGlobalModelId` | `validatorProvider` + `validatorModelId` | +| Title Summarization | Generación automática de títulos | `titleSummarizerGlobalProvider` + `titleSummarizerGlobalModelId` | `titleSummarizerProvider` + `titleSummarizerModelId` | +| Workflow Step Refinement | Refinamiento de prompts con IA | (usa `defaultProvider`/`defaultModelId`) | (usa `modelProvider`/`modelId` en WorkflowStep) | + +**Sobreescrituras por tarea:** Las tareas pueden sobreescribir los canales de executor, validator y planning con campos de modelo por tarea (`modelProvider`/`modelId`, `validatorModelProvider`/`validatorModelId`, `planningModelProvider`/`planningModelId`). + +**Precedencia:** Por tarea → Sobreescritura de proyecto → Canal global → `defaultProvider`/`defaultModelId` → Resolución automática. + +Para la documentación completa de configuración, consulta la [Referencia de configuración](./docs/settings-reference.md). + +### Tareas programadas / automatizaciones + +Fusion soporta automatización de tareas programadas a través de los endpoints `/api/automations`. Las automatizaciones pueden ejecutar comandos de shell o flujos de trabajo de múltiples pasos en un horario configurable. + +#### Alcance de la programación + +Las automatizaciones y rutinas pueden ejecutarse en dos alcances: + +- **Global** — Se ejecuta en todos los proyectos. Úsalo para mantenimiento entre proyectos, copias de seguridad o reportes unificados. +- **Proyecto** — Se ejecuta solo dentro de un proyecto específico. Úsalo para CI, pruebas o tareas de despliegue específicas del proyecto. + +Cuando creas una programación sin elegir un alcance, Fusion usa por defecto el **alcance de proyecto** con el ID de proyecto `default` por compatibilidad con versiones anteriores. + +Para especificar un alcance de forma explícita: +- En el modal de **Tareas programadas** del panel, usa el selector **Global / Proyecto**. +- Mediante la API, pasa `?scope=global` o `?scope=project&projectId=` en los endpoints de automatización/rutina. + +**Reglas de resolución de alcance:** +- `scope=global` siempre se resuelve en el canal de automatización/rutina global, independientemente del proyecto activo. +- `scope=project` requiere un `projectId`. Si se omite, vuelve a `"default"`. +- Las operaciones de CRUD, ejecución, activación/desactivación y webhook están estrictamente aisladas por alcance: una programación global no puede ser modificada desde una solicitud de alcance de proyecto, y viceversa. + +**Orientación operativa para configuraciones multiproyecto:** +- Prefiere programaciones **globales** para infraestructura compartida (p. ej., copias de seguridad nocturnas, extracción de información de memoria). +- Prefiere programaciones de **proyecto** para automatización por repositorio (p. ej., ejecutores de pruebas por proyecto, hooks de despliegue). +- Los canales global y de proyecto son sondeados de forma independiente por el motor, por lo que las ejecuciones pendientes en un canal no bloquean al otro. + +#### Automatizaciones + +| Endpoint | Método | Descripción | +|---------|--------|-------------| +| `/api/automations` | GET | Listar todas las automatizaciones (filtradas por alcance si se especifica) | +| `/api/automations` | POST | Crear automatización (el alcance predeterminado es `project`) | +| `/api/automations/:id` | GET | Obtener automatización por ID | +| `/api/automations/:id` | PATCH | Actualizar automatización | +| `/api/automations/:id` | DELETE | Eliminar automatización | +| `/api/automations/:id/run` | POST | Activar ejecución manual | +| `/api/automations/:id/toggle` | POST | Activar/desactivar | +| `/api/automations/:id/steps/reorder` | POST | Reordenar pasos de la automatización | + +#### Rutinas + +Las rutinas son tareas de agente de IA activadas por programaciones cron, webhooks o ejecución manual. Las rutinas comparten el mismo modelo de alcance global/proyecto que las automatizaciones. + +| Endpoint | Método | Descripción | +|---------|--------|-------------| +| `/api/routines` | GET | Listar todas las rutinas (filtradas por alcance si se especifica) | +| `/api/routines` | POST | Crear rutina (el alcance predeterminado es `project`) | +| `/api/routines/:id` | GET | Obtener rutina por ID | +| `/api/routines/:id` | PATCH | Actualizar rutina | +| `/api/routines/:id` | DELETE | Eliminar rutina | +| `/api/routines/:id/run` | POST | Activar manualmente | +| `/api/routines/:id/trigger` | POST | Activación manual canónica | +| `/api/routines/:id/runs` | GET | Obtener historial de ejecuciones | +| `/api/routines/:id/webhook` | POST | Activación por webhook (verificación de firma compatible) | + +--- + +## Ejemplos rápidos de CLI + +```bash +fn task create "Fix the login bug" # Entrada rápida → planificación +fn task plan "Build auth system" # Planificación guiada por IA +fn task import owner/repo --labels bug # Importar issues de GitHub +fn task show FN-001 # Ver detalles de la tarea +fn task logs FN-001 --follow # Transmitir registros de ejecución +fn task steer FN-001 "Use TypeScript" # Guiar al agente durante la ejecución + +fn project add my-app /path/to/app # Registrar un proyecto +fn project list # Listar todos los proyectos + +fn settings set maxConcurrent 4 # Configurar ajustes +fn settings export # Exportar configuración + +fn mission create "Auth System" "Build auth" # Crear misión +fn mission activate-slice # Activar un slice + +fn skills search react # Buscar en skills.sh +fn skills install firebase/agent-skills # Instalar habilidades de agente +``` + +--- + +## Paquetes + +| Paquete | Descripción | +|---------|-------------| +| `@fusion/core` | Modelo de dominio — tareas, columnas del tablero, almacén SQLite | +| `@fusion/dashboard` | Interfaz web — servidor Express + tablero kanban con SSE | +| `@fusion/engine` | Motor de IA — planificación, ejecución, programación, pasos del flujo | +| `@runfusion/fusion` | CLI + extensión — publicado en npm | + +--- + +## Desarrollo + +```bash +pnpm install # Instalar dependencias +pnpm local # Iniciar panel/API local en un puerto distinto al 4040 +pnpm local -- --engine # Iniciar panel local con el motor de IA +pnpm build # Compilar paquetes del espacio de trabajo predeterminado (excluye escritorio/móvil) +pnpm build:all # Compilar todos los paquetes (incluyendo escritorio/móvil) +pnpm dev dashboard # Ejecutar panel + motor de IA +pnpm dev:ui # Solo el panel (sin motor de IA) +pnpm lint # Verificar estilo de código en todos los paquetes +pnpm typecheck # Verificar tipos en todos los paquetes +pnpm test # Ejecutar todas las pruebas +``` + +### Compilar un ejecutable independiente + +Compila un binario `fn` autocontenido usando [Bun](https://bun.sh/): + +```bash +pnpm build:exe # Compilar para la plataforma actual +pnpm build:exe:all # Compilación cruzada para todas las plataformas +``` + +--- + +## Licencia + +MIT — código abierto, sin dependencia de proveedor. Ver [LICENSE](./LICENSE). + +
+ +**[runfusion.ai →](https://runfusion.ai)** + +
diff --git a/README.fr.md b/README.fr.md new file mode 100644 index 0000000000..ed18bbd973 --- /dev/null +++ b/README.fr.md @@ -0,0 +1,469 @@ +
+ +Fusion + +# Fusion + +### De l'idée brute au code de production — automatiquement. + +**Orchestrateur d'agents multi-nœuds** — tâches, agents, missions, git, fichiers et worktrees, avec n'importe quel modèle, local ou cloud. + +[**runfusion.ai →**](https://runfusion.ai) · [Docs](./docs/README.md) · [GitHub](https://github.com/Runfusion/Fusion) · [npm](https://www.npmjs.com/package/@runfusion/fusion) · [Discord](https://discord.gg/ksrfuy7WYR) + +[English](./README.md) · [简体中文](./README.zh-CN.md) · [繁體中文](./README.zh-TW.md) · **Français** · [Español](./README.es.md) · [한국어](./README.ko.md) + +*Traduction automatique — le README anglais fait foi.* + +[![License: MIT](https://img.shields.io/badge/license-MIT-3fb950.svg)](./LICENSE) +[![npm](https://img.shields.io/npm/v/@runfusion/fusion.svg?color=58a6ff)](https://www.npmjs.com/package/@runfusion/fusion) +[![Discord](https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white)](https://discord.gg/ksrfuy7WYR) +![Status](https://img.shields.io/badge/status-early%20preview-d29922.svg) +![Shipping](https://img.shields.io/badge/shipping-weekly-bc8cff.svg) + +
+ +Démo Fusion : de l'idée brute au code de production + +
+
+ + + Tableau de bord Fusion : colonnes kanban Planification, À faire, En cours, En révision, Terminé avec des cartes de tâches actives + + +
+ +--- + +## Tout votre environnement de développement. Sur un seul écran. + +Décrivez une tâche en langage naturel. Un agent de planification lit votre projet, comprend le contexte et rédige un plan `PROMPT.md` complet — étapes, périmètre des fichiers, critères d'acceptation. Fusion planifie ensuite, révise, exécute et révise à nouveau, dans un worktree git isolé, avec une validation humaine où vous le souhaitez. + +Un tableau. Contrôlé de n'importe où. Laptop, Mac mini, serveur Linux, VM cloud, téléphone — tous connectés. + +> Comme Trello, mais vos tâches sont spécifiées, exécutées et livrées par l'IA. Construit sur l'excellent travail de [dustinbyrne/kb](https://github.com/dustinbyrne/kb). + +--- + +## Le flux + +``` + ① Décrire ② Planification ③ Le tableau ④ Worktree isolé + ───────────── ───────────── ───────────── ───────────────────── + "Ajouter un → L'agent rédige → Plan → Révision → → branche fusion/FN-123 + bouton mode PROMPT.md Exécution → Révision concurrent, zéro + sombre dans le (étapes, périmètre, (par étape, jusqu'à conflit de fichiers + panneau réglages" acceptation) la fin) +``` + +### Voir chaque étape avant la fusion + +
+ Détail d'une tâche Fusion : étapes du workflow visibles sur une tâche en cours avec diffs et modifications de fichiers +
+ +Chaque tâche affiche son plan, ses révisions, ses diffs et ses modifications de fichiers en temps réel. Intervenez sur une tâche active pour réorienter, affiner les contraintes, mettre en pause ou reformuler. + +--- + +## Ce qui la différencie + +| | | +|---|---| +| 🧠 **Planification IA** | Décrivez une tâche en langage naturel. Les agents de planification la transforment en plan `PROMPT.md` avec étapes, périmètre des fichiers et critères d'acceptation. | +| 🔁 **Portes de workflow** | Plan → Révision → Exécution → Révision à chaque étape. Les portes pré-fusion bloquent le mauvais code ; les portes post-fusion effectuent des vérifications informatives. | +| 🌳 **Isolation par worktree** | Chaque tâche s'exécute dans sa propre branche et son propre worktree (`fusion/{task-id}`). Tâches parallèles. Zéro conflit. Délégation [worktrunk](https://github.com/max-sixty/worktrunk) optionnelle via [`worktrunk.enabled`](./docs/settings-reference.md#worktree-backend-settings) (voir [abstraction WorktreeBackend](./docs/architecture.md#worktreebackend-abstraction)). | +| ⚡ **Fusion intelligente** | Toutes les portes franchies ? Fusion effectue un squash-merge et passe à la suite. Activez la validation manuelle où vous le souhaitez. | +| 🛰️ **Maillage multi-nœuds** | Laptop, Mac mini, serveur Linux, VM cloud, téléphone — tout synchronisé. Bureau, mobile, web. | +| 🧩 **N'importe quel modèle** | Anthropic, OpenAI, Ollama et plus encore. Local et cloud coexistent. | +| 🏢 **Entreprises d'agents** | Importez des équipes prédéfinies — plus de 440 agents répartis dans 16 entreprises — et faites-les fonctionner de façon autonome pendant des semaines. | +| 📬 **Messagerie inter-agents** | Boîte aux lettres intégrée entre agents. Déléguer, clarifier, coordonner. | +| 🗨️ **Salles de discussion multi-agents** | Conversations de groupe à portée de projet où plusieurs membres peuvent répondre : les membres mentionnés sont des répondants directs, et des membres ambiants supplémentaires peuvent répondre jusqu'à un certain plafond. Actuellement **expérimental** — activez `chatRooms` dans **Paramètres → Fonctionnalités expérimentales → Salles de discussion**. ([Documentation des salles de discussion](./docs/dashboard-guide.md#chat-rooms)) | +| 🗺️ **Missions** | Planification hiérarchique (Mission → Jalon → Tranche → Fonctionnalité → Tâche) avec pilotage automatique et contrats de validation. | +| 🔬 **Recherche** | Exécutions de recherche délimitées avec recherche web, GitHub, docs locaux et synthèse LLM (plus prise en charge intégrée de WebSearch/WebFetch dans les flux de planification et de synthèse lorsque disponible). Transformez les résultats en tâches. ([Docs](./docs/research.md)) | +| 🧪 **Auto-amélioration** | Les agents réfléchissent à leurs propres résultats et mettent à jour leurs prompts au fur et à mesure qu'ils apprennent votre base de code. | +| 🔓 **Open source. MIT.** | Pas d'enfermement propriétaire. Faites-le tourner sur votre propre matériel. Livraisons hebdomadaires. | + +--- + +## Comment ça fonctionne + +```mermaid +graph TD + H((Vous)) -->|idée brute| T["Planification
planification automatique"] + T --> TD["À faire
programmé pour l'exécution"] + TD --> IP["En cours
pour chaque étape :
plan, révision, exécution, révision
"] + + subgraph IP["En cours"] + direction TD + NS([Commencer l'étape]) --> P[Plan] + P --> R1{Révision} + R1 -->|réviser| P + R1 -->|approuver| E[Exécuter] + E --> R2{Révision} + R2 -->|réviser| E + R2 -->|étape suivante| NS + R2 -->|repenser| P + end + + R2 -->|terminé| IR["En révision
prêt à fusionner,
ou auto-complétion
"] + IR -->|squash merge direct
ou PR fusionnée| D["Terminé"] + + style H fill:#161b22,stroke:#8b949e,color:#e6edf3 + style T fill:#2d2006,stroke:#d29922,color:#d29922 + style TD fill:#0d2044,stroke:#58a6ff,color:#58a6ff + style IP fill:#1a0d2e,stroke:#bc8cff,color:#bc8cff + style P fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style R1 fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style E fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style R2 fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style NS fill:#1a0d2e,stroke:#bc8cff,color:#bc8cff + style IR fill:#0d2d16,stroke:#3fb950,color:#3fb950 + style D fill:#1a1a1a,stroke:#8b949e,color:#8b949e +``` + +Les tâches avec dépendances sont traitées séquentiellement. Les tâches indépendantes s'exécutent en parallèle. Vous pouvez exiger une validation manuelle avant que les tâches passent de Planification à À faire (paramètre `requirePlanApproval`). + +--- + +## Multi-nœuds. Un tableau. Toutes les plateformes. + +
+ +Maillage Fusion : laptop, Mac mini, serveur Linux, VM cloud, téléphone — tous synchronisés + +
+ +![macOS](https://img.shields.io/badge/macOS-000000?style=for-the-badge&logo=apple&logoColor=white) +![Windows](https://img.shields.io/badge/Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white) +![Linux](https://img.shields.io/badge/Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black) +![Web](https://img.shields.io/badge/Web-4285F4?style=for-the-badge&logo=googlechrome&logoColor=white) +![iOS](https://img.shields.io/badge/iOS-000000?style=for-the-badge&logo=apple&logoColor=white) +![Android](https://img.shields.io/badge/Android-3DDC84?style=for-the-badge&logo=android&logoColor=white) + +
+ +Laptop, Mac mini, serveur Linux, VM cloud, téléphone — chaque nœud est un pair. L'état de vos tâches, vos agents, vos journaux et vos diffs restent synchronisés sur tout le maillage. Le même Fusion est livré sous forme de : + +- 🖥️ **Application de bureau** — Electron pour **macOS** (Intel + Apple Silicon), **Windows** 10/11 et **Linux** +- 📱 **Application mobile** — Capacitor pour **iOS/iPadOS** et **Android** ([MOBILE.md](./MOBILE.md)) +- 🌐 **Tableau de bord web** — tout navigateur moderne, servi par le démon `fn dashboard` +- 🔌 **CLI** — binaire `fn` + extension pour les workflows orientés terminal + +Démarrez le démon sur n'importe quel nœud, connectez vos autres appareils, et le tableau vous suit partout. + +--- + +## Faire tourner une entreprise d'agents + +
+ +Entreprise d'agents Fusion : importer une équipe, la faire tourner de façon autonome pendant des semaines + +
+ +Importez une équipe. Faites-la tourner de façon autonome pendant des semaines. **Plus de 440 agents répartis dans 16 entreprises**, câblés pour les missions, les boîtes aux lettres et la délégation inter-agents. + +```bash +npx companies.sh add paperclipai/companies/gstack +``` + +--- + +## Compatible avec les outils que vous utilisez déjà. + +Fusion s'intègre avec les outils que vous aimez. **Hermes**, **Paperclip** et **OpenClaw** sont tous livrés comme plugins de première classe — routez n'importe quel espace de travail vers le runtime qui convient à la tâche. Et n'importe quelle entreprise d'agents Paperclip s'importe en une seule commande. + +
+ Hermes +
+ +### [Hermes](https://hermes-agent.nousresearch.com) `experimental` + +Nous Research + +L'agent autonome open source de **Nous Research**. Installez le plugin Hermes et exécutez des agents via Hermes pour les travaux de longue durée à contexte croissant — routez n'importe quel espace de travail Fusion vers lui. + +### OpenClaw `experimental` + +La prise en charge du runtime OpenClaw est disponible sous forme de plugin expérimental (`fusion-plugin-openclaw-runtime`) pour la parité de découverte/configuration du runtime. Configurez les agents avec `runtimeConfig.runtimeHint: "openclaw"` après installation du plugin. + +
+ +
+ Paperclip +
+ +### [Paperclip](https://paperclip.ing) `experimental` + +paperclip.ing + +Le plan de contrôle humain pour le travail IA. Installez le plugin Paperclip pour exécuter des agents via Paperclip dans Fusion. + +Fusion prend également en charge nativement le standard d'entreprises d'agents **[`companies.sh`](https://github.com/paperclipai/companies)** : importez une équipe prédéfinie — **plus de 440 agents répartis dans 16 entreprises** — et laissez-les se coordonner via la boîte aux lettres, les missions et les portes de workflow de Fusion pendant des semaines de travail autonome. Même format d'entreprise, mêmes agents, mêmes compétences que Paperclip. + +```bash +npx companies.sh add paperclipai/companies/gstack +``` + +
+ +> **Hermes**, **Paperclip** et **OpenClaw** sont des plugins de runtime **expérimentaux** — les API et les formats de communication peuvent évoluer entre les versions mineures. + +--- + +## Démarrage rapide + +**Sans installation, directement depuis npm :** + +```bash +npx runfusion.ai +``` + +Cela lance le tableau de bord. Les sous-commandes passent directement : `npx runfusion.ai task create "fix X"`, `npx runfusion.ai --help`, etc. (Ou de façon verbeuse : `npx @runfusion/fusion dashboard`.) + +**Installateur en une ligne** (macOS et Linux — choisit automatiquement Homebrew, bascule sur npm en secours) : + +```bash +curl -fsSL https://runfusion.ai/install.sh | sh +fusion dashboard +``` + +**Homebrew** (macOS et Linux) : + +```bash +brew tap runfusion/fusion +brew install fusion +fusion dashboard # ou : fn dashboard +``` + +Ou en une ligne (tap automatique) : `brew install runfusion/fusion/fusion`. + +**npm global** : + +```bash +npm install -g @runfusion/fusion +fn dashboard # ou : fusion dashboard +``` + +**Depuis un clone** (pour le développement) : + +```bash +pnpm dev dashboard +``` + +Cliquez ensuite sur l'URL `Open:` affichée dans le terminal. Elle intègre un jeton bearer +(`http://localhost:4040/?token=fn_...`) que le navigateur capture dans +`localStorage` à la première visite et réutilise automatiquement par la suite. Côté +serveur, Fusion persiste désormais le jeton du tableau de bord/démon dans +`~/.fusion/settings.json` à la première exécution authentifiée et le réutilise +lors des démarrages ultérieurs, sauf si vous le remplacez (`--token`, +`FUSION_DASHBOARD_TOKEN`, `FUSION_DAEMON_TOKEN`) ou désactivez l'authentification +avec `--no-auth`. Voir +[Référence CLI → fn dashboard → Authentification](./docs/cli-reference.md#fn-dashboard) +pour la précédence complète et les options de réinitialisation/révocation. + +### Configuration au premier lancement + +Au premier lancement, Fusion ouvre l'**assistant d'intégration** en trois étapes guidées : + +1. **Configuration IA** — Utilisez la liste simplifiée de fournisseurs de démarrage rapide (fournisseurs recommandés et fournisseurs déjà connectés), puis développez les **Paramètres avancés du fournisseur** uniquement si vous avez besoin de fournisseurs supplémentaires ou de détails de configuration. Un seul fournisseur suffit pour commencer. Les entrées de fournisseurs dépréciés Google Gemini CLI / Antigravity sont intentionnellement masquées ; les chemins clé API Google/Gemini, Google Generative AI, Vertex et Cloud Code restent pris en charge. +2. **GitHub (optionnel)** — Connectez GitHub pour l'import de tickets et la gestion des PR +3. **Première tâche** — Créez votre première tâche ou importez depuis GitHub (si aucun projet n'est actif, l'assistant vous invite d'abord à enregistrer/sélectionner un répertoire de projet) + +L'assistant est **dismissable et non bloquant** — cliquez sur **Ignorer pour l'instant** pour utiliser le tableau de bord immédiatement. Relancez-le plus tard depuis **Paramètres → Authentification → Rouvrir le guide d'intégration**. + +### Mobile + +Pour le workflow Capacitor + PWA, voir [MOBILE.md](./MOBILE.md). + +--- + +## Documentation + +| Guide | Ce qu'il couvre | +|---|---| +| [Premiers pas](./docs/getting-started.md) | Installation et intégration | +| [Guide du tableau de bord](./docs/dashboard-guide.md) | Vues tableau/liste, terminal, gestionnaire git | +| [Gestion des tâches](./docs/task-management.md) | Cycle de vie des tâches et commandes CLI | +| [Référence CLI](./docs/cli-reference.md) | Référence complète des commandes et du démon | +| [Référence des paramètres](./docs/settings-reference.md) | Options de configuration | +| [Architecture](./docs/architecture.md) | Internals du système | +| [Agents](./docs/agents.md) | Gestion des agents, instanciation, heartbeat | +| [Étapes de workflow](./docs/workflow-steps.md) | Portes de qualité, modèles, phases | +| [Missions](./docs/missions.md) | Hiérarchie de missions, planification, pilotage automatique | +| [Multi-projet](./docs/multi-project.md) | Registre central, modes d'isolation | +| [Docker](./docs/docker.md) | Déploiement en conteneur | + +--- + +## Fonctionnalités principales + +- **Planification IA** — L'agent de planification génère un `PROMPT.md` détaillé avec étapes, périmètre des fichiers et critères d'acceptation +- **Exécution pas à pas** — Cycle Plan → Révision → Exécution → Révision pour chaque étape de tâche +- **Isolation par worktree git** — Chaque tâche s'exécute dans son propre worktree (branche `fusion/{task-id}`) +- **Étapes de workflow** — Portes de qualité configurables (pré-fusion : bloque la fusion ; post-fusion : informatif) +- **Intégration GitHub** — Import de tickets, création de PR, badges PR/ticket en temps réel +- **Tableau de bord** — Tableau kanban en temps réel, gestion des agents, terminal, gestionnaire git, planificateur de missions +- **Missions** — Planification hiérarchique (Mission → Jalon → Tranche → Fonctionnalité → Tâche) avec pilotage automatique, contrats de validation, nouvelles tentatives sur correctifs/fonctionnalités et sémantique de transfert en cas de blocage +- **Multi-projet** — Gérez plusieurs projets depuis une installation unique avec isolation des projets +- **Messagerie inter-agents** — Messagerie intégrée pour la coordination entre agents et utilisateurs +- **Salles de discussion (Expérimental)** — Discussion de groupe à portée de projet où les membres mentionnés sont routés comme répondants directs et des membres ambiants supplémentaires peuvent répondre jusqu'à un certain plafond (activer via **Paramètres → Fonctionnalités expérimentales → Salles de discussion** ; détails dans [Guide du tableau de bord → Salles de discussion](./docs/dashboard-guide.md#chat-rooms)) + +### Authentification des fournisseurs + +Fusion prend en charge l'authentification OAuth pour les fournisseurs IA configurée via **Paramètres → Authentification**. Pour la plupart des fournisseurs OAuth, lorsque le tableau de bord est accédé via un hôte non-localhost (nœud distant, hôte/IP LAN ou proxy inverse), les URL de connexion du fournisseur sont réécrites pour router les callbacks OAuth via un endpoint bridge (`/api/auth/oauth-callback`) afin que les redirections atteignent la session navigateur active. + +- **Anthropic (Claude)** — Utilise un flux de code d'autorisation collé dans Paramètres/l'assistant : connectez-vous, puis collez l'URL de redirection finale (ou le code) dans Fusion pour terminer la connexion +- **OpenAI Codex** — Utilise le même flux de code d'autorisation collé avec validation d'état sécurisée +- **Factory AI — via Droid CLI** *(optionnel)* — nécessite une installation locale de Droid CLI + `droid auth login` ; la détection suit le chemin du binaire runtime effectif (par défaut `droid`, ou `droidBinaryPath` du plugin si configuré), puis activez dans **Paramètres → Authentification** et redémarrez Fusion +- **llama.cpp — via serveur HTTP** *(optionnel)* — configurez l'URL de votre serveur llama.cpp (par défaut `http://127.0.0.1:8080`) et la clé API optionnelle, puis activez dans **Paramètres → Authentification** +- **Autres fournisseurs** — Authentifiez via la saisie de clé API dans Paramètres (y compris clé API Google/Gemini, Google Generative AI, Vertex et alias Cloud Code) + +### Système de modèles + +Fusion utilise une hiérarchie de modèles à double portée avec cinq voies indépendantes. Les paramètres globaux définissent les valeurs par défaut de base ; les paramètres de projet fournissent des remplacements par projet. + +| Voie | Objectif | Clés globales de base | Clés de remplacement par projet | +|------|---------|---------------------|----------------------| +| Exécuteur | Agent d'exécution des tâches | `executionGlobalProvider` + `executionGlobalModelId` | `executionProvider` + `executionModelId` | +| Planification | Agent de planification des tâches | `planningGlobalProvider` + `planningGlobalModelId` | `planningProvider` + `planningModelId` | +| Validateur | Réviseur de plan/code | `validatorGlobalProvider` + `validatorGlobalModelId` | `validatorProvider` + `validatorModelId` | +| Résumé de titre | Génération automatique de titre | `titleSummarizerGlobalProvider` + `titleSummarizerGlobalModelId` | `titleSummarizerProvider` + `titleSummarizerModelId` | +| Raffinement des étapes de workflow | Raffinement de prompt IA | (utilise `defaultProvider`/`defaultModelId`) | (utilise `modelProvider`/`modelId` sur WorkflowStep) | + +**Remplacements par tâche :** Les tâches peuvent remplacer les voies exécuteur, validateur et planification avec des champs de modèle par tâche (`modelProvider`/`modelId`, `validatorModelProvider`/`validatorModelId`, `planningModelProvider`/`planningModelId`). + +**Précédence :** Par tâche → Remplacement projet → Voie globale → `defaultProvider`/`defaultModelId` → Résolution automatique. + +Pour la documentation complète des paramètres, voir la [Référence des paramètres](./docs/settings-reference.md). + +### Tâches planifiées / automatisations + +Fusion prend en charge l'automatisation de tâches planifiées via les endpoints `/api/automations`. Les automatisations peuvent exécuter des commandes shell ou des workflows multi-étapes selon un calendrier configurable. + +#### Portée de la planification + +Les automatisations et les routines peuvent s'exécuter dans deux portées : + +- **Globale** — S'exécute sur tous les projets. À utiliser pour la maintenance inter-projets, les sauvegardes ou les rapports unifiés. +- **Projet** — S'exécute uniquement dans un projet spécifique. À utiliser pour la CI, les tests ou les déploiements spécifiques au projet. + +Lorsque vous créez une planification sans choisir de portée, Fusion utilise par défaut la **portée projet** avec l'ID de projet `default` pour la compatibilité ascendante. + +Pour cibler explicitement une portée : +- Dans le modal **Tâches planifiées** du tableau de bord, utilisez le bouton **Global / Projet**. +- Via l'API, passez `?scope=global` ou `?scope=project&projectId=` sur les endpoints d'automatisation/routine. + +**Règles de résolution de portée :** +- `scope=global` se résout toujours vers la voie d'automatisation/routine globale, indépendamment du projet actif. +- `scope=project` nécessite un `projectId`. S'il est omis, il bascule sur `"default"`. +- Les opérations CRUD, exécution, bascule et webhook sont strictement isolées par portée : une planification globale ne peut pas être modifiée depuis une requête à portée projet, et vice versa. + +**Conseils opérationnels pour les configurations multi-projets :** +- Préférez les planifications **globales** pour l'infrastructure partagée (ex. : sauvegardes nocturnes, extraction de résumés mémorisés). +- Préférez les planifications **projet** pour l'automatisation par dépôt (ex. : lanceurs de tests par projet, hooks de déploiement). +- Les voies globale et projet sont interrogées indépendamment par le moteur, donc les exécutions dues dans une voie ne bloquent pas l'autre. + +#### Automatisations + +| Endpoint | Méthode | Description | +|---------|--------|-------------| +| `/api/automations` | GET | Lister toutes les automatisations (filtrées par portée si spécifiée) | +| `/api/automations` | POST | Créer une automatisation (portée par défaut : `project`) | +| `/api/automations/:id` | GET | Obtenir une automatisation par ID | +| `/api/automations/:id` | PATCH | Mettre à jour une automatisation | +| `/api/automations/:id` | DELETE | Supprimer une automatisation | +| `/api/automations/:id/run` | POST | Déclencher une exécution manuelle | +| `/api/automations/:id/toggle` | POST | Activer/désactiver | +| `/api/automations/:id/steps/reorder` | POST | Réordonner les étapes d'automatisation | + +#### Routines + +Les routines sont des tâches d'agents IA déclenchées par des planifications cron, des webhooks ou une exécution manuelle. Les routines partagent le même modèle de portée global/projet que les automatisations. + +| Endpoint | Méthode | Description | +|---------|--------|-------------| +| `/api/routines` | GET | Lister toutes les routines (filtrées par portée si spécifiée) | +| `/api/routines` | POST | Créer une routine (portée par défaut : `project`) | +| `/api/routines/:id` | GET | Obtenir une routine par ID | +| `/api/routines/:id` | PATCH | Mettre à jour une routine | +| `/api/routines/:id` | DELETE | Supprimer une routine | +| `/api/routines/:id/run` | POST | Déclenchement manuel | +| `/api/routines/:id/trigger` | POST | Déclenchement manuel canonique | +| `/api/routines/:id/runs` | GET | Obtenir l'historique d'exécution | +| `/api/routines/:id/webhook` | POST | Déclenchement par webhook (vérification de signature prise en charge) | + +--- + +## Exemples CLI rapides + +```bash +fn task create "Fix the login bug" # Entrée rapide → planification +fn task plan "Build auth system" # Planification guidée par IA +fn task import owner/repo --labels bug # Importer des tickets GitHub +fn task show FN-001 # Voir les détails d'une tâche +fn task logs FN-001 --follow # Suivre les journaux d'exécution +fn task steer FN-001 "Use TypeScript" # Guider l'agent en cours d'exécution + +fn project add my-app /path/to/app # Enregistrer un projet +fn project list # Lister tous les projets + +fn settings set maxConcurrent 4 # Configurer les paramètres +fn settings export # Exporter la configuration + +fn mission create "Auth System" "Build auth" # Créer une mission +fn mission activate-slice # Activer une tranche + +fn skills search react # Rechercher dans skills.sh +fn skills install firebase/agent-skills # Installer des compétences d'agent +``` + +--- + +## Paquets + +| Paquet | Description | +|---------|-------------| +| `@fusion/core` | Modèle de domaine — tâches, colonnes du tableau, store SQLite | +| `@fusion/dashboard` | Interface web — serveur Express + tableau kanban avec SSE | +| `@fusion/engine` | Moteur IA — planification, exécution, ordonnancement, étapes de workflow | +| `@runfusion/fusion` | CLI + extension — publié sur npm | + +--- + +## Développement + +```bash +pnpm install # Installer les dépendances +pnpm local # Démarrer le tableau de bord/API local sur un port différent de 4040 +pnpm local -- --engine # Démarrer le tableau de bord local avec le moteur IA +pnpm build # Construire les paquets du workspace par défaut (exclut bureau/mobile) +pnpm build:all # Construire tous les paquets (y compris bureau/mobile) +pnpm dev dashboard # Exécuter le tableau de bord + le moteur IA +pnpm dev:ui # Tableau de bord seul (sans moteur IA) +pnpm lint # Linter tous les paquets +pnpm typecheck # Vérifier les types de tous les paquets +pnpm test # Exécuter tous les tests +``` + +### Construire un exécutable autonome + +Construisez un binaire `fn` autonome et auto-contenu avec [Bun](https://bun.sh/) : + +```bash +pnpm build:exe # Construire pour la plateforme actuelle +pnpm build:exe:all # Compilation croisée pour toutes les plateformes +``` + +--- + +## Licence + +MIT — open source, sans enfermement propriétaire. Voir [LICENSE](./LICENSE). + +
+ +**[runfusion.ai →](https://runfusion.ai)** + +
diff --git a/README.ko.md b/README.ko.md new file mode 100644 index 0000000000..beead4c0bc --- /dev/null +++ b/README.ko.md @@ -0,0 +1,468 @@ +
+ +Fusion + +# Fusion + +### 거친 아이디어에서 프로덕션 코드까지 — 자동으로. + +**멀티 노드 에이전트 오케스트레이터** — 태스크, 에이전트, 미션, git, 파일, 워크트리를 어떤 모델에서도, 로컬 또는 클라우드에서 실행합니다. + +[**runfusion.ai →**](https://runfusion.ai) · [문서](./docs/README.md) · [GitHub](https://github.com/Runfusion/Fusion) · [npm](https://www.npmjs.com/package/@runfusion/fusion) · [Discord](https://discord.gg/ksrfuy7WYR) + +[English](./README.md) · [简体中文](./README.zh-CN.md) · [繁體中文](./README.zh-TW.md) · [Français](./README.fr.md) · [Español](./README.es.md) · **한국어** + +*이 문서는 기계 번역본입니다. 공식 원본은 [영문 README](./README.md)를 참조하세요.* + +[![License: MIT](https://img.shields.io/badge/license-MIT-3fb950.svg)](./LICENSE) +[![npm](https://img.shields.io/npm/v/@runfusion/fusion.svg?color=58a6ff)](https://www.npmjs.com/package/@runfusion/fusion) +[![Discord](https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white)](https://discord.gg/ksrfuy7WYR) +![Status](https://img.shields.io/badge/status-early%20preview-d29922.svg) +![Shipping](https://img.shields.io/badge/shipping-weekly-bc8cff.svg) + +
+ +Fusion 릴: 거친 아이디어에서 프로덕션 코드까지 + +
+
+ + + Fusion 대시보드: Planning, Todo, In Progress, In Review, Done 칸반 컬럼과 활성 태스크 카드 + + +
+ +--- + +## 전체 개발 환경을 하나의 화면에서. + +평문으로 태스크를 설명하면, 계획 에이전트가 프로젝트를 읽고 컨텍스트를 파악한 뒤 단계, 파일 범위, 완료 기준이 담긴 `PROMPT.md` 계획서를 작성합니다. 이후 Fusion은 격리된 git 워크트리에서 계획, 검토, 실행, 재검토를 순서대로 수행하며, 원하는 곳마다 사람의 승인 단계를 추가할 수 있습니다. + +보드 하나로. 어디서든 제어. 노트북, Mac mini, Linux 서버, 클라우드 VM, 휴대폰 — 모두 연결됩니다. + +> Trello와 유사하지만, 태스크의 명세 작성, 실행, 납품을 AI가 수행합니다. [dustinbyrne/kb](https://github.com/dustinbyrne/kb)의 훌륭한 작업을 기반으로 구축되었습니다. + +--- + +## 흐름 + +``` + ① 설명 ② 계획 ③ 보드 ④ 격리된 워크트리 + ───────────── ───────────── ───────────── ───────────────────── + "설정 패널에 → 에이전트가 → 계획 → 검토 → → fusion/FN-123 브랜치 + 다크 모드 토글 PROMPT.md 작성 실행 → 검토 동시 실행, + 추가" (단계, 범위, (각 단계마다, 파일 충돌 없음 + 완료 기준) 완료까지) +``` + +### 머지 전에 모든 단계를 확인하세요 + +
+ Fusion 태스크 상세: 진행 중인 태스크의 워크플로우 단계, 차이점, 파일 변경 내역이 실시간으로 표시 +
+ +모든 태스크는 계획, 검토, 차이점, 파일 변경 내역을 실시간으로 보여줍니다. 진행 중인 태스크에 들어가 방향을 조정하거나, 제약을 강화하거나, 일시 정지하거나, 재프롬프트할 수 있습니다. + +--- + +## 차별점 + +| | | +|---|---| +| 🧠 **AI 계획** | 평문으로 태스크를 설명하면, 계획 에이전트가 단계, 파일 범위, 완료 기준이 포함된 `PROMPT.md` 계획서로 변환합니다. | +| 🔁 **워크플로우 게이트** | 모든 단계마다 계획 → 검토 → 실행 → 검토 주기를 거칩니다. 사전 머지 게이트는 불량 코드를 차단하고, 사후 머지 게이트는 정보성 검사를 실행합니다. | +| 🌳 **워크트리 격리** | 각 태스크는 자체 브랜치와 워크트리(`fusion/{task-id}`)에서 실행됩니다. 병렬 태스크. 충돌 없음. [`worktrunk.enabled`](./docs/settings-reference.md#worktree-backend-settings)를 통한 선택적 [worktrunk](https://github.com/max-sixty/worktrunk) 위임 지원([WorktreeBackend 추상화](./docs/architecture.md#worktreebackend-abstraction) 참조). | +| ⚡ **스마트 머지** | 모든 게이트 통과 시 Fusion이 스쿼시 머지하고 다음으로 넘어갑니다. 어디서든 수동 승인을 선택할 수 있습니다. | +| 🛰️ **멀티 노드 메시** | 노트북, Mac mini, Linux 서버, 클라우드 VM, 휴대폰 — 모두 동기화됩니다. 데스크톱, 모바일, 웹. | +| 🧩 **모든 모델** | Anthropic, OpenAI, Ollama 등 다양한 모델을 지원합니다. 로컬과 클라우드가 공존합니다. | +| 🏢 **에이전트 컴퍼니** | 사전 구축된 팀 — 16개 컴퍼니에 걸쳐 440개 이상의 에이전트 — 을 임포트하여 몇 주 동안 자율적으로 실행합니다. | +| 📬 **에이전트 간 메시징** | 에이전트 간 내장 메일박스. 위임, 확인, 조율이 가능합니다. | +| 🗨️ **멀티 에이전트 채팅 룸** | 여러 룸 구성원이 답할 수 있는 프로젝트 범위 그룹 대화: 언급된 구성원은 직접 응답자로, 추가 주변 구성원은 최대 한도까지 응답할 수 있습니다. 현재 **실험적** — **설정 → 실험적 기능 → 채팅 룸**에서 `chatRooms`를 활성화하세요. ([채팅 룸 문서](./docs/dashboard-guide.md#chat-rooms)) | +| 🗺️ **미션** | 계층적 계획(미션 → 마일스톤 → 슬라이스 → 기능 → 태스크), 자동 조종, 검증 계약 포함. | +| 🔬 **리서치** | 웹 검색, GitHub, 로컬 문서, LLM 합성을 활용한 경계 있는 리서치 실행(계획 및 합성 흐름에서 런타임 내장 WebSearch/WebFetch 지원 포함). 결과를 태스크로 전환합니다. ([문서](./docs/research.md)) | +| 🧪 **자기 개선** | 에이전트가 자신의 출력물을 돌아보고 코드베이스를 학습하면서 프롬프트를 업데이트합니다. | +| 🔓 **오픈 소스. MIT.** | 벤더 종속 없음. 자체 하드웨어에서 실행. 매주 배포. | + +--- + +## 작동 방식 + +```mermaid +graph TD + H((사용자)) -->|거친 아이디어| T["계획 중
자동 계획"] + T --> TD["할 일
실행 예약됨"] + TD --> IP["진행 중
각 단계마다:
계획, 검토, 실행, 검토
"] + + subgraph IP["진행 중"] + direction TD + NS([단계 시작]) --> P[계획] + P --> R1{검토} + R1 -->|수정| P + R1 -->|승인| E[실행] + E --> R2{검토} + R2 -->|수정| E + R2 -->|다음 단계| NS + R2 -->|재검토| P + end + + R2 -->|완료| IR["검토 중
머지 준비,
또는 자동 완료
"] + IR -->|직접 스쿼시 머지
또는 PR 머지| D["완료"] + + style H fill:#161b22,stroke:#8b949e,color:#e6edf3 + style T fill:#2d2006,stroke:#d29922,color:#d29922 + style TD fill:#0d2044,stroke:#58a6ff,color:#58a6ff + style IP fill:#1a0d2e,stroke:#bc8cff,color:#bc8cff + style P fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style R1 fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style E fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style R2 fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style NS fill:#1a0d2e,stroke:#bc8cff,color:#bc8cff + style IR fill:#0d2d16,stroke:#3fb950,color:#3fb950 + style D fill:#1a1a1a,stroke:#8b949e,color:#8b949e +``` + +의존성이 있는 태스크는 순차적으로 처리됩니다. 독립적인 태스크는 병렬로 실행됩니다. 태스크가 계획 단계에서 할 일로 이동하기 전에 수동 승인을 요구하도록 설정할 수 있습니다(`requirePlanApproval` 설정). + +--- + +## 멀티 노드. 하나의 보드. 모든 플랫폼. + +
+ +Fusion 메시: 노트북, Mac mini, Linux 서버, 클라우드 VM, 휴대폰 — 모두 동기화 + +
+ +![macOS](https://img.shields.io/badge/macOS-000000?style=for-the-badge&logo=apple&logoColor=white) +![Windows](https://img.shields.io/badge/Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white) +![Linux](https://img.shields.io/badge/Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black) +![Web](https://img.shields.io/badge/Web-4285F4?style=for-the-badge&logo=googlechrome&logoColor=white) +![iOS](https://img.shields.io/badge/iOS-000000?style=for-the-badge&logo=apple&logoColor=white) +![Android](https://img.shields.io/badge/Android-3DDC84?style=for-the-badge&logo=android&logoColor=white) + +
+ +노트북, Mac mini, Linux 서버, 클라우드 VM, 휴대폰 — 모든 노드가 동등한 피어입니다. 태스크 상태, 에이전트, 로그, 차이점이 메시 전반에 걸쳐 동기화된 상태로 유지됩니다. 동일한 Fusion이 다음과 같이 제공됩니다: + +- 🖥️ **데스크톱 앱** — **macOS**(Intel + Apple Silicon), **Windows** 10/11, **Linux**용 Electron +- 📱 **모바일 앱** — **iOS/iPadOS** 및 **Android**용 Capacitor ([MOBILE.md](./MOBILE.md)) +- 🌐 **웹 대시보드** — `fn dashboard` 데몬에서 제공되는 모든 최신 브라우저 +- 🔌 **CLI** — 터미널 중심 워크플로우를 위한 `fn` 바이너리 + 확장 + +임의의 노드에서 데몬을 시작하고 다른 기기를 연결하면, 보드가 어디서든 따라다닙니다. + +--- + +## 에이전트 컴퍼니 운영 + +
+ +Fusion 에이전트 컴퍼니: 팀을 임포트하여 몇 주 동안 자율적으로 운영 + +
+ +팀을 임포트하세요. 몇 주 동안 자율적으로 운영하세요. 미션, 메일박스, 에이전트 간 위임을 위해 연결된 **16개 컴퍼니에 걸쳐 440개 이상의 에이전트**. + +```bash +npx companies.sh add paperclipai/companies/gstack +``` + +--- + +## 이미 사용 중인 도구와 호환됩니다. + +Fusion은 여러분이 좋아하는 도구와 통합됩니다. **Hermes**, **Paperclip**, **OpenClaw**는 모두 일급 플러그인으로 제공되어 — 작업에 맞는 런타임으로 워크스페이스를 라우팅할 수 있습니다. 그리고 모든 Paperclip 에이전트 컴퍼니는 단일 명령으로 임포트됩니다. + +
+ Hermes +
+ +### [Hermes](https://hermes-agent.nousresearch.com) `experimental` + +Nous Research + +**Nous Research**의 오픈 소스 자율 에이전트. Hermes 플러그인을 설치하고 장시간 실행되는 컨텍스트가 증가하는 작업에 Hermes를 통해 에이전트를 실행하세요 — 임의의 Fusion 워크스페이스를 라우팅할 수 있습니다. + +### OpenClaw `experimental` + +OpenClaw 런타임 지원은 런타임 탐색/설정 동등성을 위한 실험적 플러그인(`fusion-plugin-openclaw-runtime`)으로 제공됩니다. 플러그인을 설치한 후 `runtimeConfig.runtimeHint: "openclaw"`로 에이전트를 설정하세요. + +
+ +
+ Paperclip +
+ +### [Paperclip](https://paperclip.ing) `experimental` + +paperclip.ing + +AI 노동을 위한 사람 제어 플레인. Paperclip 플러그인을 설치하여 Fusion 내에서 Paperclip을 통해 에이전트를 실행하세요. + +Fusion은 **[`companies.sh`](https://github.com/paperclipai/companies)** 에이전트 컴퍼니 표준을 네이티브로 지원합니다: 사전 구축된 팀 — **16개 컴퍼니에 걸쳐 440개 이상의 에이전트** — 을 임포트하고, 수 주 동안의 자율 작업을 위해 Fusion의 메일박스, 미션, 워크플로우 게이트를 통해 조율하게 하세요. Paperclip과 동일한 컴퍼니 형식, 동일한 에이전트, 동일한 스킬. + +```bash +npx companies.sh add paperclipai/companies/gstack +``` + +
+ +> **Hermes**, **Paperclip**, **OpenClaw**는 **실험적** 런타임 플러그인입니다 — API와 와이어 형식은 마이너 릴리스 사이에 변경될 수 있습니다. + +--- + +## 빠른 시작 + +**설치 없이 npm에서 바로:** + +```bash +npx runfusion.ai +``` + +이 명령은 대시보드를 실행합니다. 하위 명령은 다음과 같이 전달됩니다: `npx runfusion.ai task create "fix X"`, `npx runfusion.ai --help` 등. (또는 명시적으로: `npx @runfusion/fusion dashboard`.) + +**원라인 설치 프로그램** (macOS & Linux — Homebrew를 자동 선택하고, 없으면 npm으로 대체): + +```bash +curl -fsSL https://runfusion.ai/install.sh | sh +fusion dashboard +``` + +**Homebrew** (macOS & Linux): + +```bash +brew tap runfusion/fusion +brew install fusion +fusion dashboard # 또는: fn dashboard +``` + +또는 원라인(자동 탭 추가): `brew install runfusion/fusion/fusion`. + +**npm 전역 설치**: + +```bash +npm install -g @runfusion/fusion +fn dashboard # 또는: fusion dashboard +``` + +**클론으로 시작** (개발용): + +```bash +pnpm dev dashboard +``` + +터미널에 출력되는 `Open:` URL을 클릭하세요. URL에는 베어러 토큰 +(`http://localhost:4040/?token=fn_...`)이 포함되어 있으며, 브라우저가 첫 방문 시 +`localStorage`에 캡처하여 이후 자동으로 재사용합니다. 서버 측에서 Fusion은 +첫 번째 인증된 실행 시 `~/.fusion/settings.json`에 대시보드/데몬 토큰을 +저장하고, 이후 시작 시 재사용합니다(`--token`, `FUSION_DASHBOARD_TOKEN`, +`FUSION_DAEMON_TOKEN`으로 재정의하거나 `--no-auth`로 인증을 비활성화하지 않는 한). +전체 우선순위 및 재설정/취소 옵션은 +[CLI 참조 → fn dashboard → Authentication](./docs/cli-reference.md#fn-dashboard)을 +참조하세요. + +### 최초 실행 설정 + +Fusion을 처음 시작하면 세 단계로 안내하는 **온보딩 마법사**가 열립니다: + +1. **AI 설정** — 간소화된 빠른 시작 공급자 목록(권장 공급자 및 이미 연결된 공급자)을 사용하고, 추가 공급자나 설정 세부 사항이 필요한 경우에만 **고급 공급자 설정**을 펼칩니다. 시작하려면 공급자 하나만 있으면 됩니다. 더 이상 사용되지 않는 Google Gemini CLI / Antigravity 공급자 항목은 의도적으로 숨겨져 있으며, Google/Gemini API 키, Google Generative AI, Vertex, Cloud Code 경로는 계속 지원됩니다. +2. **GitHub (선택 사항)** — 이슈 임포트 및 PR 관리를 위해 GitHub 연결 +3. **첫 번째 태스크** — 첫 번째 태스크를 생성하거나 GitHub에서 임포트(활성 프로젝트가 없는 경우, 온보딩이 먼저 프로젝트 디렉터리 등록/선택을 안내합니다) + +마법사는 **해제 가능하며 비차단적** — **지금 건너뛰기**를 클릭하면 즉시 대시보드를 사용할 수 있습니다. 나중에 **설정 → 인증 → 온보딩 가이드 다시 열기**에서 재실행할 수 있습니다. + +### 모바일 + +Capacitor + PWA 워크플로우는 [MOBILE.md](./MOBILE.md)를 참조하세요. + +--- + +## 문서 + +| 가이드 | 내용 | +|---|---| +| [시작하기](./docs/getting-started.md) | 설치 및 온보딩 | +| [대시보드 가이드](./docs/dashboard-guide.md) | 보드/목록 뷰, 터미널, git 관리자 | +| [태스크 관리](./docs/task-management.md) | 태스크 수명 주기 및 CLI 명령 | +| [CLI 참조](./docs/cli-reference.md) | 전체 명령 및 데몬 참조 | +| [설정 참조](./docs/settings-reference.md) | 구성 옵션 | +| [아키텍처](./docs/architecture.md) | 시스템 내부 구조 | +| [에이전트](./docs/agents.md) | 에이전트 관리, 스폰, 하트비트 | +| [워크플로우 단계](./docs/workflow-steps.md) | 품질 게이트, 템플릿, 단계 | +| [미션](./docs/missions.md) | 미션 계층 구조, 계획, 자동 조종 | +| [멀티 프로젝트](./docs/multi-project.md) | 중앙 레지스트리, 격리 모드 | +| [Docker](./docs/docker.md) | 컨테이너 배포 | + +--- + +## 핵심 기능 + +- **AI 계획** — 계획 에이전트가 단계, 파일 범위, 완료 기준이 담긴 상세한 `PROMPT.md`를 생성합니다 +- **단계별 실행** — 각 태스크 단계마다 계획 → 검토 → 실행 → 검토 주기를 진행합니다 +- **Git 워크트리 격리** — 각 태스크는 자체 워크트리(`fusion/{task-id}` 브랜치)에서 실행됩니다 +- **워크플로우 단계** — 구성 가능한 품질 게이트(사전 머지: 머지 차단; 사후 머지: 정보 제공) +- **GitHub 연동** — 이슈 임포트, PR 생성, 실시간 PR/이슈 배지 +- **대시보드** — 실시간 칸반 보드, 에이전트 관리, 터미널, git 관리자, 미션 플래너 +- **미션** — 계층적 계획(미션 → 마일스톤 → 슬라이스 → 기능 → 태스크), 자동 조종, 검증 계약, 수정-기능 재시도, 차단 핸드오프 시맨틱 포함 +- **멀티 프로젝트** — 단일 설치에서 여러 프로젝트를 프로젝트 격리로 관리 +- **에이전트 간 메시징** — 에이전트와 사용자 간 조율을 위한 내장 메시징 +- **채팅 룸 (실험적)** — 언급된 구성원이 직접 응답자로 라우팅되고 추가 주변 구성원이 최대 한도까지 답할 수 있는 프로젝트 범위 그룹 채팅(**설정 → 실험적 기능 → 채팅 룸**에서 활성화; [대시보드 가이드 → 채팅 룸](./docs/dashboard-guide.md#chat-rooms)에서 자세히 확인) + +### 공급자 인증 + +Fusion은 **설정 → 인증**을 통해 구성된 AI 공급자의 OAuth 기반 인증을 지원합니다. 대부분의 OAuth 공급자의 경우, 대시보드가 비 localhost 호스트(원격 노드, LAN 호스트/IP, 또는 리버스 프록시)를 통해 접근될 때, 공급자 로그인 URL이 OAuth 콜백을 브리지 엔드포인트(`/api/auth/oauth-callback`)를 통해 라우팅하도록 재작성되어 리다이렉트가 활성 브라우저 세션에 도달합니다. + +- **Anthropic (Claude)** — 설정/온보딩에서 붙여넣기 인가 코드 흐름을 사용합니다: 로그인한 후 최종 리다이렉트 URL(또는 코드)을 Fusion에 붙여넣어 로그인을 완료합니다 +- **OpenAI Codex** — 안전한 상태 검증이 포함된 동일한 붙여넣기 인가 코드 흐름을 사용합니다 +- **Factory AI — Droid CLI 경유** *(선택 사항)* — 로컬 Droid CLI 설치 + `droid auth login` 필요; 탐지는 유효한 런타임 바이너리 경로를 따릅니다(기본값 `droid`, 또는 플러그인 설정 시 `droidBinaryPath`), 이후 **설정 → 인증**에서 활성화하고 Fusion을 재시작하세요 +- **llama.cpp — HTTP 서버 경유** *(선택 사항)* — llama.cpp 서버 URL(기본값 `http://127.0.0.1:8080`)과 선택적 API 키를 설정한 후 **설정 → 인증**에서 활성화하세요 +- **기타 공급자** — 설정에서 API 키 입력으로 인증합니다(Google/Gemini API 키, Google Generative AI, Vertex, Cloud Code 별칭 포함) + +### 모델 시스템 + +Fusion은 다섯 개의 독립적인 레인을 가진 이중 범위 모델 계층 구조를 사용합니다. 전역 설정은 기준 기본값을 정의하고, 프로젝트 설정은 프로젝트별 재정의를 제공합니다. + +| 레인 | 목적 | 전역 기준 키 | 프로젝트 재정의 키 | +|------|---------|---------------------|----------------------| +| Executor | 태스크 실행 에이전트 | `executionGlobalProvider` + `executionGlobalModelId` | `executionProvider` + `executionModelId` | +| Planning | 태스크 계획 에이전트 | `planningGlobalProvider` + `planningGlobalModelId` | `planningProvider` + `planningModelId` | +| Validator | 계획/코드 검토자 | `validatorGlobalProvider` + `validatorGlobalModelId` | `validatorProvider` + `validatorModelId` | +| Title Summarization | 자동 제목 생성 | `titleSummarizerGlobalProvider` + `titleSummarizerGlobalModelId` | `titleSummarizerProvider` + `titleSummarizerModelId` | +| Workflow Step Refinement | AI 프롬프트 개선 | (`defaultProvider`/`defaultModelId` 사용) | (WorkflowStep의 `modelProvider`/`modelId` 사용) | + +**태스크별 재정의:** 태스크는 태스크별 모델 필드(`modelProvider`/`modelId`, `validatorModelProvider`/`validatorModelId`, `planningModelProvider`/`planningModelId`)로 executor, validator, planning 레인을 재정의할 수 있습니다. + +**우선순위:** 태스크별 → 프로젝트 재정의 → 전역 레인 → `defaultProvider`/`defaultModelId` → 자동 해결. + +전체 설정 문서는 [설정 참조](./docs/settings-reference.md)를 참조하세요. + +### 예약된 태스크 / 자동화 + +Fusion은 `/api/automations` 엔드포인트를 통해 예약된 태스크 자동화를 지원합니다. 자동화는 구성 가능한 일정에 따라 셸 명령 또는 다단계 워크플로우를 실행할 수 있습니다. + +#### 스케줄링 범위 + +자동화와 루틴은 두 가지 범위에서 실행될 수 있습니다: + +- **전역** — 모든 프로젝트에 걸쳐 실행됩니다. 프로젝트 간 유지 관리, 백업, 또는 통합 보고에 사용하세요. +- **프로젝트** — 특정 프로젝트 내에서만 실행됩니다. 프로젝트별 CI, 테스트, 또는 배포 태스크에 사용하세요. + +범위를 선택하지 않고 일정을 생성하면, Fusion은 하위 호환성을 위해 `default` 프로젝트 ID로 **프로젝트 범위**를 기본값으로 사용합니다. + +범위를 명시적으로 지정하려면: +- 대시보드 **예약된 태스크** 모달에서 **전역 / 프로젝트** 토글을 사용하세요. +- API를 통해서는 자동화/루틴 엔드포인트에 `?scope=global` 또는 `?scope=project&projectId=`를 전달하세요. + +**범위 해결 규칙:** +- `scope=global`은 항상 활성 프로젝트와 독립적으로 전역 자동화/루틴 레인으로 해결됩니다. +- `scope=project`는 `projectId`를 필요로 합니다. 생략하면 `"default"`로 대체됩니다. +- CRUD, 실행, 토글, 웹훅 작업은 엄격하게 범위 격리됩니다: 전역 일정은 프로젝트 범위 요청에서 변경될 수 없고, 그 반대도 마찬가지입니다. + +**멀티 프로젝트 설정을 위한 운영 지침:** +- 공유 인프라(예: 야간 백업, 메모리 인사이트 추출)에는 **전역** 일정을 선호하세요. +- 저장소별 자동화(예: 프로젝트별 테스트 실행기, 배포 훅)에는 **프로젝트** 일정을 선호하세요. +- 전역 및 프로젝트 레인은 엔진에 의해 독립적으로 폴링되므로, 한 레인의 예정된 실행이 다른 레인을 차단하지 않습니다. + +#### 자동화 + +| 엔드포인트 | 메서드 | 설명 | +|---------|--------|-------------| +| `/api/automations` | GET | 모든 자동화 목록 조회 (범위가 지정된 경우 필터링됨) | +| `/api/automations` | POST | 자동화 생성 (범위 기본값: `project`) | +| `/api/automations/:id` | GET | ID로 자동화 조회 | +| `/api/automations/:id` | PATCH | 자동화 업데이트 | +| `/api/automations/:id` | DELETE | 자동화 삭제 | +| `/api/automations/:id/run` | POST | 수동 실행 트리거 | +| `/api/automations/:id/toggle` | POST | 활성화/비활성화 토글 | +| `/api/automations/:id/steps/reorder` | POST | 자동화 단계 순서 변경 | + +#### 루틴 + +루틴은 크론 일정, 웹훅, 또는 수동 실행으로 트리거되는 AI 에이전트 태스크입니다. 루틴은 자동화와 동일한 전역/프로젝트 범위 모델을 공유합니다. + +| 엔드포인트 | 메서드 | 설명 | +|---------|--------|-------------| +| `/api/routines` | GET | 모든 루틴 목록 조회 (범위가 지정된 경우 필터링됨) | +| `/api/routines` | POST | 루틴 생성 (범위 기본값: `project`) | +| `/api/routines/:id` | GET | ID로 루틴 조회 | +| `/api/routines/:id` | PATCH | 루틴 업데이트 | +| `/api/routines/:id` | DELETE | 루틴 삭제 | +| `/api/routines/:id/run` | POST | 수동 트리거 | +| `/api/routines/:id/trigger` | POST | 정식 수동 트리거 | +| `/api/routines/:id/runs` | GET | 실행 기록 조회 | +| `/api/routines/:id/webhook` | POST | 웹훅 트리거 (서명 검증 지원) | + +--- + +## CLI 빠른 예제 + +```bash +fn task create "Fix the login bug" # 빠른 입력 → 계획 단계 +fn task plan "Build auth system" # AI 안내 계획 수립 +fn task import owner/repo --labels bug # GitHub 이슈 임포트 +fn task show FN-001 # 태스크 세부 정보 보기 +fn task logs FN-001 --follow # 실행 로그 스트리밍 +fn task steer FN-001 "Use TypeScript" # 실행 중 에이전트 방향 안내 + +fn project add my-app /path/to/app # 프로젝트 등록 +fn project list # 모든 프로젝트 목록 + +fn settings set maxConcurrent 4 # 설정 구성 +fn settings export # 설정 내보내기 + +fn mission create "Auth System" "Build auth" # 미션 생성 +fn mission activate-slice # 슬라이스 활성화 + +fn skills search react # skills.sh 검색 +fn skills install firebase/agent-skills # 에이전트 스킬 설치 +``` + +--- + +## 패키지 + +| 패키지 | 설명 | +|---------|-------------| +| `@fusion/core` | 도메인 모델 — 태스크, 보드 컬럼, SQLite 저장소 | +| `@fusion/dashboard` | 웹 UI — Express 서버 + SSE가 포함된 칸반 보드 | +| `@fusion/engine` | AI 엔진 — 계획, 실행, 스케줄링, 워크플로우 단계 | +| `@runfusion/fusion` | CLI + 확장 — npm에 게시됨 | + +--- + +## 개발 + +```bash +pnpm install # 의존성 설치 +pnpm local # 비 4040 포트에서 로컬 대시보드/API 시작 +pnpm local -- --engine # AI 엔진과 함께 로컬 대시보드 시작 +pnpm build # 기본 워크스페이스 패키지 빌드 (데스크톱/모바일 제외) +pnpm build:all # 모든 패키지 빌드 (데스크톱/모바일 포함) +pnpm dev dashboard # 대시보드 + AI 엔진 실행 +pnpm dev:ui # 대시보드만 실행 (AI 엔진 없음) +pnpm lint # 모든 패키지 린트 +pnpm typecheck # 모든 패키지 타입 검사 +pnpm test # 모든 테스트 실행 +``` + +### 독립 실행 파일 빌드 + +[Bun](https://bun.sh/)을 사용하여 단일 자급자족 `fn` 바이너리를 빌드합니다: + +```bash +pnpm build:exe # 현재 플랫폼용 빌드 +pnpm build:exe:all # 모든 플랫폼용 크로스 컴파일 +``` + +--- + +## 라이선스 + +MIT — 오픈 소스, 벤더 종속 없음. [LICENSE](./LICENSE) 참조. + +
+ +**[runfusion.ai →](https://runfusion.ai)** + +
diff --git a/README.md b/README.md index df726dfdfe..54ef74879d 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,8 @@ [**runfusion.ai →**](https://runfusion.ai) · [Docs](./docs/README.md) · [GitHub](https://github.com/Runfusion/Fusion) · [npm](https://www.npmjs.com/package/@runfusion/fusion) · [Discord](https://discord.gg/ksrfuy7WYR) +**English** · [简体中文](./README.zh-CN.md) · [繁體中文](./README.zh-TW.md) · [Français](./README.fr.md) · [Español](./README.es.md) · [한국어](./README.ko.md) + [![License: MIT](https://img.shields.io/badge/license-MIT-3fb950.svg)](./LICENSE) [![npm](https://img.shields.io/npm/v/@runfusion/fusion.svg?color=58a6ff)](https://www.npmjs.com/package/@runfusion/fusion) [![Discord](https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white)](https://discord.gg/ksrfuy7WYR) diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 0000000000..0f95341ee1 --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,466 @@ +
+ +Fusion + +# Fusion + +### 从粗糙想法到生产代码——全程自动化。 + +**多节点智能体编排器** — 任务、智能体、任务群、Git、文件与工作树,支持任意模型,本地与云端皆可。 + +[**runfusion.ai →**](https://runfusion.ai) · [文档](./docs/README.md) · [GitHub](https://github.com/Runfusion/Fusion) · [npm](https://www.npmjs.com/package/@runfusion/fusion) · [Discord](https://discord.gg/ksrfuy7WYR) + +[English](./README.md) · **简体中文** · [繁體中文](./README.zh-TW.md) · [Français](./README.fr.md) · [Español](./README.es.md) · [한국어](./README.ko.md) + +*本文档为社区机器翻译版本,英文 README 为权威原版。* + +[![License: MIT](https://img.shields.io/badge/license-MIT-3fb950.svg)](./LICENSE) +[![npm](https://img.shields.io/npm/v/@runfusion/fusion.svg?color=58a6ff)](https://www.npmjs.com/package/@runfusion/fusion) +[![Discord](https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white)](https://discord.gg/ksrfuy7WYR) +![Status](https://img.shields.io/badge/status-early%20preview-d29922.svg) +![Shipping](https://img.shields.io/badge/shipping-weekly-bc8cff.svg) + +
+ +Fusion 演示:从粗糙想法到生产代码 + +
+
+ + + Fusion 仪表板:包含待规划、待办、进行中、审核中、已完成看板列及活跃任务卡片 + + +
+ +--- + +## 你的整个开发环境。尽在一块面板之上。 + +用自然语言描述一个任务。规划智能体会读取你的项目、理解上下文,并撰写完整的 `PROMPT.md` 计划——包括步骤、文件范围和验收标准。随后 Fusion 在隔离的 Git 工作树中完成规划、审核、执行与再审核,你可以在任意环节设置人工审批门控。 + +一块看板。随处操控。笔记本、Mac mini、Linux 服务器、云虚拟机、手机——全部互联。 + +> 就像 Trello,只不过你的任务由 AI 来定义、执行和交付。基于 [dustinbyrne/kb](https://github.com/dustinbyrne/kb) 的出色工作构建。 + +--- + +## 工作流程 + +``` + ① 描述 ② 规划 ③ 看板 ④ 隔离工作树 + ───────────── ───────────── ───────────── ───────────────────── + "在设置面板 → 智能体撰写 → 规划 → 审核 → → fusion/FN-123 分支 + 添加深色模式 PROMPT.md 执行 → 审核 并行运行,零 + 切换按钮" (步骤、范围、 (逐步进行,直到 文件冲突 + 验收标准) 完成) +``` + +### 合并前看清每一步 + +
+ Fusion 任务详情:进行中的任务显示工作流步骤、差异对比和文件变更 +
+ +每个任务都会实时展示其计划、审核记录、差异对比和文件变更。你可以随时介入活跃任务,调整方向、收紧约束、暂停执行或重新提示。 + +--- + +## 与众不同之处 + +| | | +|---|---| +| 🧠 **AI 规划** | 用自然语言描述任务。规划智能体将其转化为包含步骤、文件范围和验收标准的 `PROMPT.md` 计划。 | +| 🔁 **工作流门控** | 每个步骤均经历:规划 → 审核 → 执行 → 审核。合并前门控阻止劣质代码,合并后门控执行信息性检查。 | +| 🌳 **工作树隔离** | 每个任务在独立分支和工作树(`fusion/{task-id}`)中运行,支持并行任务,零冲突。可通过 [`worktrunk.enabled`](./docs/settings-reference.md#worktree-backend-settings) 选择性启用 [worktrunk](https://github.com/max-sixty/worktrunk) 委托(参见 [WorktreeBackend 抽象](./docs/architecture.md#worktreebackend-abstraction))。 | +| ⚡ **智能合并** | 通过所有门控后,Fusion 自动压缩合并并继续推进。你也可以在任意环节开启手动审批。 | +| 🛰️ **多节点网格** | 笔记本、Mac mini、Linux 服务器、云虚拟机、手机——全部同步。桌面端、移动端、Web 端均支持。 | +| 🧩 **任意模型** | 支持 Anthropic、OpenAI、Ollama 等,本地与云端并存。 | +| 🏢 **智能体公司** | 导入预构建团队——16 家公司共 440+ 个智能体——自主运行数周。 | +| 📬 **智能体间消息** | 内置智能体间邮箱,支持委派、澄清与协调。 | +| 🗨️ **多智能体聊天室** | 项目范围内的群组会话,多位成员可以回复:被提及成员为直接响应者,其他旁听成员在上限内也可参与回复。当前为**实验性**功能——在**设置 → 实验性功能 → 聊天室**中启用 `chatRooms`。([聊天室文档](./docs/dashboard-guide.md#chat-rooms)) | +| 🗺️ **任务群** | 层级式规划(任务群 → 里程碑 → 切片 → 功能 → 任务),支持自动驾驶和验证契约。 | +| 🔬 **调研** | 有边界的调研运行,集成网络搜索、GitHub、本地文档和 LLM 综合分析(规划与综合流程中还支持运行时内置 WebSearch/WebFetch)。将调研发现直接转化为任务。([文档](./docs/research.md)) | +| 🧪 **自我改进** | 智能体反思自身输出,并在熟悉你的代码库后持续更新其提示词。 | +| 🔓 **开源,MIT 协议。** | 无供应商锁定。可在自有硬件上运行。每周持续更新。 | + +--- + +## 工作原理 + +```mermaid +graph TD + H((你)) -->|粗糙想法| T["规划中
自动规划"] + T --> TD["待办
已安排执行"] + TD --> IP["进行中
每步骤:
规划、审核、执行、审核
"] + + subgraph IP["进行中"] + direction TD + NS([开始步骤]) --> P[规划] + P --> R1{审核} + R1 -->|修改| P + R1 -->|批准| E[执行] + E --> R2{审核} + R2 -->|修改| E + R2 -->|下一步| NS + R2 -->|重新规划| P + end + + R2 -->|完成| IR["审核中
待合并,
或自动完成
"] + IR -->|直接压缩合并
或 PR 合并| D["已完成"] + + style H fill:#161b22,stroke:#8b949e,color:#e6edf3 + style T fill:#2d2006,stroke:#d29922,color:#d29922 + style TD fill:#0d2044,stroke:#58a6ff,color:#58a6ff + style IP fill:#1a0d2e,stroke:#bc8cff,color:#bc8cff + style P fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style R1 fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style E fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style R2 fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style NS fill:#1a0d2e,stroke:#bc8cff,color:#bc8cff + style IR fill:#0d2d16,stroke:#3fb950,color:#3fb950 + style D fill:#1a1a1a,stroke:#8b949e,color:#8b949e +``` + +有依赖关系的任务按顺序处理,相互独立的任务并行运行。可选择在任务从规划移至待办前要求手动审批(`requirePlanApproval` 设置)。 + +--- + +## 多节点。一块看板。全平台覆盖。 + +
+ +Fusion 网格:笔记本、Mac mini、Linux 服务器、云虚拟机、手机——全部同步 + +
+ +![macOS](https://img.shields.io/badge/macOS-000000?style=for-the-badge&logo=apple&logoColor=white) +![Windows](https://img.shields.io/badge/Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white) +![Linux](https://img.shields.io/badge/Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black) +![Web](https://img.shields.io/badge/Web-4285F4?style=for-the-badge&logo=googlechrome&logoColor=white) +![iOS](https://img.shields.io/badge/iOS-000000?style=for-the-badge&logo=apple&logoColor=white) +![Android](https://img.shields.io/badge/Android-3DDC84?style=for-the-badge&logo=android&logoColor=white) + +
+ +笔记本、Mac mini、Linux 服务器、云虚拟机、手机——每个节点都是对等方。你的任务状态、智能体、日志和差异对比在整个网格中保持同步。同一个 Fusion 提供以下形态: + +- 🖥️ **桌面应用** — 基于 Electron,支持 **macOS**(Intel + Apple Silicon)、**Windows** 10/11 和 **Linux** +- 📱 **移动应用** — 基于 Capacitor,支持 **iOS/iPadOS** 和 **Android**([MOBILE.md](./MOBILE.md)) +- 🌐 **Web 仪表板** — 任意现代浏览器,由 `fn dashboard` 守护进程提供服务 +- 🔌 **CLI** — `fn` 二进制文件 + 扩展,面向终端优先的工作流 + +在任意节点启动守护进程,连接其他设备,看板随你所在。 + +--- + +## 运行一个智能体公司 + +
+ +Fusion 智能体公司:导入团队,自主运行数周 + +
+ +导入一个团队,自主运行数周。**16 家公司共 440+ 个智能体**,预置了任务群、邮箱和智能体间委派机制。 + +```bash +npx companies.sh add paperclipai/companies/gstack +``` + +--- + +## 与你已在使用的工具兼容。 + +Fusion 与你喜爱的工具深度集成。**Hermes**、**Paperclip** 和 **OpenClaw** 均作为一等公民插件发布——将任意工作区路由到最适合该任务的运行时。任何 Paperclip 智能体公司均可通过单条命令导入。 + +
+ Hermes +
+ +### [Hermes](https://hermes-agent.nousresearch.com) `experimental` + +Nous Research + +**Nous Research** 出品的开源自主智能体。安装 Hermes 插件后,可通过 Hermes 运行智能体以处理长期运行、上下文持续增长的工作——将任意 Fusion 工作区路由至其上。 + +### OpenClaw `experimental` + +OpenClaw 运行时支持以实验性插件(`fusion-plugin-openclaw-runtime`)的形式提供,用于运行时发现与配置对等。安装插件后,使用 `runtimeConfig.runtimeHint: "openclaw"` 配置智能体。 + +
+ +
+ Paperclip +
+ +### [Paperclip](https://paperclip.ing) `experimental` + +paperclip.ing + +AI 劳动力的人工控制平面。安装 Paperclip 插件后,可在 Fusion 内部通过 Paperclip 运行智能体。 + +Fusion 还原生支持 **[`companies.sh`](https://github.com/paperclipai/companies)** 智能体公司标准:导入预构建团队——**16 家公司共 440+ 个智能体**——让它们通过 Fusion 的邮箱、任务群和工作流门控协作,自主运行数周。与 Paperclip 共用相同的公司格式、相同的智能体和相同的技能。 + +```bash +npx companies.sh add paperclipai/companies/gstack +``` + +
+ +> **Hermes**、**Paperclip** 和 **OpenClaw** 均为**实验性**运行时插件——API 和通信格式可能在次要版本间发生变更。 + +--- + +## 快速上手 + +**无需安装,直接通过 npm 运行:** + +```bash +npx runfusion.ai +``` + +这将启动仪表板。子命令可透传:`npx runfusion.ai task create "fix X"`、`npx runfusion.ai --help` 等(或完整写法:`npx @runfusion/fusion dashboard`)。 + +**一键安装脚本**(macOS 和 Linux——自动选用 Homebrew,失败则回退到 npm): + +```bash +curl -fsSL https://runfusion.ai/install.sh | sh +fusion dashboard +``` + +**Homebrew**(macOS 和 Linux): + +```bash +brew tap runfusion/fusion +brew install fusion +fusion dashboard # 或:fn dashboard +``` + +或使用一行命令(自动添加 tap):`brew install runfusion/fusion/fusion`。 + +**npm 全局安装**: + +```bash +npm install -g @runfusion/fusion +fn dashboard # 或:fusion dashboard +``` + +**从克隆仓库启动**(用于开发): + +```bash +pnpm dev dashboard +``` + +然后点击终端输出的 `Open:` URL。该 URL 内嵌了一个持有者令牌 +(`http://localhost:4040/?token=fn_...`),浏览器首次访问时会将其捕获并存入 +`localStorage`,此后自动复用。在服务端,Fusion 会在首次经过身份验证的运行时将 +仪表板/守护进程令牌持久化至 `~/.fusion/settings.json`,并在后续启动时复用, +除非你通过 `--token`、`FUSION_DASHBOARD_TOKEN`、`FUSION_DAEMON_TOKEN` 覆盖, +或使用 `--no-auth` 禁用鉴权。完整的优先级规则及重置/吊销选项,请参见 +[CLI 参考 → fn dashboard → 身份验证](./docs/cli-reference.md#fn-dashboard)。 + +### 首次运行向导 + +首次启动时,Fusion 会打开**引导向导**,分三步引导: + +1. **AI 配置** — 使用简化的快速启动提供商列表(推荐提供商加上已连接的提供商),如需添加更多提供商或查看详细设置,展开**高级提供商设置**即可。入门只需一个提供商。已弃用的 Google Gemini CLI / Antigravity 提供商条目已被有意隐藏;Google/Gemini API 密钥、Google Generative AI、Vertex 和 Cloud Code 路径仍受支持。 +2. **GitHub(可选)** — 连接 GitHub 以导入 Issue 和管理 PR +3. **第一个任务** — 创建你的第一个任务,或从 GitHub 导入(若当前无活跃项目,引导向导会先提示你注册/选择项目目录) + +向导**可关闭且不阻塞**——点击**暂时跳过**即可立即使用仪表板。稍后可从**设置 → 身份验证 → 重新打开引导向导**再次触发。 + +### 移动端 + +Capacitor + PWA 工作流,请参见 [MOBILE.md](./MOBILE.md)。 + +--- + +## 文档 + +| 指南 | 内容 | +|---|---| +| [入门指南](./docs/getting-started.md) | 安装与引导 | +| [仪表板指南](./docs/dashboard-guide.md) | 看板/列表视图、终端、Git 管理器 | +| [任务管理](./docs/task-management.md) | 任务生命周期与 CLI 命令 | +| [CLI 参考](./docs/cli-reference.md) | 完整命令与守护进程参考 | +| [设置参考](./docs/settings-reference.md) | 配置选项 | +| [架构](./docs/architecture.md) | 系统内部机制 | +| [智能体](./docs/agents.md) | 智能体管理、生成与心跳 | +| [工作流步骤](./docs/workflow-steps.md) | 质量门控、模板与阶段 | +| [任务群](./docs/missions.md) | 任务群层级、规划与自动驾驶 | +| [多项目](./docs/multi-project.md) | 中央注册表与隔离模式 | +| [Docker](./docs/docker.md) | 容器部署 | + +--- + +## 核心功能 + +- **AI 规划** — 规划智能体生成包含步骤、文件范围和验收标准的详细 `PROMPT.md` +- **逐步执行** — 每个任务步骤均经历规划 → 审核 → 执行 → 审核循环 +- **Git 工作树隔离** — 每个任务在独立工作树(`fusion/{task-id}` 分支)中运行 +- **工作流步骤** — 可配置的质量门控(合并前:阻止合并;合并后:信息性检查) +- **GitHub 集成** — 导入 Issue、创建 PR、实时 PR/Issue 徽章 +- **仪表板** — 实时看板、智能体管理、终端、Git 管理器、任务群规划器 +- **任务群** — 层级式规划(任务群 → 里程碑 → 切片 → 功能 → 任务),支持自动驾驶、验证契约、修复功能重试和阻塞移交语义 +- **多项目** — 从单一安装管理多个项目,项目间相互隔离 +- **智能体间消息** — 内置消息机制,用于智能体与用户之间的协调 +- **聊天室(实验性)** — 项目范围内的群组聊天,被提及成员作为直接响应者路由,其他旁听成员在上限内可回复(通过**设置 → 实验性功能 → 聊天室**启用;详情见[仪表板指南 → 聊天室](./docs/dashboard-guide.md#chat-rooms)) + +### 提供商身份验证 + +Fusion 支持通过**设置 → 身份验证**为 AI 提供商配置基于 OAuth 的身份验证。对于大多数 OAuth 提供商,当仪表板通过非 localhost 主机访问(远程节点、局域网主机/IP 或反向代理)时,提供商登录 URL 会被重写,通过桥接端点(`/api/auth/oauth-callback`)路由 OAuth 回调,以确保重定向能到达活跃的浏览器会话。 + +- **Anthropic (Claude)** — 在设置/引导向导中使用粘贴授权码流程:登录后,将最终重定向 URL(或授权码)粘贴回 Fusion 以完成登录 +- **OpenAI Codex** — 使用相同的粘贴授权码流程,附带安全状态验证 +- **Factory AI — 通过 Droid CLI** *(可选)* — 需要本地安装 Droid CLI 并执行 `droid auth login`;检测遵循有效运行时二进制路径(默认为 `droid`,或配置了插件 `droidBinaryPath` 时使用该路径),然后在**设置 → 身份验证**中启用并重启 Fusion +- **llama.cpp — 通过 HTTP 服务器** *(可选)* — 配置你的 llama.cpp 服务器 URL(默认 `http://127.0.0.1:8080`)和可选 API 密钥,然后在**设置 → 身份验证**中启用 +- **其他提供商** — 在设置中通过 API 密钥条目进行身份验证(包括 Google/Gemini API 密钥、Google Generative AI、Vertex 和 Cloud Code 别名) + +### 模型系统 + +Fusion 使用双作用域模型层级,包含五条独立通道。全局设置定义基准默认值,项目设置提供每个项目的覆盖配置。 + +| 通道 | 用途 | 全局基准键 | 项目覆盖键 | +|------|---------|---------------------|----------------------| +| 执行器 | 任务执行智能体 | `executionGlobalProvider` + `executionGlobalModelId` | `executionProvider` + `executionModelId` | +| 规划器 | 任务规划智能体 | `planningGlobalProvider` + `planningGlobalModelId` | `planningProvider` + `planningModelId` | +| 验证器 | 计划/代码审核 | `validatorGlobalProvider` + `validatorGlobalModelId` | `validatorProvider` + `validatorModelId` | +| 标题摘要 | 自动标题生成 | `titleSummarizerGlobalProvider` + `titleSummarizerGlobalModelId` | `titleSummarizerProvider` + `titleSummarizerModelId` | +| 工作流步骤优化 | AI 提示词优化 | (使用 `defaultProvider`/`defaultModelId`) | (使用 WorkflowStep 上的 `modelProvider`/`modelId`) | + +**任务级覆盖:** 任务可通过任务级模型字段(`modelProvider`/`modelId`、`validatorModelProvider`/`validatorModelId`、`planningModelProvider`/`planningModelId`)覆盖执行器、验证器和规划器通道。 + +**优先级:** 任务级 → 项目覆盖 → 全局通道 → `defaultProvider`/`defaultModelId` → 自动解析。 + +完整设置文档,请参见[设置参考](./docs/settings-reference.md)。 + +### 计划任务 / 自动化 + +Fusion 通过 `/api/automations` 端点支持计划任务自动化。自动化任务可按可配置的计划运行 Shell 命令或多步骤工作流。 + +#### 调度范围 + +自动化任务和例程可在两种范围内运行: + +- **全局** — 跨所有项目运行。适用于跨项目维护、备份或统一报告。 +- **项目** — 仅在特定项目内运行。适用于项目特定的 CI、测试或部署任务。 + +创建计划时若未选择范围,Fusion 默认使用 **project 范围**并以 `default` 项目 ID,以保持向后兼容。 + +显式指定范围的方式: +- 在仪表板的**计划任务**模态框中,使用**全局 / 项目**切换开关。 +- 通过 API,在自动化/例程端点上传递 `?scope=global` 或 `?scope=project&projectId=`。 + +**范围解析规则:** +- `scope=global` 始终解析到全局自动化/例程通道,与活跃项目无关。 +- `scope=project` 需要 `projectId`。若省略,则回退到 `"default"`。 +- 增删改查、运行、切换和 Webhook 操作严格按范围隔离:全局计划不能通过项目范围请求修改,反之亦然。 + +**多项目环境操作建议:** +- 共享基础设施(如夜间备份、记忆洞察提取)优先使用**全局**计划。 +- 仓库级自动化(如每项目测试运行器、部署钩子)优先使用**项目**计划。 +- 全局通道和项目通道由引擎独立轮询,一个通道中到期的运行不会阻塞另一个。 + +#### 自动化任务 + +| 端点 | 方法 | 说明 | +|---------|--------|-------------| +| `/api/automations` | GET | 列出所有自动化任务(若指定范围则按范围过滤) | +| `/api/automations` | POST | 创建自动化任务(范围默认为 `project`) | +| `/api/automations/:id` | GET | 按 ID 获取自动化任务 | +| `/api/automations/:id` | PATCH | 更新自动化任务 | +| `/api/automations/:id` | DELETE | 删除自动化任务 | +| `/api/automations/:id/run` | POST | 触发手动运行 | +| `/api/automations/:id/toggle` | POST | 切换启用/禁用 | +| `/api/automations/:id/steps/reorder` | POST | 重排自动化步骤顺序 | + +#### 例程 + +例程是由 Cron 计划、Webhook 或手动执行触发的 AI 智能体任务。例程与自动化任务共用相同的全局/项目范围模型。 + +| 端点 | 方法 | 说明 | +|---------|--------|-------------| +| `/api/routines` | GET | 列出所有例程(若指定范围则按范围过滤) | +| `/api/routines` | POST | 创建例程(范围默认为 `project`) | +| `/api/routines/:id` | GET | 按 ID 获取例程 | +| `/api/routines/:id` | PATCH | 更新例程 | +| `/api/routines/:id` | DELETE | 删除例程 | +| `/api/routines/:id/run` | POST | 手动触发 | +| `/api/routines/:id/trigger` | POST | 规范化手动触发 | +| `/api/routines/:id/runs` | GET | 获取执行历史 | +| `/api/routines/:id/webhook` | POST | Webhook 触发(支持签名验证) | + +--- + +## CLI 快速示例 + +```bash +fn task create "Fix the login bug" # 快速录入 → 规划 +fn task plan "Build auth system" # AI 辅助规划 +fn task import owner/repo --labels bug # 导入 GitHub Issue +fn task show FN-001 # 查看任务详情 +fn task logs FN-001 --follow # 流式查看执行日志 +fn task steer FN-001 "Use TypeScript" # 在执行中途引导智能体 + +fn project add my-app /path/to/app # 注册项目 +fn project list # 列出所有项目 + +fn settings set maxConcurrent 4 # 配置设置 +fn settings export # 导出配置 + +fn mission create "Auth System" "Build auth" # 创建任务群 +fn mission activate-slice # 激活切片 + +fn skills search react # 搜索 skills.sh +fn skills install firebase/agent-skills # 安装智能体技能 +``` + +--- + +## 包结构 + +| 包 | 说明 | +|---------|-------------| +| `@fusion/core` | 领域模型——任务、看板列、SQLite 存储 | +| `@fusion/dashboard` | Web UI——Express 服务器 + 带 SSE 的看板 | +| `@fusion/engine` | AI 引擎——规划、执行、调度、工作流步骤 | +| `@runfusion/fusion` | CLI + 扩展——发布至 npm | + +--- + +## 开发 + +```bash +pnpm install # 安装依赖 +pnpm local # 在非 4040 端口启动本地仪表板/API +pnpm local -- --engine # 启动带 AI 引擎的本地仪表板 +pnpm build # 构建默认工作区包(不含桌面端/移动端) +pnpm build:all # 构建所有包(含桌面端/移动端) +pnpm dev dashboard # 运行仪表板 + AI 引擎 +pnpm dev:ui # 仅仪表板(无 AI 引擎) +pnpm lint # 对所有包执行代码检查 +pnpm typecheck # 对所有包执行类型检查 +pnpm test # 运行所有测试 +``` + +### 构建独立可执行文件 + +使用 [Bun](https://bun.sh/) 构建单个自包含的 `fn` 二进制文件: + +```bash +pnpm build:exe # 为当前平台构建 +pnpm build:exe:all # 跨平台编译所有目标 +``` + +--- + +## 许可证 + +MIT — 开源,无供应商锁定。详见 [LICENSE](./LICENSE)。 + +
+ +**[runfusion.ai →](https://runfusion.ai)** + +
diff --git a/README.zh-TW.md b/README.zh-TW.md new file mode 100644 index 0000000000..d4d15d287c --- /dev/null +++ b/README.zh-TW.md @@ -0,0 +1,467 @@ +
+ +Fusion + +# Fusion + +### 從粗略想法到正式上線的程式碼——全自動完成。 + +**多節點代理人協調器** — 任務、代理人、任務群組、git、檔案與工作樹,支援任何模型,本地或雲端皆可。 + +[**runfusion.ai →**](https://runfusion.ai) · [文件](./docs/README.md) · [GitHub](https://github.com/Runfusion/Fusion) · [npm](https://www.npmjs.com/package/@runfusion/fusion) · [Discord](https://discord.gg/ksrfuy7WYR) + +[English](./README.md) · [简体中文](./README.zh-CN.md) · **繁體中文** · [Français](./README.fr.md) · [Español](./README.es.md) · [한국어](./README.ko.md) + +*本文件為機器翻譯,英文版 README 為權威版本。* + +[![License: MIT](https://img.shields.io/badge/license-MIT-3fb950.svg)](./LICENSE) +[![npm](https://img.shields.io/npm/v/@runfusion/fusion.svg?color=58a6ff)](https://www.npmjs.com/package/@runfusion/fusion) +[![Discord](https://img.shields.io/badge/Discord-join-5865F2?logo=discord&logoColor=white)](https://discord.gg/ksrfuy7WYR) +![Status](https://img.shields.io/badge/status-early%20preview-d29922.svg) +![Shipping](https://img.shields.io/badge/shipping-weekly-bc8cff.svg) + +
+ +Fusion 展示影片:從粗略想法到正式上線的程式碼 + +
+
+ + + Fusion 儀表板:規劃中、待辦、進行中、審閱中、已完成看板欄位,以及作用中的任務卡 + + +
+ +--- + +## 整個開發環境。盡在一個畫面。 + +用白話文描述一個任務。規劃代理人讀取你的專案、理解脈絡,並撰寫完整的 `PROMPT.md` 計畫——包含步驟、檔案範圍與驗收條件。接著 Fusion 在獨立的 git 工作樹中依序規劃、審閱、執行、再審閱,並在你指定的任何環節設置人工核准關卡。 + +一個看板。從任何地方操控。筆電、Mac mini、Linux 伺服器、雲端虛擬機、手機——全部連線。 + +> 就像 Trello,但你的任務由 AI 負責規格撰寫、執行與交付。基於 [dustinbyrne/kb](https://github.com/dustinbyrne/kb) 的優秀成果打造。 + +--- + +## 工作流程 + +``` + ① 描述 ② 規劃 ③ 看板 ④ 獨立工作樹 + ───────────── ───────────── ───────────── ───────────────────── + 「在設定面板 → 代理人撰寫 → 規劃 → 審閱 → → fusion/FN-123 分支 + 加入深色模式 PROMPT.md 執行 → 審閱 並行執行,零 + 切換開關」 (步驟、範圍、 (每步驟,直到 檔案衝突 + 驗收條件) 完成) +``` + +### 合併前看清每個步驟 + +
+ Fusion 任務詳情:進行中的任務顯示工作流程步驟、差異比較與檔案變更 +
+ +每個任務都即時顯示其計畫、審閱紀錄、差異比較與檔案變更。進入作用中的任務,調整方向、收緊限制條件、暫停或重新提示。 + +--- + +## 與眾不同之處 + +| | | +|---|---| +| 🧠 **AI 規劃** | 用白話文描述任務。規劃代理人將其轉換為含步驟、檔案範圍與驗收條件的 `PROMPT.md` 計畫。 | +| 🔁 **工作流程關卡** | 每個步驟皆執行:規劃 → 審閱 → 執行 → 審閱。合併前關卡阻擋劣質程式碼;合併後關卡執行資訊性檢查。 | +| 🌳 **工作樹隔離** | 每個任務在各自的分支與工作樹(`fusion/{task-id}`)中執行。任務並行執行,零衝突。可選用 [worktrunk](https://github.com/max-sixty/worktrunk) 委派,透過 [`worktrunk.enabled`](./docs/settings-reference.md#worktree-backend-settings) 設定(詳見 [WorktreeBackend 抽象層](./docs/architecture.md#worktreebackend-abstraction))。 | +| ⚡ **智慧合併** | 通過所有關卡後,Fusion 自動壓縮合併並繼續執行。可在任何環節選擇手動核准。 | +| 🛰️ **多節點網狀架構** | 筆電、Mac mini、Linux 伺服器、雲端虛擬機、手機——全部同步。桌面、行動裝置、網頁皆支援。 | +| 🧩 **任意模型** | 支援 Anthropic、OpenAI、Ollama 等。本地與雲端模型共存。 | +| 🏢 **代理人公司** | 匯入預建團隊——橫跨 16 家公司的 440+ 個代理人——自主運行數週。 | +| 📬 **代理人間訊息傳遞** | 代理人之間內建郵件信箱。委派、釐清、協調。 | +| 🗨️ **多代理人聊天室** | 專案範圍的群組對話,多位成員可回覆:被提及的成員為直接回應者,其餘環境成員最多可回應至上限。目前為**實驗性功能**——在**設定 → 實驗性功能 → 聊天室**中啟用 `chatRooms`。([聊天室文件](./docs/dashboard-guide.md#chat-rooms)) | +| 🗺️ **任務群組** | 層級式規劃(任務群組 → 里程碑 → 切片 → 功能 → 任務),具備自動駕駛模式與驗證合約。 | +| 🔬 **研究** | 有界研究執行,整合網頁搜尋、GitHub、本地文件與 LLM 合成(規劃與合成流程中亦支援執行時內建的 WebSearch/WebFetch)。將研究結果轉換為任務。([文件](./docs/research.md)) | +| 🧪 **自我改善** | 代理人反思自身輸出,並隨著對你的程式碼庫的了解更新自身提示詞。 | +| 🔓 **開放原始碼,MIT 授權。** | 無廠商綁定。在自己的硬體上執行。每週持續更新。 | + +--- + +## 運作原理 + +```mermaid +graph TD + H((你)) -->|粗略想法| T["規劃中
自動規劃"] + T --> TD["待辦
排定執行"] + TD --> IP["進行中
每個步驟:
規劃、審閱、執行、審閱
"] + + subgraph IP["進行中"] + direction TD + NS([開始步驟]) --> P[規劃] + P --> R1{審閱} + R1 -->|修訂| P + R1 -->|核准| E[執行] + E --> R2{審閱} + R2 -->|修訂| E + R2 -->|下一步驟| NS + R2 -->|重新思考| P + end + + R2 -->|完成| IR["審閱中
準備合併
或自動完成
"] + IR -->|直接壓縮合併
或已合併的 PR| D["已完成"] + + style H fill:#161b22,stroke:#8b949e,color:#e6edf3 + style T fill:#2d2006,stroke:#d29922,color:#d29922 + style TD fill:#0d2044,stroke:#58a6ff,color:#58a6ff + style IP fill:#1a0d2e,stroke:#bc8cff,color:#bc8cff + style P fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style R1 fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style E fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style R2 fill:#1a0d2e,stroke:#bc8cff,color:#e6edf3 + style NS fill:#1a0d2e,stroke:#bc8cff,color:#bc8cff + style IR fill:#0d2d16,stroke:#3fb950,color:#3fb950 + style D fill:#1a1a1a,stroke:#8b949e,color:#8b949e +``` + +有相依關係的任務依序處理;獨立任務並行執行。可選擇在任務從「規劃中」移至「待辦」前要求手動核准(`requirePlanApproval` 設定)。 + +--- + +## 多節點。一個看板。全平台支援。 + +
+ +Fusion 網狀架構:筆電、Mac mini、Linux 伺服器、雲端虛擬機、手機——全部同步 + +
+ +![macOS](https://img.shields.io/badge/macOS-000000?style=for-the-badge&logo=apple&logoColor=white) +![Windows](https://img.shields.io/badge/Windows-0078D6?style=for-the-badge&logo=windows&logoColor=white) +![Linux](https://img.shields.io/badge/Linux-FCC624?style=for-the-badge&logo=linux&logoColor=black) +![Web](https://img.shields.io/badge/Web-4285F4?style=for-the-badge&logo=googlechrome&logoColor=white) +![iOS](https://img.shields.io/badge/iOS-000000?style=for-the-badge&logo=apple&logoColor=white) +![Android](https://img.shields.io/badge/Android-3DDC84?style=for-the-badge&logo=android&logoColor=white) + +
+ +筆電、Mac mini、Linux 伺服器、雲端虛擬機、手機——每個節點都是對等節點。你的任務狀態、代理人、日誌與差異比較在整個網狀架構中保持同步。同一個 Fusion 以下列形式發布: + +- 🖥️ **桌面應用程式** — 支援 **macOS**(Intel + Apple Silicon)、**Windows** 10/11 與 **Linux** 的 Electron 應用程式 +- 📱 **行動應用程式** — 支援 **iOS/iPadOS** 與 **Android** 的 Capacitor 應用程式([MOBILE.md](./MOBILE.md)) +- 🌐 **網頁儀表板** — 任何現代瀏覽器,由 `fn dashboard` 背景程式提供服務 +- 🔌 **命令列介面** — `fn` 執行檔 + 適合以終端機為主要工作流程的擴充功能 + +在任意節點啟動背景程式,連接其他裝置,看板就會跟著你到任何地方。 + +--- + +## 執行代理人公司 + +
+ +Fusion 代理人公司:匯入團隊,自主執行數週 + +
+ +匯入一個團隊,自主執行數週。**橫跨 16 家公司的 440+ 個代理人**,專為任務群組、信箱與代理人間委派而設計。 + +```bash +npx companies.sh add paperclipai/companies/gstack +``` + +--- + +## 與你已在使用的工具相容。 + +Fusion 整合你喜愛的工具。**Hermes**、**Paperclip** 與 **OpenClaw** 皆作為一等公民外掛程式發布——將任何工作區路由至最適合該任務的執行環境。任何 Paperclip 代理人公司都能以單一指令匯入。 + +
+ Hermes +
+ +### [Hermes](https://hermes-agent.nousresearch.com) `experimental` + +Nous Research + +來自 **Nous Research** 的開放原始碼自主代理人。安裝 Hermes 外掛程式,透過 Hermes 執行代理人,適合需要長時間執行、上下文持續增長的工作——可將任何 Fusion 工作區路由至 Hermes。 + +### OpenClaw `experimental` + +OpenClaw 執行環境支援作為實驗性外掛程式(`fusion-plugin-openclaw-runtime`)提供,可進行執行環境探索與設定對等。安裝外掛程式後,以 `runtimeConfig.runtimeHint: "openclaw"` 設定代理人。 + +
+ +
+ Paperclip +
+ +### [Paperclip](https://paperclip.ing) `experimental` + +paperclip.ing + +AI 勞動力的人類控制平面。安裝 Paperclip 外掛程式,在 Fusion 內透過 Paperclip 執行代理人。 + +Fusion 也原生支援 **[`companies.sh`](https://github.com/paperclipai/companies)** 代理人公司標準:匯入預建團隊——**橫跨 16 家公司的 440+ 個代理人**——讓他們透過 Fusion 的信箱、任務群組與工作流程關卡協調作業,自主工作數週。相同的公司格式、相同的代理人、相同的技能,與 Paperclip 一致。 + +```bash +npx companies.sh add paperclipai/companies/gstack +``` + +
+ +> **Hermes**、**Paperclip** 與 **OpenClaw** 為**實驗性**執行環境外掛程式——API 與通訊格式可能在次要版本之間有所變動。 + +--- + +## 快速開始 + +**免安裝,直接從 npm 執行:** + +```bash +npx runfusion.ai +``` + +這會啟動儀表板。子指令可直接傳遞:`npx runfusion.ai task create "fix X"`、`npx runfusion.ai --help` 等。(或完整形式:`npx @runfusion/fusion dashboard`。) + +**單行安裝程式**(macOS 與 Linux——自動選用 Homebrew,若無則退回 npm): + +```bash +curl -fsSL https://runfusion.ai/install.sh | sh +fusion dashboard +``` + +**Homebrew**(macOS 與 Linux): + +```bash +brew tap runfusion/fusion +brew install fusion +fusion dashboard # 或:fn dashboard +``` + +或使用單行指令(自動新增 tap):`brew install runfusion/fusion/fusion`。 + +**npm 全域安裝**: + +```bash +npm install -g @runfusion/fusion +fn dashboard # 或:fusion dashboard +``` + +**從複本執行**(供開發使用): + +```bash +pnpm dev dashboard +``` + +然後點擊終端機中顯示的 `Open:` 網址。該網址內嵌一個不記名令牌 +(`http://localhost:4040/?token=fn_...`),瀏覽器會在首次造訪時擷取並存入 +`localStorage`,之後自動重複使用。在伺服器端,Fusion 會在首次驗證執行時 +將儀表板與背景程式令牌持久化至 `~/.fusion/settings.json`,並在後續啟動時 +重複使用,除非你覆蓋它(`--token`、`FUSION_DASHBOARD_TOKEN`、 +`FUSION_DAEMON_TOKEN`)或以 `--no-auth` 停用驗證。完整的優先順序與 +重設/撤銷選項,請參閱 +[命令列參考 → fn dashboard → 驗證](./docs/cli-reference.md#fn-dashboard)。 + +### 首次執行設定 + +首次啟動時,Fusion 會開啟**引導精靈**,提供三個引導步驟: + +1. **AI 設定** — 使用簡化的快速啟動供應商清單(建議的供應商,加上已連線的供應商),只有在需要其他供應商或詳細設定時,才展開**進階供應商設定**。只需一個供應商即可開始使用。已棄用的 Google Gemini CLI / Antigravity 供應商項目已刻意隱藏;Google/Gemini API 金鑰、Google Generative AI、Vertex 與 Cloud Code 路徑仍受支援。 +2. **GitHub(選填)** — 連結 GitHub 以匯入議題並管理 PR +3. **第一個任務** — 建立你的第一個任務或從 GitHub 匯入(若無作用中的專案,引導精靈會先提示你註冊/選取專案目錄) + +精靈**可關閉且不阻擋操作**——點擊**暫時略過**即可立即使用儀表板。之後可從**設定 → 驗證 → 重新開啟引導指南**再次觸發。 + +### 行動裝置 + +Capacitor + PWA 工作流程,請參閱 [MOBILE.md](./MOBILE.md)。 + +--- + +## 文件 + +| 指南 | 涵蓋內容 | +|---|---| +| [入門指南](./docs/getting-started.md) | 安裝與引導 | +| [儀表板指南](./docs/dashboard-guide.md) | 看板/清單檢視、終端機、git 管理器 | +| [任務管理](./docs/task-management.md) | 任務生命週期與命令列指令 | +| [命令列參考](./docs/cli-reference.md) | 完整指令與背景程式參考 | +| [設定參考](./docs/settings-reference.md) | 組態選項 | +| [系統架構](./docs/architecture.md) | 系統內部運作 | +| [代理人](./docs/agents.md) | 代理人管理、生成與心跳 | +| [工作流程步驟](./docs/workflow-steps.md) | 品質關卡、範本、階段 | +| [任務群組](./docs/missions.md) | 任務群組層級、規劃、自動駕駛模式 | +| [多專案](./docs/multi-project.md) | 中央登錄表、隔離模式 | +| [Docker](./docs/docker.md) | 容器部署 | + +--- + +## 核心功能 + +- **AI 規劃** — 規劃代理人產生詳細的 `PROMPT.md`,包含步驟、檔案範圍與驗收條件 +- **逐步執行** — 每個任務步驟執行「規劃 → 審閱 → 執行 → 審閱」循環 +- **Git 工作樹隔離** — 每個任務在各自的工作樹(`fusion/{task-id}` 分支)中執行 +- **工作流程步驟** — 可設定的品質關卡(合併前:阻擋合併;合併後:資訊性) +- **GitHub 整合** — 匯入議題、建立 PR、即時 PR/議題徽章 +- **儀表板** — 即時看板、代理人管理、終端機、git 管理器、任務群組規劃器 +- **任務群組** — 層級式規劃(任務群組 → 里程碑 → 切片 → 功能 → 任務),具備自動駕駛模式、驗證合約、修復功能重試與封鎖交接語意 +- **多專案** — 從單一安裝管理多個專案,具備專案隔離 +- **代理人間訊息傳遞** — 代理人與使用者之間協調用的內建訊息傳遞 +- **聊天室(實驗性)** — 專案範圍的群組對話,被提及的成員為直接回應者,其餘環境成員最多可回覆至上限(在**設定 → 實驗性功能 → 聊天室**中啟用;詳見[儀表板指南 → 聊天室](./docs/dashboard-guide.md#chat-rooms)) + +### 供應商驗證 + +Fusion 透過**設定 → 驗證**支援 AI 供應商的 OAuth 驗證。對大多數 OAuth 供應商而言,當儀表板透過非 localhost 主機存取(遠端節點、區域網路主機/IP 或反向代理),供應商登入網址會被重寫,以透過橋接端點(`/api/auth/oauth-callback`)路由 OAuth 回呼,確保重導向能到達作用中的瀏覽器工作階段。 + +- **Anthropic (Claude)** — 在設定/引導精靈中使用貼上授權碼流程:登入後,將最終的重導向網址(或授權碼)貼回 Fusion 以完成登入 +- **OpenAI Codex** — 使用相同的貼上授權碼流程,搭配安全的狀態驗證 +- **Factory AI — 透過 Droid CLI** *(選填)* — 需要本地安裝 Droid CLI 並執行 `droid auth login`;偵測依照有效的執行環境二進位路徑(預設為 `droid`,或設定後的外掛程式 `droidBinaryPath`),然後在**設定 → 驗證**中啟用並重新啟動 Fusion +- **llama.cpp — 透過 HTTP 伺服器** *(選填)* — 設定你的 llama.cpp 伺服器網址(預設 `http://127.0.0.1:8080`)與選填的 API 金鑰,然後在**設定 → 驗證**中啟用 +- **其他供應商** — 在設定中透過輸入 API 金鑰進行驗證(包含 Google/Gemini API 金鑰、Google Generative AI、Vertex 與 Cloud Code 別名) + +### 模型系統 + +Fusion 使用具備五條獨立通道的雙範圍模型層級。全域設定定義基準預設值;專案設定提供每個專案的覆蓋值。 + +| 通道 | 用途 | 全域基準金鑰 | 專案覆蓋金鑰 | +|------|---------|---------------------|----------------------| +| Executor | 任務執行代理人 | `executionGlobalProvider` + `executionGlobalModelId` | `executionProvider` + `executionModelId` | +| Planning | 任務規劃代理人 | `planningGlobalProvider` + `planningGlobalModelId` | `planningProvider` + `planningModelId` | +| Validator | 計畫/程式碼審閱者 | `validatorGlobalProvider` + `validatorGlobalModelId` | `validatorProvider` + `validatorModelId` | +| Title Summarization | 自動標題產生 | `titleSummarizerGlobalProvider` + `titleSummarizerGlobalModelId` | `titleSummarizerProvider` + `titleSummarizerModelId` | +| Workflow Step Refinement | AI 提示詞精煉 | (使用 `defaultProvider`/`defaultModelId`) | (使用 WorkflowStep 上的 `modelProvider`/`modelId`) | + +**每任務覆蓋:** 任務可透過每任務模型欄位(`modelProvider`/`modelId`、`validatorModelProvider`/`validatorModelId`、`planningModelProvider`/`planningModelId`)覆蓋執行器、驗證器與規劃通道。 + +**優先順序:** 每任務 → 專案覆蓋 → 全域通道 → `defaultProvider`/`defaultModelId` → 自動解析。 + +完整的設定文件,請參閱[設定參考](./docs/settings-reference.md)。 + +### 排程任務/自動化 + +Fusion 透過 `/api/automations` 端點支援排程任務自動化。自動化可按設定的排程執行 shell 指令或多步驟工作流程。 + +#### 排程範圍 + +自動化與常式可在兩種範圍中執行: + +- **全域** — 跨所有專案執行。適用於跨專案維護、備份或統一報告。 +- **專案** — 僅在特定專案中執行。適用於特定專案的 CI、測試或部署任務。 + +當你建立排程而未選擇範圍時,Fusion 為了向後相容,預設使用 `default` 專案 ID 的**專案範圍**。 + +明確指定範圍的方式: +- 在儀表板的**排程任務**對話框中,使用**全域 / 專案**切換。 +- 透過 API,在自動化/常式端點上傳遞 `?scope=global` 或 `?scope=project&projectId=`。 + +**範圍解析規則:** +- `scope=global` 永遠解析至全域自動化/常式通道,與作用中的專案無關。 +- `scope=project` 需要 `projectId`。若省略,退回至 `"default"`。 +- CRUD、執行、切換與 webhook 操作嚴格進行範圍隔離:全域排程無法從專案範圍的請求進行變更,反之亦然。 + +**多專案設定的操作指引:** +- 偏好使用**全域**排程處理共用基礎設施(例如每夜備份、記憶體洞察擷取)。 +- 偏好使用**專案**排程處理每個儲存庫的自動化(例如每個專案的測試執行器、部署鉤子)。 +- 全域與專案通道由引擎獨立輪詢,因此一個通道中的到期執行不會阻擋另一個通道。 + +#### 自動化 + +| 端點 | 方法 | 說明 | +|---------|--------|-------------| +| `/api/automations` | GET | 列出所有自動化(若指定範圍則依範圍篩選) | +| `/api/automations` | POST | 建立自動化(範圍預設為 `project`) | +| `/api/automations/:id` | GET | 依 ID 取得自動化 | +| `/api/automations/:id` | PATCH | 更新自動化 | +| `/api/automations/:id` | DELETE | 刪除自動化 | +| `/api/automations/:id/run` | POST | 觸發手動執行 | +| `/api/automations/:id/toggle` | POST | 切換啟用/停用 | +| `/api/automations/:id/steps/reorder` | POST | 重新排序自動化步驟 | + +#### 常式 + +常式是由 cron 排程、webhook 或手動執行觸發的 AI 代理人任務。常式與自動化共用相同的全域/專案範圍模型。 + +| 端點 | 方法 | 說明 | +|---------|--------|-------------| +| `/api/routines` | GET | 列出所有常式(若指定範圍則依範圍篩選) | +| `/api/routines` | POST | 建立常式(範圍預設為 `project`) | +| `/api/routines/:id` | GET | 依 ID 取得常式 | +| `/api/routines/:id` | PATCH | 更新常式 | +| `/api/routines/:id` | DELETE | 刪除常式 | +| `/api/routines/:id/run` | POST | 手動觸發 | +| `/api/routines/:id/trigger` | POST | 正式手動觸發端點 | +| `/api/routines/:id/runs` | GET | 取得執行歷史 | +| `/api/routines/:id/webhook` | POST | Webhook 觸發(支援簽章驗證) | + +--- + +## 命令列快速範例 + +```bash +fn task create "Fix the login bug" # 快速輸入 → 規劃 +fn task plan "Build auth system" # AI 引導規劃 +fn task import owner/repo --labels bug # 匯入 GitHub 議題 +fn task show FN-001 # 檢視任務詳情 +fn task logs FN-001 --follow # 串流執行日誌 +fn task steer FN-001 "Use TypeScript" # 執行中引導代理人 + +fn project add my-app /path/to/app # 註冊專案 +fn project list # 列出所有專案 + +fn settings set maxConcurrent 4 # 設定組態 +fn settings export # 匯出組態 + +fn mission create "Auth System" "Build auth" # 建立任務群組 +fn mission activate-slice # 啟動切片 + +fn skills search react # 搜尋 skills.sh +fn skills install firebase/agent-skills # 安裝代理人技能 +``` + +--- + +## 套件 + +| 套件 | 說明 | +|---------|-------------| +| `@fusion/core` | 領域模型——任務、看板欄位、SQLite 儲存庫 | +| `@fusion/dashboard` | 網頁 UI——Express 伺服器 + 搭配 SSE 的看板 | +| `@fusion/engine` | AI 引擎——規劃、執行、排程、工作流程步驟 | +| `@runfusion/fusion` | 命令列介面 + 擴充功能——發布至 npm | + +--- + +## 開發 + +```bash +pnpm install # 安裝相依套件 +pnpm local # 在非 4040 連接埠啟動本地儀表板/API +pnpm local -- --engine # 啟動本地儀表板並包含 AI 引擎 +pnpm build # 建置預設工作區套件(不含桌面/行動裝置) +pnpm build:all # 建置所有套件(包含桌面/行動裝置) +pnpm dev dashboard # 執行儀表板 + AI 引擎 +pnpm dev:ui # 僅儀表板(不含 AI 引擎) +pnpm lint # 對所有套件執行 lint +pnpm typecheck # 對所有套件進行型別檢查 +pnpm test # 執行所有測試 +``` + +### 建置獨立執行檔 + +使用 [Bun](https://bun.sh/) 建置單一自包含的 `fn` 執行檔: + +```bash +pnpm build:exe # 為目前平台建置 +pnpm build:exe:all # 跨平台編譯所有平台 +``` + +--- + +## 授權條款 + +MIT——開放原始碼,無廠商綁定。請參閱 [LICENSE](./LICENSE)。 + +
+ +**[runfusion.ai →](https://runfusion.ai)** + +
diff --git a/docs/cli-reference.md b/docs/cli-reference.md index bf693aa305..cad8358f5b 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -207,8 +207,14 @@ fn dashboard --no-auth # disable bearer auth (local only) fn dashboard --interactive fn dashboard --paused fn dashboard --dev +fn dashboard --lang zh-TW # force a UI locale for this run ``` +The terminal UI is localized. `--lang ` (one of `en`, `zh-CN`, `zh-TW`, +`fr`, `es`, `ko`) takes precedence over the saved dashboard language setting and the +`LC_ALL`/`LC_MESSAGES`/`LANG`/`LANGUAGE` environment. See +[Localization contributor guide](./i18n-contributing.md). + | Option | Description | |---|---| | `--port`, `-p` | Dashboard HTTP port (default `4040`). | diff --git a/docs/contributing.md b/docs/contributing.md index d1f6cdcd4f..78c21adf59 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -237,6 +237,15 @@ Fusion can automatically extract insights from memory and prune transient conten See [Settings Reference](./settings-reference.md#background-memory-summarization--audit) for configuration details. +## Localization (i18n) + +User-facing strings are localized with react-i18next across both the dashboard +and the terminal UI. English is the source-of-truth; catalogs and shared config +live in the `@fusion/i18n` package. To translate, add a language, or wire new +strings, see the [Localization contributor guide](./i18n-contributing.md). When +adding user-facing copy, prefer `t("namespace:key", "English default")` over a +hardcoded string and run `pnpm i18n:extract` to register the key. + ## Dashboard CSS Organization The dashboard's CSS has been modularized: diff --git a/docs/i18n-contributing.md b/docs/i18n-contributing.md new file mode 100644 index 0000000000..14d0b28396 --- /dev/null +++ b/docs/i18n-contributing.md @@ -0,0 +1,73 @@ +# Localization (i18n) contributor guide + +Fusion's UI is localized with [react-i18next]. English (`en`) is the +source-of-truth language; everything else is a translation of it. Both UI +surfaces — the React dashboard and the Ink terminal UI — share one set of +catalogs and config in the `@fusion/i18n` package. + +## Where things live + +| Path | What it is | +| ---- | ---------- | +| `packages/i18n/locales/{locale}/{namespace}.json` | Authored catalogs (translators edit here). `en` is the source. | +| `packages/i18n/src/config.ts` | Shared i18next config: namespaces, fallback chain, plural setup. | +| `packages/core` (`SUPPORTED_LOCALES`, `Locale`) | The single list of supported locale codes. | +| `i18next.config.ts` (repo root) | `i18next-cli` workflow config. | + +Namespaces: `common` (shared), `app` (dashboard-only), `errors`, and `cli` +(terminal-only). The dashboard loads `common`/`app`/`errors`; the CLI loads +`common`/`cli`/`errors`. + +## The workflow + +All commands run from the repo root: + +```bash +pnpm i18n:extract # pull t()/ keys from source into the en catalogs +pnpm i18n:sync # propagate the en key structure to every other locale +pnpm i18n:types # regenerate key types from the en catalogs +pnpm i18n:status # per-locale completion report +pnpm i18n:lint # flag hardcoded user-facing strings +pnpm i18n:gen-cli # regenerate the CLI static catalog import map +``` + +## Translating an existing language + +1. Run `pnpm i18n:sync` so every catalog has the current `en` keys (untranslated + entries are empty strings). +2. Fill the empty strings in `packages/i18n/locales/{locale}/*.json`. +3. Keep interpolation placeholders verbatim: `{{brand}}`, `{{detail}}`, + `{{key}}`. Never translate a `[{{key}}]` keybinding accelerator — only the + words around it. +4. `pnpm i18n:status` to confirm the locale is complete. + +`zh-CN` and `zh-TW` are independent — different script **and** vocabulary. Do +not machine-convert one into the other. + +## Adding a new language (near-zero code) + +1. Add the locale code to `SUPPORTED_LOCALES` in `packages/core/src/types.ts` + and to `locales` in `i18next.config.ts`. +2. `pnpm i18n:sync` — scaffolds a full set of catalog files for the new locale + with the correct plural categories. +3. `pnpm i18n:gen-cli` — adds the locale to the CLI's static import map. +4. Translate the new catalogs, then `pnpm i18n:status` to verify. + +No feature code changes are required: the dashboard discovers the locale through +the generated `app/locales/` tree, and the CLI through the regenerated import +map. Add the language's endonym to `ENDONYMS` in +`packages/dashboard/app/components/LanguageSelector.tsx` so it appears in the +Settings switcher. + +## Using a non-English locale + +- **Dashboard / mobile:** Settings → Appearance → Language. The choice persists + to `localStorage` and to server settings. +- **Terminal UI:** resolved from `--lang ` → the saved dashboard language + setting → the `LC_ALL`/`LC_MESSAGES`/`LANG`/`LANGUAGE` environment → `en`. + + ```bash + fusion dashboard --lang zh-TW + ``` + +[react-i18next]: https://react.i18next.com/ diff --git a/docs/plans/2026-06-03-001-feat-ui-localization-i18n-plan.md b/docs/plans/2026-06-03-001-feat-ui-localization-i18n-plan.md new file mode 100644 index 0000000000..5ebd423e46 --- /dev/null +++ b/docs/plans/2026-06-03-001-feat-ui-localization-i18n-plan.md @@ -0,0 +1,428 @@ +--- +title: "feat: Add UI localization (i18n) across dashboard and terminal UI" +type: feat +status: completed +date: 2026-06-03 +deepened: 2026-06-03 +--- + +# feat: Add UI localization (i18n) across dashboard and terminal UI + +## Summary + +Stand up a react-i18next localization foundation that serves both Fusion UI surfaces — the React web dashboard (`packages/dashboard/app`, inherited by the Capacitor mobile wrapper) and the Ink terminal UI (`packages/cli`) — migrate user-facing strings into translation catalogs, ship four non-English locales (`zh-CN`, `zh-TW`, `fr`, `es`) atop an English source-of-truth base, and establish an `i18next-cli`-driven workflow so adding a future language is a near-zero-code, translate-only operation. + +--- + +## Problem Frame + +Fusion's UI is currently English-only with strings hardcoded inline across ~464 dashboard `.tsx` files and the Ink TUI components. There is **no i18n library anywhere** in the monorepo (greenfield — confirmed across `packages/` and `plugins/`), and locale-sensitive formatting at ~45 dashboard call sites relies on the implicit browser default (`toLocaleDateString(undefined, …)`), with zero `navigator.language` or `Intl.*` usage. + +Fusion's strategy targets a developer audience "across surfaces and machines," and the published CLI (`@runfusion/fusion`) plus the dashboard are the two surfaces users actually read. Supporting Simplified Chinese, Traditional Chinese, French, and Spanish — and lowering the cost of every future language — widens reach without betting the product on any one locale. Because this is greenfield, there is no prior library to reconcile or migrate away from; the cost is entirely in standing up the foundation and the one-time string extraction. + +--- + +## Requirements + +### Localization foundation + +- R1. A single localization runtime (`react-i18next` + `i18next`) powers both the dashboard and the Ink TUI from one shared catalog source-of-truth, with English as the source language. +- R2. Translation catalogs are organized as `{locale}/{namespace}.json` with nested, ID-style keys (not natural-language keys), split into namespaces so feature areas and the CLI-only surface can be loaded independently. +- R3. Supported locales are a single typed list — `en`, `zh-CN`, `zh-TW`, `fr`, `es` — defined once in `@fusion/core` and consumed by every surface. `en` is the fallback for all. +- R4. Pluralization uses i18next's native CLDR plural categories (via `Intl.PluralRules`); date/number/relative-time formatting uses i18next's built-in `Intl` formatters bound to the active locale. No ICU message format. + +### Dashboard (web + mobile) + +- R5. The dashboard resolves the active locale at startup with precedence `localStorage → navigator → en`, constrained to `supportedLngs`, and sets `document.documentElement.lang`. +- R6. Only the active locale's catalogs load on first paint; the other four locales are code-split and fetched on demand, consistent with the existing lazy-load/prefetch bundle discipline. +- R7. Users can change language from the Settings UI; the choice persists to `localStorage` and writes through to server-side `GlobalSettings.language`, mirroring the existing theme-preference pattern. +- R8. Locale-sensitive date/number formatting in the dashboard reflects the active i18n locale rather than the implicit browser default. + +### Terminal UI (CLI) + +- R9. The Ink TUI renders translated strings via the same library, using a separate Node-side i18next instance with statically bundled catalogs and synchronous init (first frame is localized). +- R10. The CLI resolves locale with precedence `--lang flag → persisted GlobalSettings → environment (LC_ALL/LANG/…) → en`. +- R11. CJK and accented text render without breaking the TUI's width-sensitive layouts; single-letter keybinding accelerators are never translated. + +### Translations and contributor workflow + +- R12. Complete `zh-CN`, `zh-TW`, `fr`, and `es` catalogs are shipped, each independently localized (no auto-conversion between the two Chinese scripts). +- R13. An `i18next-cli` workflow extracts keys from source, syncs missing/orphaned keys across all locales, generates key types, and reports per-locale completion; CI fails on missing keys, stale types, or incomplete catalogs. +- R14. Adding a new language requires no feature code beyond registering the locale code and providing translated catalogs; the procedure is documented for contributors. + +--- + +## Key Technical Decisions + +- KTD1. **Library: `react-i18next` + `i18next` v26 for both surfaces.** react-i18next is framework-agnostic and runs in Node, so the same stack powers the Vite SPA and the Ink React tree — no second i18n system. v26's built-in `Intl` formatter is always active and its native pluralization uses CLDR categories, covering our formatting and plural needs without `i18next-icu`. (Note v26 breaking changes: the legacy `interpolation.format` function is removed; `TFunction` imports from `i18next`, not `react-i18next`.) + +- KTD2. **Catalogs: `{locale}/{namespace}.json`, nested ID-style keys, multiple namespaces.** Namespaces are i18next's lazy-load unit, so splitting by feature area enables per-surface and per-route code-splitting (a `cli` namespace the web bundle skips; an `errors`/`common`/`app` split for the dashboard). ID-style keys (`settings.appearance.languageLabel`) survive English copy rewrites without orphaning translations — the maintainability the request asks for. English text lives as `defaultValue`/extraction, not as the key. + +- KTD3. **Single catalog source-of-truth in a dedicated `@fusion/i18n` package, consumed differently per surface.** Catalogs live in a new `packages/i18n` workspace package (`@fusion/i18n`) — *not* in `@fusion/core`. Putting presentation strings in the domain/settings root would be a layering inversion (core sits under engine and CLI and has no other UI-string responsibility). `@fusion/i18n` owns the authored `locales/{lng}/{ns}.json` source-of-truth, the shared i18next config (namespace list, fallback chain, plural setup), and namespace key types. It `import type`s `Locale` from `@fusion/core` (type-only, no runtime cycle); locale primitives and the persisted `GlobalSettings.language` field stay in core (KTD8). The dashboard lazy-loads the active locale via Vite code-splitting from catalogs generated into its own tree (KTD3a); the CLI statically inlines all catalogs directly from `@fusion/i18n` via tsup (`noExternal: [/^@fusion\//]` already bundles `@fusion/*` from source). Rejected alternatives: catalogs *authored* in `@fusion/core` (layering inversion — the domain root has no UI-string responsibility); catalogs *authored* in `packages/dashboard/app/locales/` and imported across the boundary by the CLI (dependency inversion — terminal UI reaching into the SPA's internals). Note these are distinct from KTD3a's primary wiring, which *generates* catalogs into the dashboard tree from the `@fusion/i18n` source — the dashboard never authors them and the CLI never imports the generated copy. The dashboard's i18n init calls `i18next-resources-to-backend` directly at the (app-relative) call site; no separate factory abstraction is introduced. + +- KTD3a. **Dashboard per-locale code-splitting requires a *relative*, package-local dynamic-import template; the authored source-of-truth stays in `@fusion/i18n` and is generated into the dashboard tree at build time.** Vite 6's variable-dynamic-import analysis (via `@rollup/plugin-dynamic-import-vars`) only code-splits `import(\`./locales/${lng}/${ns}.json\`)` when the prefix is relative *to the importing file* and each variable is exactly one path segment. An aliased, bare, or cross-package/workspace specifier in a *variable* `import()` defeats static analysis — Vite eager-bundles with a build warning or fails at runtime — and `import.meta.glob` refuses to cross the `node_modules` boundary. A relative template living inside `@fusion/i18n`'s own source would still resolve through the workspace symlink at the dashboard build; that *can* slip through but is **not a documented guarantee**, and the dashboard has zero existing variable-dynamic-import precedent to lean on. **Decision (primary wiring):** `@fusion/i18n` remains the single authored source-of-truth, but `i18next-cli sync` generates the catalog tree into a gitignored `packages/dashboard/app/locales/` (mirroring the engine `dist` convention — a `predev`/`prebuild` step in the dashboard package), and the dashboard's backend factory imports them with a plainly app-relative `import(\`./locales/${lng}/${ns}.json\`)`. This makes per-locale splitting *guaranteed* rather than dependent on undocumented symlink behavior. The cross-package symlink path (import template inside `@fusion/i18n`, no generation step) is recorded only as an optional optimization to prove out later, not the shipped path. The CLI is unaffected — tsup statically inlines catalogs directly from `@fusion/i18n` across the package boundary (KTD5). U3 keeps a build assertion that per-locale chunks emit, as a regression guard on the generated-catalog wiring. + +- KTD4. **Dashboard lazy-loading via `i18next-resources-to-backend` + dynamic `import()`.** Preferred over `i18next-http-backend` for a Vite SPA: hashed assets, offline-capable, no separate static-serving concern. Only the active locale's loaded namespaces touch the main path; switching language fetches the new chunk. Add a `vendor-i18n` `manualChunk` alongside the existing `vendor-react`/`vendor-xterm` splits. + +- KTD5. **CLI init is synchronous with statically bundled catalogs (`initImmediate: false`).** Lazy loading is pointless in Node; synchronous init guarantees the first rendered frame is already localized. The CLI gets its own i18next instance (no DOM, no HTTP backend, locale from env/flag/settings — not `localStorage`). + +- KTD6. **Tooling: `i18next-cli`, not `i18next-parser`.** `i18next-parser` was archived Feb 2026; `i18next-cli` (SWC-based) unifies `extract`, `sync`, `types`, `status`, and `lint`. Its AST-based `lint` for hardcoded strings is the primary guardrail (CI, warn-first), avoiding a noisy 464-file ESLint sweep. A scoped `eslint-plugin-i18next`/`no-restricted-syntax` rule is deferred (see Scope Boundaries) — the repo's existing `no-restricted-syntax` precedent makes it easy to add later if editor squiggles are wanted. + +- KTD7. **zh-CN and zh-TW are fully independent catalogs.** Different script *and* vocabulary — never auto-convert one to the other. Configure script-aware fallback (`zh-Hans→zh-CN`, `zh-Hant→zh-TW`, `zh→zh-CN`, default `en`) and keep `load: 'currentOnly'` so the two never collapse into a generic `zh`. Both have a single CLDR plural category (`other`); French and Spanish carry `one`/`many`/`other`. + +- KTD8. **Persisted-locale plumbing extends the existing theme-preference pattern.** Add `language?: Locale` to `GlobalSettings` in core (registered in `DEFAULT_GLOBAL_SETTINGS`, `GLOBAL_SETTINGS_KEYS`, schema/validation). Dashboard persistence mirrors `useTheme.ts`: a `localStorage` cache (using the neighbor-consistent `kb-dashboard-*` key prefix — do **not** pre-empt the kb→fn rename here) plus `updateGlobalSettings` write-through. The CLI reads the same `GlobalSettings.language` server-side. + +- KTD9. **Brand tokens stay as interpolation variables in catalogs.** Because the kb→fn rename is in flight, extract product-name occurrences as `{{brand}}`-style variables (or leave brand-only keys untranslated) so the rename can sweep them later without churning all five catalogs. + +--- + +## High-Level Technical Design + +### Surface and catalog topology + +```mermaid +flowchart TB + subgraph core["@fusion/core (domain/settings root)"] + LOC["Locale, SUPPORTED_LOCALES, DEFAULT_LOCALE,
GlobalSettings.language"] + end + + subgraph i18n["@fusion/i18n (new package — authored source-of-truth)"] + CAT["locales/{lng}/{ns}.json"] + CFG["shared config + generated cli import map"] + end + + subgraph dash["packages/dashboard/app (Vite SPA)"] + DI["i18n init (browser instance)"] + DP["I18nextProvider in App.tsx stack"] + SW["Language switcher (SettingsModal)"] + FMT["Intl formatters / toLocale* sites"] + end + + subgraph cli["packages/cli (Ink TUI)"] + CI["i18n init (Node instance, sync)"] + CP["I18nextProvider at Ink render()"] + end + + mobile["@fusion/mobile (Capacitor)"] + + LOC -.->|"import type Locale"| i18n + LOC --> DI & CI & SW + CAT -->|"i18next-cli sync → gitignored app/locales/
app-relative import() → per-locale chunks"| DI + CAT -->|"statically inlined via tsup (all locales)"| CI + DI --> DP --> FMT + CI --> CP + dash -->|"built dist inherited"| mobile +``` + +### Dashboard language-switch flow + +```mermaid +sequenceDiagram + participant U as User + participant S as SettingsModal (Appearance) + participant H as useLanguage hook + participant I as i18next (browser) + participant LS as localStorage + participant API as updateGlobalSettings + + U->>S: select locale (e.g. zh-TW) + S->>H: setLanguage("zh-TW") + H->>I: changeLanguage("zh-TW") + I-->>I: lazy-fetch zh-TW namespace chunk(s) + I-->>S: re-render translated tree + H->>LS: cache "zh-TW" (kb-dashboard-language) + H->>API: write-through GlobalSettings.language + H->>I: set document.documentElement.lang +``` + +### CLI locale resolution precedence + +```mermaid +flowchart LR + A["--lang flag"] -->|set| Z["active locale"] + A -->|unset| B["GlobalSettings.language"] + B -->|set| Z + B -->|unset| C["env LC_ALL/LC_MESSAGES/LANG/LANGUAGE"] + C -->|parsed & supported| Z + C -->|none| D["en (fallback)"] + D --> Z +``` + +--- + +## Output Structure + +New and notably-modified files (per-unit `Files` sections remain authoritative): + +``` +packages/ + i18n/ (new @fusion/i18n package — authored source-of-truth) + package.json (source export condition, JSON support) + locales/ (authored catalogs — translators edit here) + en/ common.json app.json errors.json cli.json + zh-CN/ common.json app.json errors.json cli.json + zh-TW/ ... + fr/ ... + es/ ... + src/ + config.ts (shared i18next config, namespace + key types) + cli-catalogs.ts (generated static import map for the CLI, from SUPPORTED_LOCALES) + index.ts + core/ + src/ + types.ts (+ Locale, SUPPORTED_LOCALES, DEFAULT_LOCALE, GlobalSettings.language) + settings-schema.ts (+ language default & key) + settings-validation.ts + index.ts (+ exports) + dashboard/ + app/ + locales/ (GITIGNORED — generated from @fusion/i18n by i18next-cli sync) + en/ … zh-CN/ … zh-TW/ … fr/ … es/ + i18n/ + index.ts (browser init: app-relative resources-to-backend, detector, formatters, fallback) + useLanguage.ts (switch + persist hook) + components/ + LanguageSelector.tsx + package.json (predev/prebuild → i18next-cli sync into app/locales) + vite.config.ts (vendor-i18n chunk) + cli/ + src/ + i18n/ + index.ts (Node sync init, static catalogs, env/flag detection) +i18next.config.ts (extract/sync/types/status/lint config) +docs/ + i18n-contributing.md (adding a language) +``` + +--- + +## Implementation Units + +Phased: **A. Foundation** (U1–U2) → **B. Dashboard** (U3–U5) → **C. Terminal UI** (U6–U7) → **D. Translations & workflow** (U8). Each unit is independently landable. + +### U1. Core locale primitives and settings field + +- Goal: Define the single source of locale truth and the persisted preference field in `@fusion/core`. +- Requirements: R3, R7 (settings field), R10 (shared field for CLI). +- Dependencies: none. +- Files: + - `packages/core/src/types.ts` — add `Locale` union, `SUPPORTED_LOCALES` tuple (`["en","zh-CN","zh-TW","fr","es"]`), `DEFAULT_LOCALE`, and `language?: Locale` on `GlobalSettings` (near line 2439, beside `dashboardFontScalePct`). Locale primitives must live in `types.ts` specifically — the dashboard Vite alias resolves `@fusion/core` to `types.ts` only. + - `packages/core/src/settings-schema.ts` — register `language` in `DEFAULT_GLOBAL_SETTINGS` (line ~18) so it flows into `GLOBAL_SETTINGS_KEYS`. + - `packages/core/src/settings-validation.ts` — validate `language` against `SUPPORTED_LOCALES`. + - `packages/core/src/index.ts` — export `Locale`, `SUPPORTED_LOCALES`, `DEFAULT_LOCALE`. + - `packages/core/src/__tests__/settings-schema.test.ts` (or matching existing settings test) — coverage. +- Approach: Pure type + constant additions; no runtime behavior beyond settings validation. `language` is optional so existing settings files remain valid (absence → resolve at runtime, not persisted default-en, to keep "follow the browser/env" behavior until the user chooses). +- Patterns to follow: `THEME_MODES`/`COLOR_THEMES` const tuples and the `themeMode`/`colorTheme` optional fields; `isGlobalSettingsKey` validation flow. +- Test scenarios: + - `SUPPORTED_LOCALES` contains exactly the five codes; `DEFAULT_LOCALE` is `en`. + - `isGlobalSettingsKey("language")` returns true; `language` appears in `GLOBAL_SETTINGS_KEYS`. + - Validation accepts each supported code and rejects an unsupported code (e.g. `"de"`, `"zh"`). + - A settings object without `language` round-trips through load/merge unchanged (backward compatibility). +- Verification: `@fusion/core` typechecks and its settings tests pass; the new symbols are importable from the barrel. + +### U2. `@fusion/i18n` package, catalog source-of-truth, and i18next-cli tooling + +- Goal: Create the `@fusion/i18n` package with shared config and authored `en` base catalogs, the generated CLI import map, and the extract/sync/types/status/lint workflow with a CI gate. +- Requirements: R1 (shared source), R2 (layout/keys/namespaces), R13 (tooling + CI), R14 (drop-in language config). +- Dependencies: U1. +- Files: + - `packages/i18n/package.json` — new `@fusion/i18n` workspace package; `source` export condition (so the CLI's tsup `conditions: ["source"]` inlines `.ts`/`.json` from source like other `@fusion/*`); JSON import support in its build. Zero runtime internal deps; `import type` only from `@fusion/core` for `Locale`. + - `packages/i18n/src/config.ts` (shared i18next config: namespace list, script-aware fallback chain, plural setup), `packages/i18n/src/index.ts`. + - `packages/i18n/src/cli-catalogs.ts` — **generated** static import map (one `import` per `{locale}/{ns}`) produced from `SUPPORTED_LOCALES` by a codegen step, so the CLI's static-bundle path (KTD5) gains a new locale with no hand-edited import block — this is what keeps R14's "near-zero-code" promise true for the terminal surface, not just the dashboard. + - `packages/i18n/locales/en/{common,app,errors,cli}.json` — initial namespaces (seeded from already-centralized constants like `COLUMN_LABELS`/`COLUMN_DESCRIPTIONS` as the first real keys). + - `packages/i18n/locales/{zh-CN,zh-TW,fr,es}/*.json` — scaffolded (synced) placeholders so structure exists before U8 fills them. + - `i18next.config.ts` (repo root) — `defineConfig` with `locales`, `extract.input` globs covering `packages/dashboard/app/**` and `packages/cli/src/**`, `extract.output` → `packages/i18n/locales/{{language}}/{{namespace}}.json`, `types.output`, per-input-tree default-namespace mapping (dashboard globs → `app`/`common`/`errors`; CLI globs → `cli`) so extracted keys land in the right namespace, and `lint` accepted tags/attrs to cut false positives. + - root `package.json` — scripts: `i18n:extract`, `i18n:sync`, `i18n:types`, `i18n:status`, `i18n:lint`, plus the CLI import-map codegen. + - `packages/cli/scripts/prepare-publish-manifest.mjs` — add `@fusion/i18n` to the private-dep strip list (alongside the existing `@fusion/core`/`@fusion/engine` handling) so `npm install @runfusion/fusion` does not 404 on the private workspace dep; declare `@fusion/i18n` as a CLI devDependency (inlined via `noExternal`), matching the existing pattern. + - CI workflow (existing `.github/workflows/*`) — add a job running `extract --ci`, `types --ci`, and `status`. (`lint` runs here too but is the same `i18next-cli lint` named the primary guardrail in KTD6 — not a duplicate ESLint pass.) + - `.changeset/*.md` — `@runfusion/fusion` minor (published surface gains i18n; `@fusion/i18n` is private/bundled, so no changeset for it per AGENTS.md). +- Approach: `en` is primary; `i18next-cli sync` scaffolds the other four with correct per-locale plural suffixes so contributors never hand-author plural categories. Keep the published-CLI footprint lean (`i18next` + `react-i18next` + `@fusion/i18n` catalogs only; tooling is devDependencies). **CI gate vs. incremental key growth:** because U5/U7 continuously add `en` keys (each re-opening gaps in the four locales), the 100%-completion gate (U8) must not deadlock CI during the migration window. Resolve by having `status` gate at 100% only for a tracked *shipped* set, with newly-added-but-untranslated keys allowed via an explicit pending-keys allowlist (or a per-namespace freeze) until U8 — `extract --ci` (no missing `en` key) and `types --ci` (no stale types) stay hard gates throughout. +- Patterns to follow: existing `@fusion/core` package shape (`source` export condition, tsc build); the engine `dist` gitignored-generated-artifact convention for the dashboard catalog generation (U3); existing root scripts and the docs-sync self-checking test idiom (`app/__tests__/lazy-loaded-views-docs.test.ts`). +- Test scenarios: + - `i18n:status` exits non-zero when a non-`en` catalog is missing a *shipped* key present in `en`; a key on the pending allowlist does not trip the gate. + - `i18n:extract --ci` exits non-zero when a `t()` key in source is absent from the `en` catalog. + - `i18n:sync` adds a newly-introduced `en` key to all four locales and removes an orphaned key from all; a dashboard-namespace key and a `cli`-namespace key route to their correct namespace files. + - Generated key types include a representative nested key and reject a typo'd key (compile-fail fixture). + - The generated `cli-catalogs.ts` import map contains exactly one entry per `SUPPORTED_LOCALES × namespace`; regenerating after adding a locale code adds its entries with no hand edit. + - Covers R13. Covers R14: adding a sixth locale code to `i18next.config.ts` + `SUPPORTED_LOCALES`, then running `sync` + codegen, produces a fully-scaffolded catalog set AND a CLI import map that picks up the locale — no hand-edited feature code on either surface. +- Verification: All `i18n:*` scripts run locally; the CI job is green with `en` populated and the four locales synced (even if untranslated, structure matches); `npm pack` on the CLI produces a manifest with no unresolved `@fusion/*` deps. + +### U3. Dashboard i18n runtime + +- Goal: Initialize the browser i18next instance with lazy catalog loading, detection, fallback, and Intl formatters; mount the provider. +- Requirements: R1, R4, R5, R6. +- Dependencies: U1, U2. +- Files: + - `packages/dashboard/app/i18n/index.ts` — init: `initReactI18next`, `i18next-browser-languagedetector` (order `localStorage → navigator → htmlTag`, `supportedLngs`, `caches: ['localStorage']`), `i18next-resources-to-backend` with an **app-relative** `import(\`./locales/${lng}/${ns}.json\`)` over the generated `app/locales/` tree (KTD3a), script-aware `fallbackLng` (KTD7), `load: 'currentOnly'`, and shared config imported from `@fusion/i18n`. + - `packages/dashboard/package.json` — `predev`/`prebuild` step running `i18next-cli sync` to generate `app/locales/` from the `@fusion/i18n` source (gitignored), mirroring the engine `dist` convention. + - `packages/dashboard/app/main.tsx` — import the i18n side-effect before `createRoot`; gate first paint on i18next `ready` (Suspense boundary or a top-level loading state) so the UI never renders raw keys during the first catalog fetch (avoids flash-of-untranslated-content); set `document.documentElement.lang` on `languageChanged`. + - `packages/dashboard/app/App.tsx` — wrap the provider stack (around lines 2044–2058) with `` so toasts/dialogs are translatable. + - `packages/dashboard/vite.config.ts` — add a `vendor-i18n` `manualChunk` for the `i18next`/`react-i18next` runtime. Note: catalogs are natural async chunks (not `node_modules`), so `manualChunks` needs **no** change to keep them split — record this as an explicit non-change. + - `packages/dashboard/app/i18n/__tests__/i18n.test.ts` — init/detection/fallback coverage. + - Build-assertion (the KTD3a verification gate): a check (test or build script) asserting per-locale catalog chunks are emitted to `dist/client/assets` and are NOT folded into the main/entry chunk. +- Approach: The active locale's namespaces load for first paint; other locales become separate chunks fetched on `changeLanguage`. The per-locale `import()` template is **app-relative** over the generated `app/locales/` tree (KTD3a), so Vite static-analyzes and splits it — no dynamic-string specifier or `@vite-ignore` in app code (AGENTS.md), and no dependency on undocumented cross-package symlink resolution. The build assertion is a regression guard that the split actually holds. First paint gates on i18next `ready` so no raw-key flash occurs (the catalog fetch is the only async step before the tree is translatable). +- Patterns to follow: `prefetchLazyViews()` idle-prefetch idiom and `React.lazy("./...")` relative-literal import style in `App.tsx` (the exact shape the locale `import()` mirrors); existing provider-nesting convention (`context/XContext.tsx` + `use*` hook); the engine `dist` gitignored-generated convention for `app/locales/`. +- Test scenarios: + - With no stored preference and `navigator.language = "fr"`, the resolved locale is `fr`; with `navigator.language = "de"` (unsupported), it falls back to `en`. + - A stored `localStorage` locale wins over `navigator`. + - `zh` (generic) resolves to `zh-CN` via fallback; `zh-Hant` resolves to `zh-TW`; `zh-CN` does not collapse to a generic `zh`. + - Switching to a not-yet-loaded locale triggers exactly one catalog fetch and re-renders translated text. + - A missing key in `fr` falls back to the `en` value, not the raw key. + - First paint shows the loading state (not raw keys) until the active catalog resolves. + - Build assertion: each non-`en` locale produces its own async chunk; the main entry chunk contains no non-`en` catalog payload. + - Covers R5, R6. +- Verification: Dashboard boots showing the loading state then the resolved locale (no raw-key flash); switching locale at runtime updates rendered strings; the build assertion confirms per-locale chunks exist and the initial chunk carries only the active locale. + +### U4. Dashboard language switcher and persistence + +- Goal: Let users pick a language in Settings and persist it across reloads and to the server. +- Requirements: R7. +- Dependencies: U3. +- Files: + - `packages/dashboard/app/hooks/useLanguage.ts` — read/set active locale; `localStorage` cache (`kb-dashboard-language`, neighbor-consistent prefix per KTD8) + `updateGlobalSettings({ language })` write-through; hydrate from `fetchGlobalSettings` on mount. + - `packages/dashboard/app/components/LanguageSelector.tsx` — option list modeled on `ThemeSelector.tsx` (`{value, label}` with native locale endonyms: 简体中文 / 繁體中文 / Français / Español / English). + - `packages/dashboard/app/components/SettingsModal.tsx` — render `LanguageSelector` in the Appearance section (case `"appearance"`, line ~3691, beside `ThemeSelector`). + - `packages/dashboard/app/hooks/__tests__/useLanguage.test.ts`, `packages/dashboard/app/components/__tests__/LanguageSelector.test.tsx` (lands in the `settings-*` test shard). +- Approach: Three-tier persistence exactly as `useTheme.ts`: instant `localStorage` pre-hydration read, server write-through, hydrate-from-server on mount. **Switching applies in place via `changeLanguage` — no full-page reload** (a reload would drop unsaved form state and disrupt in-flight agent views; the sequence diagram reflects this). This requires components to read copy through `useTranslation`/`t()` rather than caching resolved strings outside the React tree, so the re-render propagates. Endonyms are intentionally untranslated (each language names itself). Placement beside `ThemeSelector` in Appearance is the pragmatic home; if Settings grows a General/Preferences section later, language is a content (not visual) preference and would migrate there — noted, not blocking. +- Patterns to follow: `useTheme.ts` (three-tier persistence) and `ThemeSelector.tsx` (switcher UI); Appearance-section rendering in `SettingsModal.tsx`. +- Test scenarios: + - Selecting a locale calls `changeLanguage`, writes the `localStorage` key, and calls `updateGlobalSettings` once with the new code. + - Switching language updates rendered copy in place with no `window.location.reload` (assert no reload occurs). + - On mount, a server `GlobalSettings.language` value hydrates the active locale when no fresher `localStorage` value exists. + - `localStorage`-unavailable path degrades gracefully (no throw; server write still attempted). + - Selector shows all five endonyms and marks the active one. + - Covers R7. +- Verification: Changing language in Settings persists across a reload and is reflected in server settings; mobile (Capacitor) build inherits the switcher with no extra work. + +### U5. Dashboard string migration and locale-aware formatting + +- Goal: Replace hardcoded user-facing strings with `t()` keys and thread the active locale into date/number formatting — incrementally. +- Requirements: R8, and the dashboard portion of R2 (real keys in catalogs). +- Dependencies: U3, U4. +- Files (incremental — representative, not exhaustive): + - `packages/core/src/index.ts` consumers of `COLUMN_LABELS`/`COLUMN_DESCRIPTIONS` — route through i18n keys first (already centralized → cheapest win). + - `packages/dashboard/app/components/SettingsModal.tsx`, `ThemeSelector.tsx`, and Appearance/Settings copy — first migrated view cluster. + - High-traffic shells: `App.tsx` toast/error strings (e.g. lines ~1036, ~1327), primary navigation and board column UI. + - The ~45 `toLocale*` call sites (e.g. `ActivityFeed.tsx`, `AgentDetailView.tsx`, `ActivityLogModal.tsx`) — pass the active locale or route through a shared `formatDate`/`formatNumber` helper bound to i18next's Intl formatters. + - `packages/i18n/locales/en/*.json` — grows with each migrated cluster. +- Approach: **Incremental per-view migration**, starting with already-centralized constants and the Settings surface, then high-traffic views. Do not attempt a big-bang sweep of all 464 files in one unit — land clusters as separate commits under this unit. Keep diffs JSX-surgical (text → `t("key")`); do not disturb component CSS imports. Run `i18n:extract` after each cluster to keep `en` in sync. Brand tokens become `{{brand}}` variables (KTD9). +- Completion criterion (unit exit gate): this unit is done when a **named set of high-traffic/centralized surfaces** — board column UI (`COLUMN_LABELS`/`COLUMN_DESCRIPTIONS`), Settings, primary navigation, and `App.tsx` toast/error strings — are fully migrated and `i18n:status` reports the agreed coverage threshold for that named set. The low-traffic long tail is explicitly out of this unit (Scope Boundaries). Without this gate U5 has no reviewable done state; the threshold is the exit signal, not "all 464 files." +- Execution note: Lead each cluster by adding the keys to the `en` catalog (via `i18n:extract`) and a render test asserting the translated output, then swap the source strings. +- Patterns to follow: existing `useTranslation`-style hook usage; the centralized-constants pattern in core. +- Test scenarios: + - A migrated component renders the `en` value identical to its prior hardcoded string (no visible regression). + - The same component renders the `fr` value when locale is `fr` (fixture catalog). + - A date rendered via the shared helper formats per active locale (`en` vs `fr` vs `zh-CN` differ as expected). + - A pluralized string (e.g. "N tasks") selects the correct CLDR category in `en`, `fr`, and `zh-CN` (single `other`). + - A width-constrained component (board column header, sidebar item, badge/chip) with a long translated string (e.g. a ~35% longer `fr`/`de`-shaped fixture) truncates/wraps per its CSS rather than overflowing or breaking layout. + - Covers R8. +- Verification: Migrated clusters show no English regression in `en`; switching to a populated fixture locale changes the rendered copy and date/number formatting; width-constrained components hold their layout under longer strings; `i18n:status` hits the named-set threshold. + +### U6. CLI i18n runtime and CJK-safe rendering + +- Goal: Stand up the Node-side i18next instance for the Ink TUI with env/flag detection and width-safe layout. +- Requirements: R9, R10, R11. +- Dependencies: U1, U2. +- Files: + - `packages/cli/src/i18n/index.ts` — synchronous init (`initImmediate: false`), `initReactI18next`, catalogs from the **generated** `@fusion/i18n` `cli-catalogs.ts` import map (`cli` + shared namespaces; tsup inlines via existing `noExternal: [/^@fusion\//]` + `splitting: false`), `fallbackLng: 'en'`, env detection (`LC_ALL → LC_MESSAGES → LANG → LANGUAGE`). Using the generated map (not a hand-edited import block) is what makes a new locale drop-in here, satisfying R14 on the CLI surface. + - `packages/cli/src/commands/dashboard-tui/controller.ts` — wrap `DashboardApp` with `` at the `render(...)` call (line 685); resolve locale via precedence flag → `GlobalSettings.language` → env → `en`. + - `packages/cli/src/bin.ts` and the relevant command(s) — accept a `--lang` flag and pass it into init. + - Ink width handling: decide between **upgrading `ink` 6.8 → 7.0** (correct CJK double-width measurement built in) or staying on 6.8 with explicit `string-width` math at hand-built layout sites. If upgrading: bump `react`/`@types/react` in `packages/cli/package.json` from `^19.0.0` to `^19.2.0` to match Ink 7's declared peer floor, and add `string-width` only if staying on 6.8. See Risks for the trade-off. + - `packages/cli/src/i18n/__tests__/i18n.test.ts`, plus a TUI width/snapshot test. +- Execution note: **Spike first** — before committing the runtime, verify `useTranslation` re-renders on `changeLanguage` and `` interpolation behave under Ink's custom reconciler (not react-dom). The single-runtime decision (KTD1) assumes this works; there is no cited precedent. If `` misbehaves under Ink, prefer plain `t()` calls over `` in TUI components (the synchronous `initImmediate: false` init already avoids the Suspense path). +- Approach: Separate instance from the browser (no DOM/HTTP backend). Catalogs bundle into the published binary via tsup; keep them small. Detection precedence is explicit and unit-tested. Never translate single-letter keybinding accelerators (`C`/`V`/`X`/`P`/…) — translate only their labels. +- Patterns to follow: existing Ink render setup in `controller.ts`; existing command/flag parsing in `commands/`. +- Test scenarios: + - `--lang zh-TW` overrides a conflicting `GlobalSettings.language` and a conflicting `LANG` env value. + - With no flag and no setting, `LANG=fr_FR.UTF-8` resolves to `fr`; an unsupported `LANG=de_DE` falls back to `en`. + - First rendered frame is already localized (synchronous init — no English flash). + - `changeLanguage` under the Ink reconciler re-renders translated labels (validates the single-runtime assumption). + - A CJK-translated label in a bordered/columnar layout does not misalign borders (width measured as double-width). + - Keybinding accelerators remain ASCII single letters regardless of locale. + - Covers R9, R10, R11. +- Verification: `fusion` TUI launches localized per env/flag/settings; CJK labels render without breaking section layouts; a newly-added locale appears in the TUI after regen with no hand-edited CLI source; published CLI dependency footprint stays minimal. + +### U7. CLI string migration + +- Goal: Migrate Ink TUI user-facing labels into the `cli` (and shared) namespaces. +- Requirements: R12 readiness for the CLI surface; CLI portion of R2. +- Dependencies: U6. +- Files (representative): + - `packages/cli/src/commands/dashboard-tui/app.tsx` and TUI sub-components — `` literals → `t()`. + - `packages/cli/src/commands/dashboard-tui/state.ts` — `SECTION_ORDER`/section labels routed through keys. + - `packages/cli/src/commands/*.ts` — top-level CLI command output strings (help/status lines) as warranted. + - `packages/i18n/locales/en/cli.json` — grows with migrated keys. +- Approach: Same JSX-surgical discipline as U5. Translate labels and prose; leave accelerators, file paths, and special-cased QR/SVG payloads untouched. Run `i18n:extract` after each cluster. +- Patterns to follow: U5's migration approach; existing Ink component structure. +- Test scenarios: + - A migrated TUI screen renders identical `en` output to its prior hardcoded form. + - The same screen renders translated output under a fixture locale. + - Width-sensitive sections still align with the longest translated label (CJK fixture). + - Covers the CLI portion of R2. +- Verification: TUI screens render correctly in `en` and a populated fixture locale; `i18n:status` reflects `cli` namespace coverage. + +### U8. Translations and contributor workflow + +- Goal: Ship complete `zh-CN`, `zh-TW`, `fr`, `es` catalogs and document the drop-in language process. +- Requirements: R12, R14 (documentation), R13 (status gate enforced full). +- Dependencies: U5, U7 (catalogs must be key-complete before translation). +- Files: + - `packages/i18n/locales/{zh-CN,zh-TW,fr,es}/*.json` — filled translations (each independently localized; zh-CN and zh-TW never auto-converted). + - `docs/i18n-contributing.md` — "Adding a language" + "Updating translations" guide: the `i18next.config.ts` + `SUPPORTED_LOCALES` two-line registration, `i18n:sync` to scaffold, translate, `i18n:status` to verify. + - `docs/contributing.md` and `docs/cli-reference.md` — cross-link the i18n guide; document the `--lang` flag and the Settings language control. + - CI — flip the `status` gate to require 100% completion for the **shipped key set** per locale; newly-added migration keys land on the pending allowlist (U2) until translated, so adding `en` keys never deadlocks CI mid-migration. +- Approach: Translations may be sourced however the team prefers (in-house, vendor, community) — the unit's engineering deliverable is key-complete, plural-correct, structurally-synced catalogs plus the gate and docs. **Precondition:** because the 100% gate cannot pass without real translations, name the sourcing owner/path before U8 starts; until then the four locales stay on the pending allowlist (not "shipped") so the rest of the plan ships an English-only-but-localization-ready product without a red CI gate. Endonyms and brand `{{brand}}` variables handled per KTD9. +- Patterns to follow: existing `docs/` topical-guide structure. +- Test scenarios: + - `i18n:status` reports 100% for all four locales (CI gate passes). + - Each locale loads and renders in the dashboard and TUI without missing-key fallback to `en` for shipped namespaces. + - French/Spanish plural-bearing keys carry the `one`/`many`/`other` forms; both Chinese carry only `other`. + - Test expectation for the docs file: none -- documentation only. + - Covers R12, R14. +- Verification: All four locales render end-to-end on both surfaces; the "add a language" doc walks a contributor from zero to a synced catalog set with no feature-code edits. + +--- + +## Scope Boundaries + +In scope: the localization runtime for both surfaces, English extraction of user-facing strings (incremental), the four target locales, locale-aware formatting, persistence, and the contributor workflow. + +### Deferred to Follow-Up Work + +- A dedicated `eslint-plugin-i18next`/`no-restricted-syntax` editor-time guardrail for hardcoded strings (KTD6 uses `i18next-cli lint` in CI as the primary guard; the ESLint rule is additive polish and noisy across 464 files). +- Migrating the **long tail** of low-traffic dashboard views — U5 establishes the pattern and covers high-traffic/centralized surfaces; remaining views are mechanical follow-ups gated by `i18n:status` rather than blocking this plan. +- Server-side / API error message localization beyond what surfaces in the UI (the Express API in `packages/dashboard/src` is not a user-reading surface). +- RTL language support (Arabic/Hebrew) — none of the target locales are RTL; layout mirroring is out of scope until an RTL locale is requested. +- Switching the persisted-locale `localStorage` key from the `kb-` to `fn-` prefix — owned by the kb→fn rename track, not this plan (KTD8). + +### Outside this work + +- Translating documentation, marketing, or README content (this is product-UI localization). +- A translation-management SaaS integration (Locize, Crowdin, etc.) — the `i18next-cli` file-based workflow is the chosen path. + +--- + +## Risks & Dependencies + +- **Ink 6.8 → 7.0 upgrade for CJK width (U6).** Ink 7.0 measures CJK as double-width (via `string-width`) and fixes column/border alignment, but it also reworked input handling (a major bump needing a TUI regression pass) and raises the React peer floor to 19.2. Mitigation: prefer the upgrade for correctness with the React peer bump (U6); fallback is staying on 6.8 with explicit `string-width` math at hand-built layout sites if the input-handling changes prove disruptive. Decide early in U6; treat as the unit's primary risk. +- **Vite variable dynamic-import code-splitting (KTD3a/U3).** Vite 6 only code-splits a variable `import()` when the prefix is *relative to the importing file*; an aliased, bare, or cross-package specifier defeats `@rollup/plugin-dynamic-import-vars`, and `import.meta.glob` won't cross `node_modules`. The plan resolves this by making the **app-local generated-catalog path primary** (catalogs synced into a gitignored `app/locales/`, imported by a plainly app-relative template) rather than relying on undocumented cross-package symlink resolution. Residual risk: the dashboard has no existing variable-dynamic-import precedent, so U3 keeps a build assertion that per-locale chunks actually emit, as a regression guard before U5 builds on the runtime. +- **react-i18next under the Ink reconciler (KTD1/U6).** The single-runtime decision assumes `useTranslation`/`` work under Ink's custom (non-react-dom) reconciler; there is no cited precedent. Mitigation: U6 spikes this before committing the runtime; synchronous `initImmediate: false` init already sidesteps Suspense, and plain `t()` is the fallback if `` misbehaves. +- **CLI ships all locales in the published binary.** tsup `splitting: false` + `noExternal` inlines every catalog into `@runfusion/fusion`'s `dist/bin.js`, growing linearly with translation volume and locale count. Mitigation: accepted tradeoff for v1; keep the `cli` namespace separate so dashboard strings aren't dragged in; lazy fs-loading of copied catalog assets is a future optimization if size becomes material. +- **String-extraction surface is large (~464 dashboard files).** Mitigation: incremental per-view migration (U5/U7) with a named-set completion gate, not a big-bang sweep; the plan ships a working foundation + high-traffic coverage and defers the long tail. +- **kb→fn rename collision.** Touching user-facing strings during the in-flight rename risks churn. Mitigation: KTD9 (brand tokens as `{{brand}}` variables) and KTD8 (reuse `kb-` localStorage prefix) keep this plan rename-neutral. +- **Published-package resolution.** `@fusion/i18n` is a private workspace dep inlined into the published CLI; without stripping it from the publish manifest, `npm install @runfusion/fusion` would 404. Mitigation: U2 adds `@fusion/i18n` to `prepare-publish-manifest.mjs` and verifies via `npm pack`; core `i18next` + `react-i18next` only in the CLI runtime, tooling in devDependencies, plus the required changeset. +- **Translation sourcing & quality / zh-CN vs zh-TW.** The two Chinese catalogs must be independently localized; auto-conversion produces unnatural text (KTD7). The 100% CI gate cannot pass without real translations and every migrated `en` key re-opens locale gaps — mitigated by the pending-keys allowlist (U2/U8) and by naming a sourcing owner before U8 starts. Dependency: actual translation sourcing (process, not engineering). + +--- + +## Sources / Research + +- i18next v26 (built-in Intl formatter always active; legacy `interpolation.format` removed; `TFunction` from `i18next`) — i18next migration guide & TypeScript docs. +- `i18next-cli` (SWC-based extract/sync/types/status/lint) replaces the archived `i18next-parser` (archived Feb 2026) — i18next-cli GitHub. +- Lazy catalogs via `i18next-resources-to-backend` + Vite dynamic import — i18next "add or load translations"; lazy-loading guidance. +- Script-aware Chinese fallback + `load: 'currentOnly'` for zh-CN/zh-TW separation — i18next fallback principles, issue #1467. +- Ink 7.0 CJK/`string-width` rendering fixes — Ink GitHub; Ink 7.0 release writeup. +- Env-based CLI detection (`LC_ALL/LANG/…`) — `i18next-cli-language-detector`. +- Vite 6 variable-dynamic-import code-splitting rules (relative-prefix requirement, one `*` per segment, no alias/bare/node_modules resolution via `@rollup/plugin-dynamic-import-vars`; `import.meta.glob` cross-package limitation) — Vite Features docs; `vitejs/vite` issues #2390, #5728, #12180; `i18next-resources-to-backend` recommended loader shape (i18next docs). Drives KTD3a and the U3 build-assertion gate. +- `@fusion/i18n` as the catalog home (vs. `@fusion/core` layering inversion, vs. dashboard-app-tree dependency inversion) — repo seams: dashboard `@fusion/core` type-only alias `packages/dashboard/vite.config.ts:124`; CLI `noExternal: [/^@fusion\//]` + `splitting:false` + `conditions:["source"]` in `packages/cli/tsup.config.ts`; core `files:["dist","README.md"]` in `packages/core/package.json`. +- Repo seams: provider stack `packages/dashboard/app/App.tsx:2044`; settings `packages/core/src/types.ts:2433`, `packages/core/src/settings-schema.ts:18`; theme-persistence pattern `packages/dashboard/app/hooks/useTheme.ts`; Settings Appearance `packages/dashboard/app/components/SettingsModal.tsx:3691`; Ink mount `packages/cli/src/commands/dashboard-tui/controller.ts:685`; ESLint `no-restricted-syntax` precedent `eslint.config.mjs`; AGENTS.md changeset (published-only) and static-import rules. diff --git a/docs/settings-reference.md b/docs/settings-reference.md index 179225d0b2..e5e33abf8e 100644 --- a/docs/settings-reference.md +++ b/docs/settings-reference.md @@ -33,6 +33,7 @@ Defaults from `DEFAULT_GLOBAL_SETTINGS`; key scope from `GLOBAL_SETTINGS_KEYS`. |---|---|---:|---| | `themeMode` | `"dark" \| "light" \| "system"` | `"dark"` | Dashboard theme mode. | | `colorTheme` | `ColorTheme` | `"default"` | Dashboard color theme preset. | +| `language` | `"en" \| "zh-CN" \| "zh-TW" \| "fr" \| "es" \| "ko"` | `undefined` | UI language for the dashboard and TUI. When unset, the dashboard detects from localStorage → browser language and the CLI from `--lang` flag → environment locale, falling back to `en`. Validated at the store write boundary (`validateLocale`); invalid values are dropped. Reset to auto-detect via the dashboard's "Auto" language option or `fn settings set language auto` (clears the persisted key). | | `dashboardFontScalePct` | `number` | `100` | Dashboard font scale percentage used by Appearance settings. Valid range: `85` to `125`; applied pre-hydration via document root font-size so board typography (column headers/counts, task cards, and quick-entry text) scales with the setting from first paint. | | `defaultProvider` | `string` | `undefined` | Default AI provider. | | `defaultModelId` | `string` | `undefined` | Default AI model ID. | diff --git a/docs/solutions/architecture-patterns/i18n-foundation-vite-ink-monorepo-code-split-catalogs.md b/docs/solutions/architecture-patterns/i18n-foundation-vite-ink-monorepo-code-split-catalogs.md new file mode 100644 index 0000000000..bfd42abaa4 --- /dev/null +++ b/docs/solutions/architecture-patterns/i18n-foundation-vite-ink-monorepo-code-split-catalogs.md @@ -0,0 +1,185 @@ +--- +title: "i18n foundation for a Vite + Ink monorepo with code-split catalogs" +date: 2026-06-03 +category: architecture-patterns +module: "@fusion/i18n" +problem_type: architecture_pattern +component: tooling +severity: medium +related_components: + - "@fusion/i18n" + - "@fusion/core" + - dashboard + - cli +applies_when: + - "Adding i18n to a pnpm monorepo that ships both a Vite/React surface and an Ink/CJK TUI" + - "Code-split locale catalogs are needed and Vite dynamic-import-vars rejects cross-package or aliased specifiers" + - "A single source of truth for locale + namespace lists must be shared across packages" + - "Supporting Chinese locale pairs where zh-CN and zh-TW must never collapse into a generic zh" + - "Upgrading i18next to v26 (initImmediate removed; synchronous init with inline resources)" +symptoms: + - "Locale catalogs leak into the main bundle instead of code-splitting into per-locale chunks" + - "vi.mock of @fusion/core breaks CI after adding a new SUPPORTED_LOCALES export" + - "i18next v26 rejects initImmediate; convertDetectedLanguage silently ignored at top level" +tags: + - i18n + - vite + - ink + - react-i18next + - code-splitting + - monorepo + - cjk + - dynamic-import +--- + +# i18n foundation for a Vite + Ink monorepo with code-split catalogs + +## Context + +Fusion ships two UI surfaces from one pnpm monorepo: a React/Vite browser dashboard and an Ink-based terminal UI. The goal was full internationalization (en, zh-CN, zh-TW, fr, es) across both surfaces with `react-i18next` v17 / `i18next` v26, while keeping "add a new locale" a near-zero-code operation and ensuring per-locale catalogs never bloat the initial bundle. The two surfaces have different runtimes (browser with lazy code-splitting vs. Node with synchronous startup), so each builds its own `i18next` instance but they share locale list, namespace split, fallback chain, and base options from a single `@fusion/i18n` package. Shipped in PR #1352; this doc captures the load-bearing constraints and failure modes the plan and contributor guide do not cover. + +## Guidance + +**Single source of truth for namespaces.** `packages/i18n/namespaces.json` is the one file that defines which namespaces exist and which surface loads which subset. The runtime config and all three build scripts read it, so they can't drift: + +```json +{ "all": ["common","app","errors","cli"], + "dashboard": ["common","app","errors"], + "cli": ["common","cli","errors"] } +``` + +**Relative dynamic-import + sync-script pattern (dashboard code-splitting).** `@rollup/plugin-dynamic-import-vars` only splits a variable dynamic import if the specifier is app-relative with one variable per path segment. A cross-package or aliased specifier silently defeats it and inlines every catalog into the main bundle. So a predev/prebuild script (`packages/dashboard/scripts/sync-locales.mjs`) copies catalogs from `packages/i18n/locales/` into the gitignored `packages/dashboard/app/locales/`, and the runtime imports them app-relatively: + +```ts +// packages/dashboard/app/i18n/index.ts +i18next.use(resourcesToBackend((language: string, namespace: string) => + import(`../locales/${language}/${namespace}.json`))) +``` + +A build-time guard, `packages/dashboard/scripts/assert-locale-chunks.mjs`, derives the expected chunk count from the authored locale directory (no hardcoded count) and fails the build if any locale/namespace chunk is missing or catalog content leaks into `index-*.js`. The failure mode is silent otherwise — the guard is what makes the split durable. + +**`normalizeToSupportedLocale` — shared Chinese script/region routing.** One helper, used by both dashboard navigator detection (`convertDetectedLanguage`) and CLI env detection, so zh resolution is identical on both surfaces: + +```ts +// packages/i18n/src/config.ts +export function normalizeToSupportedLocale(tag: string): Locale | undefined { + if (!tag) return undefined; + const norm = tag.replaceAll("_", "-"); // POSIX zh_CN → zh-CN + if (isLocale(norm)) return norm; + const lower = norm.toLowerCase(); + if (lower.startsWith("zh")) { + if (lower.includes("hans")) return "zh-CN"; // explicit script wins over region (zh-Hans-HK) + if (lower.includes("hant") || lower.includes("-tw") || + lower.includes("-hk") || lower.includes("-mo")) return "zh-TW"; + return "zh-CN"; + } + const base = lower.split("-")[0]; // fr-FR → fr + return isLocale(base) ? base : undefined; +} +``` + +Paired with a script-aware fallback chain plus `load: "currentOnly"` in `baseInitOptions`, so `zh-CN`/`zh-TW` never collapse into a generic `zh`: + +```ts +export const FALLBACK_LNG = { "zh-Hans": ["zh-CN"], "zh-Hant": ["zh-TW"], + zh: ["zh-CN"], default: [DEFAULT_LOCALE] }; +``` + +**Three-tier persistence (`useLanguage`, mirrored from `useTheme`).** localStorage cache (`kb-dashboard-language`) + server write-through to `GlobalSettings.language` + hydrate-on-mount, with a `userSetRef` guard so in-flight hydration can't clobber a concurrent user choice, plus a cross-tab `storage` listener: + +```ts +// packages/dashboard/app/hooks/useLanguage.ts +const setLanguage = useCallback((locale: Locale) => { + userSetRef.current = true; // user choice now wins over hydration + void i18n.changeLanguage(locale); + localStorage.setItem(LANGUAGE_STORAGE_KEY, locale); + void updateGlobalSettings({ language: locale }).catch(/* warn, don't throw */); +}, [i18n]); + +// hydrate effect — the guard the ref protects: +void fetchGlobalSettings().then((settings) => { + if (cancelled || userSetRef.current) return; // never clobber a user choice + ... +}); +``` + +The write boundary is also guarded server-side in `packages/core/src/store.ts` via `validateLocale` (invalid values are dropped, never persisted). + +**CLI inline-resources init (synchronous startup).** The TUI bundles all catalogs statically via a generated `cliResources` map and inits synchronously, so the first Ink frame is already localized — no async backend, no flash of raw keys: + +```ts +// packages/cli/src/i18n/index.ts +void i18next.use(initReactI18next).init({ + ...baseInitOptions(), + lng: locale, + ns: [...CLI_NAMESPACES], + resources: cliResources as unknown as Resource, // inline → sync init + react: { useSuspense: false }, +}); +``` + +`cliResources` is generated by `packages/i18n/scripts/gen-cli-catalogs.mjs` from the `locales/` directory — adding a locale is "add the folder, regenerate, done." CLI locale precedence: `--lang` flag → `GlobalSettings.language` → env (`LC_ALL`/`LANG`/…) → `en`. + +**Locale primitives live in `packages/core/src/types.ts`.** The dashboard's Vite alias resolves the entire `@fusion/core` package to that single file: + +```ts +// packages/dashboard/vite.config.ts +"@fusion/core": resolve(__dirname, "../core/src/types.ts"), +``` + +Anything the dashboard imports from `@fusion/core` must be reachable from `types.ts` — `SUPPORTED_LOCALES`, `Locale`, `DEFAULT_LOCALE`, and `isLocale` were placed there, not in a new module. + +## What Didn't Work + +1. **`initImmediate: true` at top level** — rejected by i18next v26's `InitOptions` types. v26 removed the flag; with inline `resources` and no async backend, init is already synchronous, so the fix was to drop the option entirely. +2. **`convertDetectedLanguage` as a top-level `InitOptions` field** — silently ignored. It is an `i18next-browser-languagedetector` option and belongs inside the `detection` block. Moving it there made navigator normalization (e.g. `zh-Hant-TW` → `zh-TW`) actually fire. +3. **Vitest couldn't resolve `@fusion/core`** without a per-package alias-to-source — the dashboard's runtime Vite alias does not carry into the test runner, so each consuming package needed its own `vitest.config.ts` alias. +4. **CI shard 1: `vi.mock("@fusion/core")` in `settings.test.ts` was incomplete** — the hand-written mock lacked the newly added `SUPPORTED_LOCALES` export, so the locale enum resolved to `undefined` and the shard failed deterministically (initially misread locally as flaky). Lesson: a manual module mock is a second source of truth that must be updated alongside the real module's public surface. +5. **CI shard 2: `LanguageSelector.css` used the banned `--text-secondary` token** — the FN-4286 text-token-canonicalization guard rejects it; canonical is `--text-muted`. + +## Why This Matters + +- **Bundle-size correctness.** The relative-import + assert-chunks guard is the difference between lazily-fetched per-locale chunks and one fat main bundle carrying all five languages — and the regression is silent without the guard. +- **zh-CN / zh-TW correctness.** Simplified vs. Traditional Chinese are not interchangeable. The normalizer + script-aware fallback + `load: "currentOnly"` guarantee Traditional-script users never silently get Simplified. +- **Single source of truth prevents drift.** `namespaces.json` is read by config, sync-locales, assert-locale-chunks, and gen-cli-catalogs; chunk-count expectations are derived, not hardcoded. +- **Settings parity across surfaces.** Both surfaces detect via the same normalizer, persist to the same `GlobalSettings.language`, and validate at the same store boundary — a locale chosen in the dashboard carries into the TUI and vice versa. + +## When to Apply + +- Adding i18n to a Vite app that relies on code-splitting catalogs — the relative-import constraint and a chunk-leak guard apply directly. +- Supporting script/region-split language pairs (zh-CN/zh-TW, sr-Latn/sr-Cyrl) where a generic base tag must not collapse the variants. +- Terminal/CJK UIs: budget for double-width rendering (Ink 6.8→7.0 here) and prefer inline-resource synchronous init so the first frame is localized. +- Monorepos where catalogs live in a shared package but the consuming app's bundler only statically analyzes app-relative specifiers — copy into the app tree (gitignored) rather than importing cross-package. + +## Examples + +**Cross-package import that fails vs. app-relative that splits:** + +```ts +// ✗ defeats @rollup/plugin-dynamic-import-vars — all catalogs inline into main bundle +import(`@fusion/i18n/locales/${language}/${namespace}.json`) + +// ✓ app-relative, one var per segment — Vite emits one chunk per locale/namespace +import(`../locales/${language}/${namespace}.json`) +``` + +**i18next v26 migration:** + +```ts +// ✗ i18next ≤25 +i18next.init({ initImmediate: false, convertDetectedLanguage: normalize, ... }) + +// ✓ i18next 26: initImmediate gone (inline resources are sync anyway); +// convertDetectedLanguage lives in the languagedetector detection block +i18next.use(LanguageDetector).init({ + detection: { order: [...], convertDetectedLanguage: normalize }, + ... +}) +``` + +## Related + +- `docs/i18n-contributing.md` — the how-to guide for adding locales/strings (workflow; this doc covers the failure modes behind it) +- `docs/plans/2026-06-03-001-feat-ui-localization-i18n-plan.md` — the implementation plan (status: completed) +- GitHub issue #64 — "[i18n] Chinese (Simplified) Language Support for Dashboard" (originating request) +- PR #1352 — the implementation diff --git a/docs/solutions/architecture-patterns/mass-migration-agent-fleet-orchestration.md b/docs/solutions/architecture-patterns/mass-migration-agent-fleet-orchestration.md new file mode 100644 index 0000000000..a26f0942c1 --- /dev/null +++ b/docs/solutions/architecture-patterns/mass-migration-agent-fleet-orchestration.md @@ -0,0 +1,77 @@ +--- +title: "Orchestrating a mass code migration with an agent fleet" +date: 2026-06-04 +category: architecture-patterns +module: workflow-orchestration +problem_type: architecture_pattern +component: development_workflow +severity: medium +applies_when: + - "A mechanical change must land across hundreds of files (string migration, API rename, codemod-with-judgment)" + - "Many agents would otherwise contend on one shared artifact (catalog/registry/index file)" + - "Agent-made changes must be verified against a test suite with pre-existing local failures" +tags: + - multi-agent + - workflow + - i18n-migration + - test-triage + - structured-output +--- + +# Orchestrating a mass code migration with an agent fleet + +## Context + +The i18n full sweep (PR #1352) migrated ~6,900 strings across 216 files to i18next keys with 6-locale machine drafts, using ~190 subagents over three workflow rounds. The orchestration itself failed twice before working, and the verification phase initially looked like 1,051 test failures. These are the patterns that made it land. + +## Guidance + +**Partition by file ownership; size batches by work density, not file count.** Build file-disjoint batches from a scouted work-list (grep-count translatable strings per file); heavy files (here ≥40 hits) get a dedicated agent, light files get batched 3–8 per agent. No two agents ever own the same file → no worktree isolation or merge step needed. + +**Never let N agents write one shared artifact.** All 60 migrators needed to add keys to the same 20 catalog JSONs. Instead: each agent writes its own fragment file (`/tmp/frags/batch-N.json`) and the orchestrator merges deterministically afterward (with a quote-escaping repair pass — about 1 in 50 LLM-written JSON fragments has unescaped quotes inside values). + +**Keep the mechanical change behavior-invariant so tests stay meaningful.** Here: `t("key", "Exact original English")` inline defaults made `en` rendering byte-identical, so the existing suite verified the migration for free. + +**Pair every migrator with a read-only verifier, and require honesty fields.** A second-stage agent re-reads the files and reports residuals; the migrator schema includes `files_partial`/`files_skipped`. Round 1 verifiers found 457 residual strings the migrators had claimed done or silently skipped — that report became the exact work-list for round 2 (whose agents also got the regressed test names and self-verified by running them). + +**Workflow plumbing that failed before it worked:** +- All 60 agents "completed without calling StructuredOutput" → the prompt must say the FINAL action is the StructuredOutput call and that ending without it discards the work. +- `args` can arrive JSON-stringified → parse defensively: `const A = typeof args === 'string' ? JSON.parse(args) : args`. +- A "loader agent" asked to read the work-list file returned an empty list — pass payloads inline in args, don't delegate orchestration inputs to an agent. +- Concurrency cap below the runtime default: chunked `parallel()` groups with a barrier per chunk (`for (i; i += CHUNK) await parallel(group...)`). + +**Triage agent-caused test failures with a clean-baseline diff, not absolute counts.** Run the suite on the branch AND on a clean `origin/main` worktree in the same environment; only the set difference is yours. Here 276 local failures shrank to 23 real regressions (the rest were local-environment fake-timer/`waitFor` hangs that CI's Linux runners never see). Without the baseline, days would have been wasted "fixing" pre-existing noise — with it, CI went green on the first push of the full sweep. + +## Why This Matters + +Fleet output quality is bimodal: most batches are clean, a predictable tail is partial or subtly wrong (flattened inline JSX markup, helper functions left unmigrated, hook added above an early return). The verify-stage + honesty-fields + round-2 loop converts that tail from "silent regressions" into a bounded, enumerable work-list. And the baseline-diff discipline keeps the operator from drowning in failures the fleet didn't cause. + +## When to Apply + +- Any 100+-file mechanical migration where per-file judgment is still needed (so a codemod alone won't do). +- Whenever multiple agents must contribute entries to one registry/catalog/index — fragment-and-merge, never shared writes. +- Any time a large agent-made diff meets a test suite that isn't green locally — build the clean-baseline failure set first. + +## Examples + +Migrator/verifier pipeline stage shape (workflow script): + +```js +const results = await pipeline(batches, + (b) => agent(migratePrompt(b), { schema: MIGRATE_SCHEMA, model: big(b) ? 'sonnet' : 'haiku' }), + (m, b) => m && agent(verifyPrompt(b, m), { schema: VERIFY_SCHEMA, model: 'haiku' }) + .then((v) => ({ b, m, v }))) +``` + +Baseline-diff triage: + +```bash +git worktree add /tmp/main-probe origin/main && (cd /tmp/main-probe && pnpm i && vitest run > baseline.txt) +# delta = failures(branch) − failures(baseline) → only fix the delta +``` + +## Related + +- `docs/solutions/ui-bugs/skill-autocomplete-highlight-reset-on-swr-revalidation.md` — the "N stabilization passes means product race" rule used during triage +- AGENTS.md → "Fix the Invariant, Not the Repro (FN-5893)" +- PR #1352 — the i18n full sweep this pattern shipped diff --git a/docs/solutions/ui-bugs/skill-autocomplete-highlight-reset-on-swr-revalidation.md b/docs/solutions/ui-bugs/skill-autocomplete-highlight-reset-on-swr-revalidation.md new file mode 100644 index 0000000000..068eaa39ed --- /dev/null +++ b/docs/solutions/ui-bugs/skill-autocomplete-highlight-reset-on-swr-revalidation.md @@ -0,0 +1,120 @@ +--- +title: "Skill autocomplete highlight reset on SWR cache revalidation" +date: 2026-06-03 +category: ui-bugs +module: packages/dashboard/app/components/ChatView +problem_type: ui_bug +component: frontend_stimulus +symptoms: + - "Open slash-skill autocomplete menu loses keyboard highlight position when SWR cache revalidation lands mid-interaction" + - "ChatView arrow-navigation test fails intermittently on CI shards: expected chat-skill-menu-item--highlighted class missing" + - "Test passes locally but flakes on slow CI; three prior stabilization commits (FN-5864, FN-5745, FN-5725) patched symptoms without finding the cause" + - "Highlight resets to index 0 whenever useDiscoveredSkillsCache re-delivers a content-identical list with a fresh array identity" +root_cause: async_timing +resolution_type: code_fix +severity: medium +related_components: + - testing_framework +tags: + - swr-cache + - react-useeffect + - array-identity + - flaky-test + - async-race + - highlight-state + - test-isolation + - chatview +--- + +# Skill autocomplete highlight reset on SWR cache revalidation + +## Problem + +A recurring "flaky" CI test in the Fusion dashboard — ArrowUp in the slash-skill menu failing to highlight the wrapped-to-last item — was root-caused as a real product bug, not a test-environment quirk: the SWR skills cache re-delivers content-identical skill lists with fresh array *identities*, and a highlight-reset `useEffect` keyed on that identity wiped the user's (and the test's) keyboard position whenever a revalidation landed mid-navigation. Fixed in commit `87d044f18`. + +## Symptoms + +- CI shard intermittently failed asserting a menu item carried the `chat-skill-menu-item--highlighted` class after `ArrowUp` (expected wrap to the last item); the class was missing. +- Passed locally every run; the failure only surfaced on CI shards. +- A repeat-stabilization history: the same test family (`packages/dashboard/app/components/__tests__/ChatView.test.tsx`) had been "stabilized" three separate times without the flake going away — a tell-tale sign the cause was upstream of the assertions. + +## What Didn't Work + +The initial instinct — treat it as a flaky environment and rerun the shard — only masked it, because the race window simply didn't reopen every run. Three prior commits each patched the *test*, never the product: + +- **FN-5725** (`158f74962`, "streamline ChatView room-creation and slash-autocomplete tests") — reduced setup and tightened slash-autocomplete assertions; a net deletion of test code. Touched assertions/structure only. +- **FN-5745** (`8e2c19285`, "optimize ChatView agent-mentions test timing") — swapped to a local user-event instance and replaced async DOM lookup with immediate assertion. Pure timing/interaction tuning. +- **FN-5864** (`04e1701d9`, "stabilize ChatView skill-menu keyboard assertions") — wrapped the post-`ArrowUp` highlighted-option assertion in `waitFor` to avoid synchronous timing races. + +None could fix it: `waitFor` retries an assertion, but here a *later* async event (revalidation) actively resets state back to `0` after the highlight is correct, so waiting longer can land on the wrong side of the reset. The bug was a product state race, and no amount of assertion/timing massaging in the test addresses product state. + +## Solution + +Key the reset effect on a *semantic* derived value (the joined skill-id list) instead of array identity. `packages/dashboard/app/components/ChatView.tsx`: + +Before: + +```tsx +useEffect(() => { + setHighlightedSkillIndex(0); +}, [filteredSkills]); +``` + +After: + +```tsx +const filteredSkillsKey = useMemo( + () => filteredSkills.map((skill) => skill.id).join(" "), + [filteredSkills], +); +useEffect(() => { + setHighlightedSkillIndex(0); +}, [filteredSkillsKey]); +``` + +Now the effect only fires when the *contents* of the skill list change, so an identity-only revalidation no longer resets the keyboard position. + +**Regression test technique** (`ChatView.test.tsx`, "keeps the keyboard highlight when revalidation re-delivers an identical skill list"): seed the SWR cache so the menu renders from cache, defer the revalidation fetch behind a manually-held resolver, navigate, then resolve with identical content but a fresh identity and assert the highlight survives: + +```tsx +writeCache(`${SWR_CACHE_KEYS.DISCOVERED_SKILLS_PREFIX}proj-123`, skillsList); +let resolveFetch!: (skills: DiscoveredSkill[]) => void; +mockFetchDiscoveredSkills.mockImplementationOnce( + () => new Promise((resolve) => { resolveFetch = resolve; }), +); +// ... open menu, ArrowUp to /gamma/, assert it's highlighted ... +await act(async () => { + resolveFetch(JSON.parse(JSON.stringify(skillsList)) as DiscoveredSkill[]); +}); +expect(screen.getByRole("option", { name: /gamma/i })) + .toHaveClass("chat-skill-menu-item--highlighted"); +``` + +The `JSON.parse(JSON.stringify(...))` is the key move: same content, new object identities — exactly what the SWR layer produces. The test fails on the old identity-keyed reset in all three vitest projects. + +## Why This Works + +React `useEffect` dependency comparison is `Object.is` (reference identity), not deep equality. `filteredSkills` is a fresh array on every identity-changing render, so the old effect re-ran on churn and re-fired `setHighlightedSkillIndex(0)`. The derived `filteredSkillsKey` is a string; it is `Object.is`-equal across identity-only churn, so the effect stays inert until the actual skill set changes. + +The identity churn comes from three places in the SWR layer: + +- **Re-parse on read** — `swrCache.ts` `readCache` does `JSON.parse(raw)` every call, minting a brand-new object graph each time (`useDiscoveredSkillsCache` reads via `readCachedSkills` repeatedly: in state init, in the effect, for `loading`, and for `hasCachedStateRef`). +- **Fresh array on notify** — revalidation calls `notifyListeners(projectKey, nextSkills)` delivering a newly-fetched array to every subscriber, replacing the in-state array with a new identity even when contents match. +- **Module-level shared maps** — `inflightByProject` and `listenersByProject` are module-scoped `Map`s, so revalidation state bleeds across renders and, in tests, across cases sharing the module — making a stray revalidation more likely to fire at an inconvenient moment. + +**Why CI-only:** the reset is a genuine race between the keypress-driven highlight and an async revalidation. Slower, more contended CI shards widen the window between "ArrowUp set the highlight" and "the assertion reads it," giving the revalidation room to land in between and zero it out. Fast local machines almost always finish the assertion before revalidation resolves. + +## Prevention + +- **Never key a state-reset `useEffect` on the identity of an array/object that originates from an SWR/cache hook.** Cache layers legitimately hand back content-identical-but-new references. Key the effect on a derived *semantic* value (`xs.map(x => x.id).join(" ")`, a count, a hash) so it fires only on real content change. +- **Treat "this test needed N stabilization passes" as a product-race smell, not a timing smell.** Three assertion/timing patches that don't stick means the test is correctly catching a real race; stop patching the test and find the state mutation that fights it. Resist the "flaky env, just rerun" reflex. (This is the AGENTS.md "Fix the Invariant, Not the Repro" rule, FN-5893, applied to flake triage.) +- **Identity-churn regression pattern (reusable):** seed the cache (`writeCache`), defer the revalidation fetch behind a captured `resolve`, drive the user interaction, then resolve with `JSON.parse(JSON.stringify(original))` to simulate identical-content/new-identity revalidation landing mid-interaction, and assert the user-state invariant holds. This deterministically reproduces a race that only flaked under CI timing. +- **Grep heuristic** for other reset effects fed by cache/array identity: `git grep -nE -A1 'set\w*Index\(0\)'` (search the setter-call line; the dep array is on the following line) and inspect any dep that is a memoized array from a cache/SWR hook. The reset effects span multiple lines, so a single-line `useEffect(...)` pattern matches nothing — search the setter call, not the hook call. This audit at fix time found the same bug class in `QuickChatFAB.tsx` (fixed alongside), while `setMentionHighlightIndex` in both components is keyed on `[mentionFilter, mentionPopupVisible]` — primitives — so the bug class does not apply there. That is the shape to keep: reset on primitive/semantic inputs, never on a cached array's identity. + +## Related Issues + +- AGENTS.md → "Standing Rule: Fix the Invariant, Not the Repro (FN-5893)" — this fix is a direct application of that rule to flaky-test triage. +- `docs/testing.md` — fake-timer guidance covers timer flakes; this doc covers the *identity-churn* flake class. +- Prior stabilization attempts: FN-5864 (`04e1701d9`), FN-5745 (`8e2c19285`), FN-5725 (`158f74962`). +- Distinct from the engine timeout-flake family (FN-5573/FN-5542/FN-5518) — those are real-timer/subprocess timeouts, a different class. +- Fix: commit `87d044f18` on PR #1352. diff --git a/i18next.config.ts b/i18next.config.ts new file mode 100644 index 0000000000..a57acc83c5 --- /dev/null +++ b/i18next.config.ts @@ -0,0 +1,46 @@ +import { + defineConfig, + recommendedAcceptedAttributes, + recommendedAcceptedTags, +} from "i18next-cli"; + +/** + * i18next-cli workflow config for the whole monorepo. + * + * - `extract` pulls t()/ keys from the dashboard and CLI source into the + * authored `en` catalogs under @fusion/i18n. + * - `sync` propagates the `en` key structure to the four other locales. + * - `types` regenerates key types from the `en` catalogs. + * - `status` reports per-locale completion (CI gate). + * - `lint` flags hardcoded user-facing strings (primary guardrail). + * + * Namespaces are routed by the `ns:` prefix in keys / `useTranslation(ns)` in + * source, not by file path. `common` is the default namespace. + */ +export default defineConfig({ + locales: ["en", "zh-CN", "zh-TW", "fr", "es", "ko"], + extract: { + input: [ + "packages/dashboard/app/**/*.{ts,tsx}", + "packages/cli/src/**/*.{ts,tsx}", + "!**/__tests__/**", + "!**/*.test.*", + ], + output: "packages/i18n/locales/{{language}}/{{namespace}}.json", + primaryLanguage: "en", + defaultNS: "common", + keySeparator: ".", + nsSeparator: ":", + // Untranslated secondary-locale keys stay empty so `status` can measure + // real completion; the active locale falls back to `en` at runtime. + defaultValue: "", + }, + types: { + input: ["packages/i18n/locales/en/*.json"], + output: "packages/i18n/src/i18next-resources.d.ts", + }, + lint: { + acceptedTags: recommendedAcceptedTags, + acceptedAttributes: recommendedAcceptedAttributes, + }, +}); diff --git a/package.json b/package.json index 7580556bdf..34a91cf147 100644 --- a/package.json +++ b/package.json @@ -46,6 +46,12 @@ "test:coverage:dashboard": "pnpm --filter @fusion/dashboard exec vitest run --silent=passed-only --reporter=dot --coverage", "test:slow-cli": "pnpm --filter @runfusion/fusion test:slow-cli", "typecheck": "pnpm -r --filter=!@fusion/desktop --filter=!@fusion/mobile typecheck", + "i18n:extract": "i18next-cli extract", + "i18n:sync": "i18next-cli sync", + "i18n:types": "i18next-cli types", + "i18n:status": "i18next-cli status", + "i18n:lint": "i18next-cli lint", + "i18n:gen-cli": "pnpm --filter @fusion/i18n gen:cli-catalogs", "changeset": "changeset", "version": "changeset version", "release": "node scripts/release.mjs", @@ -85,6 +91,7 @@ "@eslint/js": "^9.0.0", "eslint": "^9.0.0", "fast-glob": "^3.3.3", + "i18next-cli": "^1.59.1", "react-devtools-core": "^7.0.1", "tsx": "^4.19.0", "typescript": "^5.7.0", diff --git a/packages/cli/package.json b/packages/cli/package.json index 784b1aace3..c314eff427 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -60,13 +60,15 @@ "@earendil-works/pi-coding-agent": "^0.78.0", "dockerode": "^4.0.12", "express": "^5.1.0", - "ink": "^6.8.0", + "i18next": "^26.3.1", + "ink": "^7.0.5", "ink-spinner": "^5.0.0", "ink-text-input": "^6.0.0", "ioredis": "^5.6.0", "multer": "^2.1.1", "node-pty": "npm:@homebridge/node-pty-prebuilt-multiarch@^0.13.1", - "react": "^19.0.0" + "react": "^19.2.0", + "react-i18next": "^17.0.8" }, "peerDependencies": { "@earendil-works/pi-ai": "*", @@ -88,10 +90,11 @@ "@fusion/core": "workspace:*", "@fusion/dashboard": "workspace:*", "@fusion/engine": "workspace:*", + "@fusion/i18n": "workspace:*", "@fusion/pi-claude-cli": "workspace:*", "@fusion/pi-llama-cpp": "workspace:*", "@types/node": "^22.0.0", - "@types/react": "^19.0.0", + "@types/react": "^19.2.0", "@vitest/coverage-v8": "^3.1.0", "cross-env": "^7.0.0", "esbuild": "^0.25.12", diff --git a/packages/cli/scripts/prepare-publish-manifest.mjs b/packages/cli/scripts/prepare-publish-manifest.mjs index a19a9d523f..8a872f646d 100644 --- a/packages/cli/scripts/prepare-publish-manifest.mjs +++ b/packages/cli/scripts/prepare-publish-manifest.mjs @@ -8,6 +8,7 @@ export function applyPrepackTransform(pkg) { delete devDependencies["@fusion/core"]; delete devDependencies["@fusion/dashboard"]; delete devDependencies["@fusion/engine"]; + delete devDependencies["@fusion/i18n"]; delete devDependencies["@fusion/pi-claude-cli"]; delete devDependencies["@fusion/pi-llama-cpp"]; delete devDependencies["@fusion-plugin-examples/roadmap"]; diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.ts index 4ade1a74a9..781e5b8275 100644 --- a/packages/cli/src/bin.ts +++ b/packages/cli/src/bin.ts @@ -431,6 +431,7 @@ Options: --interactive Interactive mode (port selection for dashboard, issue selection for import) --paused Start with engine paused (automation disabled) --dev Start dashboard only (no AI engine) + --lang Terminal-UI locale for this run (en, zh-CN, zh-TW, fr, es, ko); the browser dashboard resolves its own language --attach Attach file(s) on task create (repeatable) --depends Declare dependency on task create (repeatable) --no-dedup Bypass deterministic duplicate guard on task create @@ -748,7 +749,18 @@ async function main() { const noAuth = args.includes("--no-auth"); const dashTokenIdx = args.indexOf("--token"); const token = dashTokenIdx !== -1 && dashTokenIdx + 1 < args.length ? args[dashTokenIdx + 1] : undefined; - await runDashboard(port, { paused, dev, interactive, host, noAuth, token }); + const dashLangIdx = args.indexOf("--lang"); + const lang = dashLangIdx !== -1 && dashLangIdx + 1 < args.length ? args[dashLangIdx + 1] : undefined; + if (lang !== undefined) { + // Fail loudly on a bad explicit flag instead of silently falling back + // to setting/env resolution inside the TUI. + const { isLocale, SUPPORTED_LOCALES } = await import("@fusion/core"); + if (!isLocale(lang)) { + console.error(`Invalid --lang "${lang}". Supported: ${SUPPORTED_LOCALES.join(", ")}`); + process.exit(1); + } + } + await runDashboard(port, { paused, dev, interactive, host, noAuth, token, lang }); break; } diff --git a/packages/cli/src/commands/__tests__/settings.test.ts b/packages/cli/src/commands/__tests__/settings.test.ts index a0755b2b1c..b1b82659d6 100644 --- a/packages/cli/src/commands/__tests__/settings.test.ts +++ b/packages/cli/src/commands/__tests__/settings.test.ts @@ -25,6 +25,7 @@ vi.mock("@fusion/core", () => { return { GlobalSettingsStore: vi.fn(), DEFAULT_SETTINGS, + SUPPORTED_LOCALES: ["en", "zh-CN", "zh-TW", "fr", "es", "ko"], resolveWorktrunkSettings: (globalValue: any, projectValue: any) => ({ enabled: projectValue?.enabled ?? globalValue?.enabled ?? false, ...(projectValue?.binaryPath ?? globalValue?.binaryPath ? { binaryPath: projectValue?.binaryPath ?? globalValue?.binaryPath } : {}), @@ -155,6 +156,34 @@ describe("settings commands", () => { expect(resolveProject).not.toHaveBeenCalled(); }); + it("runSettingsSet language persists a supported locale globally", async () => { + const updateSettings = vi.fn().mockResolvedValue(makeSettings({ language: "zh-TW" } as any)); + const getSettings = vi.fn().mockResolvedValue(makeSettings({ language: "zh-TW" } as any)); + (GlobalSettingsStore as unknown as ReturnType).mockImplementation(() => ({ + init: vi.fn().mockResolvedValue(undefined), + updateSettings, + getSettings, + })); + + await runSettingsSet("language", "zh-TW"); + + expect(updateSettings).toHaveBeenCalledWith({ language: "zh-TW" }); + }); + + it("runSettingsSet language auto clears the persisted locale (null-as-delete)", async () => { + const updateSettings = vi.fn().mockResolvedValue(makeSettings({})); + const getSettings = vi.fn().mockResolvedValue(makeSettings({})); + (GlobalSettingsStore as unknown as ReturnType).mockImplementation(() => ({ + init: vi.fn().mockResolvedValue(undefined), + updateSettings, + getSettings, + })); + + await runSettingsSet("language", "auto"); + + expect(updateSettings).toHaveBeenCalledWith({ language: null }); + }); + it("runSettingsSet with project updates project-only settings", async () => { const updateSettings = vi.fn().mockResolvedValue(makeSettings({ maxConcurrent: 6 })); const getSettings = vi.fn().mockResolvedValue(makeSettings({ maxConcurrent: 6 })); diff --git a/packages/cli/src/commands/dashboard-tui/__tests__/app.test.tsx b/packages/cli/src/commands/dashboard-tui/__tests__/app.test.tsx index 71c55544c7..afd9a1c615 100644 --- a/packages/cli/src/commands/dashboard-tui/__tests__/app.test.tsx +++ b/packages/cli/src/commands/dashboard-tui/__tests__/app.test.tsx @@ -1,7 +1,9 @@ import React from "react"; import { describe, it, expect, vi, afterEach } from "vitest"; import { render } from "ink-testing-library"; +import { I18nextProvider } from "react-i18next"; import { DashboardApp } from "../app.js"; +import { initCliI18n } from "../../../i18n/index.js"; import { DashboardTUI } from "../controller.js"; import { createInitialState } from "../state.js"; import type { ProjectItem, TaskItem, AgentItem, AgentDetailItem, ModelItem, SettingsValues, TaskDetailData } from "../state.js"; @@ -10,8 +12,17 @@ function newController(): DashboardTUI { return new DashboardTUI(); } +// Initialize the real CLI i18n instance so t() interpolation runs in tests — +// without a provider, react-i18next's fallback returns defaults with literal +// {{placeholders}}. Mirrors the production wrap in controller.render(). +const testI18n = initCliI18n("en"); + function renderDashboardAppNode(controller: DashboardTUI) { - return React.createElement(DashboardApp, { controller }); + return React.createElement( + I18nextProvider, + { i18n: testI18n }, + React.createElement(DashboardApp, { controller }), + ); } function makeSystemInfo() { diff --git a/packages/cli/src/commands/dashboard-tui/app.tsx b/packages/cli/src/commands/dashboard-tui/app.tsx index b9d1c18f2a..ebb51aceb0 100644 --- a/packages/cli/src/commands/dashboard-tui/app.tsx +++ b/packages/cli/src/commands/dashboard-tui/app.tsx @@ -2,6 +2,8 @@ import React, { useState, useSyncExternalStore, useCallback, useEffect, useRef } import { Box, Text, useInput, useApp, useStdout } from "ink"; import Spinner from "ink-spinner"; import TextInput from "ink-text-input"; +import { useTranslation } from "react-i18next"; +import type { TFunction } from "i18next"; import { spawn } from "node:child_process"; import { appendFileSync } from "node:fs"; @@ -220,6 +222,7 @@ const LARGE_LOGO_MIN_COLS = 70; const LARGE_LOGO_MIN_ROWS = 16; function SplashScreen({ loadingStatus, updateStatus }: { loadingStatus: string; updateStatus: UpdateStatus | null }) { + const { t } = useTranslation("cli"); const { stdout } = useStdout(); const cols = stdout?.columns ?? 80; const rows = stdout?.rows ?? 24; @@ -237,7 +240,7 @@ function SplashScreen({ loadingStatus, updateStatus }: { loadingStatus: string; {FUSION_URL} {`v${FUSION_VERSION}`} {updateStatus?.updateAvailable && ( - {`Update available: v${updateStatus.currentVersion} → v${updateStatus.latestVersion}. Run \`fn update\` for an installed CLI, or pull this source checkout.`} + {t("tui.updateAvailable", "Update available: v{{currentVersion}} → v{{latestVersion}}. Run `fn update` for an installed CLI, or pull this source checkout.", { currentVersion: updateStatus.currentVersion, latestVersion: updateStatus.latestVersion })} )} @@ -299,15 +302,16 @@ function Panel({ title, isFocused, children, flexGrow, flexShrink, width }: Pane // ── System panel ────────────────────────────────────────────────────────────── function SystemPanel({ state, isFocused }: { state: DashboardState; isFocused: boolean }) { + const { t } = useTranslation("cli"); const info = state.systemInfo; const { stdout } = useStdout(); const cols = stdout?.columns ?? 80; // Watcher is the lowest-signal chip — drop it first when chips would wrap. const showWatcher = cols >= 100; return ( - + {!info ? ( - System information not available. + {t("tui.systemInfoUnavailable", "System information not available.")} ) : ( {/* Status chips wrap to multiple rows at narrow widths. */} @@ -344,7 +348,7 @@ function SystemPanel({ state, isFocused }: { state: DashboardState; isFocused: b off-panel. The token in particular MUST always render in full so users can copy it (via [c]) or click-drag select it. */} {state.isReady && Number.isFinite(info.startupDurationMs) && ( - {`Ready in ${((info.startupDurationMs ?? 0) / 1000).toFixed(1)}s`} + {t("tui.readyIn", "Ready in {{secs}}s", { secs: ((info.startupDurationMs ?? 0) / 1000).toFixed(1) })} )} URL @@ -364,11 +368,11 @@ function SystemPanel({ state, isFocused }: { state: DashboardState; isFocused: b token, regardless of split focus. */} - [Enter] open URL + [Enter] {t("tui.systemOpenUrl", "open URL")} {info.authToken ? ( - · [c] copy token · select token text to copy manually + · [c] {t("tui.systemCopyTokenHint", "copy token · select token text to copy manually")} ) : ( - · drag to select + · {t("tui.systemDragToSelect", "drag to select")} )} @@ -436,6 +440,7 @@ function StatRow({ label, children }: { label: string; children: React.ReactNode } function StatsPanel({ state, isFocused }: { state: DashboardState; isFocused: boolean }) { + const { t } = useTranslation("cli"); const sys = state.systemStats; const systemMemUsed = sys ? sys.systemTotalMem - sys.systemFreeMem : 0; const systemMemUsageColor = sys ? sysMemColor(systemMemUsed, sys.systemTotalMem) : undefined; @@ -445,7 +450,7 @@ function StatsPanel({ state, isFocused }: { state: DashboardState; isFocused: bo : null; return ( - + {sys ? ( <> @@ -483,7 +488,7 @@ function StatsPanel({ state, isFocused }: { state: DashboardState; isFocused: bo ) : ( - Stats not available. + {t("tui.statsUnavailable", "Stats not available.")} )} @@ -493,11 +498,12 @@ function StatsPanel({ state, isFocused }: { state: DashboardState; isFocused: bo // ── Settings panel (status mode) ────────────────────────────────────────────── function SettingsPanel({ state, isFocused }: { state: DashboardState; isFocused: boolean }) { + const { t } = useTranslation("cli"); const s = state.settings; return ( - + {!s ? ( - Settings not available. + {t("tui.settingsUnavailable", "Settings not available.")} ) : ( {( @@ -601,9 +607,10 @@ function LogsPanel({ const hiddenAbove = visibleStart; const hiddenBelow = entries.length - visibleEnd; + const { t } = useTranslation("cli"); const panelTitle = state.clipboardFlash - ? `Logs (${state.logEntries.length}/1000) · ${state.clipboardFlash.ok ? "✓ Copied!" : "✗ Copy failed"}` - : `Logs (${state.logEntries.length}/1000)`; + ? `${t("tui.logsPanelTitle", "Logs")} (${state.logEntries.length}/1000) · ${state.clipboardFlash.ok ? t("tui.copiedSuccess", "✓ Copied!") : t("tui.copyFailed", "✗ Copy failed")}` + : `${t("tui.logsPanelTitle", "Logs")} (${state.logEntries.length}/1000)`; return ( {logsExpandedMode && entries[cursor] ? ( @@ -614,9 +621,9 @@ function LogsPanel({ clipboardFlash={state.clipboardFlash} /> ) : entries.length === 0 ? ( - No log entries yet. + {t("tui.noLogEntries", "No log entries yet.")} ) : entries.length !== state.logEntries.length && entries.length === 0 ? ( - No entries match filter {logsSeverityFilter.toUpperCase()}. + {t("tui.noEntriesMatchFilter", "No entries match filter {{filter}}.", { filter: logsSeverityFilter.toUpperCase() })} ) : ( @@ -707,29 +714,30 @@ function ExpandedLog({ total: number; clipboardFlash: { ok: boolean; at: number } | null; }) { + const { t } = useTranslation("cli"); return ( - Entry {index + 1}/{total} · [Enter/Esc] close · [c] copy + {t("tui.expandedLogHeader", "Entry {{index}}/{{total}} · [Enter/Esc] close · [c] copy", { index: index + 1, total })} {clipboardFlash && ( - {clipboardFlash.ok ? "✓ Copied!" : "✗ Copy failed"} + {clipboardFlash.ok ? t("tui.copiedSuccess", "✓ Copied!") : t("tui.copyFailed", "✗ Copy failed")} )} - Time: + {t("tui.expandedLogTime", "Time:")} {formatTimestamp(entry.timestamp)} - Level: + {t("tui.expandedLogLevel", "Level:")} {entry.level.toUpperCase()} {entry.prefix && ( - Prefix: + {t("tui.expandedLogPrefix", "Prefix:")} {entry.prefix} )} @@ -742,19 +750,20 @@ function ExpandedLog({ // ── Utilities panel ─────────────────────────────────────────────────────────── function UtilitiesPanel({ state, isFocused }: { state: DashboardState; isFocused: boolean }) { + const { t } = useTranslation("cli"); const autoKill = state.autoKillVitestOnPressure; const thresholdPct = Math.round(state.vitestKillThreshold * 100); const actions: Array<{ key: string; label: string }> = [ - { key: "r", label: "Refresh Stats" }, - { key: "c", label: "Clear Logs" }, - { key: "t", label: "Toggle Engine Pause" }, - { key: "k", label: "Kill Vitest Processes" }, - { key: "v", label: `Auto-Kill Vitest >${thresholdPct}% Mem: ${autoKill ? "ON" : "OFF"}` }, - { key: "+/-", label: `Adjust Threshold (${thresholdPct}%)` }, - { key: "?", label: "Help" }, + { key: "r", label: t("tui.utilitiesRefreshStats", "Refresh Stats") }, + { key: "c", label: t("tui.utilitiesClearLogs", "Clear Logs") }, + { key: "t", label: t("tui.utilitiesToggleEnginePause", "Toggle Engine Pause") }, + { key: "k", label: t("tui.utilitiesKillVitest", "Kill Vitest Processes") }, + { key: "v", label: t("tui.utilitiesAutoKillVitest", "Auto-Kill Vitest >{{pct}}% Mem: {{state}}", { pct: thresholdPct, state: autoKill ? "ON" : "OFF" }) }, + { key: "+/-", label: t("tui.utilitiesAdjustThreshold", "Adjust Threshold ({{pct}}%)", { pct: thresholdPct }) }, + { key: "?", label: t("tui.utilitiesHelp", "Help") }, ]; return ( - + {actions.map((action) => ( @@ -770,49 +779,50 @@ function UtilitiesPanel({ state, isFocused }: { state: DashboardState; isFocused // ── Help overlay ────────────────────────────────────────────────────────────── function HelpOverlay() { + const { t } = useTranslation("cli"); const shortcuts: Array<[string, string]> = [ - ["[m] / [s]", "Main (status mode)"], - ["[b]", "Board view"], - ["[a]", "Agents view"], - ["[g]", "Settings view"], - ["[t]", "Git view"], - ["[f]", "Files (when not on Logs); cycles log severity filter on Logs"], - ["[Tab]", "Cycle focused panel / pane forward"], - ["[Shift+Tab]", "Cycle focused panel / pane backward"], - ["[1-5]", "Jump to panel (Main: System/Logs/Stats/Utilities/Settings)"], - ["[← / →]", "Switch pane (Agents, Settings, Files, Git)"], - ["[→] / [↓] / [n]", "Next panel (Main; ↑/↓ scroll on Logs)"], - ["[←] / [↑] / [p]", "Previous panel (Main; ↑/↓ scroll on Logs)"], - ["[Enter]", "Expand log + release mouse for text selection (Logs)"], - ["[r]", "Refresh stats (Utilities)"], - ["[c]", "Clear logs (Utilities)"], - ["[k]", "Kill all vitest processes (Utilities)"], - ["[v]", "Toggle auto-kill vitest on memory pressure (Utilities)"], - ["[+/-]", "Adjust vitest kill memory threshold (Utilities)"], - ["[Enter]", "Open dashboard URL in browser (System)"], - ["[c]", "Copy auth token to clipboard (System)"], - ["[M]", "Manual mouse-mode toggle (auto: on for Logs/Files/Git/Board, off elsewhere)"], - ["[↑/↓/k/j]", "Navigate list / log entries"], - ["[Home / G]", "First / last log entry (Logs)"], - ["[Enter/Space]", "Expand log entry (Logs)"], - ["[c]", "Copy selected log entry to clipboard (Logs)"], - ["[w]", "Toggle word wrap (Logs / Files)"], - ["[Space]", "Toggle boolean (Settings)"], - ["[+/-]", "Adjust number (Settings)"], - ["[p]", "Project picker (Board, Files)"], - ["[n]", "New task (Board)"], - ["[D]", "Delete agent — requires confirm (Agents)"], - ["[P] / [F]", "Push / fetch (Git)"], - ["[.]", "Toggle hidden files (Files)"], - ["[?] / [h]", "Toggle help"], - ["[q]", "Quit"], - ["[Ctrl+C]", "Force quit"], + ["[m] / [s]", t("tui.helpShortcutMain", "Main (status mode)")], + ["[b]", t("tui.helpShortcutBoard", "Board view")], + ["[a]", t("tui.helpShortcutAgents", "Agents view")], + ["[g]", t("tui.helpShortcutSettings", "Settings view")], + ["[t]", t("tui.helpShortcutGit", "Git view")], + ["[f]", t("tui.helpShortcutFiles", "Files (when not on Logs); cycles log severity filter on Logs")], + ["[Tab]", t("tui.helpShortcutTabForward", "Cycle focused panel / pane forward")], + ["[Shift+Tab]", t("tui.helpShortcutTabBackward", "Cycle focused panel / pane backward")], + ["[1-5]", t("tui.helpShortcutJumpPanel", "Jump to panel (Main: System/Logs/Stats/Utilities/Settings)")], + ["[← / →]", t("tui.helpShortcutSwitchPane", "Switch pane (Agents, Settings, Files, Git)")], + ["[→] / [↓] / [n]", t("tui.helpShortcutNextPanel", "Next panel (Main; ↑/↓ scroll on Logs)")], + ["[←] / [↑] / [p]", t("tui.helpShortcutPrevPanel", "Previous panel (Main; ↑/↓ scroll on Logs)")], + ["[Enter]", t("tui.helpShortcutExpandLog", "Expand log + release mouse for text selection (Logs)")], + ["[r]", t("tui.helpShortcutRefreshStats", "Refresh stats (Utilities)")], + ["[c]", t("tui.helpShortcutClearLogs", "Clear logs (Utilities)")], + ["[k]", t("tui.helpShortcutKillVitest", "Kill all vitest processes (Utilities)")], + ["[v]", t("tui.helpShortcutToggleAutoKill", "Toggle auto-kill vitest on memory pressure (Utilities)")], + ["[+/-]", t("tui.helpShortcutAdjustThreshold", "Adjust vitest kill memory threshold (Utilities)")], + ["[Enter]", t("tui.helpShortcutOpenUrl", "Open dashboard URL in browser (System)")], + ["[c]", t("tui.helpShortcutCopyToken", "Copy auth token to clipboard (System)")], + ["[M]", t("tui.helpShortcutMouseToggle", "Manual mouse-mode toggle (auto: on for Logs/Files/Git/Board, off elsewhere)")], + ["[↑/↓/k/j]", t("tui.helpShortcutNavigate", "Navigate list / log entries")], + ["[Home / G]", t("tui.helpShortcutFirstLast", "First / last log entry (Logs)")], + ["[Enter/Space]", t("tui.helpShortcutExpandEntry", "Expand log entry (Logs)")], + ["[c]", t("tui.helpShortcutCopyEntry", "Copy selected log entry to clipboard (Logs)")], + ["[w]", t("tui.helpShortcutWordWrap", "Toggle word wrap (Logs / Files)")], + ["[Space]", t("tui.helpShortcutToggleBool", "Toggle boolean (Settings)")], + ["[+/-]", t("tui.helpShortcutAdjustNumber", "Adjust number (Settings)")], + ["[p]", t("tui.helpShortcutProjectPicker", "Project picker (Board, Files)")], + ["[n]", t("tui.helpShortcutNewTask", "New task (Board)")], + ["[D]", t("tui.helpShortcutDeleteAgent", "Delete agent — requires confirm (Agents)")], + ["[P] / [F]", t("tui.helpShortcutPushFetch", "Push / fetch (Git)")], + ["[.]", t("tui.helpShortcutHiddenFiles", "Toggle hidden files (Files)")], + ["[?] / [h]", t("tui.helpShortcutToggleHelp", "Toggle help")], + ["[q]", t("tui.helpShortcutQuit", "Quit")], + ["[Ctrl+C]", t("tui.helpShortcutForceQuit", "Force quit")], ]; const rowKeyWidth = 22; const rowDescWidth = Math.max(...shortcuts.map(([, d]) => d.length)); const innerWidth = rowKeyWidth + 2 + rowDescWidth + 2; - const titleRow = " KEYBOARD SHORTCUTS".padEnd(innerWidth); + const titleRow = ` ${t("tui.helpTitle", "KEYBOARD SHORTCUTS")}`.padEnd(innerWidth); return ( @@ -1020,11 +1030,12 @@ function StatusModeSingle({ } function StatusBar({ state, controller: _controller }: { state: DashboardState; controller: DashboardTUI }) { + const { t } = useTranslation("cli"); const { systemInfo, updateStatus } = state; const hasUpdate = updateStatus?.updateAvailable === true; const uptime = systemInfo ? formatUptime(Date.now() - systemInfo.startTimeMs) : null; const url = systemInfo?.baseUrl ?? null; - const help = "Tab cycle panel · 1-5 jump"; + const help = t("tui.statusBarHelp", "Tab cycle panel · 1-5 jump"); // Single Text so Yoga truncates the tail (help text) when natural width // exceeds cols — guarantees a one-row footer with version/url preserved. @@ -1048,6 +1059,7 @@ function StatusBar({ state, controller: _controller }: { state: DashboardState; // ── Unified main header — used by both status and interactive modes ────────── function MainHeader({ state }: { state: DashboardState }) { + const { t } = useTranslation("cli"); const inInteractive = state.mode === "interactive"; const interactiveView = state.interactiveView; const { stdout } = useStdout(); @@ -1056,12 +1068,12 @@ function MainHeader({ state }: { state: DashboardState }) { | { key: string; label: string; kind: "main" } | { key: string; label: string; kind: "interactive"; view: InteractiveView }; const tabs: Tab[] = [ - { key: "m", label: "Main", kind: "main" }, - { key: "b", label: "Board", kind: "interactive", view: "board" }, - { key: "a", label: "Agents", kind: "interactive", view: "agents" }, - { key: "g", label: "Settings", kind: "interactive", view: "settings" }, - { key: "t", label: "Git", kind: "interactive", view: "git" }, - { key: "f", label: "Files", kind: "interactive", view: "files" }, + { key: "m", label: t("tui.tabMain", "Main"), kind: "main" }, + { key: "b", label: t("tui.tabBoard", "Board"), kind: "interactive", view: "board" }, + { key: "a", label: t("tui.tabAgents", "Agents"), kind: "interactive", view: "agents" }, + { key: "g", label: t("tui.tabSettings", "Settings"), kind: "interactive", view: "settings" }, + { key: "t", label: t("tui.tabGit", "Git"), kind: "interactive", view: "git" }, + { key: "f", label: t("tui.tabFiles", "Files"), kind: "interactive", view: "files" }, ]; const showHelpHint = cols >= 110; const fullLabels = cols >= 90; @@ -1105,14 +1117,16 @@ function MainHeader({ state }: { state: DashboardState }) { {state.remoteStatus?.state === "running" && ( - ● tunnel{state.remoteStatus.url ? ` ${state.remoteStatus.url}` : ""}{cols >= 80 ? " [^Q] QR" : ""} + ● {t("tui.headerTunnelRunning", "tunnel")} + {state.remoteStatus.url ? ` ${state.remoteStatus.url}` : ""} + {cols >= 80 ? t("tui.headerTunnelQrHint", " [^Q] QR") : ""} )} {state.remoteStatus?.state === "starting" && ( - ● tunnel starting… + ● {t("tui.headerTunnelStarting", "tunnel starting…")} )} - {showHelpHint && [?] help [q] quit} + {showHelpHint && {t("tui.headerHelpQuitHint", "[?] help [q] quit")}} ); } @@ -1142,11 +1156,12 @@ function TaskCard({ selected: boolean; width: number; }) { + const { t } = useTranslation("cli"); const accent = COLUMN_COLORS[task.column] ?? "white"; const borderColor = selected ? "cyanBright" : "gray"; const titleColor = selected ? "whiteBright" : undefined; const shortId = task.id.length > 10 ? task.id.slice(0, 8) : task.id; - const title = task.title ?? task.description ?? "(untitled)"; + const title = task.title ?? task.description ?? t("tui.taskCardUntitled", "(untitled)"); return ( void; }) { + const { t } = useTranslation("cli"); const current = projects[selectedIndex] ?? null; if (!open) { return ( - Project: - {current?.name ?? "(none)"} - [p] change + {t("tui.projectSelectorLabel", "Project:")} + {current?.name ?? t("tui.projectSelectorNone", "(none)")} + {t("tui.projectSelectorChangeHint", "[p] change")} ); } @@ -1276,9 +1292,9 @@ function ProjectSelector({ backgroundColor="black" width={Math.max(30, ...projects.map((p) => p.name.length + 4))} > - Pick a project + {t("tui.projectSelectorPickTitle", "Pick a project")} {projects.length === 0 ? ( - (no projects registered) + {t("tui.projectSelectorNoProjects", "(no projects registered)")} ) : ( projects.map((p, i) => { const isSel = i === selectedIndex; @@ -1293,7 +1309,7 @@ function ProjectSelector({ }) )} - ↑↓ navigate · Enter select · Esc cancel + {t("tui.projectSelectorNavHints", "↑↓ navigate · Enter select · Esc cancel")} ); } @@ -1353,6 +1369,7 @@ function TaskDetailScreen({ interactiveData: DashboardState["interactiveData"]; controller: DashboardTUI; }) { + const { t } = useTranslation("cli"); const { stdout } = useStdout(); const cols = stdout?.columns ?? 80; const isNarrow = cols < NARROW_THRESHOLD; @@ -1531,7 +1548,7 @@ function TaskDetailScreen({ ▶ {task.agentState} )} - [Esc] back + {t("tui.taskDetailBack", "[Esc] back")} @@ -1545,12 +1562,12 @@ function TaskDetailScreen({ {detail === null && ( - Loading task details… + {t("tui.taskDetailLoading", "Loading task details…")} )} {detail === "unavailable" && ( - Task no longer available — Esc to go back + {t("tui.taskDetailUnavailable", "Task no longer available — Esc to go back")} )} {detail && detail !== "unavailable" && ( @@ -1576,9 +1593,9 @@ function TaskDetailScreen({ {/* Steps section */} - ── Steps ────────────────────────────────────── + {t("tui.taskDetailStepsSectionHeader", "── Steps ──────────────────────────────────────")} {detail.steps.length === 0 ? ( - (no steps yet) + {t("tui.taskDetailNoSteps", "(no steps yet)")} ) : ( detail.steps.map((step) => { const icon = STEP_ICON[step.status] ?? "·"; @@ -1589,10 +1606,10 @@ function TaskDetailScreen({ let durationText = ""; if (isRunning && step.startedAt) { const elapsed = Date.now() - new Date(step.startedAt).getTime(); - durationText = ` (running — ${formatDurationMs(elapsed)})`; + durationText = t("tui.stepDurationRunning", " (running — {{duration}})", { duration: formatDurationMs(elapsed) }); } else if (isDone && step.startedAt && step.endedAt) { const elapsed = new Date(step.endedAt).getTime() - new Date(step.startedAt).getTime(); - durationText = ` (${step.status} — ${formatDurationMs(elapsed)})`; + durationText = t("tui.stepDurationDone", " ({{status}} — {{duration}})", { status: step.status, duration: formatDurationMs(elapsed) }); } return ( @@ -1613,14 +1630,14 @@ function TaskDetailScreen({ {/* Logs section — flexGrow so it fills remaining vertical space */} - ── Logs ─────────────────────────────────────── + {t("tui.taskDetailLogsSectionHeader", "── Logs ───────────────────────────────────────")} - {autoFollow ? "[live]" : "[paused]"} + {autoFollow ? t("tui.taskDetailLogsLive", "[live]") : t("tui.taskDetailLogsPaused", "[paused]")} {detail.recentLogs.length === 0 ? ( - (no log entries yet) + {t("tui.taskDetailNoLogEntries", "(no log entries yet)")} ) : ( {/* Compute the visible window from the bottom, offset by scroll position. */} @@ -1667,7 +1684,7 @@ function TaskDetailScreen({ )} - ↑↓/j/k scroll · PgUp/PgDn half-page · g top · G bottom · Esc back + {t("tui.taskDetailScrollHints", "↑↓/j/k scroll · PgUp/PgDn half-page · g top · G bottom · Esc back")} ); } @@ -1695,6 +1712,7 @@ function groupTasksByColumn(tasks: TaskItem[]): Record } function BoardView({ state, controller }: { state: DashboardState; controller: DashboardTUI }) { + const { t } = useTranslation("cli"); const { stdout } = useStdout(); const cols = stdout?.columns ?? 80; const rows = stdout?.rows ?? 24; @@ -1852,11 +1870,11 @@ function BoardView({ state, controller }: { state: DashboardState; controller: D const submitNewTask = async () => { const title = newTaskTitle.trim(); if (!title) { - setCreateError("Title cannot be empty"); + setCreateError(t("tui.boardCreateTaskTitleEmpty", "Title cannot be empty")); return; } if (!state.interactiveData || !selectedProject) { - setCreateError("No project selected"); + setCreateError(t("tui.boardCreateTaskNoProject", "No project selected")); return; } setCreating(true); @@ -1898,17 +1916,17 @@ function BoardView({ state, controller }: { state: DashboardState; controller: D paddingY={1} width={Math.min(80, Math.max(40, cols - 8))} > - New Task - Project: {selectedProject?.name ?? "(none)"} + {t("tui.boardNewTaskTitle", "New Task")} + {t("tui.boardNewTaskProject", "Project: {{name}}", { name: selectedProject?.name ?? "(none)" })} - Title + {t("tui.boardNewTaskTitleLabel", "Title")} ▸ void submitNewTask()} - placeholder="What needs doing?" + placeholder={t("tui.boardNewTaskPlaceholder", "What needs doing?")} /> @@ -1918,10 +1936,10 @@ function BoardView({ state, controller }: { state: DashboardState; controller: D {creating ? ( - Creating… + {t("tui.boardCreatingTask", "Creating…")} ) : ( - Enter to create · Esc to cancel + {t("tui.boardCreateTaskHints", "Enter to create · Esc to cancel")} )} @@ -1937,12 +1955,13 @@ function BoardView({ state, controller }: { state: DashboardState; controller: D ) : tasksState.loading ? ( - Loading tasks… + {t("tui.loadingTasks", "Loading tasks…")} ) : tasksState.tasks.length === 0 ? ( - No tasks in this project. - Press [p] to switch projects. + {t("tui.noTasks", "No tasks in this project.")} + {/* Keybinding accelerator [{{key}}] stays literal — never translated. */} + {t("tui.switchProjectsHint", { key: "p", defaultValue: "Press [{{key}}] to switch projects." })} ) : ( @@ -1995,18 +2014,18 @@ function heartbeatFreshness(lastHeartbeatAt?: string): { fresh: boolean; label: type AgentSubView = "list" | "confirm-delete"; -function formatRunStatusLabel(status: string): string { +function formatRunStatusLabel(status: string, t: TFunction): string { switch (status) { case "completed": - return "Completed"; + return t("tui.runStatusCompleted", "Completed"); case "failed": - return "Failed"; + return t("tui.runStatusFailed", "Failed"); case "terminated": - return "Terminated"; + return t("tui.runStatusTerminated", "Terminated"); case "active": - return "Active"; + return t("tui.runStatusActive", "Active"); default: - return status.length > 0 ? `${status[0]!.toUpperCase()}${status.slice(1)}` : "Unknown"; + return status.length > 0 ? `${status[0]!.toUpperCase()}${status.slice(1)}` : t("tui.runStatusUnknown", "Unknown"); } } @@ -2025,29 +2044,30 @@ function runStatusColor(status: string): "green" | "red" | "yellow" | "cyanBrigh } } -function getRunLogLines(run: AgentRunItem): string[] { +function getRunLogLines(run: AgentRunItem, t: TFunction): string[] { if (Array.isArray(run.logs) && run.logs.length > 0) return run.logs; const lines: string[] = []; - if (run.triggerDetail) lines.push(`trigger: ${run.triggerDetail}`); - if (run.invocationSource) lines.push(`source: ${run.invocationSource}`); + if (run.triggerDetail) lines.push(`${t("tui.runLogTrigger", "trigger")}: ${run.triggerDetail}`); + if (run.invocationSource) lines.push(`${t("tui.runLogSource", "source")}: ${run.invocationSource}`); if (run.stdoutExcerpt) { - lines.push("stdout:"); + lines.push(t("tui.runLogStdout", "stdout:")); lines.push(...run.stdoutExcerpt.split(/\r?\n/).filter((line) => line.length > 0)); } if (run.stderrExcerpt) { - lines.push("stderr:"); + lines.push(t("tui.runLogStderr", "stderr:")); lines.push(...run.stderrExcerpt.split(/\r?\n/).filter((line) => line.length > 0)); } if (run.resultJson) { - lines.push("result:"); + lines.push(t("tui.runLogResult", "result:")); lines.push(JSON.stringify(run.resultJson)); } - return lines.length > 0 ? lines : ["No logs captured for this run."]; + return lines.length > 0 ? lines : [t("tui.runLogNone", "No logs captured for this run.")]; } function AgentsView({ state }: { state: DashboardState }) { + const { t } = useTranslation("cli"); const { stdout } = useStdout(); const cols = stdout?.columns ?? 80; // Narrow mode: hide the inactive pane so list and detail don't overlap side-by-side. @@ -2122,7 +2142,7 @@ function AgentsView({ state }: { state: DashboardState }) { if (!data || !selectedAgent) { setSubView("list"); return; } data.deleteAgent(selectedAgent.id) .then(() => { - setStatusMsg(`Deleted agent ${selectedAgent.name}`); + setStatusMsg(t("tui.agentDeleted", "Deleted agent {{name}}", { name: selectedAgent.name })); return refreshList(); }) .catch((err: unknown) => setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`)) @@ -2183,14 +2203,14 @@ function AgentsView({ state }: { state: DashboardState }) { if (input === "s") { if (!data || !selectedAgent) return; data.updateAgentState(selectedAgent.id, "active") - .then(() => { setStatusMsg("Agent started"); return refreshList(); }) + .then(() => { setStatusMsg(t("tui.agentStarted", "Agent started")); return refreshList(); }) .catch((err: unknown) => setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`)); return; } if (input === "x") { if (!data || !selectedAgent) return; data.updateAgentState(selectedAgent.id, "idle") - .then(() => { setStatusMsg("Agent stopped"); return refreshList(); }) + .then(() => { setStatusMsg(t("tui.agentStopped", "Agent stopped")); return refreshList(); }) .catch((err: unknown) => setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`)); return; } @@ -2208,12 +2228,12 @@ function AgentsView({ state }: { state: DashboardState }) { return ( - Delete agent? + {t("tui.agentDeleteConfirmTitle", "Delete agent?")} - Agent: {selectedAgent.name} - ID: {selectedAgent.id} + {t("tui.agentDeleteConfirmName", "Agent:")} {selectedAgent.name} + {t("tui.agentDeleteConfirmId", "ID:")} {selectedAgent.id} - [y] confirm delete [any other key] cancel + {t("tui.agentDeleteConfirmHints", "[y] confirm delete [any other key] cancel")} ); @@ -2240,12 +2260,12 @@ function AgentsView({ state }: { state: DashboardState }) { > - Agents ({agents.length}) + {t("tui.agentsListTitle", "Agents ({{count}})", { count: agents.length })} {agents.length === 0 ? ( - No agents found. + {t("tui.agentsNoAgents", "No agents found.")} ) : ( agents.map((agent, i) => { const isSel = i === selectedIndex; @@ -2286,19 +2306,19 @@ function AgentsView({ state }: { state: DashboardState }) { > - Agent Detail + {t("tui.agentDetailTitle", "Agent Detail")} {!selectedAgent ? ( - Select an agent from the list. + {t("tui.agentDetailSelectHint", "Select an agent from the list.")} ) : loadingDetail ? ( - Loading… + {t("tui.loading", "Loading…")} ) : !detail ? ( - Could not load agent detail. + {t("tui.agentDetailLoadError", "Could not load agent detail.")} ) : ( {detail.name} @@ -2307,60 +2327,60 @@ function AgentsView({ state }: { state: DashboardState }) { {showRunLogs && selectedRun ? ( <> - Run logs ({selectedRunIndex + 1}) - ID: {selectedRun.id} + {t("tui.agentRunLogsTitle", "Run logs ({{index}})", { index: selectedRunIndex + 1 })} + {t("tui.agentRunId", "ID:")} {selectedRun.id} - {getRunLogLines(selectedRun).slice(0, 10).map((line, i) => ( + {getRunLogLines(selectedRun, t).slice(0, 10).map((line, i) => ( {line} ))} - [Esc/q] back to runs + {t("tui.agentRunLogsBackHint", "[Esc/q] back to runs")} ) : ( <> - State: + {t("tui.agentDetailState", "State:")} {detail.state} - Role: + {t("tui.agentDetailRole", "Role:")} {detail.role} {detail.title && ( - Title: + {t("tui.agentDetailTitle2", "Title:")} {detail.title} )} {detail.taskId && ( - Task: + {t("tui.agentDetailTask", "Task:")} {detail.taskId} )} {detail.capabilities.length > 0 && ( - Caps: + {t("tui.agentDetailCaps", "Caps:")} {detail.capabilities.join(", ")} )} {recentRuns.length > 0 && ( <> - Run history (latest first): + {t("tui.agentRunHistory", "Run history (latest first):")} {recentRuns.slice(0, 5).map((run, i) => ( {detailFocused && i === selectedRunIndex ? "▶" : " "} - {formatRunStatusLabel(run.status)} + {formatRunStatusLabel(run.status, t)} {run.startedAt.slice(11, 19)} {run.triggerDetail && {run.triggerDetail}} ))} - [Enter] open logs + {t("tui.agentOpenLogsHint", "[Enter] open logs")} )} @@ -2374,9 +2394,9 @@ function AgentsView({ state }: { state: DashboardState }) { {/* Footer */} - [s] start [x] stop [D] delete [r] refresh [Tab] focus ↑↓ select + {t("tui.agentsFooterHints", "[s] start [x] stop [D] delete [r] refresh [Tab] focus ↑↓ select")} {isNarrow && ( - [narrow] {detailFocused ? "detail" : "list"} + {t("tui.narrowModeIndicator", "[narrow]")} {detailFocused ? t("tui.agentNarrowDetail", "detail") : t("tui.agentNarrowList", "list")} )} @@ -2389,25 +2409,27 @@ type SettingKey = "maxConcurrent" | "maxWorktrees" | "autoMerge" | "mergeStrateg interface SettingDef { key: SettingKey; - label: string; + labelKey: string; + labelDefault: string; type: "number" | "boolean" | "enum"; options?: string[]; } const SETTING_DEFS: SettingDef[] = [ - { key: "maxConcurrent", label: "Max Concurrent", type: "number" }, - { key: "maxWorktrees", label: "Max Worktrees", type: "number" }, - { key: "autoMerge", label: "Auto Merge", type: "boolean" }, - { key: "mergeStrategy", label: "Merge Strategy", type: "enum", options: ["direct", "squash", "rebase"] }, - { key: "pollIntervalMs", label: "Poll Interval (ms)", type: "number" }, - { key: "enginePaused", label: "Engine Paused", type: "boolean" }, - { key: "globalPause", label: "Global Pause", type: "boolean" }, - { key: "remoteActiveProvider", label: "Remote Provider", type: "enum", options: ["tailscale", "cloudflare"] }, - { key: "remoteShortLivedEnabled", label: "Short-Lived Tokens", type: "boolean" }, - { key: "remoteShortLivedTtlMs", label: "Short-Lived TTL (ms)", type: "number" }, + { key: "maxConcurrent", labelKey: "tui.settingMaxConcurrent", labelDefault: "Max Concurrent", type: "number" }, + { key: "maxWorktrees", labelKey: "tui.settingMaxWorktrees", labelDefault: "Max Worktrees", type: "number" }, + { key: "autoMerge", labelKey: "tui.settingAutoMerge", labelDefault: "Auto Merge", type: "boolean" }, + { key: "mergeStrategy", labelKey: "tui.settingMergeStrategy", labelDefault: "Merge Strategy", type: "enum", options: ["direct", "squash", "rebase"] }, + { key: "pollIntervalMs", labelKey: "tui.settingPollIntervalMs", labelDefault: "Poll Interval (ms)", type: "number" }, + { key: "enginePaused", labelKey: "tui.settingEnginePaused", labelDefault: "Engine Paused", type: "boolean" }, + { key: "globalPause", labelKey: "tui.settingGlobalPause", labelDefault: "Global Pause", type: "boolean" }, + { key: "remoteActiveProvider", labelKey: "tui.settingRemoteActiveProvider", labelDefault: "Remote Provider", type: "enum", options: ["tailscale", "cloudflare"] }, + { key: "remoteShortLivedEnabled", labelKey: "tui.settingRemoteShortLivedEnabled", labelDefault: "Short-Lived Tokens", type: "boolean" }, + { key: "remoteShortLivedTtlMs", labelKey: "tui.settingRemoteShortLivedTtlMs", labelDefault: "Short-Lived TTL (ms)", type: "number" }, ]; function SettingsInteractiveView({ state, controller }: { state: DashboardState; controller: DashboardTUI }) { + const { t } = useTranslation("cli"); const [selectedIndex, setSelectedIndex] = useState(0); const [localSettings, setLocalSettings] = useState(null); const [models, setModels] = useState([]); @@ -2463,7 +2485,7 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; const remoteStatus = data.remote ? await data.remote.getStatus().catch(() => null) : null; const remoteSettingsSnapshot = data.remote ? await data.remote.getSettings().catch(() => updated.remoteSettingsSnapshot) : undefined; setLocalSettings(remoteStatus ? { ...updated, remoteStatus, remoteSettingsSnapshot } : updated); - setStatusMsg("Saved"); + setStatusMsg(t("tui.settingsSaved", "Saved")); } catch (err) { setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`); } finally { @@ -2521,14 +2543,14 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; if (ttlInputMode) { if (key.escape) { setTtlInputMode(false); - setStatusMsg("Cancelled short-lived token input"); + setStatusMsg(t("tui.settingsCancelledTokenInput", "Cancelled short-lived token input")); } return; } if (inputUpper === "R") { void refreshRemoteStatus(); - setStatusMsg("Remote status refreshed"); + setStatusMsg(t("tui.settingsRemoteStatusRefreshed", "Remote status refreshed")); return; } @@ -2537,24 +2559,24 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; if (data?.remote && inputUpper === "C") { const provider = localSettings.remoteActiveProvider; if (!provider) { - setStatusMsg("Select a remote provider first"); + setStatusMsg(t("tui.settingsSelectProviderFirst", "Select a remote provider first")); } else { void data.remote.activateProvider(provider) .then(() => refreshRemoteStatus()) - .then(() => setStatusMsg(`Activated provider: ${provider}`)) + .then(() => setStatusMsg(t("tui.settingsActivatedProvider", "Activated provider: {{provider}}", { provider }))) .catch((err) => setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`)); } return; } if (data?.remote && inputUpper === "V") { - void data.remote.startTunnel().then(() => refreshRemoteStatus()).then(() => setStatusMsg("Remote tunnel starting")) + void data.remote.startTunnel().then(() => refreshRemoteStatus()).then(() => setStatusMsg(t("tui.settingsTunnelStarting", "Remote tunnel starting"))) .catch((err) => setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`)); return; } if (data?.remote && inputUpper === "X") { - void data.remote.stopTunnel().then(() => refreshRemoteStatus()).then(() => setStatusMsg("Remote tunnel stopped")) + void data.remote.stopTunnel().then(() => refreshRemoteStatus()).then(() => setStatusMsg(t("tui.settingsTunnelStopped", "Remote tunnel stopped"))) .catch((err) => setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`)); return; } @@ -2563,7 +2585,7 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; void data.remote.regeneratePersistentToken() .then((result) => { setPersistentMaskedToken(result.maskedToken ?? null); - setStatusMsg("Persistent token regenerated"); + setStatusMsg(t("tui.settingsPersistentTokenRegenerated", "Persistent token regenerated")); }) .catch((err) => setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`)); return; @@ -2572,20 +2594,20 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; if (data?.remote && inputUpper === "L") { setTtlInputValue(String(localSettings.remoteShortLivedTtlMs)); setTtlInputMode(true); - setStatusMsg("Enter TTL milliseconds and press Enter"); + setStatusMsg(t("tui.settingsEnterTtl", "Enter TTL milliseconds and press Enter")); return; } if (data?.remote && inputUpper === "U") { void handleFetchRemoteUrl("persistent") - .then(() => setStatusMsg("Remote URL fetched")) + .then(() => setStatusMsg(t("tui.settingsRemoteUrlFetched", "Remote URL fetched"))) .catch((err) => setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`)); return; } if (data?.remote && inputUpper === "K") { void handleFetchRemoteQr("persistent") - .then(() => setStatusMsg("QR payload fetched")) + .then(() => setStatusMsg(t("tui.settingsQrFetched", "QR payload fetched"))) .catch((err) => setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`)); return; } @@ -2672,7 +2694,7 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; if (!data?.remote || !localSettings) return; const ttlMs = Number(value.trim()); if (!Number.isFinite(ttlMs) || ttlMs <= 0) { - setStatusMsg("TTL must be a positive number (ms)"); + setStatusMsg(t("tui.settingsTtlMustBePositive", "TTL must be a positive number (ms)")); return; } @@ -2685,7 +2707,7 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; setLocalSettings({ ...localSettings, remoteShortLivedTtlMs: ttlMs }); await saveField({ remoteShortLivedTtlMs: ttlMs }); await handleFetchRemoteUrl("short-lived", ttlMs); - setStatusMsg("Short-lived token generated"); + setStatusMsg(t("tui.settingsShortLivedTokenGenerated", "Short-lived token generated")); } catch (err) { setStatusMsg(`Error: ${err instanceof Error ? err.message : String(err)}`); } finally { @@ -2697,7 +2719,7 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; {statusMsg && ( - {saving ? "Saving…" : statusMsg} + {saving ? t("tui.settingsSavingInProgress", "Saving…") : statusMsg} )} @@ -2711,12 +2733,12 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; > - Settings + {t("tui.settingsInteractivePanelTitle", "Settings")} {!localSettings ? ( - Loading… + {t("tui.loading", "Loading…")} ) : ( SETTING_DEFS.map((def, i) => { const isSel = i === selectedIndex; @@ -2724,7 +2746,7 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; {isSel ? "▶" : " "} - {def.label} + {t(def.labelKey, def.labelDefault)} {renderValue(def, localSettings)} @@ -2745,32 +2767,32 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; > - Edit / Models + {t("tui.settingsEditModelsTitle", "Edit / Models")} {!localSettings ? ( - Loading settings… + {t("tui.settingsLoadingSettings", "Loading settings…")} ) : !selectedDef ? null : ( <> - {selectedDef.label} + {t(selectedDef.labelKey, selectedDef.labelDefault)} - Current: + {t("tui.settingsCurrentLabel", "Current:")} {renderValue(selectedDef, localSettings)} {selectedDef.type === "boolean" && ( - [Space] toggle + {t("tui.settingsBoolToggleHint", "[Space] toggle")} )} {selectedDef.type === "number" && ( - {selectedDef.key === "pollIntervalMs" ? "[+/-] adjust by 5000ms" : "[+/-] adjust by 1"} + {selectedDef.key === "pollIntervalMs" ? t("tui.settingsAdjust5000ms", "[+/-] adjust by 5000ms") : t("tui.settingsAdjust1", "[+/-] adjust by 1")} )} {selectedDef.type === "enum" && selectedDef.options && ( - [←/→] cycle options: + {t("tui.settingsEnumCycleHint", "[←/→] cycle options:")} {selectedDef.options.map((opt) => ( @@ -2783,31 +2805,31 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; )} - ──── Remote ──── + {t("tui.settingsRemoteHeader", "──── Remote ────")} - Provider: - {localSettings.remoteActiveProvider ?? "none"} - State: - {localSettings.remoteStatus?.state ?? "unknown"} + {t("tui.settingsRemoteProvider", "Provider:")} + {localSettings.remoteActiveProvider ?? t("tui.settingsRemoteProviderNone", "none")} + {t("tui.settingsRemoteState", "State:")} + {localSettings.remoteStatus?.state ?? t("tui.settingsRemoteStateUnknown", "unknown")} - Short-lived: - {localSettings.remoteSettingsSnapshot?.shortLivedEnabled ? "on" : "off"} + {t("tui.settingsRemoteShortLived", "Short-lived:")} + {localSettings.remoteSettingsSnapshot?.shortLivedEnabled ? t("tui.settingsRemoteOn", "on") : t("tui.settingsRemoteOff", "off")} {localSettings.remoteStatus?.url && ( - Tunnel URL: {localSettings.remoteStatus.url} + {t("tui.settingsRemoteTunnelUrl", "Tunnel URL:")} {localSettings.remoteStatus.url} )} {remoteUrl && ( - Auth URL: {remoteUrl} + {t("tui.settingsRemoteAuthUrl", "Auth URL:")} {remoteUrl} )} {remoteTokenMeta && ( - Token: {remoteTokenMeta} + {t("tui.settingsRemoteToken", "Token:")} {remoteTokenMeta} )} {persistentMaskedToken && ( - Persistent token: {persistentMaskedToken} + {t("tui.settingsRemotePersistentToken", "Persistent token:")} {persistentMaskedToken} )} {shortLivedExpiresAt && ( - Short-lived expires: {new Date(shortLivedExpiresAt).toLocaleString()} + {t("tui.settingsRemoteShortLivedExpires", "Short-lived expires:")} {new Date(shortLivedExpiresAt).toLocaleString()} )} {remoteQrDisplay && ( @@ -2821,7 +2843,7 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; )} {ttlInputMode && ( - TTL ms: + {t("tui.settingsTtlLabel", "TTL ms:")} - [Enter] generate [Esc] cancel + {t("tui.settingsTtlHints", "[Enter] generate [Esc] cancel")} )} - [C] activate provider [V] start [X] stop [P] persistent token [L] short-lived token - [U] URL hand-off [K] QR hand-off [R] refresh + {t("tui.settingsRemoteActions1", "[C] activate provider [V] start [X] stop [P] persistent token [L] short-lived token")} + {t("tui.settingsRemoteActions2", "[U] URL hand-off [K] QR hand-off [R] refresh")} {/* Models subsection */} {models.length > 0 && ( <> - ──── Available Models ──── - Configure default model in web dashboard + {t("tui.settingsAvailableModelsHeader", "──── Available Models ────")} + {t("tui.settingsConfigureModelInDashboard", "Configure default model in web dashboard")} {models.slice(0, 8).map((m) => ( @@ -2850,7 +2872,7 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; ))} {models.length > 8 && ( - … and {models.length - 8} more + {t("tui.settingsMoreModels", "… and {{count}} more", { count: models.length - 8 })} )} )} @@ -2861,7 +2883,7 @@ function SettingsInteractiveView({ state, controller }: { state: DashboardState; - [Tab] switch panel ↑↓ select setting [Space] toggle bool [+/-] adjust num [←/→] cycle enum [C/V/X/P/L/U/K/R] remote actions + {t("tui.settingsFooterHints", "[Tab] switch panel ↑↓ select setting [Space] toggle bool [+/-] adjust num [←/→] cycle enum [C/V/X/P/L/U/K/R] remote actions")} ); @@ -2918,6 +2940,7 @@ function PushModal({ onConfirm: () => void; onCancel: () => void; }) { + const { t } = useTranslation("cli"); useInput((_input, key) => { if (key.return) { onConfirm(); return; } if (key.escape) { onCancel(); return; } @@ -2934,18 +2957,18 @@ function PushModal({ paddingY={1} backgroundColor="black" > - Push to remote + {t("tui.gitPushModalTitle", "Push to remote")} - Branch: + {t("tui.gitPushModalBranch", "Branch:")} {status.branch} - ahead + {t("tui.gitPushModalAhead", "ahead")} {status.ahead} {toPush.length > 0 && ( <> - Commits to push (oldest→newest): + {t("tui.gitPushModalCommits", "Commits to push (oldest→newest):")} {[...toPush].reverse().map((c) => ( {c.shortSha} @@ -2955,12 +2978,13 @@ function PushModal({ )} - [Enter] push [Esc] cancel + {t("tui.gitPushModalHints", "[Enter] push [Esc] cancel")} ); } function GitView({ state, controller }: { state: DashboardState; controller: DashboardTUI }) { + const { t } = useTranslation("cli"); const { stdout } = useStdout(); const cols = stdout?.columns ?? 80; @@ -3046,7 +3070,7 @@ function GitView({ state, controller }: { state: DashboardState; controller: Das setPushModal({ phase: "pushing" }); if (data && projectPath) { data.git.push(projectPath).then((result) => { - setPushModal({ phase: "done", message: result.output || (result.success ? "Push successful" : "Push failed"), isError: !result.success }); + setPushModal({ phase: "done", message: result.output || (result.success ? t("tui.gitPushSuccessful", "Push successful") : t("tui.gitPushFailed", "Push failed")), isError: !result.success }); if (result.success) { setTimeout(() => { setPushModal(null); void refresh(); }, 2000); } @@ -3083,9 +3107,9 @@ function GitView({ state, controller }: { state: DashboardState; controller: Das } if (input === "F" && data && projectPath) { - setStatusMsg("Fetching…"); + setStatusMsg(t("tui.gitFetching", "Fetching…")); data.git.fetch(projectPath).then((result) => { - setStatusMsg(result.success ? "Fetched" : `Fetch failed: ${result.output}`); + setStatusMsg(result.success ? t("tui.gitFetched", "Fetched") : t("tui.gitFetchFailed", "Fetch failed: {{output}}", { output: result.output })); void refresh(); }).catch((err: unknown) => { setStatusMsg(`Fetch error: ${err instanceof Error ? err.message : String(err)}`); @@ -3160,14 +3184,14 @@ function GitView({ state, controller }: { state: DashboardState; controller: Das {/* Top bar: project selector + status */} - Project: - {selectedProject?.name ?? "(none)"} - [p] change + {t("tui.projectSelectorLabel", "Project:")} + {selectedProject?.name ?? t("tui.projectSelectorNone", "(none)")} + {t("tui.projectSelectorChangeHint", "[p] change")} {loading && ( - refreshing + {t("tui.gitRefreshing", "refreshing")} )} {statusMsg && {statusMsg}} @@ -3214,7 +3238,7 @@ function GitView({ state, controller }: { state: DashboardState; controller: Das {!gitStatus ? ( - {projectPath ? "Loading…" : "No project"} + {projectPath ? t("tui.loading", "Loading…") : t("tui.gitNoProject", "No project")} ) : ( <> @@ -3327,7 +3351,7 @@ function GitView({ state, controller }: { state: DashboardState; controller: Das {commits.length === 0 ? ( - {loading ? "Loading…" : "No commits"} + {loading ? t("tui.loading", "Loading…") : t("tui.gitNoCommits", "No commits")} ) : ( commits.map((c, i) => { const isSel = i === commitIndex; @@ -3435,7 +3459,7 @@ function GitView({ state, controller }: { state: DashboardState; controller: Das ) : ( - Working tree clean + {t("tui.gitWorkingTreeClean", "Working tree clean")} )} @@ -3447,10 +3471,10 @@ function GitView({ state, controller }: { state: DashboardState; controller: Das {/* Footer */} - [r] refresh {gitStatus && gitStatus.ahead > 0 ? "[P] push " : ""}[F] fetch [↑↓] rows [←→] status▸branches{worktrees.length > 1 ? "▸worktrees" : ""}▸commits▸changes [p] project [Esc/s] back + {t("tui.gitFooterHints", "[r] refresh {{push}}[F] fetch [↑↓] rows [←→] status▸branches{{worktrees}}▸commits▸changes [p] project [Esc/s] back", { push: gitStatus && gitStatus.ahead > 0 ? "[P] push " : "", worktrees: worktrees.length > 1 ? "▸worktrees" : "" })} {isNarrow && ( - [narrow] {activePane} + {t("tui.narrowModeIndicator", "[narrow]")} {activePane} )} @@ -3477,7 +3501,7 @@ function GitView({ state, controller }: { state: DashboardState; controller: Das setPushModal({ phase: "pushing" }); if (data && projectPath) { data.git.push(projectPath).then((result) => { - setPushModal({ phase: "done", message: result.output || (result.success ? "Push successful" : "Push failed"), isError: !result.success }); + setPushModal({ phase: "done", message: result.output || (result.success ? t("tui.gitPushSuccessful", "Push successful") : t("tui.gitPushFailed", "Push failed")), isError: !result.success }); if (result.success) { setTimeout(() => { setPushModal(null); void refresh(); }, 2000); } @@ -3500,7 +3524,7 @@ function GitView({ state, controller }: { state: DashboardState; controller: Das backgroundColor="black" > - Pushing to origin/{gitStatus?.branch ?? "…"} + {t("tui.gitPushingToOrigin", "Pushing to origin/{{branch}}", { branch: gitStatus?.branch ?? "…" })} )} {pushModal.phase === "done" && ( @@ -3515,7 +3539,7 @@ function GitView({ state, controller }: { state: DashboardState; controller: Das {pushModal.message} - {pushModal.isError && [Esc] dismiss} + {pushModal.isError && {t("tui.gitPushDismissHint", "[Esc] dismiss")}} )} @@ -3579,6 +3603,7 @@ function entriesToNodes(entries: FileEntry[], depth: number): TreeNode[] { } function FilesView({ state, controller }: { state: DashboardState; controller: DashboardTUI }) { + const { t } = useTranslation("cli"); const { stdout } = useStdout(); const cols = stdout?.columns ?? 80; @@ -3897,10 +3922,10 @@ function FilesView({ state, controller }: { state: DashboardState; controller: D {treeLoading ? ( - Loading… + {t("tui.loading", "Loading…")} ) : flatNodes.length === 0 ? ( - (empty) + {t("tui.filesEmpty", "(empty)")} ) : ( flatNodes.map((node, i) => { const isSelected = focusedPane === "tree" && i === selectedIndex; @@ -3965,18 +3990,18 @@ function FilesView({ state, controller }: { state: DashboardState; controller: D {previewLoading ? ( - Loading… + {t("tui.loading", "Loading…")} ) : !previewEntry ? ( - Select a file to preview + {t("tui.filesSelectToPreview", "Select a file to preview")} ) : previewResult === null ? ( - Unable to read file + {t("tui.filesUnableToRead", "Unable to read file")} ) : previewResult.isBinary ? ( - [binary file, {formatFileSize(previewResult.size)}] + {t("tui.filesBinary", "[binary file, {{size}}]", { size: formatFileSize(previewResult.size) })} ) : previewResult.tooLarge ? ( - {formatFileSize(previewResult.size)} — [too large to preview] + {t("tui.filesTooLarge", "{{size}} — [too large to preview]", { size: formatFileSize(previewResult.size) })} ) : previewResult.content === "" ? ( - (empty file) + {t("tui.filesEmptyFile", "(empty file)")} ) : previewLines ? ( {previewLines.map((line, i) => { @@ -3991,7 +4016,7 @@ function FilesView({ state, controller }: { state: DashboardState; controller: D ); })} {totalLines > previewScroll + previewHeight && ( - … {totalLines - previewScroll - previewHeight} more lines + {t("tui.filesMoreLines", "… {{count}} more lines", { count: totalLines - previewScroll - previewHeight })} )} ) : null} @@ -4003,10 +4028,10 @@ function FilesView({ state, controller }: { state: DashboardState; controller: D {/* Footer hints */} - [Tab] switch pane [↑↓/jk] move [Enter] open [←/→] collapse/expand [.] hidden [w] wrap [p] project [r] reload + {t("tui.filesFooterHints", "[Tab] switch pane [↑↓/jk] move [Enter] open [←/→] collapse/expand [.] hidden [w] wrap [p] project [r] reload")} {isNarrow && ( - [narrow] {focusedPane} + {t("tui.narrowModeIndicator", "[narrow]")} {focusedPane} )} @@ -4021,7 +4046,7 @@ function FilesView({ state, controller }: { state: DashboardState; controller: D paddingY={1} backgroundColor="black" > - Select Project + {t("tui.filesSelectProject", "Select Project")} {projectsState.projects.map((proj, i) => ( @@ -4041,11 +4066,12 @@ function FilesView({ state, controller }: { state: DashboardState; controller: D // ── Interactive mode root ───────────────────────────────────────────────────── function InteractiveMode({ state, controller }: { state: DashboardState; controller: DashboardTUI }) { + const { t } = useTranslation("cli"); if (state.interactiveData === null) { return ( - Interactive mode unavailable — no data source + {t("tui.interactiveModeUnavailable", "Interactive mode unavailable — no data source")} ); @@ -4072,6 +4098,7 @@ interface DashboardAppProps { } export function DashboardApp({ controller }: DashboardAppProps) { + const { t } = useTranslation("cli"); const { exit } = useApp(); const { stdout } = useStdout(); @@ -4194,7 +4221,7 @@ export function DashboardApp({ controller }: DashboardAppProps) { const remote = state.interactiveData?.remote; if (!remote) return; if (state.remoteStatus?.state !== "running") { - setQrOverlay({ state: "error", message: "No remote tunnel is running. Start one in Settings (g)." }); + setQrOverlay({ state: "error", message: t("tui.qrNoTunnelRunning", "No remote tunnel is running. Start one in Settings (g).") }); return; } setQrOverlay({ state: "loading" }); @@ -4581,8 +4608,8 @@ export function DashboardApp({ controller }: DashboardAppProps) { )} {qrOverlay && ( - Remote Access — Scan to connect - {qrOverlay.state === "loading" && Generating QR…} + {t("tui.qrOverlayTitle", "Remote Access — Scan to connect")} + {qrOverlay.state === "loading" && {t("tui.qrGenerating", "Generating QR…")}} {qrOverlay.state === "error" && {qrOverlay.message}} {qrOverlay.state === "ready" && ( <> @@ -4596,7 +4623,7 @@ export function DashboardApp({ controller }: DashboardAppProps) { )} - [Esc] close + {t("tui.qrCloseHint", "[Esc] close")} )} diff --git a/packages/cli/src/commands/dashboard-tui/controller.ts b/packages/cli/src/commands/dashboard-tui/controller.ts index f4862db202..a84ce30e5c 100644 --- a/packages/cli/src/commands/dashboard-tui/controller.ts +++ b/packages/cli/src/commands/dashboard-tui/controller.ts @@ -172,6 +172,9 @@ export class DashboardTUI { // will reapply the auto policy. mouseEnabled: boolean = false; + // Optional `--lang` override; highest-precedence locale source for the TUI. + lang?: string; + constructor() { this.logBuffer = new LogRingBuffer(); } @@ -675,6 +678,20 @@ export class DashboardTUI { const { render } = await import("ink"); const { createElement } = await import("react"); const { DashboardApp } = await import("./app.js"); + const { I18nextProvider } = await import("react-i18next"); + const { initCliI18n, resolveCliLocale } = await import("../../i18n/index.js"); + const { GlobalSettingsStore } = await import("@fusion/core"); + + // Resolve locale: --lang flag → persisted GlobalSettings → env → en. + let settingLanguage: string | undefined; + try { + settingLanguage = (await new GlobalSettingsStore().getSettings())?.language; + } catch { + // Settings unreadable — fall back to env/default. + } + const i18n = initCliI18n( + resolveCliLocale({ flag: this.lang, setting: settingLanguage, env: process.env }), + ); // Enter the terminal's alternate-screen buffer before mounting Ink so // the TUI gets a dedicated fullscreen surface that doesn't share @@ -689,7 +706,7 @@ export class DashboardTUI { } this.inkInstance = render( - createElement(DashboardApp, { controller: this }), + createElement(I18nextProvider, { i18n }, createElement(DashboardApp, { controller: this })), ); // Mouse mode must be enabled AFTER Ink mounts (which calls diff --git a/packages/cli/src/commands/dashboard.ts b/packages/cli/src/commands/dashboard.ts index 3c147c3340..cb7fa0248f 100644 --- a/packages/cli/src/commands/dashboard.ts +++ b/packages/cli/src/commands/dashboard.ts @@ -688,7 +688,7 @@ async function resolveDashboardAuthToken(opts: { noAuth?: boolean; token?: strin return tokenManager.generateToken(); } -export async function runDashboard(port: number, opts: { paused?: boolean; dev?: boolean; interactive?: boolean; open?: boolean; host?: string; noAuth?: boolean; token?: string } = {}) { +export async function runDashboard(port: number, opts: { paused?: boolean; dev?: boolean; interactive?: boolean; open?: boolean; host?: string; noAuth?: boolean; token?: string; lang?: string } = {}) { // Default to localhost so the dashboard (and its shell-capable terminal API) // is not exposed on the LAN. Pass --host 0.0.0.0 explicitly to opt-in. const selectedHost = opts.host ?? "127.0.0.1"; @@ -754,6 +754,7 @@ export async function runDashboard(port: number, opts: { paused?: boolean; dev?: if (isTTY) { tui = new DashboardTUI(); + tui.lang = opts.lang; void startupUpdateStatusPromise.then((updateStatus) => { tui?.setUpdateStatus(updateStatus); }); diff --git a/packages/cli/src/commands/settings.ts b/packages/cli/src/commands/settings.ts index 856523e283..84fea3e418 100644 --- a/packages/cli/src/commands/settings.ts +++ b/packages/cli/src/commands/settings.ts @@ -4,6 +4,7 @@ import { type GlobalSettings, DEFAULT_SETTINGS, resolveWorktrunkSettings, + SUPPORTED_LOCALES, } from "@fusion/core"; import { probeWorktrunk, resolveWorktrunkBinary } from "@fusion/engine"; import { resolveProject } from "../project-context.js"; @@ -28,9 +29,10 @@ export const VALID_SETTINGS = [ "worktrunk.enabled", "worktrunk.binaryPath", "worktrunk.onFailure", + "language", ] as const; -const GLOBAL_ONLY_SETTINGS = ["ntfyEnabled", "ntfyTopic", "defaultModel"] as const; +const GLOBAL_ONLY_SETTINGS = ["ntfyEnabled", "ntfyTopic", "defaultModel", "language"] as const; const PROJECT_ONLY_SETTINGS = [ "maxConcurrent", "maxWorktrees", @@ -64,6 +66,8 @@ const ENUM_SETTINGS: Record = { worktreeNaming: ["random", "task-id", "task-title"], unavailableNodePolicy: ["block", "fallback-local"], "worktrunk.onFailure": ["fail", "fallback-native"], + // "auto" clears the persisted locale and reverts to runtime detection. + language: [...SUPPORTED_LOCALES, "auto"], }; const STRING_SETTINGS: readonly string[] = [ @@ -336,6 +340,16 @@ export async function runSettingsSet(key: string, value: string, projectName?: s try { const parsedValue = parseValue(validKey, value); + if (key === "language" && parsedValue === "auto") { + // null-as-delete: removes the persisted key so the dashboard re-detects + // from the browser and the TUI falls back to the environment locale. + await globalStore!.updateSettings({ language: null } as unknown as Partial); + console.log(); + console.log(" ✓ Language reset to auto-detect (browser/environment locale)"); + console.log(); + return; + } + if (key === "defaultModel") { const parts = (parsedValue as string).split("/"); if (parts.length !== 2) { diff --git a/packages/cli/src/i18n/__tests__/i18n.test.tsx b/packages/cli/src/i18n/__tests__/i18n.test.tsx new file mode 100644 index 0000000000..43d86297c3 --- /dev/null +++ b/packages/cli/src/i18n/__tests__/i18n.test.tsx @@ -0,0 +1,142 @@ +import { Text } from "ink"; +import { render } from "ink-testing-library"; +import { createElement } from "react"; +import { I18nextProvider, useTranslation } from "react-i18next"; +import { afterEach, describe, expect, it } from "vitest"; +import { cliI18n, detectEnvLocale, initCliI18n, resolveCliLocale } from "../index.js"; + +// cliI18n is a module singleton: restore the locale after each test so cases +// that switch language (zh-CN/fr) can't leak state into later tests. +afterEach(async () => { + if (cliI18n.isInitialized && cliI18n.language !== "en") { + await cliI18n.changeLanguage("en"); + } +}); + +describe("detectEnvLocale", () => { + it("parses POSIX locale env values to a supported locale", () => { + expect(detectEnvLocale({ LANG: "fr_FR.UTF-8" })).toBe("fr"); + expect(detectEnvLocale({ LC_ALL: "es_ES.UTF-8" })).toBe("es"); + expect(detectEnvLocale({ LANG: "zh_CN.UTF-8" })).toBe("zh-CN"); + expect(detectEnvLocale({ LANG: "zh_TW" })).toBe("zh-TW"); + }); + + it("honors precedence LC_ALL > LC_MESSAGES > LANG > LANGUAGE", () => { + expect(detectEnvLocale({ LC_ALL: "fr_FR", LANG: "es_ES" })).toBe("fr"); + expect(detectEnvLocale({ LC_MESSAGES: "es_ES", LANG: "fr_FR" })).toBe("es"); + }); + + it("falls back to a bare language and undefined for unsupported", () => { + expect(detectEnvLocale({ LANG: "zh" })).toBe("zh-CN"); + expect(detectEnvLocale({ LANG: "de_DE.UTF-8" })).toBeUndefined(); + expect(detectEnvLocale({})).toBeUndefined(); + }); + + it("resolves Traditional-script Chinese tags to zh-TW, not Simplified", () => { + expect(detectEnvLocale({ LANG: "zh_Hant_TW.UTF-8" })).toBe("zh-TW"); + expect(detectEnvLocale({ LANG: "zh_Hant" })).toBe("zh-TW"); + expect(detectEnvLocale({ LANG: "zh_HK.UTF-8" })).toBe("zh-TW"); + expect(detectEnvLocale({ LANG: "zh_MO" })).toBe("zh-TW"); + // Simplified-script and mainland tags stay Simplified. + expect(detectEnvLocale({ LANG: "zh_Hans_CN" })).toBe("zh-CN"); + expect(detectEnvLocale({ LANG: "zh_SG" })).toBe("zh-CN"); + }); + + it("normalizes multi-underscore POSIX tags", () => { + expect(detectEnvLocale({ LANG: "en_US_POSIX" })).toBe("en"); + expect(detectEnvLocale({ LANGUAGE: "fr_FR.UTF-8" })).toBe("fr"); + }); +}); + +describe("resolveCliLocale precedence", () => { + it("flag overrides setting and env", () => { + expect(resolveCliLocale({ flag: "zh-TW", setting: "fr", env: { LANG: "es_ES" } })).toBe("zh-TW"); + }); + it("setting overrides env", () => { + expect(resolveCliLocale({ setting: "fr", env: { LANG: "es_ES" } })).toBe("fr"); + }); + it("env used when no flag/setting", () => { + expect(resolveCliLocale({ env: { LANG: "es_ES.UTF-8" } })).toBe("es"); + }); + it("defaults to en", () => { + expect(resolveCliLocale({ env: {} })).toBe("en"); + expect(resolveCliLocale({ flag: "de", env: {} })).toBe("en"); + }); +}); + +// The load-bearing spike: react-i18next must work under Ink's custom reconciler. +function Loading() { + const { t } = useTranslation("cli"); + return createElement(Text, null, t("tui.loading", "Loading…")); +} + +describe("react-i18next under the Ink reconciler", () => { + it("renders a localized first frame synchronously", () => { + const i18n = initCliI18n("en"); + const { lastFrame } = render( + createElement(I18nextProvider, { i18n }, createElement(Loading)), + ); + expect(lastFrame()).toContain("Loading…"); + }); + + it("renders from a real catalog, not the defaultValue fallback", async () => { + // t("tui.loading", "Loading…") can't distinguish a loaded catalog from the + // inline defaultValue. A non-en lookup with no defaultValue proves the + // bundled catalog itself resolved. + const i18n = initCliI18n("en"); + await i18n.changeLanguage("fr"); + function FrLoading() { + const { t } = useTranslation("cli"); + return createElement(Text, null, t("tui.loading")); + } + const { lastFrame } = render( + createElement(I18nextProvider, { i18n }, createElement(FrLoading)), + ); + expect(lastFrame()).toContain("Chargement…"); + await i18n.changeLanguage("en"); + }); + + it("re-renders on changeLanguage", async () => { + const i18n = initCliI18n("en"); + cliI18n.addResourceBundle("zh-CN", "cli", { tui: { loading: "加载中…" } }, true, true); + const { lastFrame } = render( + createElement(I18nextProvider, { i18n }, createElement(Loading)), + ); + expect(lastFrame()).toContain("Loading…"); + await i18n.changeLanguage("zh-CN"); + expect(lastFrame()).toContain("加载中…"); + }); +}); + +// Keybinding accelerators must stay literal even inside translated hints. +function ProjectHint() { + const { t } = useTranslation("cli"); + return createElement( + Text, + null, + t("tui.switchProjectsHint", { key: "p", defaultValue: "Press [{{key}}] to switch projects." }), + ); +} + +describe("CLI string migration", () => { + it("renders the migrated en label", () => { + const i18n = initCliI18n("en"); + function Tasks() { + const { t } = useTranslation("cli"); + return createElement(Text, null, t("tui.loadingTasks", "Loading tasks…")); + } + const { lastFrame } = render( + createElement(I18nextProvider, { i18n }, createElement(Tasks)), + ); + expect(lastFrame()).toContain("Loading tasks…"); + }); + + it("keeps the [p] accelerator literal in an interpolated hint", () => { + const i18n = initCliI18n("en"); + const { lastFrame } = render( + createElement(I18nextProvider, { i18n }, createElement(ProjectHint)), + ); + expect(lastFrame()).toContain("[p]"); + expect(lastFrame()).toContain("Press"); + }); +}); diff --git a/packages/cli/src/i18n/index.ts b/packages/cli/src/i18n/index.ts new file mode 100644 index 0000000000..f2aa7353bb --- /dev/null +++ b/packages/cli/src/i18n/index.ts @@ -0,0 +1,77 @@ +import { DEFAULT_LOCALE, isLocale, type Locale } from "@fusion/core"; +import { + baseInitOptions, + CLI_NAMESPACES, + cliResources, + DEFAULT_NAMESPACE, + normalizeToSupportedLocale, +} from "@fusion/i18n"; +import i18next, { type i18n as I18nInstance, type Resource } from "i18next"; +import { initReactI18next } from "react-i18next"; + +/** + * Terminal-UI i18next instance. + * + * Unlike the dashboard, the CLI bundles all catalogs statically (via the + * generated @fusion/i18n cli map) and initializes synchronously (inline + * resources, no async backend) so the very first rendered Ink frame is + * already localized — no flash of untranslated keys. + */ + +/** + * Parse a POSIX locale environment value (e.g. `fr_FR.UTF-8`, `zh_CN`, + * `zh-Hant`) into a supported {@link Locale}, or undefined when none matches. + */ +export function detectEnvLocale(env: NodeJS.ProcessEnv = process.env): Locale | undefined { + const raw = env.LC_ALL || env.LC_MESSAGES || env.LANG || env.LANGUAGE; + if (!raw) return undefined; + // Strip encoding/modifier (`.UTF-8`, `@euro`), then normalize via the shared + // helper so env detection matches the dashboard's navigator detection + // (incl. Traditional-script Chinese → zh-TW). + return normalizeToSupportedLocale(raw.split(/[.:@\s]/)[0]); +} + +/** + * Resolve the active CLI locale with precedence: + * `--lang flag → persisted GlobalSettings.language → environment → en`. + */ +export function resolveCliLocale(opts: { + flag?: string | undefined; + setting?: string | undefined; + env?: NodeJS.ProcessEnv; +} = {}): Locale { + const { flag, setting, env = process.env } = opts; + if (isLocale(flag)) return flag; + if (isLocale(setting)) return setting; + return detectEnvLocale(env) ?? DEFAULT_LOCALE; +} + +let initialized = false; + +/** Initialize (synchronously) or switch the CLI i18next instance to `locale`. */ +export function initCliI18n(locale: Locale): I18nInstance { + if (!initialized) { + void i18next.use(initReactI18next).init({ + ...baseInitOptions(), + lng: locale, + ns: [...CLI_NAMESPACES], + defaultNS: DEFAULT_NAMESPACE, + // Inline resources + no async backend => init completes synchronously, + // so the first rendered Ink frame is already localized (i18next v26 + // dropped the old `initImmediate` flag; this is now the default for + // backend-less, resource-inlined init). + resources: cliResources as unknown as Resource, + react: { useSuspense: false }, + }); + initialized = true; + } else if (i18next.language !== locale) { + // changeLanguage is async; the instance carries the previous locale until + // the microtask queue drains. Benign in production (called once per + // process) — callers that need the settled locale before rendering should + // await i18next.changeLanguage(locale) directly. + void i18next.changeLanguage(locale); + } + return i18next; +} + +export { i18next as cliI18n }; diff --git a/packages/core/src/__tests__/locale-settings.test.ts b/packages/core/src/__tests__/locale-settings.test.ts new file mode 100644 index 0000000000..84a096039a --- /dev/null +++ b/packages/core/src/__tests__/locale-settings.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, expectTypeOf, it } from "vitest"; +import { + DEFAULT_GLOBAL_SETTINGS, + DEFAULT_LOCALE, + GLOBAL_SETTINGS_KEYS, + isGlobalSettingsKey, + isLocale, + isProjectSettingsKey, + type Locale, + SUPPORTED_LOCALES, + validateLocale, +} from "../index.js"; + +describe("locale primitives", () => { + it("exposes exactly the six supported locale codes", () => { + expect([...SUPPORTED_LOCALES]).toEqual(["en", "zh-CN", "zh-TW", "fr", "es", "ko"]); + }); + + it("uses en as the default/source locale", () => { + expect(DEFAULT_LOCALE).toBe("en"); + expectTypeOf().toEqualTypeOf<"en" | "zh-CN" | "zh-TW" | "fr" | "es" | "ko">(); + }); + + it("narrows supported codes and rejects everything else via isLocale", () => { + for (const code of SUPPORTED_LOCALES) { + expect(isLocale(code)).toBe(true); + } + expect(isLocale("zh")).toBe(false); + expect(isLocale("de")).toBe(false); + expect(isLocale("")).toBe(false); + expect(isLocale(undefined)).toBe(false); + expect(isLocale(42)).toBe(false); + }); +}); + +describe("language global setting", () => { + it("registers language as a global-only settings key", () => { + expect(isGlobalSettingsKey("language")).toBe(true); + expect(isProjectSettingsKey("language")).toBe(false); + expect(GLOBAL_SETTINGS_KEYS).toContain("language"); + }); + + it("defaults language to undefined (resolve-at-runtime, not persisted en)", () => { + expect(DEFAULT_GLOBAL_SETTINGS.language).toBeUndefined(); + }); + + it("validates supported codes and rejects unsupported ones", () => { + expect(validateLocale("en")).toBe("en"); + expect(validateLocale("zh-CN")).toBe("zh-CN"); + expect(validateLocale("zh-TW")).toBe("zh-TW"); + expect(validateLocale("fr")).toBe("fr"); + expect(validateLocale("es")).toBe("es"); + expect(validateLocale(undefined)).toBeUndefined(); + expect(validateLocale("zh")).toBeUndefined(); + expect(validateLocale("de")).toBeUndefined(); + expect(validateLocale("")).toBeUndefined(); + expect(validateLocale(null)).toBeUndefined(); + expect(validateLocale(42)).toBeUndefined(); + }); + + it("round-trips a settings object without language unchanged (backward compat)", () => { + const legacy = { themeMode: "dark", colorTheme: "default" } as const; + const roundTripped = JSON.parse(JSON.stringify(legacy)) as Record; + expect("language" in roundTripped).toBe(false); + expect(validateLocale(roundTripped.language)).toBeUndefined(); + }); +}); diff --git a/packages/core/src/__tests__/settings-precedence.test.ts b/packages/core/src/__tests__/settings-precedence.test.ts index 8df5c5e82c..f33fcacc67 100644 --- a/packages/core/src/__tests__/settings-precedence.test.ts +++ b/packages/core/src/__tests__/settings-precedence.test.ts @@ -38,4 +38,18 @@ describe("settings precedence", () => { }); expect(scoped.project.worktrunk).toEqual({ enabled: false }); }); + + it("validates language at the global write boundary and clears it via null", async () => { + // Valid locale persists. + await harness.store().updateGlobalSettings({ language: "fr" }); + expect((await harness.store().getSettings()).language).toBe("fr"); + + // Invalid value is dropped at the boundary — prior choice survives. + await harness.store().updateGlobalSettings({ language: "klingon" } as never); + expect((await harness.store().getSettings()).language).toBe("fr"); + + // Explicit null clears the persisted key (reset to runtime auto-detect). + await harness.store().updateGlobalSettings({ language: null } as never); + expect((await harness.store().getSettings()).language).toBeUndefined(); + }); }); diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 516d0f0947..dc731acb8f 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,5 +1,5 @@ -export { COLUMNS, DEFAULT_COLUMN, isColumn, normalizeColumn, COLUMN_LABELS, COLUMN_DESCRIPTIONS, VALID_TRANSITIONS, DEFAULT_SETTINGS, DEFAULT_GLOBAL_SETTINGS, DEFAULT_PROJECT_SETTINGS, GLOBAL_SETTINGS_KEYS, PROJECT_SETTINGS_KEYS, isGlobalSettingsKey, isProjectSettingsKey, isMergeRequestContractShadowEnabled, resolvePersistAgentThinkingLog, THINKING_LEVELS, THEME_MODES, COLOR_THEMES, WORKFLOW_STEP_TEMPLATES, AGENT_PERMISSIONS, PERMANENT_AGENT_ACTION_CATEGORIES, AGENT_PERMISSION_POLICY_ACTION_CATEGORIES, AGENT_PROVISIONING_APPROVAL_MODES, SANDBOX_PROVISIONING_APPROVAL_MODES, AGENT_PERMISSION_POLICY_PRESET_IDS, LEGACY_AGENT_PERMISSION_POLICY_ACTION_CATEGORY_ALIASES, APPROVAL_REQUEST_STATUSES, APPROVAL_REQUEST_AUDIT_EVENT_TYPES, normalizeApprovalRequestActionCategory, isValidApprovalRequestTransition, agentToConfigSnapshot, diffConfigSnapshots, isEphemeralAgent, hasAgentIdentity, CheckoutConflictError, DEFAULT_HEARTBEAT_PROCEDURE_PATH, getDefaultHeartbeatProcedurePath, EXECUTION_MODES, DEFAULT_EXECUTION_MODE, TASK_PRIORITIES, DEFAULT_TASK_PRIORITY, HIGH_FANOUT_BLOCKER_TODO_THRESHOLD, STALE_HIGH_FANOUT_BLOCKER_AGE_THRESHOLD_MS, DASHBOARD_USER_ID, normalizeMessageParticipant, validateMessageMetadata, validateDockerNodeConfig, sanitizeDockerNodeConfigForResponse, normalizeMergeIntegrationWorktreeMode, normalizeMergeAdvanceAutoSyncMode, MERGE_ADVANCE_AUTO_SYNC_MODES, normalizeMergeConflictStrategy, normalizeMergeStrategyOverlapBehavior, normalizePostMergeAuditMode, POST_MERGE_AUDIT_MODES, normalizeMergeAuditAutoRecovery, MERGE_AUDIT_AUTO_RECOVERY_MODES, normalizeMergerMode, MERGER_MODES, normalizeAutoRecovery, AUTO_RECOVERY_MODES, buildResearchDocumentKey, REPO_OVERRIDE_RE, SHARED_STATE_SNAPSHOT_VERSION } from "./types.js"; -export type { Column, IssueInfo, IssueState, TaskSourceIssue, PrInfo, PrConflictState, PrConflictDiagnostics, PrCheckState, PrCheckStatus, PrStatus, BranchGroup, BranchGroupCreateInput, BranchGroupUpdate, BranchGroupPrState, Task, TaskTokenUsage, TaskAttachment, TaskComment, TaskCommentInput, TaskDocument, TaskDocumentRevision, TaskDocumentCreateInput, TaskDocumentWithTask, TaskCreateInput, TaskBranchContext, MeshReplicatedTaskCreatePayload, MeshReplicatedTaskApplyResult, TaskSource, SourceType, TaskDetail, RetrySummary, InboxTask, TodoList, TodoItem, TodoListCreateInput, TodoListUpdateInput, TodoItemCreateInput, TodoItemUpdateInput, TodoListWithItems, AgentLogEntry, AgentLogType, AgentRole, BoardConfig, DistributedTaskIdReserveInput, DistributedTaskIdReserveResult, DistributedTaskIdCommitInput, DistributedTaskIdCommitResult, DistributedTaskIdAbortInput, DistributedTaskIdAbortResult, DistributedTaskIdStateInput, DistributedTaskIdStateResult, AutostashOrphanRecord, AutostashOutcome, MergeDetails, MergeResult, MergeIntegrationWorktreeMode, MergeAdvanceAutoSyncMode, MergeConflictStrategy, CanonicalMergeConflictStrategy, MergeStrategyOverlapBehavior, PostMergeAuditMode, MergeAuditAutoRecoveryMode, MergerMode, MergerSettings, AutoRecoveryMode, AutoRecoveryFailureClass, AutoRecoverySettings, DirectMergeCommitStrategy, Settings, GlobalSettings, ProjectSettings, SecretsEnvConfig, WebSearchBackend, ResearchEnabledSources, ResearchGlobalDefaults, ResearchProjectLimits, ResearchProjectSettings, SandboxBackendName, SandboxFailureMode, SandboxPolicy, SandboxProjectSettings, EvalFollowUpPolicy, EvalProjectSettings, ResolvedEvalSettings, SettingsScope, DaemonTokenSettings, TaskStep, StepStatus, TaskLogEntry, RunMutationContext, ActivityLogEntry, ActivityEventType, ThinkingLevel, ThemeMode, ColorTheme, ExecutionMode, TaskPriority, MergeQueueEntry, MergeQueueEnqueueOptions, MergeQueueAcquireOptions, MergeQueueReleaseOutcome, MergeRequestState, MergeRequestRecord, CompletionHandoffMarker, HandoffEvidence, HandoffToReviewOptions, UnavailableNodePolicy, OwningNodeHandoffPolicy, PlanningQuestion, PlanningSummary, PlanningResponse, PlanningQuestionType, ArchivedTaskEntry, BatchStatusRequest, BatchStatusResponse, BatchStatusEntry, BatchStatusResult, GithubIssueAction, ModelPreset, WorkflowStep, WorkflowStepMode, WorkflowStepGateMode, WorkflowStepPhase, WorkflowStepInput, WorkflowStepResult, WorkflowStepTemplate, Agent, OrgTreeNode, AgentState, AgentDetail, AgentCreateInput, AgentUpdateInput, AgentApiKey, AgentApiKeyCreateResult, AgentCapability, AgentPromptTemplate, AgentPromptsConfig, AgentPermission, PermanentAgentActionCategory, PermanentAgentSensitiveActionCategory, PermanentAgentGatingContext, AgentPermissionPolicy, AgentPermissionPolicyRules, AgentPermissionPolicyActionCategory, AgentProvisioningApprovalMode, SandboxProvisioningApprovalMode, LegacyAgentPermissionPolicyActionCategory, ApprovalRequestActionCategoryInput, ApprovalRequestActionCategory, AgentPermissionPolicyDisposition, AgentPermissionPolicyPresetId, ApprovalRequestStatus, ApprovalRequestAuditEventType, ApprovalRequestActorSnapshot, ApprovalRequestTargetAction, ApprovalRequestAuditEvent, ApprovalRequest, ApprovalRequestCreateInput, ApprovalRequestDecisionInput, ApprovalRequestCompletionInput, ApprovalRequestListInput, TaskAssignSource, AgentAccessState, AgentHeartbeatConfig, AgentBudgetConfig, AgentBudgetStatus, InstructionsBundleConfig, MessageResponseMode, AgentHeartbeatEvent, AgentHeartbeatRun, BlockedStateSnapshot, HeartbeatInvocationSource, AgentTaskSession, AgentRating, AgentRatingSummary, AgentRatingInput, AgentConfigSnapshot, RevisionFieldDiff, AgentConfigRevision, AgentStats, ReflectionTrigger, ReflectionMetrics, AgentReflection, AgentPerformanceSummary, NtfyNotificationEvent, NotificationEvent, NotificationPayload, NotificationProviderConfig, CustomProvider, SteeringComment, ParticipantType, MessageType, Message, MessageCreateInput, MessageFilter, MessageMetadata, MessageReplyReference, Mailbox, CheckoutLease, CheckoutClaimPrecondition, TaskClaimRow, CentralClaimStore, RunAuditDomain, RunAuditEvent, RunAuditEventInput, RunAuditEventFilter, AgentMemoryInclusionMode, HeartbeatPromptTemplate, HeartbeatScopeDisciplineMode, WorktrunkSettings, WorktrunkOnFailure } from "./types.js"; +export { COLUMNS, DEFAULT_COLUMN, isColumn, normalizeColumn, COLUMN_LABELS, COLUMN_DESCRIPTIONS, VALID_TRANSITIONS, DEFAULT_SETTINGS, DEFAULT_GLOBAL_SETTINGS, DEFAULT_PROJECT_SETTINGS, GLOBAL_SETTINGS_KEYS, PROJECT_SETTINGS_KEYS, isGlobalSettingsKey, isProjectSettingsKey, isMergeRequestContractShadowEnabled, resolvePersistAgentThinkingLog, THINKING_LEVELS, THEME_MODES, COLOR_THEMES, SUPPORTED_LOCALES, DEFAULT_LOCALE, isLocale, WORKFLOW_STEP_TEMPLATES, AGENT_PERMISSIONS, PERMANENT_AGENT_ACTION_CATEGORIES, AGENT_PERMISSION_POLICY_ACTION_CATEGORIES, AGENT_PROVISIONING_APPROVAL_MODES, SANDBOX_PROVISIONING_APPROVAL_MODES, AGENT_PERMISSION_POLICY_PRESET_IDS, LEGACY_AGENT_PERMISSION_POLICY_ACTION_CATEGORY_ALIASES, APPROVAL_REQUEST_STATUSES, APPROVAL_REQUEST_AUDIT_EVENT_TYPES, normalizeApprovalRequestActionCategory, isValidApprovalRequestTransition, agentToConfigSnapshot, diffConfigSnapshots, isEphemeralAgent, hasAgentIdentity, CheckoutConflictError, DEFAULT_HEARTBEAT_PROCEDURE_PATH, getDefaultHeartbeatProcedurePath, EXECUTION_MODES, DEFAULT_EXECUTION_MODE, TASK_PRIORITIES, DEFAULT_TASK_PRIORITY, HIGH_FANOUT_BLOCKER_TODO_THRESHOLD, STALE_HIGH_FANOUT_BLOCKER_AGE_THRESHOLD_MS, DASHBOARD_USER_ID, normalizeMessageParticipant, validateMessageMetadata, validateDockerNodeConfig, sanitizeDockerNodeConfigForResponse, normalizeMergeIntegrationWorktreeMode, normalizeMergeAdvanceAutoSyncMode, MERGE_ADVANCE_AUTO_SYNC_MODES, normalizeMergeConflictStrategy, normalizeMergeStrategyOverlapBehavior, normalizePostMergeAuditMode, POST_MERGE_AUDIT_MODES, normalizeMergeAuditAutoRecovery, MERGE_AUDIT_AUTO_RECOVERY_MODES, normalizeMergerMode, MERGER_MODES, normalizeAutoRecovery, AUTO_RECOVERY_MODES, buildResearchDocumentKey, REPO_OVERRIDE_RE, SHARED_STATE_SNAPSHOT_VERSION } from "./types.js"; +export type { Column, IssueInfo, IssueState, TaskSourceIssue, PrInfo, PrConflictState, PrConflictDiagnostics, PrCheckState, PrCheckStatus, PrStatus, BranchGroup, BranchGroupCreateInput, BranchGroupUpdate, BranchGroupPrState, Task, TaskTokenUsage, TaskAttachment, TaskComment, TaskCommentInput, TaskDocument, TaskDocumentRevision, TaskDocumentCreateInput, TaskDocumentWithTask, TaskCreateInput, MeshReplicatedTaskCreatePayload, MeshReplicatedTaskApplyResult, TaskSource, SourceType, TaskDetail, RetrySummary, InboxTask, TodoList, TodoItem, TodoListCreateInput, TodoListUpdateInput, TodoItemCreateInput, TodoItemUpdateInput, TodoListWithItems, AgentLogEntry, AgentLogType, AgentRole, BoardConfig, DistributedTaskIdReserveInput, DistributedTaskIdReserveResult, DistributedTaskIdCommitInput, DistributedTaskIdCommitResult, DistributedTaskIdAbortInput, DistributedTaskIdAbortResult, DistributedTaskIdStateInput, DistributedTaskIdStateResult, AutostashOrphanRecord, AutostashOutcome, MergeDetails, MergeResult, MergeIntegrationWorktreeMode, MergeAdvanceAutoSyncMode, MergeConflictStrategy, CanonicalMergeConflictStrategy, MergeStrategyOverlapBehavior, PostMergeAuditMode, MergeAuditAutoRecoveryMode, MergerMode, MergerSettings, AutoRecoveryMode, AutoRecoveryFailureClass, AutoRecoverySettings, DirectMergeCommitStrategy, Settings, GlobalSettings, ProjectSettings, SecretsEnvConfig, WebSearchBackend, ResearchEnabledSources, ResearchGlobalDefaults, ResearchProjectLimits, ResearchProjectSettings, SandboxBackendName, SandboxFailureMode, SandboxPolicy, SandboxProjectSettings, EvalFollowUpPolicy, EvalProjectSettings, ResolvedEvalSettings, SettingsScope, DaemonTokenSettings, TaskStep, StepStatus, TaskLogEntry, RunMutationContext, ActivityLogEntry, ActivityEventType, ThinkingLevel, ThemeMode, ColorTheme, Locale, ExecutionMode, TaskPriority, MergeQueueEntry, MergeQueueEnqueueOptions, MergeQueueAcquireOptions, MergeQueueReleaseOutcome, MergeRequestState, MergeRequestRecord, CompletionHandoffMarker, HandoffEvidence, HandoffToReviewOptions, UnavailableNodePolicy, OwningNodeHandoffPolicy, PlanningQuestion, PlanningSummary, PlanningResponse, PlanningQuestionType, ArchivedTaskEntry, BatchStatusRequest, BatchStatusResponse, BatchStatusEntry, BatchStatusResult, GithubIssueAction, ModelPreset, WorkflowStep, WorkflowStepMode, WorkflowStepGateMode, WorkflowStepPhase, WorkflowStepInput, WorkflowStepResult, WorkflowStepTemplate, Agent, OrgTreeNode, AgentState, AgentDetail, AgentCreateInput, AgentUpdateInput, AgentApiKey, AgentApiKeyCreateResult, AgentCapability, AgentPromptTemplate, AgentPromptsConfig, AgentPermission, PermanentAgentActionCategory, PermanentAgentSensitiveActionCategory, PermanentAgentGatingContext, AgentPermissionPolicy, AgentPermissionPolicyRules, AgentPermissionPolicyActionCategory, AgentProvisioningApprovalMode, SandboxProvisioningApprovalMode, LegacyAgentPermissionPolicyActionCategory, ApprovalRequestActionCategoryInput, ApprovalRequestActionCategory, AgentPermissionPolicyDisposition, AgentPermissionPolicyPresetId, ApprovalRequestStatus, ApprovalRequestAuditEventType, ApprovalRequestActorSnapshot, ApprovalRequestTargetAction, ApprovalRequestAuditEvent, ApprovalRequest, ApprovalRequestCreateInput, ApprovalRequestDecisionInput, ApprovalRequestCompletionInput, ApprovalRequestListInput, TaskAssignSource, AgentAccessState, AgentHeartbeatConfig, AgentBudgetConfig, AgentBudgetStatus, InstructionsBundleConfig, MessageResponseMode, AgentHeartbeatEvent, AgentHeartbeatRun, BlockedStateSnapshot, HeartbeatInvocationSource, AgentTaskSession, AgentRating, AgentRatingSummary, AgentRatingInput, AgentConfigSnapshot, RevisionFieldDiff, AgentConfigRevision, AgentStats, ReflectionTrigger, ReflectionMetrics, AgentReflection, AgentPerformanceSummary, NtfyNotificationEvent, NotificationEvent, NotificationPayload, NotificationProviderConfig, CustomProvider, SteeringComment, ParticipantType, MessageType, Message, MessageCreateInput, MessageFilter, MessageMetadata, MessageReplyReference, Mailbox, CheckoutLease, CheckoutClaimPrecondition, TaskClaimRow, CentralClaimStore, RunAuditDomain, RunAuditEvent, RunAuditEventInput, RunAuditEventFilter, AgentMemoryInclusionMode, HeartbeatPromptTemplate, HeartbeatScopeDisciplineMode, WorktrunkSettings, WorktrunkOnFailure, TaskBranchContext } from "./types.js"; export { AGENT_VALID_TRANSITIONS, DUPLICATE_OF_METADATA_KEY } from "./types.js"; export { resolveEntryPointBranchAssignment, @@ -472,6 +472,7 @@ export { validateDirectMergeCommitStrategy, validateGithubAuthMode, validateGithubRepoSlug, + validateLocale, validateSandboxBackendName, validateSandboxFailureMode, validateSandboxPolicy, diff --git a/packages/core/src/settings-schema.ts b/packages/core/src/settings-schema.ts index cf37226559..c955e7c5ce 100644 --- a/packages/core/src/settings-schema.ts +++ b/packages/core/src/settings-schema.ts @@ -19,6 +19,7 @@ export const DEFAULT_GLOBAL_SETTINGS = { themeMode: "dark", colorTheme: "default", dashboardFontScalePct: 100, + language: undefined, defaultProvider: undefined, defaultModelId: undefined, testMode: undefined, diff --git a/packages/core/src/settings-validation.ts b/packages/core/src/settings-validation.ts index 33952de85c..2ca592b6a9 100644 --- a/packages/core/src/settings-validation.ts +++ b/packages/core/src/settings-validation.ts @@ -3,12 +3,14 @@ import type { GithubAuthMode, HeartbeatPromptTemplate, HeartbeatScopeDisciplineMode, + Locale, SandboxBackendName, SandboxFailureMode, SandboxPolicy, SandboxProjectSettings, UnavailableNodePolicy, } from "./types.js"; +import { isLocale } from "./types.js"; const UNAVAILABLE_NODE_POLICIES: readonly UnavailableNodePolicy[] = ["block", "fallback-local"] as const; const DIRECT_MERGE_COMMIT_STRATEGIES: readonly DirectMergeCommitStrategy[] = ["auto", "always-squash", "always-rebase"] as const; @@ -52,6 +54,14 @@ export function validateUnavailableNodePolicy(value: unknown): UnavailableNodePo : undefined; } +/** Returns a validated UI locale for global settings, otherwise undefined. */ +export function validateLocale(value: unknown): Locale | undefined { + if (value === undefined) { + return undefined; + } + return isLocale(value) ? value : undefined; +} + /** Returns a validated direct-merge commit strategy for project settings, otherwise undefined. */ export function validateDirectMergeCommitStrategy(value: unknown): DirectMergeCommitStrategy | undefined { if (value === undefined) { diff --git a/packages/core/src/store.ts b/packages/core/src/store.ts index a6b5a66df4..2322ed9883 100644 --- a/packages/core/src/store.ts +++ b/packages/core/src/store.ts @@ -27,6 +27,7 @@ import { * filtered out of the user-facing step manager and cleaned up on re-selection. */ const WORKFLOW_COMPILED_STEP_TEMPLATE_PREFIX = "workflow:"; import { resolveWorktrunkSettings, validateWorktrunkSettings } from "./worktrunk-settings.js"; +import { validateLocale } from "./settings-validation.js"; import { normalizeTaskPriority } from "./task-priority.js"; import { validateBranchGroupBranchName, filterTasksByBranchGroup } from "./branch-assignment.js"; import { allowsAutoMergeProcessing } from "./task-merge.js"; @@ -3323,6 +3324,23 @@ export class TaskStore extends EventEmitter { (globalPatch as Record)["experimentalFeatures"] = mergedMap; } + // Validate the optional UI locale at the write boundary: drop unrecognized + // values rather than persisting junk into settings.json. Runtime consumers + // also guard via isLocale, but the contract is `language?: Locale`. + // `null` passes through intact — GlobalSettingsStore treats null as + // "delete this key", which reverts the language to runtime auto-detect. + if ("language" in globalPatch) { + const rawLanguage = (globalPatch as Record)["language"]; + if (rawLanguage !== null) { + const validatedLanguage = validateLocale(rawLanguage); + if (validatedLanguage === undefined) { + delete (globalPatch as Record)["language"]; + } else { + globalPatch.language = validatedLanguage; + } + } + } + const updatedGlobal = await this.globalSettingsStore.updateSettings(globalPatch); const merged: Settings = { ...DEFAULT_SETTINGS, ...updatedGlobal, ...config.settings } as Settings; try { diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index e0b89c3743..8a2d4419fe 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -207,6 +207,24 @@ export const COLOR_THEMES = [ ] as const; export type ColorTheme = (typeof COLOR_THEMES)[number]; +/** UI locales supported across the dashboard and terminal UI. `en` is the + * source-of-truth language and the fallback for all others. Adding a locale + * here (plus translated catalogs) is the only code change a new language + * needs — see `@fusion/i18n`. zh-CN and zh-TW are independent catalogs and + * are never auto-converted between scripts. */ +export const SUPPORTED_LOCALES = ["en", "zh-CN", "zh-TW", "fr", "es", "ko"] as const; +export type Locale = (typeof SUPPORTED_LOCALES)[number]; +/** Source-of-truth language and the fallback for all locales. */ +export const DEFAULT_LOCALE: Locale = "en"; + +/** Narrow an arbitrary value to a supported `Locale`. */ +export function isLocale(value: unknown): value is Locale { + return ( + typeof value === "string" && + (SUPPORTED_LOCALES as readonly string[]).includes(value) + ); +} + export type PrStatus = "open" | "closed" | "merged" | "draft"; export type MergeStrategy = "direct" | "pull-request"; export type MergeIntegrationWorktreeMode = @@ -2444,6 +2462,10 @@ export interface GlobalSettings { colorTheme?: ColorTheme; /** Dashboard font size scale percentage. Bounded to 85-125. Default: 100. */ dashboardFontScalePct?: number; + /** Active UI locale (e.g. `"en"`, `"zh-CN"`, `"fr"`). One of `SUPPORTED_LOCALES`. + * When unset, each surface resolves the locale at runtime (browser/env + * detection) and falls back to `DEFAULT_LOCALE` ("en"). */ + language?: Locale; /** Default AI model provider name (e.g. `"anthropic"`, `"openai"`). * Must be set together with `defaultModelId`. When both are undefined, * the engine uses pi's automatic model resolution. */ diff --git a/packages/dashboard/app/App.tsx b/packages/dashboard/app/App.tsx index 3bcf1d8d9f..69783f81b5 100644 --- a/packages/dashboard/app/App.tsx +++ b/packages/dashboard/app/App.tsx @@ -1,4 +1,5 @@ import { useState, useCallback, useEffect, useMemo, useRef, lazy, Suspense } from "react"; +import { useTranslation } from "react-i18next"; import { computeCapacityRisk, DEFAULT_CAPACITY_RISK_TODO_THRESHOLD, @@ -49,6 +50,8 @@ import { useProjects } from "./hooks/useProjects"; import { useAgents } from "./hooks/useAgents"; import { useNodes } from "./hooks/useNodes"; import { useCurrentProject } from "./hooks/useCurrentProject"; +import { I18nextProvider } from "react-i18next"; +import i18n from "./i18n"; import { ToastProvider, useToast } from "./hooks/useToast"; import { ConfirmDialogProvider } from "./hooks/useConfirm"; import { useTheme } from "./hooks/useTheme"; @@ -234,6 +237,7 @@ export function shouldShowFirstEverBootLoader(projectsLoading: boolean, projectC } function AppInner() { + const { t } = useTranslation("app"); const { toasts, addToast, removeToast } = useToast(); const { shellApi, state: shellState, ready: shellReady, openConnectionManagerSignal } = useShellConnection(); const shellHost = useShellHostContext(); @@ -1361,7 +1365,7 @@ function AppInner() { if (showBackendConnectionErrorPage) { return ( { @@ -2085,16 +2089,18 @@ function AppInner() { export function App() { return ( - - - - - - - - - - - + + + + + + + + + + + + + ); } diff --git a/packages/dashboard/app/__tests__/agent-runs-ui.test.ts b/packages/dashboard/app/__tests__/agent-runs-ui.test.ts index 9d9e8578a7..946d4cec8e 100644 --- a/packages/dashboard/app/__tests__/agent-runs-ui.test.ts +++ b/packages/dashboard/app/__tests__/agent-runs-ui.test.ts @@ -132,8 +132,10 @@ describe("Agent runs UI — static analysis", () => { it("wires a stop run handler", () => { expect(agentDetailViewContent).toMatch(/handleStopRun|handleStop/); - expect(agentDetailViewContent).toMatch(/title:\s*"Stop Active Run"/); - expect(agentDetailViewContent).toMatch(/message:\s*"Stop the active run\? The agent's work will be interrupted\."/); + // Title may be a raw string or an i18n t() call whose default is "Stop Active Run" + expect(agentDetailViewContent).toMatch(/title:.*"Stop Active Run"/); + // Message may be a raw string or an i18n t() call whose default is the stop confirmation + expect(agentDetailViewContent).toMatch(/message:.*"Stop the active run\? The agent's work will be interrupted\."/); }); it("references stopAgentRun and stop button copy", () => { diff --git a/packages/dashboard/app/components/ActiveAgentsPanel.tsx b/packages/dashboard/app/components/ActiveAgentsPanel.tsx index b42a835e89..109e702670 100644 --- a/packages/dashboard/app/components/ActiveAgentsPanel.tsx +++ b/packages/dashboard/app/components/ActiveAgentsPanel.tsx @@ -1,5 +1,6 @@ import { useEffect, useState } from "react"; import { Activity, FileText } from "lucide-react"; +import { useTranslation } from "react-i18next"; import type { Agent } from "../api"; import type { TaskDetail } from "@fusion/core"; import { fetchTaskDetail } from "../api"; @@ -17,6 +18,7 @@ interface LiveAgentCardProps { const TASK_STATUS_POLL_MS = 5000; function LiveAgentCard({ agent, projectId, onSelect, onOpenTaskLogs }: LiveAgentCardProps) { + const { t } = useTranslation("app"); const { entries, isConnected } = useLiveTranscript(agent.taskId, projectId); const [task, setTask] = useState(null); @@ -64,8 +66,8 @@ function LiveAgentCard({ agent, projectId, onSelect, onOpenTaskLogs }: LiveAgent const nextMs = new Date(agent.lastHeartbeatAt).getTime() + intervalMs; const deltaSec = Math.round((nextMs - Date.now()) / 1000); if (!Number.isFinite(deltaSec)) return null; - if (deltaSec <= 0) return `Heartbeat overdue ${formatElapsed(-deltaSec)}`; - return `Next heartbeat in ${formatElapsed(deltaSec)}`; + if (deltaSec <= 0) return t("agents.heartbeatOverdue", "Heartbeat overdue {{elapsed}}", { elapsed: formatElapsed(-deltaSec) }); + return t("agents.nextHeartbeat", "Next heartbeat in {{elapsed}}", { elapsed: formatElapsed(deltaSec) }); })(); const currentStep = task?.steps?.[task.currentStep ?? 0]; @@ -100,7 +102,7 @@ function LiveAgentCard({ agent, projectId, onSelect, onOpenTaskLogs }: LiveAgent onKeyDown={handleKeyDown} role="button" tabIndex={0} - aria-label={`Select agent ${agent.name}`} + aria-label={t("agents.selectAgent", "Select agent {{name}}", { name: agent.name })} >
@@ -122,12 +124,11 @@ function LiveAgentCard({ agent, projectId, onSelect, onOpenTaskLogs }: LiveAgent // SSE stream to attach to; useLiveTranscript bails out with // isConnected=false. Showing "Connecting..." here is misleading // — the agent is just idle. - {agent.state === "running" ? "Starting..." : "Idle — no task assigned"} + {agent.state === "running" ? t("agents.starting", "Starting...") : t("agents.idleNoTask", "Idle — no task assigned")} ) : currentStep ? ( <>
- Step {stepNumber} - {totalSteps ? `/${totalSteps}` : ""}: {currentStep.name} + {t("agents.step", "Step {{number}}{{total}}: {{name}}", { number: stepNumber, total: totalSteps ? `/${totalSteps}` : "", name: currentStep.name })}
{executorModel && (
@@ -135,11 +136,11 @@ function LiveAgentCard({ agent, projectId, onSelect, onOpenTaskLogs }: LiveAgent
)}
- {isConnected ? "Waiting for output..." : "Connecting to log stream..."} + {isConnected ? t("agents.waitingOutput", "Waiting for output...") : t("agents.connectingStream", "Connecting to log stream...")}
) : ( - {isConnected ? "Waiting for output..." : "Connecting..."} + {isConnected ? t("agents.waitingOutput", "Waiting for output...") : t("agents.connecting", "Connecting...")} )}
) : ( @@ -167,11 +168,11 @@ function LiveAgentCard({ agent, projectId, onSelect, onOpenTaskLogs }: LiveAgent type="button" className="live-agent-card-logs-btn" onClick={handleViewLogs} - title="View live run logs" - aria-label={`View live logs for ${agent.taskId}`} + title={t("agents.viewLiveLogs", "View live run logs")} + aria-label={t("agents.viewLogsFor", "View live logs for {{taskId}}", { taskId: agent.taskId })} > - Live logs + {t("agents.liveLogs", "Live logs")} )} {isConnected && } @@ -196,6 +197,7 @@ interface ActiveAgentsPanelProps { } export function ActiveAgentsPanel({ agents, projectId, onAgentSelect, onOpenTaskLogs, className = "" }: ActiveAgentsPanelProps) { + const { t } = useTranslation("app"); // Dedupe by id defensively. The store should return unique agents but a race // between the initial fetch and an SSE refresh can briefly surface the same // agent twice — without this guard React floods the console with duplicate @@ -208,7 +210,7 @@ export function ActiveAgentsPanel({ agents, projectId, onAgentSelect, onOpenTask
- Active Agents ({uniqueAgents.length}) + {t("agents.activeAgents", "Active Agents ({{count}})", { count: uniqueAgents.length })}
{uniqueAgents.map(agent => ( diff --git a/packages/dashboard/app/components/ActivityLogModal.tsx b/packages/dashboard/app/components/ActivityLogModal.tsx index 4af53d8f94..3d213725c8 100644 --- a/packages/dashboard/app/components/ActivityLogModal.tsx +++ b/packages/dashboard/app/components/ActivityLogModal.tsx @@ -2,6 +2,8 @@ // in ScriptsModal.css. Until extracted, import that file so this eager modal is styled. import "./ScriptsModal.css"; import { useState, useEffect } from "react"; +import { useTranslation } from "react-i18next"; +import type { TFunction } from "i18next"; import { X, History, Trash2, Filter, RefreshCw, CheckCircle, XCircle, ArrowRight, Plus, Settings, AlertCircle, Loader2, Folder } from "lucide-react"; import { clearActivityLog, type ActivityLogEntry, type ActivityEventType, type ActivityFeedEntry } from "../api"; import { useActivityLog } from "../hooks/useActivityLog"; @@ -23,23 +25,25 @@ interface ActivityLogModalProps { currentProject?: ProjectInfo | null; } -const EVENT_TYPE_LABELS: Record = { - "task:created": "Task Created", - "task:moved": "Task Moved", - "task:updated": "Task Updated", - "task:deleted": "Task Deleted", - "task:merged": "Task Merged", - "task:failed": "Task Failed", - "task:duplicate-warning-overridden": "Duplicate Warning Overridden", - "task:auto-archived-ghost-bug": "Task Auto-Archived (Ghost Bug)", - "task:auto-archived-duplicate": "Task Auto-Archived (Duplicate)", - "task:merge-worktree-reacquired": "Merge Worktree Reacquired", - "task:auto-archived-deterministic-duplicate": "Task Auto-Archived (Deterministic Duplicate)", - "task:auto-archived-near-duplicate": "Task Auto-Archived (Near-Duplicate)", - "task:near-duplicate-flagged": "Near-Duplicate Flagged", - "settings:updated": "Settings Updated", - "project:isolation-transition": "Project Isolation Transition", -}; +function getEventTypeLabels(t: TFunction<"app">): Record { + return { + "task:created": t("activityLog.eventType.taskCreated", "Task Created"), + "task:moved": t("activityLog.eventType.taskMoved", "Task Moved"), + "task:updated": t("activityLog.eventType.taskUpdated", "Task Updated"), + "task:deleted": t("activityLog.eventType.taskDeleted", "Task Deleted"), + "task:merged": t("activityLog.eventType.taskMerged", "Task Merged"), + "task:failed": t("activityLog.eventType.taskFailed", "Task Failed"), + "task:duplicate-warning-overridden": t("activityLog.eventType.duplicateWarningOverridden", "Duplicate Warning Overridden"), + "task:auto-archived-ghost-bug": t("activityLog.eventType.autoArchivedGhostBug", "Task Auto-Archived (Ghost Bug)"), + "task:auto-archived-duplicate": t("activityLog.eventType.autoArchivedDuplicate", "Task Auto-Archived (Duplicate)"), + "task:merge-worktree-reacquired": t("activityLog.eventType.mergeWorktreeReacquired", "Merge Worktree Reacquired"), + "task:auto-archived-deterministic-duplicate": t("activityLog.eventType.autoArchivedDeterministicDuplicate", "Task Auto-Archived (Deterministic Duplicate)"), + "task:auto-archived-near-duplicate": t("activityLog.eventType.autoArchivedNearDuplicate", "Task Auto-Archived (Near-Duplicate)"), + "task:near-duplicate-flagged": t("activityLog.eventType.nearDuplicateFlagged", "Near-Duplicate Flagged"), + "settings:updated": t("activityLog.eventType.settingsUpdated", "Settings Updated"), + "project:isolation-transition": t("activityLog.eventType.projectIsolationTransition", "Project Isolation Transition"), + }; +} const EVENT_TYPE_ICONS: Record = { "task:created": , @@ -59,7 +63,7 @@ const EVENT_TYPE_ICONS: Record = { "project:isolation-transition": , }; -function formatTimestamp(timestamp: string): string { +function formatTimestamp(timestamp: string, t: TFunction<"app">): string { const date = new Date(timestamp); const now = new Date(); const diffMs = now.getTime() - date.getTime(); @@ -67,10 +71,10 @@ function formatTimestamp(timestamp: string): string { const diffHours = Math.floor(diffMs / 3600000); const diffDays = Math.floor(diffMs / 86400000); - if (diffMins < 1) return "Just now"; - if (diffMins < 60) return `${diffMins}m ago`; - if (diffHours < 24) return `${diffHours}h ago`; - if (diffDays < 7) return `${diffDays}d ago`; + if (diffMins < 1) return t("activityLog.time.justNow", "Just now"); + if (diffMins < 60) return t("activityLog.time.minutesAgo", "{{count}}m ago", { count: diffMins }); + if (diffHours < 24) return t("activityLog.time.hoursAgo", "{{count}}h ago", { count: diffHours }); + if (diffDays < 7) return t("activityLog.time.daysAgo", "{{count}}d ago", { count: diffDays }); return date.toLocaleDateString(undefined, { month: "short", day: "numeric" }); } @@ -91,7 +95,7 @@ function formatTimestamp(timestamp: string): string { * - Event type filter * - Real-time updates via useActivityLog hook */ -export function ActivityLogModal({ +export function ActivityLogModal({ isOpen, onClose, tasks: _tasks, @@ -101,6 +105,8 @@ export function ActivityLogModal({ onProjectFilterChange, currentProject, }: ActivityLogModalProps) { + const { t } = useTranslation("app"); + const EVENT_TYPE_LABELS = getEventTypeLabels(t); const [filteredType, setFilteredType] = useState("all"); const [filteredProjectId, setFilteredProjectId] = useState(projectId || "all"); const [showConfirmClear, setShowConfirmClear] = useState(false); @@ -209,7 +215,7 @@ export function ActivityLogModal({
- Activity Log + {t("activityLog.title", "Activity Log")}
{/* Project filter dropdown (when projects provided) */} @@ -222,7 +228,7 @@ export function ActivityLogModal({ className="activity-log-filter-select" data-testid="activity-project-filter" > - + {projects.map((project) => ( + {Object.entries(EVENT_TYPE_LABELS).map(([type, label]) => (
)} @@ -324,9 +330,9 @@ export function ActivityLogModal({

- {isFilterActive - ? "No activity matches the current filters" - : "No activity recorded yet"} + {isFilterActive + ? t("activityLog.noMatchingActivity", "No activity matches the current filters") + : t("activityLog.noActivityRecorded", "No activity recorded yet")}

{isFilterActive && ( )}
@@ -359,7 +365,7 @@ export function ActivityLogModal({ {EVENT_TYPE_LABELS[entry.type]} - {formatTimestamp(entry.timestamp)} + {formatTimestamp(entry.timestamp, t)}
@@ -386,7 +392,9 @@ export function ActivityLogModal({ )} {typeof entry.metadata.merged === "boolean" && ( - {entry.metadata.merged ? "Merged" : "Not merged"} + {entry.metadata.merged + ? t("activityLog.merged", "Merged") + : t("activityLog.notMerged", "Not merged")} )}
@@ -402,7 +410,7 @@ export function ActivityLogModal({ onClick={refresh} data-testid="activity-load-more" > - Load More + {t("activityLog.loadMore", "Load More")} )} @@ -417,20 +425,20 @@ export function ActivityLogModal({ {showConfirmClear && (
-

Clear Activity Log?

-

This will permanently delete all activity log entries. This action cannot be undone.

+

{t("activityLog.confirmClear", "Clear Activity Log?")}

+

{t("activityLog.confirmClearMessage", "This will permanently delete all activity log entries. This action cannot be undone.")}

diff --git a/packages/dashboard/app/components/AddNodeModal.tsx b/packages/dashboard/app/components/AddNodeModal.tsx index 457e62e370..3b2517e8a2 100644 --- a/packages/dashboard/app/components/AddNodeModal.tsx +++ b/packages/dashboard/app/components/AddNodeModal.tsx @@ -1,4 +1,6 @@ import { useCallback, useEffect, useMemo, useState } from "react"; +import type { TFunction } from "i18next"; +import { useTranslation } from "react-i18next"; import type { NodeProjectMappingInput, ProjectInfo, RemoteNodeDiscoveredProject, RemoteNodeProjectDiscoveryResult } from "../api"; import { validateProjectPath } from "../utils/projectDetection"; import type { ToastType } from "../hooks/useToast"; @@ -47,25 +49,25 @@ interface FormErrors { const MAX_CONCURRENT_MIN = 1; const MAX_CONCURRENT_MAX = 10; -function validateInput(input: AddNodeInput): FormErrors { +function validateInput(input: AddNodeInput, t: TFunction<"app">): FormErrors { const errors: FormErrors = { projectMappings: {} }; if (!input.name.trim()) { - errors.name = "Name is required"; + errors.name = t("nodes.nameRequired", "Name is required"); } if (input.type === "remote" && !input.url?.trim()) { - errors.url = "URL is required for remote nodes"; + errors.url = t("nodes.urlRequired", "URL is required for remote nodes"); } if (!Number.isFinite(input.maxConcurrent) || input.maxConcurrent < MAX_CONCURRENT_MIN || input.maxConcurrent > MAX_CONCURRENT_MAX) { - errors.maxConcurrent = `Concurrency must be between ${MAX_CONCURRENT_MIN} and ${MAX_CONCURRENT_MAX}`; + errors.maxConcurrent = t("nodes.concurrencyRange", "Concurrency must be between {{min}} and {{max}}", { min: MAX_CONCURRENT_MIN, max: MAX_CONCURRENT_MAX }); } for (const mapping of input.projectMappings) { const validation = validateProjectPath(mapping.path); if (!validation.valid) { - errors.projectMappings[mapping.projectId] = validation.error ?? "Path is invalid"; + errors.projectMappings[mapping.projectId] = validation.error ?? t("nodes.pathInvalid", "Path is invalid"); } } @@ -75,6 +77,7 @@ function validateInput(input: AddNodeInput): FormErrors { type DiscoveryState = "idle" | "loading" | "success" | "error"; export function AddNodeModal({ isOpen, onClose, onSubmit, onDiscoverRemoteProjects, addToast, projects }: AddNodeModalProps) { + const { t } = useTranslation("app"); useMobileScrollLock(isOpen); const [name, setName] = useState(""); const [type, setType] = useState<"local" | "remote">("local"); @@ -143,7 +146,7 @@ export function AddNodeModal({ isOpen, onClose, onSubmit, onDiscoverRemoteProjec const trimmedUrl = url.trim(); if (!trimmedUrl) { - setErrors((current) => ({ ...current, url: "URL is required for remote nodes" })); + setErrors((current) => ({ ...current, url: t("nodes.urlRequired", "URL is required for remote nodes") })); return; } @@ -175,9 +178,9 @@ export function AddNodeModal({ isOpen, onClose, onSubmit, onDiscoverRemoteProjec } catch (error) { setDiscoveryState("error"); setDiscoveredProjects([]); - setDiscoveryError(error instanceof Error ? error.message : "Failed to discover remote projects"); + setDiscoveryError(error instanceof Error ? error.message : t("nodes.discoveryFailed", "Failed to discover remote projects")); } - }, [apiKey, apiKeyMode, discoveryState, isSubmitting, onDiscoverRemoteProjects, projects, url]); + }, [apiKey, apiKeyMode, discoveryState, isSubmitting, onDiscoverRemoteProjects, projects, t, url]); useEffect(() => { if (type !== "remote") { @@ -195,7 +198,7 @@ export function AddNodeModal({ isOpen, onClose, onSubmit, onDiscoverRemoteProjec const handleSubmit = useCallback(async () => { if (isSubmitting) return; - const validationErrors = validateInput(input); + const validationErrors = validateInput(input, t); setErrors(validationErrors); if ( @@ -208,7 +211,7 @@ export function AddNodeModal({ isOpen, onClose, onSubmit, onDiscoverRemoteProjec } if (input.type === "remote" && discoveryState !== "success") { - setDiscoveryError("Discover remote projects before adding this node."); + setDiscoveryError(t("nodes.discoverBeforeAdding", "Discover remote projects before adding this node.")); return; } @@ -216,15 +219,15 @@ export function AddNodeModal({ isOpen, onClose, onSubmit, onDiscoverRemoteProjec try { await onSubmit(input); - addToast(`Node "${input.name}" registered`, "success"); + addToast(t("nodes.registered", "Node \"{{name}}\" registered", { name: input.name }), "success"); closeModal(); } catch (error) { - const message = error instanceof Error ? error.message : "Failed to register node"; + const message = error instanceof Error ? error.message : t("nodes.registerFailed", "Failed to register node"); addToast(message, "error"); } finally { setIsSubmitting(false); } - }, [addToast, closeModal, discoveryState, input, isSubmitting, onSubmit]); + }, [addToast, closeModal, discoveryState, input, isSubmitting, onSubmit, t]); const toggleProjectSelection = (project: ProjectInfo) => { setSelectedProjectPaths((current) => { @@ -253,25 +256,25 @@ export function AddNodeModal({ isOpen, onClose, onSubmit, onDiscoverRemoteProjec return (
-
event.stopPropagation()} role="dialog" aria-modal="true" aria-label="Add Node"> +
event.stopPropagation()} role="dialog" aria-modal="true" aria-label={t("nodes.addNode", "Add Node")}>
-

Add Node

-
-

Register an existing Fusion node by providing its connection details and concurrency settings.

+

{t("nodes.description", "Register an existing Fusion node by providing its connection details and concurrency settings.")}

{type === "remote" && (
@@ -384,7 +387,7 @@ export function AddNodeModal({ isOpen, onClose, onSubmit, onDiscoverRemoteProjec )}
-

Attach Existing Projects

-

Select existing projects to run on this node and provide the node-specific absolute path for each one.

+

{t("nodes.attachProjects", "Attach Existing Projects")}

+

{t("nodes.attachProjectsHint", "Select existing projects to run on this node and provide the node-specific absolute path for each one.")}

{projects.length === 0 ? ( -

No projects are currently registered.

+

{t("nodes.noProjects", "No projects are currently registered.")}

) : (
{projects.map((project) => { @@ -422,18 +425,18 @@ export function AddNodeModal({ isOpen, onClose, onSubmit, onDiscoverRemoteProjec {selected && (
- +
diff --git a/packages/dashboard/app/components/AgentDetailView.tsx b/packages/dashboard/app/components/AgentDetailView.tsx index 20d1187e6c..c5b580419d 100644 --- a/packages/dashboard/app/components/AgentDetailView.tsx +++ b/packages/dashboard/app/components/AgentDetailView.tsx @@ -1,6 +1,7 @@ import "./AgentDetailView.css"; import "./MailboxModal.css"; import { useState, useEffect, useCallback, useRef, useMemo } from "react"; +import { useTranslation } from "react-i18next"; import { Bot, Heart, Activity, Pause, Play, Square, Trash2, RefreshCw, Settings, FileText, ActivitySquare, X, Copy, @@ -43,25 +44,32 @@ function cn(...classes: (string | boolean | undefined | null)[]): string { /** * Format an ISO timestamp to a relative time string. */ -export function relativeTime(iso: string): string { +export function relativeTime(iso: string, t?: (key: string, defaultValue: string, options?: Record) => string): string { const now = Date.now(); const then = new Date(iso).getTime(); const diffMs = now - then; + // Fallback interpolates {{n}} manually when no t() is provided + const tr = t ?? ((_key: string, def: string, opts?: Record) => { + if (!opts) return def; + return def.replace(/\{\{(\w+)\}\}/g, (_, k) => String(opts[k] ?? "")); + }); // Future if (diffMs < 0) { const absDiff = Math.abs(diffMs); - if (absDiff < 60_000) return "in a moment"; - if (absDiff < 3_600_000) return `in ${Math.floor(absDiff / 60_000)}m`; - if (absDiff < 86_400_000) return `in ${Math.floor(absDiff / 3_600_000)}h`; - return `in ${Math.floor(absDiff / 86_400_000)}d`; + if (absDiff < 60_000) return tr("time.inAMoment", "in a moment"); + if (absDiff < 3_600_000) { const n = Math.floor(absDiff / 60_000); return tr("time.inMinutes", "in {{n}}m", { n }); } + if (absDiff < 86_400_000) { const n = Math.floor(absDiff / 3_600_000); return tr("time.inHours", "in {{n}}h", { n }); } + const n = Math.floor(absDiff / 86_400_000); + return tr("time.inDays", "in {{n}}d", { n }); } // Past - if (diffMs < 60_000) return "just now"; - if (diffMs < 3_600_000) return `${Math.floor(diffMs / 60_000)}m ago`; - if (diffMs < 86_400_000) return `${Math.floor(diffMs / 3_600_000)}h ago`; - return `${Math.floor(diffMs / 86_400_000)}d ago`; + if (diffMs < 60_000) return tr("time.justNow", "just now"); + if (diffMs < 3_600_000) { const n = Math.floor(diffMs / 60_000); return tr("time.minutesAgo", "{{n}}m ago", { n }); } + if (diffMs < 86_400_000) { const n = Math.floor(diffMs / 3_600_000); return tr("time.hoursAgo", "{{n}}h ago", { n }); } + const n = Math.floor(diffMs / 86_400_000); + return tr("time.daysAgo", "{{n}}d ago", { n }); } interface AgentDetailViewProps { @@ -109,18 +117,6 @@ const RUN_STATUS_ICONS: Record = { - "long-term": "Long-term", - daily: "Daily", - dreams: "Dreams", -}; - -const MEMORY_LAYER_DESCRIPTIONS: Record = { - "long-term": "Curated durable decisions, conventions, constraints, and pitfalls for this specific agent.", - daily: "Raw daily observations and open loops recorded by this agent.", - dreams: "Synthesized patterns and emerging themes distilled from this agent's daily memory.", -}; - const DEFAULT_HEARTBEAT_INTERVAL_LABEL = formatHeartbeatInterval(DEFAULT_HEARTBEAT_INTERVAL_MS); const CONFIG_AUTOSAVE_DEBOUNCE_MS = 700; @@ -135,6 +131,7 @@ function pickDefaultAgentMemoryPath(files: MemoryFileInfo[], currentPath: string } export function AgentDetailView({ agentId, projectId, onClose, addToast, onChildClick, inline = false, showInlineBackButton = false, initialTab, initialRunId, preferActiveRun = false, onMutationSuccess }: AgentDetailViewProps) { + const { t } = useTranslation("app"); const [agent, setAgent] = useState(null); const { confirm } = useConfirm(); const [logs, setLogs] = useState([]); @@ -511,11 +508,11 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild try { await updateAgentState(agentId, newState, projectId); - addToast(`Agent state updated to ${newState}`, "success"); + addToast(t("agents.stateUpdated", "Agent state updated to {{newState}}", { newState }), "success"); await handleSavedMutation(); } catch (err) { setAgent((prev) => (prev ? { ...prev, state: previousState } : prev)); - addToast(`Failed to update state: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.stateUpdateFailed", "Failed to update state: {{error}}", { error: getErrorMessage(err) }), "error"); } finally { setIsTransitioning(false); } @@ -537,13 +534,13 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild const skippedCount = nonEphemeralAgents.length - eligibleAgents.length; if (eligibleAgents.length === 0) { - addToast(`No agents eligible to ${targetState === "paused" ? "pause" : "resume"}`, "error"); + addToast(t("agents.bulkNoEligible", "No agents eligible to {{action}}", { action: targetState === "paused" ? t("agents.pause", "pause") : t("agents.resume", "resume") }), "error"); return; } const confirmed = await confirm({ - title: targetState === "paused" ? "Pause All Agents" : "Resume All Agents", - message: `${targetState === "paused" ? "Pause" : "Resume"} ${eligibleAgents.length} agent${eligibleAgents.length === 1 ? "" : "s"} in this project?`, + title: targetState === "paused" ? t("agents.pauseAllTitle", "Pause All Agents") : t("agents.resumeAllTitle", "Resume All Agents"), + message: t("agents.bulkConfirmMessage", "{{action}} {{count}} agent(s) in this project?", { action: targetState === "paused" ? t("agents.pauseAction", "Pause") : t("agents.resumeAction", "Resume"), count: eligibleAgents.length }), danger: targetState === "paused", }); if (!confirmed) return; @@ -558,21 +555,23 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild const successCount = results.length - failedResults.length; const failureCount = failedResults.length; - const baseSummary = `${targetState === "paused" ? "Paused" : "Resumed"} ${successCount} agent${successCount === 1 ? "" : "s"}; skipped ${skippedCount}`; + const actionWord = targetState === "paused" ? t("agents.pausedPast", "Paused") : t("agents.resumedPast", "Resumed"); + const agentWord = successCount === 1 ? t("agents.agentSingular", "agent") : t("agents.agentPlural", "agents"); + const baseSummary = t(successCount === 1 ? "agents.bulkResult_one" : "agents.bulkResult_other", "{{action}} {{successCount}} {{agentWord}}; skipped {{skippedCount}}", { action: actionWord, successCount, agentWord, skippedCount }); if (failureCount > 0) { const failureSummary = failedResults .slice(0, 3) .map(({ agent, result }) => `${agent.name || agent.id}: ${getErrorMessage(result.reason)}`) .join("; "); - addToast(`${baseSummary}; failed ${failureCount}${failureSummary ? ` (${failureSummary})` : ""}`, "error"); + addToast(t("agents.bulkResultWithFailures", "{{summary}}; failed {{failureCount}}{{detail}}", { summary: baseSummary, failureCount, detail: failureSummary ? ` (${failureSummary})` : "" }), "error"); } else { addToast(baseSummary, "success"); } await handleSavedMutation(); } catch (err) { - addToast(`Failed to ${targetState === "paused" ? "pause" : "resume"} agents: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.bulkActionFailed", "Failed to {{action}} agents: {{error}}", { action: targetState === "paused" ? t("agents.pause", "pause") : t("agents.resume", "resume"), error: getErrorMessage(err) }), "error"); } finally { setIsBulkActionRunning(false); } @@ -583,10 +582,10 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild setIsStartingRun(true); try { await startAgentRun(agentId, projectId, { source: "on_demand", triggerDetail: "Triggered from dashboard" }); - addToast(`Heartbeat run started for ${agent?.name ?? agentId}`, "success"); + addToast(t("agents.heartbeatStarted", "Heartbeat run started for {{name}}", { name: agent?.name ?? agentId }), "success"); setRunNowRefreshToken((prev) => prev + 1); } catch (err) { - addToast(`Failed to start heartbeat run: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.heartbeatStartFailed", "Failed to start heartbeat run: {{error}}", { error: getErrorMessage(err) }), "error"); } finally { setIsStartingRun(false); } @@ -595,18 +594,18 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild const handleDelete = async () => { if (!agent) return; const shouldDelete = await confirm({ - title: "Delete Agent", - message: `Delete agent "${agent.name}"? This cannot be undone.`, + title: t("agents.deleteTitle", "Delete Agent"), + message: t("agents.deleteConfirm", "Delete agent \"{{name}}\"? This cannot be undone.", { name: agent.name }), danger: true, }); if (!shouldDelete) return; try { await deleteAgent(agentId, projectId); - addToast(`Agent "${agent.name}" deleted`, "success"); + addToast(t("agents.deleted", "Agent \"{{name}}\" deleted", { name: agent.name }), "success"); await notifyMutationSuccess(true); onClose(); } catch (err) { - addToast(`Failed to delete agent: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.deleteFailed", "Failed to delete agent: {{error}}", { error: getErrorMessage(err) }), "error"); } }; @@ -627,7 +626,7 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild const copyAgentId = () => { if (agent) { navigator.clipboard.writeText(agent.id); - addToast("Agent ID copied to clipboard", "success"); + addToast(t("agents.idCopied", "Agent ID copied to clipboard"), "success"); } }; @@ -637,7 +636,7 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild
- Loading agent... + {t("agents.loading", "Loading agent...")}
); @@ -657,7 +656,7 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild
- Loading agent... + {t("agents.loading", "Loading agent...")}
@@ -692,10 +691,10 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild type="button" className="btn agent-detail-inline-back" onClick={onClose} - aria-label="Back to agents" + aria-label={t("agents.backToAgents", "Back to agents")} > - Agents + {t("agents.agentsLabel", "Agents")} ) : null}
@@ -726,65 +725,65 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild <> )} {agent.state === "active" && ( <> - - )} {agent.state === "paused" && ( <> - )} {agent.state === "running" && ( <> - - )} @@ -792,11 +791,11 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild <> - )} @@ -811,8 +810,8 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild onClick={() => setIsBulkMenuOpen((open) => !open)} aria-haspopup="menu" aria-expanded={isBulkMenuOpen} - aria-label="Bulk agent actions" - title="Bulk agent actions" + aria-label={t("agents.bulkActions", "Bulk agent actions")} + title={t("agents.bulkActions", "Bulk agent actions")} disabled={isTransitioning || isBulkActionRunning} > @@ -826,13 +825,13 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild onClick={() => void handleBulkStateChange("paused")} disabled={isPauseAllDisabled || isBulkActionRunning} > - Pause All Agents + {t("agents.pauseAll", "Pause All Agents")} {isBulkEligibilityLoading - ? "Loading eligible agents..." + ? t("agents.loadingEligible", "Loading eligible agents...") : isPauseAllDisabled - ? "No active agents eligible" - : `Pause ${bulkPauseEligibleCount} active/running agent${bulkPauseEligibleCount === 1 ? "" : "s"}`} + ? t("agents.noActiveEligible", "No active agents eligible") + : t(bulkPauseEligibleCount === 1 ? "agents.pauseCountHint_one" : "agents.pauseCountHint_other", bulkPauseEligibleCount === 1 ? "Pause {{count}} active/running agent" : "Pause {{count}} active/running agents", { count: bulkPauseEligibleCount })}
)}
- {!inline && ( - )} @@ -868,16 +867,31 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild {/* Tabs */}
- {TABS.map(tab => ( - - ))} + {TABS.map(tab => { + const tabLabels: Record = { + dashboard: t("agents.tabDashboard", "Dashboard"), + logs: t("agents.tabLogs", "Logs"), + mail: t("agents.tabMail", "Mail"), + runs: t("agents.tabRuns", "Runs"), + tasks: t("agents.tabTasks", "Tasks"), + employees: t("agents.tabEmployees", "Employees"), + soul: t("agents.tabSoul", "Soul"), + instructions: t("agents.tabInstructions", "Instructions"), + memory: t("agents.tabMemory", "Agent Memory"), + reflections: t("agents.tabReflections", "Evaluation"), + config: t("agents.tabConfig", "Settings"), + }; + return ( + + ); + })}
{/* Tab Content */} @@ -896,7 +910,7 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild logs={logs} isStreaming={isStreaming} hasTask={!!agent.taskId || logs.length > 0 || latestRun !== null} - fallbackLabel={!agent.taskId && latestRun ? `Latest run · ${latestRun.id.slice(0, 8)}` : null} + fallbackLabel={!agent.taskId && latestRun ? t("agents.latestRunLabel", "Latest run · {{id}}", { id: latestRun.id.slice(0, 8) }) : null} /> )} @@ -996,7 +1010,7 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild {/* Footer with agent ID */} {!inline && (
- @@ -1005,7 +1019,7 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild {agent.taskId && ( <> | - Working on: + {t("agents.workingOn", "Working on:")} {agent.taskId} @@ -1021,17 +1035,18 @@ export function AgentDetailView({ agentId, projectId, onClose, addToast, onChild // ── Dashboard Tab ─────────────────────────────────────────────────────────── -function DashboardTab({ - agent, +function DashboardTab({ + agent, health, onChildClick, projectId, -}: { - agent: AgentDetail; +}: { + agent: AgentDetail; health: AgentHealthStatus; onChildClick?: (childId: string) => void; projectId?: string; }) { + const { t } = useTranslation("app"); const stateStyle = STATE_COLORS[agent.state]; const [chainOfCommand, setChainOfCommand] = useState([]); const [isLoadingChainOfCommand, setIsLoadingChainOfCommand] = useState(true); @@ -1168,34 +1183,34 @@ function DashboardTab({ {budgetStatus?.isOverBudget && (
⚠️ - Budget Exhausted: This agent has exceeded its token budget and may operate with limited functionality. + {t("agents.budgetExhaustedTitle", "Budget Exhausted:")} {t("agents.budgetExhaustedBody", "This agent has exceeded its token budget and may operate with limited functionality.")}
)}
-

Overview

+

{t("agents.overview", "Overview")}

{agent.name} {agent.state}
{health.icon} {health.label} {(agent.pendingApprovalCount ?? 0) > 0 ? ( - + - {agent.pendingApprovalCount} pending approvals + {t("agents.pendingApprovalsCount", "{{count}} pending approvals", { count: agent.pendingApprovalCount })} ) : null} - Role: {agent.role} + {t("agents.roleLabel", "Role: {{role}}", { role: agent.role })} - {runtimeHint ? "Runtime" : "Model"} - {modelDisplay ?? "Auto"} + {runtimeHint ? t("agents.runtime", "Runtime") : t("agents.model", "Model")} + {modelDisplay ?? t("agents.auto", "Auto")} {agentSkills.length > 0 ? ( - Skills - + {t("agents.skills", "Skills")} + {agentSkills.map((skillId) => { const isSelected = selectedSkillId === skillId; return ( @@ -1206,7 +1221,7 @@ function DashboardTab({ title={skillId} onClick={() => handleSkillBadgeClick(skillId)} aria-expanded={isSelected} - aria-label={`View details for ${formatAgentSkillBadgeLabel(skillId)}`} + aria-label={t("agents.viewSkillDetails", "View details for {{skill}}", { skill: formatAgentSkillBadgeLabel(skillId) })} > {formatAgentSkillBadgeLabel(skillId)} @@ -1215,7 +1230,7 @@ function DashboardTab({ ) : ( - Skills: — + {t("agents.skillsNone", "Skills: —")} )}
{selectedSkillId ? ( @@ -1228,70 +1243,70 @@ function DashboardTab({ onClick={() => handleSkillBadgeClick(selectedSkillId)} > - Close + {t("common.close", "Close")}
{isLoadingSkillContent ? (
- Loading skill content... + {t("agents.loadingSkillContent", "Loading skill content...")}
) : skillContentError ? (
{skillContentError}
) : selectedSkillContent ? ( -
{selectedSkillContent.skillMd || "(No SKILL.md found)"}
+
{selectedSkillContent.skillMd || t("agents.noSkillMd", "(No SKILL.md found)")}
) : ( -
No skill content available
+
{t("agents.noSkillContent", "No skill content available")}
)}
) : null}
-

Heartbeat & Health

+

{t("agents.heartbeatAndHealth", "Heartbeat & Health")}

-

Last heartbeat

-

{agent.lastHeartbeatAt ? relativeTime(agent.lastHeartbeatAt) : "Never"}

+

{t("agents.lastHeartbeat", "Last heartbeat")}

+

{agent.lastHeartbeatAt ? relativeTime(agent.lastHeartbeatAt, t) : t("agents.never", "Never")}

-

Next expected

-

{nextHeartbeatAt ? relativeTime(nextHeartbeatAt) : "Not scheduled"}

+

{t("agents.nextExpected", "Next expected")}

+

{nextHeartbeatAt ? relativeTime(nextHeartbeatAt, t) : t("agents.notScheduled", "Not scheduled")}

-

Interval

+

{t("agents.interval", "Interval")}

{formatHeartbeatInterval(heartbeatIntervalMs)}

-

Status

+

{t("agents.status", "Status")}

{health.label}{health.reason && ({health.reason})}

-

Current Work

+

{t("agents.currentWork", "Current Work")}

{agent.taskId ? (
) : ( -

No active assignment

+

{t("agents.noActiveAssignment", "No active assignment")}

)}
-

Recent Runs

-

{stats.successfulRuns}/{stats.totalRuns} successful ({stats.successRate}%)

+

{t("agents.recentRuns", "Recent Runs")}

+

{t("agents.runsSuccessRate", "{{successful}}/{{total}} successful ({{rate}}%)", { successful: stats.successfulRuns, total: stats.totalRuns, rate: stats.successRate })}

{recentRuns.length === 0 ? ( -

No runs yet

+

{t("agents.noRunsYet", "No runs yet")}

) : (
{recentRuns.map((run) => { @@ -1300,7 +1315,7 @@ function DashboardTab({ return (
- {relativeTime(run.startedAt)} + {relativeTime(run.startedAt, t)} {Math.max(0, Math.round((new Date(run.endedAt || run.startedAt).getTime() - new Date(run.startedAt).getTime()) / 1000))}s
); @@ -1310,28 +1325,28 @@ function DashboardTab({
-

Throughput

+

{t("agents.throughput", "Throughput")}

-
{stats.totalRuns}
Total Runs
-
{stats.todayRuns}
Runs Today
-
{stats.successRate}%
Success Rate
+
{stats.totalRuns}
{t("agents.totalRuns", "Total Runs")}
+
{stats.todayRuns}
{t("agents.runsToday", "Runs Today")}
+
{stats.successRate}%
{t("agents.successRate", "Success Rate")}
-

Chain of Command

+

{t("agents.chainOfCommand", "Chain of Command")}

{isLoadingChainOfCommand ? ( -
Loading reporting chain...
+
{t("agents.loadingReportingChain", "Loading reporting chain...")}
) : chainOfCommand.length <= 1 ? ( -

No reporting chain

+

{t("agents.noReportingChain", "No reporting chain")}

) : ( -
+
{chainOfCommand.map((chainAgent, index) => { const isCurrent = index === chainOfCommand.length - 1; const isAncestor = !isCurrent; return (
- {!isCurrent && } @@ -1358,14 +1373,16 @@ function LogsTab({ hasTask: boolean; fallbackLabel?: string | null; }) { + const { t } = useTranslation("app"); + if (!hasTask) { return (
-

No activity yet

+

{t("agents.noActivityYet", "No activity yet")}

- Agent logs will appear here from the current task or most recent run + {t("agents.logsWillAppear", "Agent logs will appear here from the current task or most recent run")}

@@ -1375,23 +1392,23 @@ function LogsTab({ return (
- {logs.length} entries + {t("agents.logEntries", "{{count}} entries", { count: logs.length })} {fallbackLabel && ( {fallbackLabel} )} {isStreaming && ( - Live + {t("agents.live", "Live")} )}
{logs.length === 0 ? (
-

No log entries yet

+

{t("agents.noLogEntriesYet", "No log entries yet")}

- {isStreaming ? "Waiting for activity..." : "Logs will appear here when the agent is active"} + {isStreaming ? t("agents.waitingForActivity", "Waiting for activity...") : t("agents.logsWillAppearActive", "Logs will appear here when the agent is active")}

) : ( @@ -1401,18 +1418,22 @@ function LogsTab({ ); } -function formatMailboxTimestamp(ts: string): string { +function formatMailboxTimestamp(ts: string, t?: (key: string, defaultValue: string, options?: Record) => string): string { const date = new Date(ts); const now = new Date(); const diffMs = now.getTime() - date.getTime(); const diffMins = Math.floor(diffMs / 60000); const diffHours = Math.floor(diffMs / 3600000); const diffDays = Math.floor(diffMs / 86400000); + const tr = t ?? ((_key: string, def: string, opts?: Record) => { + if (!opts) return def; + return def.replace(/\{\{(\w+)\}\}/g, (_, k) => String(opts[k] ?? "")); + }); - if (diffMins < 1) return "Just now"; - if (diffMins < 60) return `${diffMins}m ago`; - if (diffHours < 24) return `${diffHours}h ago`; - if (diffDays < 7) return `${diffDays}d ago`; + if (diffMins < 1) return tr("time.justNow", "just now"); + if (diffMins < 60) return tr("time.minutesAgo", "{{n}}m ago", { n: diffMins }); + if (diffHours < 24) return tr("time.hoursAgo", "{{n}}h ago", { n: diffHours }); + if (diffDays < 7) return tr("time.daysAgo", "{{n}}d ago", { n: diffDays }); return date.toLocaleDateString(undefined, { month: "short", day: "numeric" }); } @@ -1421,14 +1442,19 @@ function mailboxParticipantLabel( id: string, type: ParticipantType, agentNamesById?: ReadonlyMap, + t?: (key: string, defaultValue: string, options?: Record) => string, ): string { - if (type === "user") return id === "dashboard" ? "You" : `User: ${id}`; + const tr = t ?? ((_key: string, def: string, opts?: Record) => { + if (!opts) return def; + return def.replace(/\{\{(\w+)\}\}/g, (_, k) => String(opts[k] ?? "")); + }); + if (type === "user") return id === "dashboard" ? tr("mailbox.you", "You") : tr("mailbox.userLabel", "User: {{id}}", { id }); if (type === "agent") { const name = agentNamesById?.get(id)?.trim(); - if (!name || name === id) return `Agent: ${id}`; - return `Agent: ${name}`; + if (!name || name === id) return tr("mailbox.agentById", "Agent: {{id}}", { id }); + return tr("mailbox.agentByName", "Agent: {{name}}", { name }); } - return "System"; + return tr("mailbox.system", "System"); } function MailTab({ @@ -1448,6 +1474,7 @@ function MailTab({ addToast?: (message: string, type?: "success" | "error") => void; onRefresh: () => void; }) { + const { t } = useTranslation("app"); const [activeSubtab, setActiveSubtab] = useState<"inbox" | "outbox">("inbox"); const [knownAgents, setKnownAgents] = useState([]); @@ -1533,25 +1560,25 @@ function MailTab({
{activeSubtab === "inbox" ? ( - {mailboxParticipantLabel(message.fromId, message.fromType, agentNamesById)} + {mailboxParticipantLabel(message.fromId, message.fromType, agentNamesById, t)} ) : ( - To: {mailboxParticipantLabel(message.toId, message.toType, agentNamesById)} + {t("agents.mailTo", "To: {{recipient}}", { recipient: mailboxParticipantLabel(message.toId, message.toType, agentNamesById, t) })} )} - {formatMailboxTimestamp(message.createdAt)} + {formatMailboxTimestamp(message.createdAt, t)}
{message.content.slice(0, 80)}{message.content.length > 80 ? "…" : ""}
- {activeSubtab === "inbox" && !message.read ?
: null} + {activeSubtab === "inbox" && !message.read ?
: null} ); return (
-

{agent.name} Mail

+

{t("agents.agentMail", "{{name}} Mail", { name: agent.name })}

@@ -1561,7 +1588,7 @@ function MailTab({ onClick={() => setActiveSubtab("inbox")} > - Inbox + {t("agents.inbox", "Inbox")} {(mailbox?.unreadCount ?? 0) > 0 ? {mailbox?.unreadCount} : null}
{isLoading && !mailbox ? (
- Loading mailbox... + {t("agents.loadingMailbox", "Loading mailbox...")}
) : null} {!isLoading && error ? (
- Failed to load mailbox: {error} + {t("agents.mailboxLoadFailed", "Failed to load mailbox: {{error}}", { error })}
) : null} @@ -1597,27 +1624,27 @@ function MailTab({ onClick={() => setSelectedMessageId(null)} > - Back to {activeSubtab === "inbox" ? "Inbox" : "Outbox"} + {activeSubtab === "inbox" ? t("agents.backToInbox", "Back to Inbox") : t("agents.backToOutbox", "Back to Outbox")}
- From - {mailboxParticipantLabel(selectedMessage.fromId, selectedMessage.fromType, agentNamesById)} + {t("agents.mailFrom", "From")} + {mailboxParticipantLabel(selectedMessage.fromId, selectedMessage.fromType, agentNamesById, t)}
- To - {mailboxParticipantLabel(selectedMessage.toId, selectedMessage.toType, agentNamesById)} + {t("agents.mailToLabel", "To")} + {mailboxParticipantLabel(selectedMessage.toId, selectedMessage.toType, agentNamesById, t)}
- Type + {t("agents.mailType", "Type")} {selectedMessage.type}
- Sent + {t("agents.mailSent", "Sent")} {new Date(selectedMessage.createdAt).toLocaleString()}
{selectedMessage.metadata?.replyTo?.messageId ? ( -
↪ Replying to message {selectedMessage.metadata.replyTo.messageId}
+
{t("agents.replyingTo", "↪ Replying to message {{id}}", { id: selectedMessage.metadata.replyTo.messageId })}
) : null}
{selectedMessage.content}
@@ -1627,7 +1654,7 @@ function MailTab({ {messages.length === 0 ? (
{activeSubtab === "inbox" ? : } -

{activeSubtab === "inbox" ? "No received messages for this agent" : "No sent messages for this agent"}

+

{activeSubtab === "inbox" ? t("agents.noInboxMessages", "No received messages for this agent") : t("agents.noOutboxMessages", "No sent messages for this agent")}

) : ( messages.map(renderMessage) @@ -1656,7 +1683,7 @@ interface AgentTokenUsageSummary { allTime: AgentTokenUsageWindowSummary; } -function RunsTab({ +function RunsTab({ addToast, agentId, projectId, @@ -1666,7 +1693,7 @@ function RunsTab({ preferActiveRun, runNowRefreshToken, isEphemeral, -}: { +}: { addToast: (msg: string, type?: "success" | "error") => void; agentId: string; projectId?: string; @@ -1677,6 +1704,7 @@ function RunsTab({ runNowRefreshToken: number; isEphemeral: boolean; }) { + const { t } = useTranslation("app"); const [runs, setRuns] = useState([]); const { confirm } = useConfirm(); const [isLoadingRuns, setIsLoadingRuns] = useState(true); @@ -1810,7 +1838,7 @@ function RunsTab({ setRunLogs(logs); setDetailRun(detail); } catch (err) { - addToast(`Failed to load run details: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.runDetailsFailed", "Failed to load run details: {{error}}", { error: getErrorMessage(err) }), "error"); setRunLogs([]); setDetailRun(null); } finally { @@ -1840,8 +1868,8 @@ function RunsTab({ const handleStopRun = async () => { const shouldStop = await confirm({ - title: "Stop Active Run", - message: "Stop the active run? The agent's work will be interrupted.", + title: t("agents.stopRunTitle", "Stop Active Run"), + message: t("agents.stopRunConfirm", "Stop the active run? The agent's work will be interrupted."), danger: true, }); if (!shouldStop) { @@ -1850,11 +1878,11 @@ function RunsTab({ try { await stopAgentRun(agentId, projectId); - addToast("Run stopped", "success"); + addToast(t("agents.runStopped", "Run stopped"), "success"); setIsLoadingRuns(true); void loadRuns(); } catch (err) { - addToast(`Failed to stop run: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.stopRunFailed", "Failed to stop run: {{error}}", { error: getErrorMessage(err) }), "error"); } }; @@ -1863,7 +1891,7 @@ function RunsTab({
- Loading runs... + {t("agents.loadingRuns", "Loading runs...")}
); @@ -1874,8 +1902,8 @@ function RunsTab({
-

No runs yet

-

Heartbeat runs will appear here

+

{t("agents.noRunsYet", "No runs yet")}

+

{t("agents.heartbeatRunsWillAppear", "Heartbeat runs will appear here")}

); @@ -1892,10 +1920,10 @@ function RunsTab({ if (!usage) return null; return (
- Input: {usage.inputTokens.toLocaleString()} - Output: {usage.outputTokens.toLocaleString()} - {usage.cachedTokens > 0 && Cache read: {usage.cachedTokens.toLocaleString()}} - {(usage.cacheWriteTokens ?? 0) > 0 && Cache write: {(usage.cacheWriteTokens ?? 0).toLocaleString()}} + {t("agents.inputTokens", "Input: {{value}}", { value: usage.inputTokens.toLocaleString() })} + {t("agents.outputTokens", "Output: {{value}}", { value: usage.outputTokens.toLocaleString() })} + {usage.cachedTokens > 0 && {t("agents.cacheReadTokens", "Cache read: {{value}}", { value: usage.cachedTokens.toLocaleString() })}} + {(usage.cacheWriteTokens ?? 0) > 0 && {t("agents.cacheWriteTokens", "Cache write: {{value}}", { value: (usage.cacheWriteTokens ?? 0).toLocaleString() })}}
); }; @@ -1903,9 +1931,9 @@ function RunsTab({ const renderRunCard = (run: AgentHeartbeatRun, index: number, isActive: boolean) => { const statusInfo = RUN_STATUS_ICONS[run.status] || RUN_STATUS_ICONS.completed; const StatusIcon = statusInfo.icon; - const duration = run.endedAt + const duration = run.endedAt ? formatDuration(new Date(run.startedAt), new Date(run.endedAt)) - : "In progress"; + : t("agents.inProgress", "In progress"); const isSelected = selectedRunId === run.id; return ( @@ -1916,7 +1944,7 @@ function RunsTab({ role="button" tabIndex={0} aria-expanded={isSelected} - aria-label={`${isActive ? "Active" : ""} run ${run.id.slice(0, 8)}, ${run.status}`} + aria-label={t("agents.runAriaLabel", "{{active}}run {{id}}, {{status}}", { active: isActive ? t("agents.activePrefix", "Active ") : "", id: run.id.slice(0, 8), status: run.status })} onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); @@ -1930,7 +1958,7 @@ function RunsTab({ {isActive ? ( - Live Run + {t("agents.liveRun", "Live Run")} ) : ( #{index + 1} {run.id.slice(0, 8)} @@ -1950,9 +1978,9 @@ function RunsTab({ e.stopPropagation(); void handleStopRun(); }} - aria-label="Stop active run" + aria-label={t("agents.stopActiveRun", "Stop active run")} > - Stop + {t("agents.stop", "Stop")} )} @@ -1961,13 +1989,13 @@ function RunsTab({ {run.heartbeatProcedureSource === "custom" && ( - Heartbeat: custom + {t("agents.heartbeatCustom", "Heartbeat: custom")} )}
- Started {relativeTime(run.startedAt)} + {t("agents.runStarted", "Started {{time}}", { time: relativeTime(run.startedAt, t) })} • {duration} {run.triggerDetail && ( @@ -1984,18 +2012,18 @@ function RunsTab({ {isLoadingDetail ? (
- Loading details... + {t("agents.loadingDetails", "Loading details...")}
) : detailRun && (
{/* System Prompt */}
- System Prompt + {t("agents.systemPrompt", "System Prompt")} {detailRun.systemPrompt ? (
{detailRun.systemPrompt}
) : ( -
System prompt not captured for this run
+
{t("agents.systemPromptNotCaptured", "System prompt not captured for this run")}
)}
@@ -2003,11 +2031,11 @@ function RunsTab({ {/* Execution Prompt */}
- Execution Prompt + {t("agents.executionPrompt", "Execution Prompt")} {detailRun.executionPrompt ? (
{detailRun.executionPrompt}
) : ( -
Execution prompt not captured for this run
+
{t("agents.executionPromptNotCaptured", "Execution prompt not captured for this run")}
)}
@@ -2015,7 +2043,7 @@ function RunsTab({ {/* Token Usage */} {detailRun.usageJson && (
-
Token Usage
+
{t("agents.tokenUsage", "Token Usage")}
{renderUsage(detailRun.usageJson)}
)} @@ -2023,7 +2051,7 @@ function RunsTab({ {/* Output */} {detailRun.stdoutExcerpt && (
-
Output
+
{t("agents.output", "Output")}
                       {detailRun.stdoutExcerpt.length > 2000
                         ? `${detailRun.stdoutExcerpt.slice(0, 2000)}\n\n... (truncated, ${detailRun.stdoutExcerpt.length} chars total)`
@@ -2035,7 +2063,7 @@ function RunsTab({
                 {/* Errors */}
                 {detailRun.stderrExcerpt && (
                   
-
Errors
+
{t("agents.errors", "Errors")}
-
Result
+
{t("agents.result", "Result")}
{JSON.stringify(detailRun.resultJson, null, 2)}
)} @@ -2063,7 +2091,7 @@ function RunsTab({ {/* Context */} {detailRun.contextSnapshot && Object.keys(detailRun.contextSnapshot).length > 0 && (
-
Context
+
{t("agents.context", "Context")}
{Object.entries(detailRun.contextSnapshot).map(([key, value]) => ( @@ -2077,21 +2105,21 @@ function RunsTab({ {/* No output state */} {!detailRun.stdoutExcerpt && !detailRun.stderrExcerpt && !detailRun.resultJson && ( -
No output captured
+
{t("agents.noOutputCaptured", "No output captured")}
)}
)} {/* Run Logs */}
-
Agent Logs
+
{t("agents.agentLogs", "Agent Logs")}
{isLoadingLogs ? (
- Loading logs... + {t("agents.loadingLogs", "Loading logs...")}
) : runLogs.length === 0 ? ( -
No logs available for this run
+
{t("agents.noLogsForRun", "No logs available for this run")}
) : ( )} @@ -2124,9 +2152,9 @@ function RunsTab({
{promptSizes.length > 0 && latestPrompt && (
-
Prompt Size
+
{t("agents.promptSize", "Prompt Size")}
- + @@ -2138,27 +2166,27 @@ function RunsTab({ )} {tokenUsageSummary && (
-
Cache hit ratio
+
{t("agents.cacheHitRatio", "Cache hit ratio")}
- {renderCacheWindow("Last 24h", tokenUsageSummary.last24h)} - {renderCacheWindow("Last 7d", tokenUsageSummary.last7d)} - {renderCacheWindow("All time", tokenUsageSummary.allTime)} + {renderCacheWindow(t("agents.last24h", "Last 24h"), tokenUsageSummary.last24h)} + {renderCacheWindow(t("agents.last7d", "Last 7d"), tokenUsageSummary.last7d)} + {renderCacheWindow(t("agents.allTime", "All time"), tokenUsageSummary.allTime)}
)}
- {runs.length} run{runs.length !== 1 ? "s" : ""} - {hasActiveRun && Live} + {t("agents.runsCount", { count: runs.length, defaultValue_one: "{{count}} run", defaultValue_other: "{{count}} runs" })} + {hasActiveRun && {t("agents.live", "Live")}}
{hasActiveRun && ( )}
@@ -2177,15 +2205,6 @@ function formatDuration(start: Date, end: Date): string { return `${Math.floor(diff / 3600)}h ${Math.floor((diff % 3600) / 60)}m`; } -const TASK_COLUMN_LABELS: Record = { - triage: "Triage", - todo: "Todo", - "in-progress": "In Progress", - "in-review": "In Review", - done: "Done", - archived: "Archived", -}; - function truncateTaskLabel(task: Task): string { const source = task.title?.trim() || task.description?.trim() || task.id; return source.length > 80 ? `${source.slice(0, 77)}...` : source; @@ -2200,6 +2219,7 @@ function TasksTab({ projectId?: string; addToast: (msg: string, type?: "success" | "error") => void; }) { + const { t } = useTranslation("app"); const [tasks, setTasks] = useState([]); const [isLoading, setIsLoading] = useState(true); @@ -2216,7 +2236,7 @@ function TasksTab({ .catch((err) => { if (!cancelled) { setTasks([]); - addToast(`Failed to load assigned tasks: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.loadTasksFailed", "Failed to load assigned tasks: {{error}}", { error: getErrorMessage(err) }), "error"); } }) .finally(() => { @@ -2234,7 +2254,7 @@ function TasksTab({ return (
-

Loading assigned tasks...

+

{t("agents.loadingTasks", "Loading assigned tasks...")}

); } @@ -2243,7 +2263,7 @@ function TasksTab({ return (
-

No tasks assigned to this agent

+

{t("agents.noTasksAssigned", "No tasks assigned to this agent")}

); } @@ -2254,13 +2274,22 @@ function TasksTab({
{task.id} - {TASK_COLUMN_LABELS[task.column]} + { + ({ + triage: t("board.triage", "Triage"), + todo: t("board.todo", "Todo"), + "in-progress": t("board.inProgress", "In Progress"), + "in-review": t("board.inReview", "In Review"), + done: t("board.done", "Done"), + archived: t("board.archived", "Archived"), + } as Record)[task.column] ?? task.column + }
{truncateTaskLabel(task)}
- {task.status ?? "idle"} · Updated {relativeTime(task.updatedAt)} + {task.status ?? "idle"} · {t("agents.taskUpdated", "Updated {{time}}", { time: relativeTime(task.updatedAt, t) })}
))} @@ -2368,6 +2397,7 @@ function SoulTab({ addToast: (message: string, type?: "success" | "error") => void; onSaved: () => Promise; }) { + const { t } = useTranslation("app"); const [soul, setSoul] = useState(agent.soul ?? ""); const [isSaving, setIsSaving] = useState(false); const [justSaved, setJustSaved] = useState(false); @@ -2392,14 +2422,14 @@ function SoulTab({ const handleSave = async () => { if (soul.length > 10000) { - addToast("Soul must be at most 10,000 characters", "error"); + addToast(t("agents.soulTooLong", "Soul must be at most 10,000 characters"), "error"); return; } setIsSaving(true); try { await updateAgentSoul(agent.id, soul, projectId); - addToast("Soul saved", "success"); + addToast(t("agents.soulSaved", "Soul saved"), "success"); setJustSaved(true); if (justSavedTimeoutRef.current) { clearTimeout(justSavedTimeoutRef.current); @@ -2407,7 +2437,7 @@ function SoulTab({ justSavedTimeoutRef.current = setTimeout(() => setJustSaved(false), 3000); await onSaved(); } catch (err) { - addToast(`Failed to save soul: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.soulSaveFailed", "Failed to save soul: {{error}}", { error: getErrorMessage(err) }), "error"); } finally { setIsSaving(false); } @@ -2416,33 +2446,33 @@ function SoulTab({ return (
-

Soul

+

{t("agents.soulTitle", "Soul")}

- Define this agent's personality and identity. + {t("agents.soulDescription", "Define this agent's personality and identity.")}

- +
@@ -2455,7 +2485,7 @@ function SoulTab({
) : (
- No soul defined yet. Switch to Edit mode to define the agent's personality. + {t("agents.soulEmptyPreview", "No soul defined yet. Switch to Edit mode to define the agent's personality.")}
) ) : ( @@ -2463,7 +2493,7 @@ function SoulTab({ id="agent-soul" className="input config-textarea-mono" rows={12} - placeholder="Describe this agent's personality, tone, and behavioral traits..." + placeholder={t("agents.soulPlaceholder", "Describe this agent's personality, tone, and behavioral traits...")} value={soul} onChange={(e) => { setSoul(e.target.value); @@ -2472,7 +2502,7 @@ function SoulTab({ /> )} {!showPreview && ( - Defines the agent's character and identity. Max 10,000 characters. + {t("agents.soulHint", "Defines the agent's character and identity. Max 10,000 characters.")} )}
@@ -2487,19 +2517,19 @@ function SoulTab({ {isSaving ? ( <> - Saving… + {t("common.saving", "Saving…")} ) : ( <> - Save Soul + {t("agents.saveSoul", "Save Soul")} )} {!hasChanges && justSaved && ( - Soul saved + {t("agents.soulSaved", "Soul saved")} )}
@@ -2520,6 +2550,7 @@ function MemoryTab({ addToast: (message: string, type?: "success" | "error") => void; onSaved: () => Promise; }) { + const { t } = useTranslation("app"); const [memory, setMemory] = useState(agent.memory ?? ""); const [isSaving, setIsSaving] = useState(false); const [justSaved, setJustSaved] = useState(false); @@ -2547,8 +2578,12 @@ function MemoryTab({ ); const selectedLayerDescription = selectedMemoryFile - ? MEMORY_LAYER_DESCRIPTIONS[selectedMemoryFile.layer] - : "Select a memory file to view or edit."; + ? ({ + "long-term": t("agents.memoryLayerLongTermDesc", "Curated durable decisions, conventions, constraints, and pitfalls for this specific agent."), + daily: t("agents.memoryLayerDailyDesc", "Raw daily observations and open loops recorded by this agent."), + dreams: t("agents.memoryLayerDreamsDesc", "Synthesized patterns and emerging themes distilled from this agent's daily memory."), + } as Record)[selectedMemoryFile.layer] ?? selectedMemoryFile.layer + : t("agents.selectMemoryFile", "Select a memory file to view or edit."); const loadSelectedMemoryFile = useCallback(async (path: string) => { setSelectedFileLoading(true); @@ -2559,7 +2594,7 @@ function MemoryTab({ setSelectedFileDirty(false); setSelectedFileJustSaved(false); } catch (err) { - addToast(`Failed to load agent memory file: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.memoryFileLoadFailed", "Failed to load agent memory file: {{error}}", { error: getErrorMessage(err) }), "error"); } finally { setSelectedFileLoading(false); } @@ -2581,7 +2616,7 @@ function MemoryTab({ const nextPath = pickDefaultAgentMemoryPath(files, preferredPath); await loadSelectedMemoryFile(nextPath); } catch (err) { - addToast(`Failed to load memory files: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.memoryFilesLoadFailed", "Failed to load memory files: {{error}}", { error: getErrorMessage(err) }), "error"); setMemoryFiles([]); setSelectedFilePath(""); setSelectedFileContent(""); @@ -2614,14 +2649,14 @@ function MemoryTab({ const handleSaveInlineMemory = async () => { if (memory.length > 50000) { - addToast("Memory must be at most 50,000 characters", "error"); + addToast(t("agents.memoryTooLong", "Memory must be at most 50,000 characters"), "error"); return; } setIsSaving(true); try { await updateAgentMemory(agent.id, memory, projectId); - addToast("Memory saved", "success"); + addToast(t("agents.memorySaved", "Memory saved"), "success"); setJustSaved(true); if (justSavedTimeoutRef.current) { clearTimeout(justSavedTimeoutRef.current); @@ -2629,7 +2664,7 @@ function MemoryTab({ justSavedTimeoutRef.current = setTimeout(() => setJustSaved(false), 3000); await onSaved(); } catch (err) { - addToast(`Failed to save memory: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.memorySaveFailed", "Failed to save memory: {{error}}", { error: getErrorMessage(err) }), "error"); } finally { setIsSaving(false); } @@ -2640,7 +2675,7 @@ function MemoryTab({ return; } if (selectedFileDirty) { - setFileSwitchHint("Save the current file before switching to another file."); + setFileSwitchHint(t("agents.saveBeforeSwitch", "Save the current file before switching to another file.")); return; } @@ -2664,10 +2699,10 @@ function MemoryTab({ selectedFileJustSavedTimeoutRef.current = setTimeout(() => setSelectedFileJustSaved(false), 3000); setFileSwitchHint(""); await loadMemoryFiles(selectedFilePath); - addToast("Agent memory file saved", "success"); + addToast(t("agents.memoryFileSaved", "Agent memory file saved"), "success"); await onSaved(); } catch (err) { - addToast(`Failed to save agent memory file: ${getErrorMessage(err)}`, "error"); + addToast(t("agents.memoryFileSaveFailed", "Failed to save agent memory file: {{error}}", { error: getErrorMessage(err) }), "error"); } finally { setSavingSelectedFile(false); } @@ -2676,21 +2711,21 @@ function MemoryTab({ return (
-

Agent Memory

+

{t("agents.memoryTitle", "Agent Memory")}

- Store context that belongs to this agent only. Workspace memory, daily notes, dreams, and qmd search live in project settings under Project Memory. + {t("agents.memoryDescription", "Store context that belongs to this agent only. Workspace memory, daily notes, dreams, and qmd search live in project settings under Project Memory.")}

{isReadOnly && (

- Read-only while this agent is running. + {t("agents.memoryReadOnly", "Read-only while this agent is running.")}

)}
- + - Short-form memory stored directly on the agent record and injected into prompts. + {t("agents.inlineMemoryHint", "Short-form memory stored directly on the agent record and injected into prompts.")}
@@ -2699,20 +2734,20 @@ function MemoryTab({ className={`btn btn-sm ${!showPreview ? "btn-primary" : ""}`} onClick={() => setShowPreview(false)} disabled={!showPreview} - aria-label="Edit mode" + aria-label={t("common.editMode", "Edit mode")} > - Edit + {t("common.edit", "Edit")} )}
@@ -2725,16 +2760,16 @@ function MemoryTab({
) : (
- No agent memory defined yet. Switch to Edit mode to add memory content. + {t("agents.memoryEmptyPreview", "No agent memory defined yet. Switch to Edit mode to add memory content.")}
) ) : (