Files
SnapOtter/apps/docs/zh-CN/guide/developer.md
T
SnapOtterandGitHub d10d0f544f fix: release QA hardening across processing, media, security, and CI gates (#649)
A release-readiness QA pass over the whole product. The commits split into
defects a user would hit and gates that were reporting green while measuring
nothing.

## Fixes that change behaviour

Rate limiting was bypassable on every install: TRUST_PROXY defaulted to true, so
request.ip came from a client-set header and a forged X-Forwarded-For got past
the login limiter. The default is now a private-network trust list.

A transient Postgres outage stranded in-flight jobs, leaving finished output on
disk with no row pointing at it. A reconciler now resolves those rows and adopts
the bytes rather than dropping the work.

A Redis connection that moved to a new address wedged every read-blocked
consumer, so completions stopped signalling while health still answered 200.
Socket timeouts plus subscriber pings recover it.

Installing more than one AI bundle left the shared venv multi-versioned and
silently broke three tools. The installer now reconciles distributions to one
version each.

Converting an image to JXL at quality 1 through 4 returned a 500, because
libjxl 0.7 rejects the distance those values compute. The quality is floored at
what the encoder honours. A missing ffmpeg was also reported to the user as a
corrupt upload; it now says the engine is unavailable.

RAW uploads reached an unpatched LibRaw on arm64, so it is built from source at
0.22.2, and the release scan was split so it can fail on an unfixed critical
instead of hiding it behind ignore-unfixed.

## Gates that could not fail

Two mutation lanes ran zero mutants because Stryker crawled the gitignored docs
build; coverage discarded its whole report on any failing test; the lint gate
skipped root tests, scripts, and two workspaces; and several generated matrices
counted a host missing ffmpeg as a passing tool. Each now measures what it
claims.

Full evidence and the outstanding release items are tracked locally and are not
part of this branch.
2026-07-27 15:37:30 +08:00

8.5 KiB
Raw Blame History

description, i18n_source_hash, i18n_provenance, i18n_output_hash, i18n_hash_version
description i18n_source_hash i18n_provenance i18n_output_hash i18n_hash_version
本地开发环境搭建、命令、代码约定,以及如何为 SnapOtter 添加新工具。 56acc1bf9a9b machine 064e6879f3bb 2

开发者指南

如何搭建本地开发环境并为 SnapOtter 贡献代码。

前置条件

  • Node.js 22.22+
  • pnpm 9+corepack enable && corepack prepare pnpm@latest --activate
  • Docker(本地 Postgres + Redis、容器构建和 AI 功能所必需)
  • Git

仅当你在开发 AI/ML sidecar(背景移除、放大、OCR)时才需要 Python 3.11+。

搭建环境

git clone https://github.com/snapotter-hq/snapotter.git
cd snapotter
docker compose -f docker-compose.dev.yml up -d   # start Postgres + Redis
pnpm install
pnpm dev

这会启动两个开发服务器:

服务 URL 备注
前端 http://localhost:1351 Vite 开发服务器,代理 /api
后端 http://localhost:13490 Fastify API(通过代理访问)

在浏览器中打开 http://localhost:1351。使用 admin / admin 登录。首次登录时会提示你修改密码。

项目结构

apps/
  api/              Fastify backend
  web/              Vite + React frontend
  docs/             VitePress documentation (this site)
packages/
  shared/           Constants, types, i18n strings
  image-engine/     Sharp-based image operations
  media-engine/     FFmpeg spawn + progress parsing
  doc-engine/       qpdf, LibreOffice, ghostscript wrappers
  ai/               Python sidecar bridge for ML models
tests/
  unit/             Vitest unit tests
  integration/      Vitest integration tests (full API)
  e2e/              Playwright end-to-end specs
  fixtures/         Small test images

命令

pnpm dev                # start frontend + backend
pnpm build              # build all workspaces
pnpm typecheck          # TypeScript check across monorepo
pnpm lint               # Biome lint + format check
pnpm lint:fix           # auto-fix lint + format
pnpm test               # unit + integration tests
pnpm test:unit          # unit tests only
pnpm test:integration   # integration tests only
pnpm test:e2e           # Playwright e2e tests
pnpm test:coverage      # tests with coverage report

代码约定

  • 双引号、分号、2 空格缩进(由 Biome 强制执行)
  • 所有工作区均使用 ES 模块
  • 用于 semantic-release 的 Conventional commits
  • 所有 API 输入验证均使用 Zod
  • 不修改 Biome、TypeScript 或编辑器配置文件。请修改代码,而不是 linter。

数据库

通过 Drizzle ORMpg-core)使用 PostgreSQL 17。本地开发需要运行 Postgres 和 Redis——用以下命令启动它们:

docker compose -f docker-compose.dev.yml up -d

这会为你提供端口 5432 上的 Postgres 和端口 6379 上的 Redis。然后生成并应用迁移:

cd apps/api
npx drizzle-kit generate   # generate a migration from schema changes
npx drizzle-kit migrate    # apply pending migrations

架构定义在 apps/api/src/db/schema.ts。表:users、sessions、settings、jobs、apiKeys、pipelines、teams、userFiles、roles、auditLog。

添加新工具

每个工具都遵循相同的模式。下面是一个最小示例。

1. 后端路由

创建 apps/api/src/routes/tools/my-tool.ts

import { z } from "zod";
import type { FastifyInstance } from "fastify";
import { createToolRoute } from "../tool-factory.js";

const settingsSchema = z.object({
  intensity: z.number().min(0).max(100).default(50),
});

export function registerMyTool(app: FastifyInstance) {
  createToolRoute(app, {
    toolId: "my-tool",
    settingsSchema,
    async process(inputBuffer, settings, filename) {
      // Use sharp or other libraries to process the image
      const sharp = (await import("sharp")).default;
      const result = await sharp(inputBuffer)
        // ... your processing logic
        .toBuffer();

      return {
        buffer: result,
        filename: filename.replace(/\.[^.]+$/, ".png"),
        contentType: "image/png",
      };
    },
  });
}

然后在 apps/api/src/routes/tools/index.ts 中注册它。

2. 前端设置组件

创建 apps/web/src/components/tools/my-tool-settings.tsx

import { useState } from "react";
import { useToolProcessor } from "@/hooks/use-tool-processor";
import { useFileStore } from "@/stores/file-store";

export function MyToolSettings() {
  const { files } = useFileStore();
  const { processFiles, processing, error, downloadUrl } =
    useToolProcessor("my-tool");

  const [intensity, setIntensity] = useState(50);

  const handleProcess = () => {
    processFiles(files, { intensity });
  };

  return (
    <div className="space-y-4">
      {/* your controls here */}
      <button
        type="button"
        onClick={handleProcess}
        disabled={files.length === 0 || processing}
        data-testid="my-tool-submit"
        className="w-full py-2.5 rounded-lg bg-primary text-primary-foreground font-medium disabled:opacity-50"
      >
        Process
      </button>
    </div>
  );
}

然后在 apps/web/src/lib/tool-registry.tsx 的前端工具注册表中注册它:

// Add the lazy import
const MyToolSettings = lazy(() =>
  import("@/components/tools/my-tool-settings").then((m) => ({
    default: m.MyToolSettings,
  })),
);

// Add to the toolRegistry Map
["my-tool", { displayMode: "before-after", Settings: MyToolSettings }],

显示模式:"side-by-side""before-after""live-preview""no-comparison""interactive-crop""interactive-eraser""no-dropzone"

3. i18n 条目

添加到 packages/shared/src/i18n/en.ts

"my-tool": {
  name: "My Tool",
  description: "Short description of what this tool does",
},

4. 测试

为你的操作按钮添加一个 data-testid 属性(如上所示),以便 e2e 测试能可靠地定位它。

Docker 构建

在本地构建完整的生产镜像:

docker build -f docker/Dockerfile -t snapotter:latest .

使用 BuildKit 缓存挂载以加快重新构建:

DOCKER_BUILDKIT=1 docker build -f docker/Dockerfile -t snapotter:latest .

发布版本域

SnapOtter 有意具有三个版本域。发布期间请勿将一个域复制到另一个域:

  • 应用程序发布版本涵盖根清单、所有私有工作区包和 APP_VERSION。 Semantic-release 提供此值,pnpm version:sync <version> 在应用程序发布之前更新每个工作区。
  • OpenAPI info.version 是稳定的公开 API-主力合约。所有本地化规范都保留在 <major>.0.0 上以实现兼容的应用程序版本,并且仅当 API 合约转移到新的主要版本时才会更改。
  • docker/feature-manifest.json 保留 imageVersion: 2.0.0 作为不可变的旧功能包存储时代。这些 v2 存档路径不是应用程序包版本。准确的 OCR 使用运行时格式 v3 并单独记录其应用程序发布来源。

tests/unit/infra/release-version-policy.test.ts 强制执行这些边界。新版本的域或迁移必须一起更新该合同和相关的工件迁移设计。 独立的 API 和旧包值位于 config/release-version-policy.json 中;应用程序版本同步绝不能隐式重写该策略文件。

环境变量

完整列表请参见 配置指南。开发中的关键项:

变量 默认值 描述
AUTH_ENABLED true 启用/禁用身份验证
DEFAULT_USERNAME admin 默认管理员用户名
DEFAULT_PASSWORD admin 默认管理员密码
SKIP_MUST_CHANGE_PASSWORD false 跳过强制修改密码(仅限 CI/开发)
RATE_LIMIT_PER_MIN 1000 每分钟 API 速率限制(0 = 禁用)
MAX_UPLOAD_SIZE_MB 100 最大上传大小(MB)(0 = 无限制)