LinguaGacha Documentation

repository·main·Indexed 24 days ago

https://github.com/neavo/linguagacha

An AI-powered text translator for novels, games, and subtitles. It features automatic glossary generation for terminology consistency and supports formats including .md, .ass, .epub, .srt, and various game engine files (RenPy, MTool, SExtractor, VNTextPatch, Translator++, WOLF Official Tool). Compatible with local interfaces like OneClickLLAMA and online providers such as VolcEngine, DeepSeek, OpenAI, Google, Anthropic, and SakuraLLM.

Tokens
21.1K
Snippets
19
Records
96
Agent score
81%

What's inside LinguaGacha

  1. LinguaGacha Design System Overview

    main

    LinguaGacha follows a design philosophy described as a "Quiet Local Alchemist" (安静的本地炼金台). The UI is designed to feel like a reliable native desktop application, prioritizing high information density, compact controls, and a stable workspace for translation, configuration, and file processing.

    Key Design Principles:

    • Native Desktop Priority: Uses fixed shells, sidebars, workspace boundaries, and immediate feedback.
    • Color Strategy: Uses a cool gray light theme by default (with a matching dark theme). Warm orange (primary) is used sparingly for main actions, selection, focus, and progress to maintain a subtle, professional feel.
    • Information Density: High density with compact controls, optimized for tables and editors.
    • Decoration with Purpose: Visual elements must serve status, selection, hierarchy, editability, or task feedback.

    Implementation Note: Global tokens and theme entry points are located in src/frontend/index.css. Basic controls are handled in src/frontend/shadcn/. Widgets, features, and pages should consume these tokens rather than defining their own visual styles.

  2. Understand the LinguaGacha Backend Architecture and Protocols

    main

    The LinguaGacha backend is structured around a set of authoritative boundaries that define how data is stored, how tasks are executed, and how the frontend communicates with the system.

    Key architectural components include:

    • ApiGatewayServer: The single entry point for all /api/* routes in the Electron runtime. It uses register_api_routes to bind paths to BackendServices.
    • State Ownership: Different services own specific parts of the system state (e.g., AppSettingService for settings, ProjectSessionState for loaded projects, and TaskRuntime for active tasks).
    • Project Storage: Data is stored in .lg files using a structured format containing sections like project, files, items, quality, prompts, analysis, and proofreading.
    • Task Execution: Tasks are managed by TaskService and executed via TaskEngine, utilizing workers for LLM orchestration and heavy computations.
    • Database: ProjectDatabase provides a typed interface for interacting with .lg files, managing SQLite transactions and Zstd-compressed assets.
  3. Understand the LinguaGacha Runtime Topology

    main

    LinguaGacha operates through a unified backend architecture shared by both the GUI (Electron) and the CLI.

    Core Components

    • src/index.ts: The single product entry point. It dispatches to either the GUI or CLI based on the --cli flag. It handles application roots and BackendWorkerExecution but does not hold business services or window states.
    • BackendBootstrap: The authority for process resource lifecycles. It manages the start and stop sequences.
    • BackendServices: The composition root used by both GUI and CLI to assemble shared services. It includes the TaskEngine and is used by the Gateway and CLI jobs.
    • Gateway: A component enabled in GUI mode to handle requests. In CLI mode, the Gateway is disabled, and the CLI consumes typed services and task snapshot subscriptions directly.

    Lifecycle and Shutdown Order

    When the application (GUI or CLI) exits, BackendBootstrap ensures a fixed shutdown sequence to prevent data loss or resource leaks. If a step fails, the subsequent release steps are still executed:

    1. Gateway: Stops accepting requests and drains existing ones.
    2. BackendServices: Waits for active tasks and workers to complete.
    3. System Proxy
    4. ProjectDatabase
    5. LogManager

    Execution Model

    • Production: Backend workers are configured to run as worker_threads.
    • Development/Testing: in_process execution is permitted only for explicit testing or source code runs and is not used as a fallback for failures.
  4. How LinguaGacha CLI manages temporary projects

    main

    The CLI operates using a transient project model to ensure isolation and cleanliness:

    1. Isolation: Each job uses a dedicated temporary .lg project.
    2. Configuration Overrides: The CLI explicitly overrides several settings for the duration of the job:
      • Source and target languages.
      • Whether to open the output directory upon completion.
      • It disables default presets for glossaries, text protection, pre/post-replacement, and translation/analysis prompts. Only the resources explicitly provided via command-line arguments are used.
    3. Persistence: Settings not explicitly overridden by the CLI (such as models, concurrency, prompt enhancement, pre-filtering, and export settings) are inherited from the current application settings.
    4. Cleanup: Regardless of whether the job succeeds, fails, or the export fails, the CLI automatically uninstalls the project, revokes transient settings, and deletes the temporary directory.
  5. Organize Frontend Code: Pages, Features, and Widgets

    main

    The frontend architecture follows a strict hierarchy to prevent circular dependencies and maintain boundaries:

    • src/domain: Import frontend entities and value objects from here.
    • src/shared: Import cross-runtime pure rules and protocol vocabularies from here.
    • src/frontend/features/<capability>: Place domain interactions, API adapters, and pure rules used by multiple pages here. Note that features should not depend on pages.
    • src/frontend/pages/<page>: Contains the page entry point and private implementation. Pages must not import each other.
    • src/frontend/widgets/interactions: Handles generic interactions and keyboard shortcuts. These must not depend on app state, page domains, the desktop bridge, backend APIs, or SSE.
    • SCREEN_REGISTRY: The unique entry point for page registration and title keys.
  6. Manage Shared Application State with DesktopStateProvider

    main

    The DesktopStateProvider serves as the shared state entry point for the main window. It manages:

    • Project identity
    • Tasks
    • Settings
    • Event streams
    • Write results

    Note: The Log window does not start this runtime; it only reads the language and consumes the log stream.

    State Synchronization Rules:

    • Project Identity: Guarded by path + epoch + phase. This identity applies to project switching, re-initialization at the same path, late events, and transient events during initial load.
    • Settings: Synchronized only via backend payloads.
    • Tasks: Synchronized only via backend snapshots or command acknowledgments (ack).
    • Project Identity: Synchronized only via backend project payloads.
    • Task Snapshotting: TaskSnapshotStore caches full backend task snapshots using run_revision to discard old values. DesktopRefreshScheduler only retains the highest revision; identical revisions allow late snapshots to overwrite based on type.
  7. LinguaGacha Color Palette and Usage Rules

    main

    The color system uses a palette of cool blue-grays for work surfaces and low-frequency warm oranges for emphasis. Dark mode maps these same semantics to deep graphite surfaces.

    Color Categories

    • Primary: Warm orange (colors.primary) for main buttons, current navigation rails, selected rows, and progress. Used sparingly. Focus is indicated by colors.ring.
    • Secondary: Cool gray (colors.secondary) for secondary buttons, segmented controls, and toolbar partitions.
    • Tertiary (Charts): Amber (chart-amber), Coral (chart-coral), and Slate (chart-slate) for statistics and project file categories.
    • Status: Success (success), Warning (warning), and Failure (failure). These are strictly for status and must not be used for general decoration.
    • Neutral: Includes background, foreground (graphite), cards/popovers (near-white), muted surfaces (foggy gray), and borders (soft cool gray).

    Named Design Rules

    • The Cool Desktop Rule: Neutral grays must maintain a slight blue-gray tone. Avoid pure black, pure white, or high-saturation cool blues.
    • The Icon Glow Scarcity Rule: Warm orange is reserved for primary actions, selection, focus, and progress. Large areas of orange break the design intent.
    • The Status Honesty Rule: Success, Warning, and Failure colors are reserved exclusively for status expression.
    • The Scoped Exception Rule: Model provider brand colors or CodeMirror syntax colors may exist within their own boundaries but must not be promoted to global emphasis colors.
  8. Handle Data Writes and Project Updates

    main

    Writing data and handling project changes follows a specific event and synchronization pattern:

    • Writing Data: When submitting a write, only submit the user's intent, settings mirror, explicit operation, and the revision returned by the query. Do not submit canonical facts calculated on the frontend.
    • Event Entry: HTTP write results and project.data_changed SSE share the same event entry, deduplication window, and recovery strategy.
    • Project Change Signals: The shared layer generates a lightweight ProjectChangeSignal. Pages should respond by re-querying their specific target section.
    • Optimistic Locking: The top-level sectionRevisions from a query serves as the source for optimistic locking during writes and task commands.
  9. Access Host Capabilities via window.desktopApp

    main

    Renderer processes must not directly import Electron, Node, src/native, preload, or backend implementations. Instead, access host capabilities exclusively through the narrow, purpose-driven interface provided by window.desktopApp.

    Native path selection is unified between preload and main via a single IPC predicate union. Do not pass Electron dialog options from the page level.

  10. Execute and Monitor Tasks via TaskRuntime

    main

    Tasks (like translation or analysis) are managed through a lifecycle that ensures state consistency.

    Starting a Task

    To start a task, you must provide the expected_section_revisions required by the TaskService for that specific task type and scope. Once the ProjectOperationGate is acquired, the system enters a busy state.

    Monitoring Task Progress

    Task status is communicated through snapshots. TaskRuntime.build_snapshot combines:

    • In-memory state: status, busy, run_revision, and request pressure.
    • .lg metadata: progress and analysis candidate count.

    Task Execution Model

    • TaskEngine: Orchestrates the task lifecycle and command execution.
    • Workers:
      • Work-unit workers: Handle prompt construction, runners, pipelines, and response processing.
      • Planning workers: Handle calculation during the planning phase.
      • BackendWorkerClient: Used for heavy, stateless computations that do not require database or project cache access.
    • Concurrency: Actual LLM concurrency is determined by model key leases and limiters, not by the number of threads.
  11. Layout and Workspace Rules

    main

    LinguaGacha follows a fixed-shell layout designed for desktop productivity rather than web-style scrolling.

    Core Layout Specs:

    • Baseline Size: 1280 × 800px minimum.
    • Title Bar: Height is injected by the host (default 40px).
    • Sidebar: Expanded width is 256px; collapsed width is 72px.
    • Workspace: Uses 16px padding and a 16px rhythm. Dense groupings should use 12px or 8px.
    • Shell: Workspace uses 8px corner radius with 1px top and left borders.

    Key Design Rules:

    • The Fixed Shell Rule: Maintain stable boundaries for the title bar, sidebar, and workspace. Do not invent new full-page navigation shells or long-scrolling browser-style pages.
    • The Dense Rhythm Rule: Use 16px as the primary rhythm. Use 12px, 8px, or 4px for internal components. Avoid large whitespace unless it serves a specific workflow purpose.
  12. LinguaGacha Typography and Hierarchy

    main

    Typography is designed to support scanning and operation, avoiding "web-style" oversized headings. The primary font is LGMono, which provides a code-editor aesthetic for paths, model names, terms, logs, and table numbers. It falls back to LGBaseFont and system fonts for Chinese readability.

    Font Hierarchy

    LevelWeightSizeLine HeightLetter SpacingUsage
    Display40042px1-0.025emStatistical numbers, key counts, large task status
    Headline50016px1.35-0.02emImportant groupings, overlay titles, drag-and-drop text
    Title50014px1.25-0.018emCard titles, settings titles, table headers, sidebar brand
    Body40013px1.50emRegular content, table cells, instructions, control text
    Label50012px1.40emTable headers, badges, toolbar hints, compact labels

    Named Design Rules

    • The Tool Text Rule: Typography must serve scanning and operation. Avoid large promotional headings or decorative display fonts in the workspace.
    • The Production Spacing Rule: Keep letter spacing restrained for standard text. Only allow deviations for statistical numbers, titles, or special editor characters.