Skip to content

fix(go): seed built-in agent templates for Go backend - #16666

Merged
yuzhichang merged 1 commit into
infiniflow:mainfrom
euvre:fix/go-canvas-template-seeding
Jul 7, 2026
Merged

yuzhichang merged 1 commit into
infiniflow:mainfrom
euvre:fix/go-canvas-template-seeding

Conversation

@euvre

@euvre euvre commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Summary

The Go backend never seeded the canvas_template table, so the "Create agent from template" page was blank when the frontend proxies to the Go API (API_PROXY_SCHEME=go). This PR adds SeedCanvasTemplates() in internal/dao, invoked from InitDB() after migrations, which loads agent/templates/*.json and mirrors Python's add_graph_templates() behavior.

Changes:

  • Add internal/dao/canvas_template_seed.go to parse and upsert built-in templates.
  • Call SeedCanvasTemplates() in InitDB().
  • Add CanvasTypes (JSONSlice) to entity.CanvasTemplate so the frontend can filter/group by category.
  • Skip seeding gracefully when the templates directory is absent.

This fixes the blank template catalogue in Go mode.

The Go backend never populated the canvas_template table, so the
"Create agent from template" page was blank when running with
API_PROXY_SCHEME=go.

- Add SeedCanvasTemplates() that loads agent/templates/*.json and
  mirrors Python's add_graph_templates() behaviour.
- Call it from InitDB() after migrations.
- Add CanvasTypes JSONSlice field to CanvasTemplate so the frontend
  can filter/group templates correctly.
- Skip seeding if the templates directory is missing (e.g. tests).

Fixes the blank template catalogue in Go mode.
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 6, 2026
@euvre euvre added the ci Continue Integration label Jul 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a new canvas template seeding module that reads JSON files from an agent/templates directory and populates the canvas_template table, wires this seeding into database initialization after migrations, and extends the CanvasTemplate entity with a new CanvasTypes field.

Changes

Canvas Template Seeding

Layer / File(s) Summary
CanvasTemplate entity field
internal/entity/canvas.go
Adds a CanvasTypes JSONSlice field mapped to the canvas_types column and JSON key on the CanvasTemplate struct.
Seeding logic and parsing helpers
internal/dao/canvas_template_seed.go
Implements SeedCanvasTemplates() to locate the templates directory, clear existing rows, and insert parsed templates from sorted .json files, plus parseCanvasTemplateFile, collectCanvasTypes, and findAgentTemplatesDir helpers.
Database initialization wiring
internal/dao/database.go
Calls SeedCanvasTemplates() after RunMigrations succeeds, logging a warning on failure without aborting startup.

Estimated code review effort: 2 (Simple) | ~15 minutes

Sequence Diagram(s)

sequenceDiagram
  participant InitDB
  participant SeedCanvasTemplates
  participant FileSystem
  participant Database

  InitDB->>SeedCanvasTemplates: call after RunMigrations
  SeedCanvasTemplates->>FileSystem: findAgentTemplatesDir()
  FileSystem-->>SeedCanvasTemplates: templates dir path or empty
  SeedCanvasTemplates->>Database: delete existing canvas_template rows
  SeedCanvasTemplates->>FileSystem: read sorted .json files
  FileSystem-->>SeedCanvasTemplates: raw JSON bytes
  SeedCanvasTemplates->>SeedCanvasTemplates: parseCanvasTemplateFile(raw)
  SeedCanvasTemplates->>Database: insert parsed CanvasTemplate
  SeedCanvasTemplates-->>InitDB: return nil or logged warning
Loading

Poem

A rabbit hopped through JSON trees, 🐇
Seeding templates, quick with ease,
Canvas types now line up neat,
DB init dances to the beat,
Warnings whispered, never fear —
Startup carries on, my dear!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main change: seeding built-in agent templates in the Go backend.
Description check ✅ Passed The description matches the required Summary template and includes background context plus a clear change list.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/dao/canvas_template_seed.go`:
- Around line 39-83: Wrap the canvas template seeding flow in a DB.Transaction
so the delete and all inserts are atomic. In canvas_template_seed.go, update the
seeding logic around findAgentTemplatesDir, DB.Exec("DELETE FROM
canvas_template"), and DB.Create(tmpl) so any read/parse/save failure returns an
error from the transaction instead of only logging and continuing, ensuring the
previous state is restored on abort rather than leaving canvas_template empty or
partially populated.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 78edebd6-a04c-4f8c-8f1c-afa605026a03

📥 Commits

Reviewing files that changed from the base of the PR and between 57625c9 and 48b0f51.

📒 Files selected for processing (3)
  • internal/dao/canvas_template_seed.go
  • internal/dao/database.go
  • internal/entity/canvas.go

Comment on lines +39 to +83
dir := findAgentTemplatesDir()
if dir == "" {
common.Warn("Agent templates directory not found, skipping canvas template seeding")
return nil
}

entries, err := os.ReadDir(dir)
if err != nil {
return fmt.Errorf("failed to read agent templates directory %s: %w", dir, err)
}

// Match Python's filter_delete([1 == 1]): start from a clean slate so
// removed built-ins disappear and updated files take effect.
if err := DB.Exec("DELETE FROM canvas_template").Error; err != nil {
return fmt.Errorf("failed to clear canvas_template: %w", err)
}

sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() })

var seeded int
for _, entry := range entries {
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {
continue
}
path := filepath.Join(dir, entry.Name())
raw, err := os.ReadFile(path)
if err != nil {
common.Warn("Failed to read agent template", zap.String("file", path), zap.Error(err))
continue
}
tmpl, err := parseCanvasTemplateFile(raw)
if err != nil {
common.Warn("Failed to parse agent template", zap.String("file", path), zap.Error(err))
continue
}
if err := DB.Create(tmpl).Error; err != nil {
common.Warn("Failed to save agent template", zap.String("file", path), zap.Error(err))
continue
}
seeded++
}

common.Info("Seeded canvas templates", zap.Int("count", seeded), zap.String("dir", dir))
return nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify whether canvas_template is used to store anything other than built-in templates
# (i.e. whether unconditional full-table DELETE could destroy user data).
rg -nP -C4 'canvas_template' --type=go internal/dao internal/service internal/api 2>/dev/null
rg -nP -C4 '\bDB\.Create\(.*CanvasTemplate' --type=go

Repository: infiniflow/ragflow

Length of output: 4188


Wrap seeding in a transaction

DELETE FROM canvas_template runs before any insert, and parse/save failures are only logged and skipped. If seeding aborts halfway, the table is left empty or partially populated while the function still returns nil. Wrap the delete and inserts in DB.Transaction(...) so a failure rolls back to the previous state instead of leaving the app with no templates.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/dao/canvas_template_seed.go` around lines 39 - 83, Wrap the canvas
template seeding flow in a DB.Transaction so the delete and all inserts are
atomic. In canvas_template_seed.go, update the seeding logic around
findAgentTemplatesDir, DB.Exec("DELETE FROM canvas_template"), and
DB.Create(tmpl) so any read/parse/save failure returns an error from the
transaction instead of only logging and continuing, ensuring the previous state
is restored on abort rather than leaving canvas_template empty or partially
populated.

@yuzhichang
yuzhichang merged commit b454067 into infiniflow:main Jul 7, 2026
11 of 12 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants