Skip to content

Go: add API mode check in file system command - #16022

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix462
Jun 15, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
JinHai-CN:fix462

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

What problem does this PR solve?

As title.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 15, 2026
@coderabbitai

coderabbitai Bot commented Jun 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The PR renames the CLI interactive entrypoint from NewRun to Run, introduces a unified execute dispatch method used by both the interactive loop and RunSingleCommand, and extracts all filesystem command logic (parsing, execution, output rendering) from cli.go into a new internal/cli/filesystem_command.go file. The dispatch call in cli_http.go is updated accordingly.

Changes

CLI execution refactor and filesystem command extraction

Layer / File(s) Summary
CLI entrypoint rename and execute dispatch
cmd/ragflow_cli.go, internal/cli/cli.go
NewRun renamed to Run; interactive loop and RunSingleCommand now both route through a new execute(input) method that calls NewParser, handleMetaCommand, and ExecuteCommand. Old in-file filesystem, search, and list helpers are removed from cli.go.
New filesystem_command.go: execution, dispatch, parsing, and rendering
internal/cli/filesystem_command.go, internal/cli/cli_http.go
Adds ExecuteFilesystemCommand with os.Pipe-based stdout capture; executeFilesystemInner dispatches ls/list, search, cat, install-skill, and uninstall-skill subcommands. Includes parseFilesystemArgs, parseSearchCommandArgs, parseListCommandArgs, printFilesystemResult, printSkillSearchResults, isBinaryContent, and exported option structs. cli_http.go updated to call the new exported method.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#15898: Directly overlaps in refactoring the CLI filesystem command dispatch path, including changes to executeFilesystemInner and the routing from the interactive/HTTP execution layers.

Suggested labels

🐞 bug, ☯️ refactor, size:L

Poem

A rabbit hopped through the code one day,
Found NewRun lurking, renamed it away.
execute now handles each command with grace,
Filesystem helpers moved to their own space.
🐇 Clean files, clean hops — a tidier place!

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is minimal and lacks detail. It only repeats the title as 'As title' and provides no context about the actual changes, rationale, or impact of the refactoring work. Expand the description with specific details about the refactoring, the changes to CLI execution flow, the migration of filesystem command logic, and why these changes were necessary.
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title mentions 'add API mode check in file system command' but the PR primarily refactors the CLI execution by renaming NewRun() to Run() and moving filesystem command handling logic to a new file. Clarify the title to better reflect the main changes, such as 'Refactor CLI execution and extract filesystem command handling' or provide more context about what the API mode check accomplishes.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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 and usage tips.

@JinHai-CN
JinHai-CN marked this pull request as ready for review June 15, 2026 07:49
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 15, 2026

@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: 3

🤖 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/cli/filesystem_command.go`:
- Around line 307-310: The plain format output loop (lines 307-310)
unconditionally formats node.CreatedAt, which displays "0001-01-01 00:00" for
unset timestamps, whereas the table format (lines 318-320) checks
node.CreatedAt.IsZero() and displays "-" instead. Apply the same zero-check
pattern to the plain format: before formatting node.CreatedAt in the fmt.Printf
call, check if node.CreatedAt.IsZero() is true and if so, use "-" as the
timestamp value, otherwise use the normal formatted timestamp.
- Around line 182-189: The code flows through after printing "(empty file)" when
content is empty or nil, causing the subsequent fmt.Println(string(content)) to
also execute and print an extra empty line. Add a return nil statement after the
fmt.Println("(empty file)") line, or restructure the conditions using else-if
chains to ensure that when content is empty or nil, the function returns
immediately and does not reach the final fmt.Println(string(content)) call.
- Around line 43-49: The global stdout redirect in the defer block of
ExecuteFilesystemCommand is not thread-safe for concurrent calls. Refactor
ExecuteFilesystemCommand to accept an io.Writer parameter instead of redirecting
os.Stdout globally. Pass this writer down to executeFilesystemInner and any
helper functions that currently write output, allowing them to write directly to
the provided writer instead of relying on stdout capture. This eliminates the
race condition that occurs when multiple goroutines call
ExecuteFilesystemCommand concurrently.
🪄 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: 1992f0dc-cdc0-4051-a0ca-dde158265bcd

📥 Commits

Reviewing files that changed from the base of the PR and between e3cb86d and 41bcd92.

📒 Files selected for processing (4)
  • cmd/ragflow_cli.go
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/filesystem_command.go

Comment on lines +43 to +49
old := os.Stdout
os.Stdout = w
defer func() {
os.Stdout = old
_ = w.Close()
_ = r.Close()
}()

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.

⚠️ Potential issue | 🟠 Major | 🏗️ Heavy lift

Global stdout redirect is not thread-safe.

Redirecting os.Stdout affects all goroutines in the process. If ExecuteFilesystemCommand is called concurrently (e.g., from multiple HTTP handlers or parallel command execution), the stdout capture will corrupt output from other calls.

Consider using a writer interface pattern where the inner function writes to a provided io.Writer instead of relying on stdout capture:

♻️ Suggested approach
-func (c *CLI) ExecuteFilesystemCommand(cmd *Command) (ResponseIf, error) {
+func (c *CLI) ExecuteFilesystemCommand(cmd *Command) (ResponseIf, error) {
 	if c.Config.CLIMode != APIMode {
 		return nil, fmt.Errorf("this command is only allowed in USER mode")
 	}
 
 	rawInput, _ := cmd.Params["command"].(string)
-
-	r, w, err := os.Pipe()
-	if err != nil {
-		return nil, fmt.Errorf("create stdout pipe: %w", err)
-	}
-	old := os.Stdout
-	os.Stdout = w
-	defer func() {
-		os.Stdout = old
-		_ = w.Close()
-		_ = r.Close()
-	}()
-
-	var buf strings.Builder
-	copyErrCh := make(chan error, 1)
-	go func() {
-		_, copyErr := io.Copy(&buf, r)
-		copyErrCh <- copyErr
-	}()
-
-	execErr := c.executeFilesystemInner(rawInput)
-	_ = w.Close() // signal EOF to reader goroutine
-	copyErr := <-copyErrCh
-	if copyErr != nil {
-		return nil, fmt.Errorf("capture filesystem output: %w", copyErr)
-	}
-	return &FileSystemResponse{Output: buf.String()}, execErr
+	var buf strings.Builder
+	execErr := c.executeFilesystemInner(rawInput, &buf)
+	return &FileSystemResponse{Output: buf.String()}, execErr
 }

Then modify executeFilesystemInner and helper functions to accept an io.Writer parameter.

🤖 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/cli/filesystem_command.go` around lines 43 - 49, The global stdout
redirect in the defer block of ExecuteFilesystemCommand is not thread-safe for
concurrent calls. Refactor ExecuteFilesystemCommand to accept an io.Writer
parameter instead of redirecting os.Stdout globally. Pass this writer down to
executeFilesystemInner and any helper functions that currently write output,
allowing them to write directly to the provided writer instead of relying on
stdout capture. This eliminates the race condition that occurs when multiple
goroutines call ExecuteFilesystemCommand concurrently.

Comment on lines +182 to +189
if content == nil || len(content) == 0 {
fmt.Println("(empty file)")
} else if isBinaryContent(content) {
return fmt.Errorf("cannot display binary file content")
}

fmt.Println(string(content))
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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Cat command prints empty file message then prints content anyway.

The control flow falls through after printing "(empty file)", causing an extra empty line to be printed. Add return nil or use else-if chain:

 if content == nil || len(content) == 0 {
     fmt.Println("(empty file)")
+    return nil
 } else if isBinaryContent(content) {
     return fmt.Errorf("cannot display binary file content")
+} else {
+    fmt.Println(string(content))
 }
-
-fmt.Println(string(content))
 return nil
🤖 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/cli/filesystem_command.go` around lines 182 - 189, The code flows
through after printing "(empty file)" when content is empty or nil, causing the
subsequent fmt.Println(string(content)) to also execute and print an extra empty
line. Add a return nil statement after the fmt.Println("(empty file)") line, or
restructure the conditions using else-if chains to ensure that when content is
empty or nil, the function returns immediately and does not reach the final
fmt.Println(string(content)) call.

Comment on lines +307 to +310
for i := 0; i < displayCount; i++ {
node := result.Nodes[i]
fmt.Printf("%s %s %s %s\n", node.Name, node.Type, node.Path, node.CreatedAt.Format("2006-01-02 15:04"))
}

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Plain format doesn't handle zero CreatedAt like table format does.

Table format (line 318-320) checks node.CreatedAt.IsZero() and displays "-", but plain format unconditionally formats the time, which would show "0001-01-01 00:00" for unset timestamps.

 for i := 0; i < displayCount; i++ {
     node := result.Nodes[i]
-    fmt.Printf("%s %s %s %s\n", node.Name, node.Type, node.Path, node.CreatedAt.Format("2006-01-02 15:04"))
+    created := node.CreatedAt.Format("2006-01-02 15:04")
+    if node.CreatedAt.IsZero() {
+        created = "-"
+    }
+    fmt.Printf("%s %s %s %s\n", node.Name, node.Type, node.Path, created)
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for i := 0; i < displayCount; i++ {
node := result.Nodes[i]
fmt.Printf("%s %s %s %s\n", node.Name, node.Type, node.Path, node.CreatedAt.Format("2006-01-02 15:04"))
}
for i := 0; i < displayCount; i++ {
node := result.Nodes[i]
created := node.CreatedAt.Format("2006-01-02 15:04")
if node.CreatedAt.IsZero() {
created = "-"
}
fmt.Printf("%s %s %s %s\n", node.Name, node.Type, node.Path, created)
}
🤖 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/cli/filesystem_command.go` around lines 307 - 310, The plain format
output loop (lines 307-310) unconditionally formats node.CreatedAt, which
displays "0001-01-01 00:00" for unset timestamps, whereas the table format
(lines 318-320) checks node.CreatedAt.IsZero() and displays "-" instead. Apply
the same zero-check pattern to the plain format: before formatting
node.CreatedAt in the fmt.Printf call, check if node.CreatedAt.IsZero() is true
and if so, use "-" as the timestamp value, otherwise use the normal formatted
timestamp.

@codecov

codecov Bot commented Jun 15, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (e3cb86d) to head (41bcd92).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16022   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit 417f805 into infiniflow:main Jun 15, 2026
1 of 2 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:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant