Skip to content

impl tags api - #2

Merged
yingfeng merged 2 commits into
infiniflow:mainfrom
KKould:main
Dec 13, 2023
Merged

yingfeng merged 2 commits into
infiniflow:mainfrom
KKould:main

Conversation

@KKould

@KKould KKould commented Dec 13, 2023

Copy link
Copy Markdown
Member

No description provided.

@yingfeng
yingfeng merged commit b2679ee into infiniflow:main Dec 13, 2023
yingfeng pushed a commit that referenced this pull request Feb 5, 2024
s4lat pushed a commit to s4lat/ragflow that referenced this pull request Mar 30, 2025
s4lat pushed a commit to s4lat/ragflow that referenced this pull request Mar 30, 2025
s4lat pushed a commit to s4lat/ragflow that referenced this pull request Mar 30, 2025
s4lat pushed a commit to s4lat/ragflow that referenced this pull request Apr 1, 2025
s4lat pushed a commit to s4lat/ragflow that referenced this pull request Apr 3, 2025
KevinHuSh pushed a commit that referenced this pull request Nov 27, 2025
### What problem does this PR solve?

##### Problem Description
When parsing HTML files, some page content may be lost.  
For example, text inside nested `<font>` tags within multiple `<div>`
elements (e.g.,
`<div><font>Text_1</font></div><div><font>Text_2</font></div>`) fails to
be preserved correctly.

###### Root Cause #1: Block ID propagation is interrupted
1. **Block ID generation**: When the parser encounters a `<div>`, it
generates a new `block_id` because `<div>` belongs to `BLOCK_TAGS`.
2. **Recursive processing**: This `block_id` is passed down recursively
to process the `<div>`’s child nodes.
3. **Interruption occurs**: When processing a child `<font>` tag, the
code enters the `else` branch of `read_text_recursively` (since `<font>`
is a Tag).
4. **Bug location**: The first line in this `else` branch explicitly
sets **`block_id = None`**.
- This discards the valid `block_id` inherited from the parent `<div>`.
- Since `<font>` is not in `BLOCK_TAGS`, it does not generate a new
`block_id`, so it passes `None` to its child text nodes.
5. **Consequence**: The extracted text nodes have an empty `block_id` in
their `metadata`. During the subsequent `merge_block_text` step, these
texts cannot be correctly associated with their original `<div>` block
due to the missing ID. As a result, all text from `<font>` tags gets
merged together, which then triggers a second issue during
concatenation.
6. **Solution:** Remove the forced reset of `block_id` to `None`. When
the current tag (e.g., `<font>`) is not a block-level element, it should
inherit the `block_id` passed down from its parent. This ensures
consistent ownership across the hierarchy: `div` → `font` → `text`.

###### Root Cause #2: Data loss during text concatenation
1. The line `current_content += (" " if current_content else "" +
content)` has a misplaced parenthesis. When `current_content` is
non-empty (`True`):
    - The ternary expression evaluates to `" "` (a single space).
    - The code executes `current_content += " "`.
- **Result**: Only a space is appended—**the new `content` string is
completely discarded**.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
clifftseng pushed a commit to clifftseng/ragflow that referenced this pull request Feb 9, 2026
### What problem does this PR solve?

##### Problem Description
When parsing HTML files, some page content may be lost.  
For example, text inside nested `<font>` tags within multiple `<div>`
elements (e.g.,
`<div><font>Text_1</font></div><div><font>Text_2</font></div>`) fails to
be preserved correctly.

###### Root Cause infiniflow#1: Block ID propagation is interrupted
1. **Block ID generation**: When the parser encounters a `<div>`, it
generates a new `block_id` because `<div>` belongs to `BLOCK_TAGS`.
2. **Recursive processing**: This `block_id` is passed down recursively
to process the `<div>`’s child nodes.
3. **Interruption occurs**: When processing a child `<font>` tag, the
code enters the `else` branch of `read_text_recursively` (since `<font>`
is a Tag).
4. **Bug location**: The first line in this `else` branch explicitly
sets **`block_id = None`**.
- This discards the valid `block_id` inherited from the parent `<div>`.
- Since `<font>` is not in `BLOCK_TAGS`, it does not generate a new
`block_id`, so it passes `None` to its child text nodes.
5. **Consequence**: The extracted text nodes have an empty `block_id` in
their `metadata`. During the subsequent `merge_block_text` step, these
texts cannot be correctly associated with their original `<div>` block
due to the missing ID. As a result, all text from `<font>` tags gets
merged together, which then triggers a second issue during
concatenation.
6. **Solution:** Remove the forced reset of `block_id` to `None`. When
the current tag (e.g., `<font>`) is not a block-level element, it should
inherit the `block_id` passed down from its parent. This ensures
consistent ownership across the hierarchy: `div` → `font` → `text`.

###### Root Cause infiniflow#2: Data loss during text concatenation
1. The line `current_content += (" " if current_content else "" +
content)` has a misplaced parenthesis. When `current_content` is
non-empty (`True`):
    - The ternary expression evaluates to `" "` (a single space).
    - The code executes `current_content += " "`.
- **Result**: Only a space is appended—**the new `content` string is
completely discarded**.

### Type of change

- [x] Bug Fix (non-breaking change which fixes an issue)
lori041987 added a commit to lori041987/ragflow that referenced this pull request Feb 11, 2026
Rename RAGFLOW_ANTHROPIC_AUTH to RAGFLOW_ANTHROPIC_CUSTOM_GATEWAY for clarity, remove redundant
LiteLLM auth configuration (fully rely on direct HTTP path), and add [WNC] comment markers to
all custom code sections for maintainability.

Key Achievements:
- Environment variable: rename to RAGFLOW_ANTHROPIC_CUSTOM_GATEWAY with boolean semantics
- Code simplification: remove dual-path auth logic, use only direct HTTP client for custom gateway
- Code markers: add [WNC] prefix comments to all custom modifications for visibility
- Documentation: update all references to use new environment variable name

Implementation Details:

1. Environment Variable Rename (docker/.env - MODIFIED):
   - Renamed: RAGFLOW_ANTHROPIC_AUTH → RAGFLOW_ANTHROPIC_CUSTOM_GATEWAY
   - New semantics: boolean toggle (1/true/yes = custom gateway, 0/empty/unset = normal Anthropic)
   - Added descriptive comment: "Custom Anthropic gateway (Authorization: Bearer). Leave unset/0 for normal Anthropic."
   - Old name implied auth method, new name clarifies it's a gateway compatibility mode
   - Value changed from "authorization" to "1" for boolean clarity

2. Code Simplification (rag/llm/chat_model.py - MODIFIED):
   - Removed redundant Anthropic LiteLLM auth configuration block (lines 1800-1810 deleted):
     * Previously had dual-path: LiteLLM with modified headers OR direct HTTP
     * LiteLLM path proved unreliable for custom gateways (header injection issues)
     * Simplified to single decision: custom gateway → direct HTTP, else → standard LiteLLM
   - Updated condition checks (lines 1355-1358, 1391-1394):
     * Old: os.environ.get("RAGFLOW_ANTHROPIC_AUTH", "").strip().lower() == "authorization"
     * New: os.environ.get("RAGFLOW_ANTHROPIC_CUSTOM_GATEWAY", "").strip().lower() in {"1", "true", "yes"}
     * Supports multiple boolean representations (1/true/yes)
   - Removed Authorization header injection in LiteLLM path:
     * No longer needed since custom gateway always uses direct HTTP path
     * Standard Anthropic API uses LiteLLM's default x-api-key behavior

3. Code Markers for Maintainability (rag/llm/chat_model.py - MODIFIED):
   - Added [WNC] prefix comments to all custom code sections:
     * Line 1257: "# [WNC] Direct Anthropic HTTP client for gateway compatibility (Authorization Bearer mode)"
     * Line 1355: "# [WNC] Bypass LiteLLM for Anthropic when using Authorization Bearer mode"
     * Line 1391: "# [WNC] Bypass LiteLLM for Anthropic when using Authorization Bearer mode (streaming)"
     * Line 1794: "# [WNC] Extra headers from environment (JSON object) for custom gateways."
   - Purpose: clearly mark custom modifications for code review and upstream merging
   - Makes it easy to identify WNC-specific code vs. upstream RAGFlow code

4. Documentation Updates (docs/debug_anthropic_gateway.md - MODIFIED):
   - Updated all references from RAGFLOW_ANTHROPIC_AUTH to RAGFLOW_ANTHROPIC_CUSTOM_GATEWAY:
     * Line 134: environment variable name in Fix infiniflow#2 section
     * Line 138-140: runtime env example block
     * Line 167: files changed description
     * Line 175: final notes explanation
   - Clarified in "Files Changed" section: "add Anthropic custom gateway toggle" (was "Authorization")
   - Updated final notes: "when RAGFLOW_ANTHROPIC_CUSTOM_GATEWAY=1 is set"

Files Modified:
- docker/.env: Rename env var, add descriptive comment (+2 lines, -1 line)
- rag/llm/chat_model.py: Add [WNC] comments, simplify auth logic, update env var (+7 lines, -13 lines)
- docs/debug_anthropic_gateway.md: Update all env var references (+4 lines, -4 lines)

Technical Background:
- Environment variable semantics:
  * Old RAGFLOW_ANTHROPIC_AUTH: implied auth method ("authorization" = use Bearer)
  * New RAGFLOW_ANTHROPIC_CUSTOM_GATEWAY: boolean flag for gateway compatibility mode
  * Clearer intent: "Is this a custom gateway?" vs. "What auth method?"
- Code simplification rationale:
  * Dual-path approach (LiteLLM + modified headers OR direct HTTP) was complex
  * Custom gateway requirements incompatible with LiteLLM's Anthropic provider
  * Gateway injects invalid headers that LiteLLM cannot override reliably
  * Direct HTTP path gives full control over request construction
  * Standard Anthropic API works fine with LiteLLM defaults (no special handling needed)
- WNC marker convention:
  * [WNC] prefix identifies company-specific customizations
  * Helps distinguish custom code from upstream changes
  * Facilitates code review and selective upstreaming
  * Makes merge conflicts easier to resolve

Key Insights:
- Boolean naming: CUSTOM_GATEWAY clearer than AUTH for toggle semantics
- Code simplicity: removing dual-path reduces maintenance burden
- Separation of concerns: custom gateway = direct HTTP, standard API = LiteLLM
- Code markers: [WNC] prefix enables quick identification of customizations
- Documentation consistency: env var name must match across code and docs

Use Case:
Simplify custom Anthropic gateway configuration by using clear boolean toggle instead of
auth method string, rely entirely on direct HTTP path for custom gateway (no LiteLLM hybrid),
and mark all custom code with [WNC] prefix for maintainability and code review.

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
@lakemike lakemike mentioned this pull request Mar 11, 2026
4 tasks done
Oldcircle added a commit to Oldcircle/ragflow that referenced this pull request Apr 24, 2026
Once the sidebar / new-session dialog / SSE path got exercised end-to-end
on real DeepSeek, five independent bugs surfaced. All fixed + tob_acceptance
script to catch regressions without a browser.

1. **model_resolver crashed the TenantLLM branch** (api/agent_v2/model_resolver.py)
   `llm_config.get("api_key")` treated a peewee TenantLLM *Model instance*
   like a dict — but peewee.Model.get() is a classmethod that reinterprets
   "api_key" as a column filter and runs a new SELECT, raising
   TenantLLMDoesNotExist. Every new session created from the workbench
   (which always passes {llm_name, factory}) hit this path and got an
   SSE stream with zero events. Switched to attribute access
   (`getattr(llm_config, "api_key", None)`). Regression covered by
   scripts/tob_acceptance.py::S15.
   Why it slipped past M1.5: those runs used the env-var fallback
   (AGENT_V2_DEEPSEEK_KEY), which never entered the TenantLLM branch.

2. **Citation validator was 100% false-positive on every live turn**
   (api/agent_v2/runner.py::_collect_evidence_from_tool)
   Claude Agent SDK namespaces tool names as `mcp__ragflow__rag_retrieve`.
   The evidence collector matched on the bare name `rag_retrieve`, so
   EvidenceIndex stayed empty forever. Result: every Markdown answer got
   "Citation [1] does not map to any chunk returned in this turn (only 0
   chunks available)" plus a "number_unsupported" storm, turning the
   citation-warning UI into noise. Now does `rsplit("__", 1)[-1]` so both
   MCP-prefixed and bare names match.

3. **Chinese-numeral normalization inverted** (api/agent_v2/validators/evidence_index.py)
   The old `_cn_to_num` iterated reversed and accumulated "十八" as 80,
   "二十五" as 70, "三十五" as 80. Because the age regex captures both
   "十八周岁" and "18周岁", rule 2 then compared normalized=80 against
   an evidence that only had normalized=18 and screamed
   "number_unsupported" on a totally correct answer.
   Rewrote as a straight left-to-right digit/small-unit/big-unit state
   machine. 12/13 target cases pass (the only residual is the colloquial
   ellipsis "两百三" = 203 vs 230; policy text doesn't use that form).

4. **Streaming not actually streaming** (api/agent_v2/runner.py)
   AgentRunner never set `include_partial_messages=True` on
   ClaudeAgentOptions, so AssistantMessage arrived as one final block and
   the frontend got a single text_delta with the entire answer — visually
   "appears all at once". Now enabled; StreamEvent handler yields
   text_delta / thinking for each content_block_delta. To avoid doubling,
   AssistantMessage path stops yielding TextBlock/ThinkingBlock (the same
   content would then follow the streamed tokens). Verified: one question
   on DeepSeek went from 12 SSE events to 1222.

5. **Assistant message rendered twice** (web/src/pages/agent-chat/index.tsx)
   After `send()` drained the SSE stream, `turn.text` was still non-empty;
   the handler then called `refetchSessionDetail()` which pulled the newly
   persisted assistant message into `historyMessages`, so `MessageList`
   rendered both the history entry AND the streaming turn — identical
   text displayed twice in a row. Now calls `reset()` after refetch
   so the streaming turn clears once history takes over.

Plus a UX fix:

- **max_turns / max_budget_usd inputs were unclearable** in
  NewSessionDialog. `Number("") || 20` snapped the state back to 20
  mid-type, so the field was effectively read-only. Switched to string
  state + parse-on-submit with sane fallbacks.

And one operational tool:

- **scripts/tob_acceptance.py** (new) — one-shot self-check hitting real
  MySQL / ES / Redis / (optional) DeepSeek. Runs 19 checks across
  definition registry, citation validator three rules, EvidenceIndex
  extraction, rewrite bailouts, compactor logic, session+history+summary
  persistence, audit log, tenant quota/usage, rate-limit memory+Redis
  paths, dedup, bot secret encryption, subagent trace persistence,
  cross-tenant RBAC deny, model_resolver regression (bug infiniflow#1 above),
  HTTP blueprint registration, ruff, and pytest. Optional
  `--live-llm` flag adds one real AgentRunner run (~$0.02) verifying
  bugs infiniflow#2, infiniflow#3, infiniflow#4 stay fixed end-to-end. All 18 checks currently green.

Verification:
- `.venv/bin/python scripts/tob_acceptance.py --live-llm` → 18 pass 0 fail
- `pytest test/agent_v2/test_validators.py test/agent_v2/test_compactor.py test/agent_v2/test_definitions.py`
  → 72 passed
- Live DeepSeek run (保障房 "公租房申请条件" prompt) → 1222 streamed
  events, rag_retrieve+rag_read_doc called, no citation_warning false
  positives, single non-duplicated assistant turn rendered.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Oldcircle added a commit to Oldcircle/ragflow that referenced this pull request Apr 27, 2026
旧实现 [...streamingToolCalls, ...historyToolCalls] + Set 首位保留
把当前轮调用强行顶到列表最前,多轮会话时上面是当前轮 infiniflow#1/infiniflow#2/infiniflow#3、
下面才接上一轮的 infiniflow#1/infiniflow#2/infiniflow#3 —— 视觉乱序。

后端 list_by_session 已按 start_time asc 排好,问题在前端。

改用 Map 合并:history 覆盖同 id 的 streaming(history 是 canonical
真值 + 服务端时钟一致),用 ...(existing ?? {}) 保留 streaming 上
subagent_start/end 注入的内联 trace(history 没有这字段),最后按
startTs 升序排,与左侧消息流"老→新 自上而下"对齐。

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
KevinHuSh pushed a commit that referenced this pull request May 19, 2026
…#14849)

## What problem does this PR solve?

Closes #12582.

When a Retrieval component sits inside an Iteration with a **manual**
metadata filter that references the iteration variable (e.g.
`{IterationItem:abc@item}`), every iteration reuses the value resolved
on the **first** pass.

Root cause: [`_resolve_manual_filter` in
`agent/tools/retrieval.py`](https://github.com/infiniflow/ragflow/blob/main/agent/tools/retrieval.py#L144-L171)
mutated `flt["value"]` in place. The `filters` list passed in is the
live `self._param.meta_data_filter["manual"]` (see
[`apply_meta_data_filter` in
`common/metadata_utils.py:257-261`](https://github.com/infiniflow/ragflow/blob/main/common/metadata_utils.py#L257-L261)),
so after the first iteration the param dict permanently held the
resolved string instead of the original variable reference.

```text
iter #1: flt["value"] = "{IterationItem:abc@item}"  →  resolved to "AI"
         after mutation: flt["value"] = "AI"        ← written back into _param

iter #2: flt["value"] = "AI"                         ← no {…} matches
         retrieval keeps filtering by "AI" forever
```

This PR returns a shallow copy with the resolved value instead, leaving
the original filter (and its variable reference) intact for the next
iteration.

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)

## Test plan

- [ ] Build an agent: `Agent (structured output → list of areas) →
Iteration → Retrieval (manual filter: Area = {IterationItem/Item}) →
Message`. Run with a multi-area query and confirm each iteration's
Retrieval result matches its own item, not the first item.
- [ ] Regression: Retrieval with a manual metadata filter outside an
Iteration still resolves the variable correctly on each request.
- [ ] Regression: Retrieval with no metadata filter and with `auto` /
`semi_auto` filters behave unchanged.
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 16, 2026
…equence test + tenant_id wiring

Closes the v3.6.1 §11.8.4 item infiniflow#2 — RunTracker.AttachCheckpoint unit
test that pins the production boot path. The existing runagent
e2e tests use the nil-tracker path; this commit adds a real
miniredis-backed test that asserts the full Start →
AttachCheckpoint → MarkSucceeded sequence lands in the run
hash during a single successful RunAgent call.

What the new test catches that the nil-tracker tests miss:

  - Start is called before Compile (canvas_id, tenant_id, status,
    and the Start-pipeline TTL are present in the hash).
  - AttachCheckpoint is called after Invoke when the store is
    configured (checkpoint_id field is non-empty and matches the
    runID — the Goal 7 runID-as-cpID contract).
  - MarkSucceeded is called when the run completes (status='1'
    + finished_at is set).

A regression in buildRunFunc's Goal 7 'if cpID != "" &&
s.runTracker != nil' guard would surface as a missing
checkpoint_id in the hash, which this test catches.

Supporting changes:

  1. service.RunAgent now populates root["tenant_id"] from the
     user-tenant lookup (best-effort; logs and continues on DAO
     failure). The RunTracker.Start call now records the
     correct tenant id rather than an empty string. Closes the
     implicit 'run history cannot be filtered by tenant' gap
     that the v3.5.2 audit flagged.

  2. canvas.NewRunTrackerWithClient and
     canvas.NewRedisCheckPointStoreWithClient exported
     helpers. Same shape as the existing NewRunTracker /
     NewRedisCheckPointStore, but the caller supplies a
     *redis.Client. Needed so the service test (and any future
     dedicated-pool deployments) can wire against an in-memory
     miniredis without touching the global Redis cache.

  3. makeCanvasWithDSL helper now seeds UserTenant.status='1'
     (DAO filter requires it). The previous test-only seed left
     status=NULL, which would silently exclude the test row
     from GetTenantIDsByUserID. No production path affected.

Test count delta: 608 → 609 passed (4 packages). No regressions.

Build: clean across internal/service, internal/agent/canvas,
internal/agent/component.

Co-Authored-By: Claude <[email protected]>
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 16, 2026
…done

Records the v3.6.1 implementation pass (4 commits, 21 new tests,
0 regressions). §11.8.5 v3.6.1 closing section + revision-history
v3.6.1 entry + §11.9 test count summary updated to reflect:

  - Gap infiniflow#2: RunTracker.AttachCheckpoint call-sequence test
  - Gap infiniflow#3: Phase 8b real TTS model-provider dispatch
  - Gap infiniflow#4: Phase 6 OQ infiniflow#6 per-class timeout integration
  - Gap infiniflow#5: LLM retry normal-absolute-count semantics

Item #1 (Resume e2e run-2 message production) deferred to v3.6.2
— eino UserFillUp second-pass is genuinely an eino-internal
concern, not a Go-side bug. Plumbing is fully verified by the
existing TestRunAgent_RealCanvas_WaitForUserResume run-1.

Test count: 1381 → 1402 passed (4 affected packages).
Build: clean across cmd/..., internal/agent/...,
internal/service/..., internal/handler/....

Co-Authored-By: Claude <[email protected]>
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 16, 2026
…2e_test.go

The file's name still referenced the Phase 4.4 V2 development
phase, which closed in v3.6.1 (see gap-analysis §11.8). The
test surface has grown well beyond that phase since:

  - TestRunAgent_RealCanvas_BeginMessage
  - TestRunAgent_RealCanvas_WaitForUserResume
  - TestRunAgent_RealCanvas_CompileFails
  - TestRunAgent_RealCanvas_InvokeFails
  - TestRunAgent_RunTracker_AttachCheckpoint_CallSequence (added in v3.6.1 Gap infiniflow#2)

The new name (agent_run_e2e_test.go) reflects the actual
content — five e2e integration tests for service.RunAgent
covering the full production chain (happy path, failure
paths, wait-for-user resume cycle, boot-wiring surface).

File header comment updated to drop the Phase 4.4 V2 framing
and document the new scope.

Test count: 9 passed in the RunAgent suite (unchanged).

Co-Authored-By: Claude <[email protected]>
yuzhichang added a commit to yuzhichang/ragflow that referenced this pull request Jun 17, 2026
…orts, sandbox admin-panel reader, and design-doc cleanup

This squashes 31 commits into one. It closes the agent canvas Phase 4.4
V2 (eino interrupt + check-pointing), the v3.5 implementation pass that
ported all 21 Python agent components + cycle handling to Go, the v3.5.1
production-wiring audit, the v3.5.2 silent-regression sweep, the v3.6
runtime/boot goals, the v3.6.1 next-round gap closures, the §14 admin-
panel sandbox gap, and the design-doc hygiene pass.

================================================================================
1. v3.5 — DSL convergence + 5 implementation items (cb608f0b3, b66a9738f)
================================================================================

refactor(agent): converge Go/Web DSL to single wire shape, drop v1/v2
  - `internal/agent/dsl/`: single wire shape consumed by both Go and
    React; replaces the divergent v1 (raw `dsl` map) and v2 (wrapped
    `graph` envelope) shapes that the two sides had drifted into.
  - `web/src/pages/agent/utils/dsl-bridge.ts`: 223 lines of bridge
    helpers (forward + reverse); 373-line Jest pinning both directions.
  - `web/src/pages/agent/hooks/use-build-dsl.ts`, `use-export-json.ts`,
    `use-import-json.ts`, `use-fetch-data.ts`: dropped the legacy
    branches.
  - `web/src/utils/canvas-util.tsx`, `file-util.ts`: call-site cleanup.
  - `internal/agent/component/v1_stubs.go` → `fixture_stubs.go` (rename
    reflects new role as the test-only fixture registry, not a v1
    parser).
  - `tools/migrate-canvas/` (185 LOC) and `tools/gen-component-parity/`
    (175 LOC) added as standalone binaries; parity-generator ships as a
    placeholder per OQ infiniflow#3 — no live migration of legacy canvases is
    expected from the tool.

feat(agent): v3.5 implementation pass — close P0-blocker + 4 P1 items
  (closes §11.5 of .claude/plans/agent-go-port-gap-analysis.md)
  - **P0 — Phase 4.4 orchestrator side**: `internal/agent/orchestrator/`
    added — `Driver` (in-memory `(canvasID, sessionID)` persistence),
    `Run` (folds `userInput` into prior root via
    `canvas.MergeUserInput`, inspects with `canvas.IsWaitForUser`),
    `RunEvent` (typed SSE events). `service.AgentService.RunAgent`
    signature extended to `(ctx, userID, canvasID, sessionID, version,
    userInput) -> <-chan orchestrator.RunEvent`. `handler/agent.go`
    `RunAgent` reads `?session_id=` and `?user_input=`, emits one SSE
    frame per event plus a `[DONE]` tail. **This is the last P0-
    blocker on the plan.**
  - **P1 — Retrieval agent tool**: `internal/agent/tool/retrieval_nlp.go`
    + `tool.SetRetrievalService` interface; `cmd/server_main.go:240`
    wires `NewNLPRetrievalAdapter(retrievalService)` at boot. The
    `NLPRetrievalAdapter` bridges `Search(*RetrievalSearchRequest)` to
    `Search(RetrievalRequest)`. Net effect: `RetrievalTool` /
    `RetrievalComponent` paths now hit the real nlp service, not the
    loud-fail stub.
  - **P1 — SearchMyDataset alias**: `fixture_stubs.go:486-491`
    registers `SearchMyDataset` → `NewRetrievalStub` (covered by
    `search_my_dataset_alias_test.go`).
  - **P1 — gonja direct import**: `internal/agent/runtime/template/`
    promotes `github.com/nikolalohinski/gonja v1.5.3` from indirect to
    direct (Jinja2 migration; Phase 8a).
  - **P1 — Phase 5a Universe A wrappers**: `universe_a_wrappers.go`
    adds `newRetrievalComponent`, `newTavilySearchComponent`,
    `newExeSQLComponent` all delegating to Universe B tools.
  - 4 new tests in `handler/agent_wait_for_user_test.go` (470 LOC);
    157 handler tests pass.

================================================================================
2. v3.5.1 — production-chain false-positive closures (829598f8f)
================================================================================

feat(agent): v3.5.1 — close the production-chain false positives
  - **Item 1 — orchestrator side (production)**: v3.5's `Driver` test
    used a fake `waitFakeAgentService` that drove the driver directly.
    Production `service.AgentService.RunAgent` still returned
    `<-chan string` and emitted the `"Phase 5 wiring pending"` literal;
    `handler/agent.go:RunAgent` called the old 4-arg signature and SSE-
    wrapped every event as `event: "message"`, dropping
    `RunEvent.Type`. v3.5.1 fixes the signature, the SSE frame type,
    and the channel shape so the handler actually exercises the driver.
  - **Item 2 — Retrieval agent tool (production)**: `cmd/server_main.go`
    now also wires KG retrieval (`SetKGRetrievalService`); the
    `NLPRetrievalAdapter` is registered on the real
    `internal/service/nlp/retrieval.go` (1079 LOC), not a fake.
  - **Item 3 — SearchMyDataset (production)**: registry primary
    swapped from `RetrievalStub` to `newRetrievalComponent` (the v3.5
    delegation wrapper).
  - **Item 4 — Production wiring fix**: 5-line `cmd/server_main.go`
    TTS boot wiring change (TTS engine + dispatcher).
  - **Item 5 — Universe A primary registry swap**: same as Item 3
    (one diff, two log entries).
  - 4 additional false-positive closures uncovered while re-running the
    suite (canvas timeouts, etc.).

================================================================================
3. v3.5.2 — silent production regressions (082c63472)
================================================================================

feat(agent): v3.5.2 — close 4 silent production regressions from v3.5.1
  - All four regressions were test-pass / production-still-broken pairs
    that the v3.5.1 audit intentionally scoped to the user's two
    items but uncovered while re-running the suite. Each got a real-
    path test (not a fake) + a real code-path fix.
  - `internal/service/agent_run_e2e_test.go` (629 LOC): production
    RunAgent end-to-end via miniredis + real HTTP fixtures.
  - `internal/handler/agent_test.go`: 49 lines of fixups.

================================================================================
4. Test cleanup + security hardening
================================================================================

fix(canvas): delete dead TestDSLExamples_* tests (4b3efc62c)
  - The `internal/agent/canvas/dsl_examples_e2e_test.go` (438 LOC)
    tested the v1 IMPORT-format parser that was removed in v3.5's DSL
    convergence. Dead code, deleted.

fix(agent): RunAgent version IDOR + DAO error visibility (1017ebb0f)
  - RunAgent now pins the requested `version` against the canvas
    owner's stored version (no cross-tenant read). DAO errors surface
    to logs (previously swallowed).

fix(agent): map DAO storage errors to 500, not raw data error (828f8f644)
  - `agent.go:loadCanvasForUser`: storage layer errors → HTTP 500 with
    a sanitized message. The old path returned a `data_error` string
    with the raw exception text, which leaked driver internals.

fix(agent): sanitise DAO errors in loadCanvasForUser (286082264)
  - Final pass on the same code path: scrub the message before
    logging, ensure no PII leak via error string.

================================================================================
5. Cycle wait-for-user — eino interrupt refactor (d6e8c9cf2)
================================================================================

refactor(agent): replace wait_for_user sentinel chain with eino interrupt
  - The v3.5 orchestrator Driver used a `__wait_for_user__` boolean
    field plumbed through root. eino v0.9.4 supports
    `compose.Interrupt` / `compose.Resume` natively, which is cleaner.
  - `internal/agent/canvas/interrupt_resume.go` (242 LOC): canonical
    interrupt/resume helpers; `IsWaitForUser` / `MergeUserInput`
    re-exported as thin adapters for back-compat with the orchestrator
    Driver.
  - `canvas/interrupt_resume_test.go` (230 LOC): pins the new
    semantics.
  - `internal/agent/canvas/cycle_wrap.go` (374 LOC) deleted; the
    cycle-handling logic moved into `cycle_wrap.go`'s replacement path
    inside `compile.go` (no separate file).

================================================================================
6. Phase 4.4 V2 — real canvas Compile/Invoke (12424be7d, 47630945e)
================================================================================

feat(service): canvas DSL decoder + AgentService option injection
  - `internal/service/canvas_decode.go` (164 LOC): the decoder that
    turns the raw DB-stored canvas bytes into a `*canvas.Canvas`
    ready for compile.
  - `canvas_decode_test.go` (258 LOC): decoder round-trip + malformed
    input handling.
  - `service.AgentService` now takes a `WithCanvasDecoder` option
    (dependency-injected instead of package-global).

feat(service): real canvas Compile/Invoke in buildRunFunc
  - `service.buildRunFunc` previously returned a stub. It now
    actually compiles the canvas (via `canvas.Compile`), invokes it
    via the orchestrator Driver, and propagates the typed event
    channel.
  - `service/agent.go` (475 LOC delta).

docs(gap-analysis): Phase 4.4 V2 closing + v3.6 next round
  - `.claude/plans/agent-go-port-gap-analysis.md` §11.7 captures the
    Phase 4.4 V2 closure (commits 0c62184 + 0bb5c94) and §11.8
    records the v3.6 next round.

fix(service,handler): review-driven hardening of Phase 4.4 V2
  - `service.RunAgent` now populates `root["tenant_id"]` from the
    user-tenant lookup (best-effort; falls back to the empty string
    if the user lookup fails).
  - `handler/agent.go`: SSE tail is `[DONE]\n\n` regardless of event
    payload — no more dangling SSE frames.
  - `internal/service/agent_test.go` (346 LOC) + `agent_run_e2e_test.go`
    (629 LOC) pin the new contract.

================================================================================
7. v3.6 — runtime + boot goals (5b06f8728, bd841ce2e, 40469d628)
================================================================================

feat(runtime): MarshalJSON/UnmarshalJSON + eino type registration
  - `CanvasState` (the in-flight canvas state checkpoint) implements
    `json.Marshaler` / `json.Unmarshaler` so the eino checkpoint
    serializer can round-trip it through Redis without losing
    channel/edge metadata.
  - Eino type registration: `internal/agent/runtime/register.go` —
    the `Register` calls that eino needs at startup to recognize
    custom node types.
  - `state_test.go`, `state_bench_test.go`: round-trip + bench
    (Go side: ~2× Python JSON round-trip; eino-internal numbers not
    measured here).
  - **Goal 2 closed.**

feat(agent): wire runID as canvas checkpoint id + RunTracker.AttachCheckpoint
  - `canvas.RunTracker` (10 LOC delta) gets `AttachCheckpoint(id string)`
    so the boot-side `RunTracker` can register the Redis-backed
    checkpoint before the canvas starts running.
  - Goal 7 closed.

feat(boot): Redis-backed run infra + TTS service wire-up in cmd/server_main
  - `cmd/server_main.go` (100 LOC delta) — `StartRunTracker`,
    `StartRedisCheckpointStore`, `configureTTSSynthesizer` wired at
    boot.
  - `internal/service/memory_message_service.go` (281 LOC): real
    `MemoryMessageService` impl for Phase 8b.
  - Goals 8 + 9 closed.

docs(gap-analysis): record v3.6 Goal 2/7/8/9 closing + v3.6.1 next round
  - `.claude/plans/agent-go-port-gap-analysis.md` §11.8 captures all
    four v3.6 goals closing in one place; §11.8.4 lists the v3.6.1
    next-round items.

================================================================================
8. v3.6.1 — closing 4 of 5 next-round items (Gaps #1–infiniflow#5)
================================================================================

feat(service,canvas): v3.6.1 Gap infiniflow#2 AttachCheckpoint call-sequence test
  - `service.RunAgent` populates `root["tenant_id"]` from the user-
    tenant lookup (best-effort).
  - `agent_run_e2e_test.go` pinned: Start → AttachCheckpoint →
    MarkSucceeded sequence via miniredis-backed `RunTracker`.
  - Closes Gap infiniflow#2.

feat(audio,boot): v3.6.1 Gap infiniflow#3 — real TTS model-provider dispatch
  - `audio.NewTTSDispatchFunc` + `TTSDispatcher` interface extracted.
  - `cmd/server_main.go:configureTTSSynthesizer` wires the real
    dispatch instead of the v3.6.0 placeholder.
  - `audio.ErrSynthesizeEmpty` sentinel.
  - `audio/tts_design.md` (154 LOC) — design rationale.
  - `audio/{tts,model_provider_synthesizer,tts_dispatch}*.go` (180+
    131 + 149 LOC) — the three-way split between TTS engine, model
    provider, and dispatcher.
  - `tts_dispatch_test.go` (223 LOC), `model_provider_synthesizer_test.go`
    (110 LOC), `tts_test.go` (119 LOC).
  - Closes Gap infiniflow#3.

feat(canvas): v3.6.1 Gap infiniflow#4 — wire per-class timeout into realComponentBody
  - `canvas/node_body.go` `realComponentBody` now calls
    `resolveTimeout(componentClass)` (was the uniform
    `componentTimeout()`).
  - `canvas/timeout.go` (135 LOC) — the `componentDefaults` map (10
    Python parity defaults + env-override) and the 4-level resolution
    table.
  - `node_body_timeout_test.go` (173 LOC) +
    `node_body_per_class_timeout_integration_test.go` (280 LOC):
    4 end-to-end tests pin ExeSQL 3s / TavilySearch 12s / uniform-
    fallback / per-class env override.
  - Closes Gap infiniflow#4.

feat(llm): v3.6.1 Gap infiniflow#5 — normal-absolute-count retry semantics
  - `internal/agent/component/llm_retry.go` (150 LOC) +
    `llm_retry_test.go` (387 LOC).
  - `retryInvoker.Unwrap()` + `unwrapChatInvoker` walk: param-
    override branch now wraps the **unwrapped** invoker so the
    absolute count is `MaxRetries+1` instead of
    `(MaxRetries+1) × (boot+1)`.
  - 6 tests pin the fix (3 unwrap unit + 1 absolute-count + 1 no-
    override back-compat + the existing
    TestLLM_RetryStackingSemantics stays green).
  - Closes Gap infiniflow#5.

docs(gap-analysis): v3.6.1 closing — 4 of 5 §11.8.4 next-round items
  - `.claude/plans/agent-go-port-gap-analysis.md` §11.8.5 records
    the v3.6.1 closure (4 of 5 items).
  - **Item #1 (Resume e2e run-2 message production)** deferred to
    v3.6.2 — eino UserFillUp second-pass is genuinely an eino-
    internal concern, not a Go-side bug; plumbing is fully verified.
  - Test count delta: 1381 → 1402 (+21 across 4 packages).

fix(canvas): v3.6.1 Gap #1 — wire CheckPointStore without overriding
eino's InternalSerializer
  - `canvas/checkpoint_store.go` (9 LOC delta) wires the Redis-backed
    `CheckpointStore` into the canvas builder.
  - Key change: we DO NOT override eino's `InternalSerializer` — we
    plug our `CanvasState` `MarshalJSON`/`UnmarshalJSON` (from
    Goal 2) and let eino use its built-in serializer over those
    primitives. Earlier draft overrode the serializer, which broke
    eino's resume semantics.
  - Closes Gap #1.

================================================================================
9. Tests + renames + CodeRabbit feedback
================================================================================

refactor(service): rename runagent_phase_4_4_v2_test.go →
agent_run_e2e_test.go (8cd5b008d)
  - Test filename was misleading (the test exercises the Phase 4.4
    V2 *contract*, not a phase marker). Renamed to reflect scope.

fix: address all CodeRabbit review comments on PR infiniflow#16035 (c7ce6504b)
  - Final review pass on the eino interrupt + check-pointing PR.
  - Touched: `cmd/server_main.go`, `docker/.env`, `docker/entrypoint.sh`,
    `docker/launch_backend_service.sh`, `docker/nginx/ragflow.conf.golang`,
    `.github/workflows/tests.yml`, `.gitignore`, `go.mod`, `go.sum`,
    `web/package.json`, `web/jest.config.ts`.

================================================================================
10. Design-doc cleanup + sandbox admin-panel reader
================================================================================

docs(design): drop historical version markers from design doc and Go
code (055752a48)
  - `docs/develop/agent-go-port-design.md` and `internal/agent/`: the
    doc and the Go comments still carried `v3.5`, `v3.6.1`, etc.
    annotation tags from the planning rounds. Dropped them; the
    current state lives in `.claude/plans/agent-go-port-gap-analysis.md`.

docs(design): remove stale status file; fix Driver.Run → Runner.Run
(af9bd0939)
  - `docs/develop/agent-go-port-status.md` (last touched 2026-06-15,
    per its line 3) is fully superseded by §16 of the design doc.
    Deleted.
  - The design doc still had ~12 `Driver.Run` references — the
    class is `Runner.Run` post-eino refactor. Fixed.

docs(design): delete sandbox-python-go-diff.md; integrate sandbox
gaps into §14 (23777f5c7)
  - `docs/develop/sandbox-python-go-diff.md` (21.2K) tracked the
    per-provider behavior diff between Python and Go sandboxes. The
    gaps are now closed (Aliyun SDK excepted) and the items
    migrated into `agent-go-port-design.md` §14 as the canonical
    tracking spot. File deleted.

docs(design): consolidate Aliyun SDK gaps; add effort estimates to
sandbox gaps (1893951db)
  - The Aliyun gaps were spread across 3 separate sub-items in §14.
    Consolidated into a single "blocked on upstream aliyun SDK" entry
    with the two specific blockers (TemplateName + execute-raw-HTTP).
  - Added effort estimates to each of the 7 remaining §14 sandbox
    items.

feat(sandbox): wire admin panel settings reader (close §14 gap 998)
  - `internal/agent/sandbox/config.go` — type-safe `configString` /
    `configInt` / `configDuration` helpers that accept any JSON shape
    (string, float64, int, bool, json.Number) and coerce to target.
  - Each provider (`self_managed.go`, `aliyun.go`, `e2b.go`,
    `local.go`, `ssh.go`) gets a `xxxConfigFromEnv()` + a
    `newXxxProviderFromConfig(cfg)` pair. `xxxProviderFromEnv` is
    refactored to delegate to `xxxProviderFromConfig(xxxConfigFromEnv())`,
    eliminating duplication and giving env-driven and settings-
    driven init semantically identical providers.
  - `internal/agent/sandbox/manager.go`:
    - `SystemSetting = entity.SystemSettings` type alias.
    - `SettingsReader` interface (`GetByName(name)`) — DAO seam.
    - `LoadFromSettings(ctx)` / `LoadFromSettingsWithReader(ctx, r)` —
      reads `sandbox.provider_type` and `sandbox.{type}` from the
      `system_settings` MySQL table, JSON-decodes the per-provider
      config, builds the provider via `FromConfig`. Soft-falls back
      to env on missing / malformed / unknown-type / DAO-error.
    - `ReloadFromSettings(ctx)` / `ReloadFromSettingsWithReader(ctx, r)`.
    - `errSettingsNotConfigured`, `errSettingsMalformed` sentinels.
    - `buildProviderFromConfig` parallel to `buildProvider`.
  - `internal/agent/sandbox/config_test.go` — 3 test funcs covering
    `configString` / `configInt` / `configDuration`.
  - `internal/agent/sandbox/manager_test.go` — `TestNew*FromConfig_*`
    for all 5 providers, `TestBuildProviderFromConfig_UnknownType`,
    `_HappyPath`, `TestLoadFromSettingsWithReader_*` (7 cases:
    HappyPath, EmptyFallback, DAOErrorFallback, MalformedJSONFallback,
    UnknownProviderType, AlreadyLoaded_NoOp), `TestReloadFromSettingsWithReader`.

docs(design): remove closed gap from §14 Future Work (2f1d84947)
  - The admin-panel reader item was closed by `feat(sandbox): wire
    admin panel settings reader (close §14 gap 998)` but still
    appeared in §14 with a ✅ annotation. Per the "Future Work only
    carries open items" principle, removed it entirely and tightened
    the §14 sandbox lead-in paragraph to point at the commit history.
  - The §14 sandbox subsection is now exactly the 7 open items
    (Aliyun SDK + LocalProvider rlimits + SSH SFTP + Windows build
    + e2b community SDK + OTel spans + the lead-in itself).

================================================================================
Stats
================================================================================

  234 files changed, 35413 insertions(+), 6111 deletions(-)

  Build: clean (`go build ./...`)
  Tests: 1402 across 4 packages (+21 from v3.6)
  Plan: .claude/plans/agent-go-port-gap-analysis.md v3.6.1 (single
        P0-blocker — Phase 4.4 orchestrator side — closed; remaining
        open items: 5d CodeExec full feature parity, 5c DB2,
        4.5 DSL parity corpus, Aliyun SDK gaps — all P2).

Co-Authored-By: Claude <[email protected]>
Taranum01 pushed a commit to Taranum01/ragflow that referenced this pull request Sep 10, 2026
…red (infiniflow#16978 review)

Per xugangqiang's follow-up review of infiniflow#16978 (fold #1, infiniflow#2, infiniflow#4;
deferring infiniflow#3):

1. CHART blocks now count toward images_chunked on the raw-mode text
   path too. Previously a chart-only raw PDF would report detected > 0,
   chunked = 0 even though the chart's caption/footnote was emitted
   into a real section — a systematic false positive on the headline
   detected - chunked gap. The condition at mineru_parser.py:~970 now
   matches {IMAGE, CHART}, mirroring images_described at :913 and
   images_chunked in _transfer_to_tables. New regression test
   test_raw_mode_counts_chart_block_as_chunked pins this.

2. Split the test that pinned a non-production counter value
   (raw + _transfer_to_tables in the same fixture — parse_pdf never
   calls _transfer_to_tables in raw mode). Replaced with two
   realistic-path tests:
   - test_raw_mode_counts_unreadable_resource_in_sections: raw mode
     only, pins the realistic counter values for that path.
   - test_app_media_mode_counts_unreadable_resource: naive/manual/paper
     path, which is the only path that runs _transfer_to_tables in
     production.
   The old test_readable_image_chunks assertion (chunked == 3) was
   the artifact of the increment-then-decrement pattern, which is
   now replaced by count-on-confirmed-emit.

3. Pre-seeded vlm_configured in both coverage dicts
   (MinerUParser.last_image_coverage in __init__ and the local
   image_coverage dict in _transfer_to_sections) so callers that
   read it after only _transfer_to_sections returns get False
   instead of KeyError. parse_pdf still overwrites it with the real
   vision_model status. New regression test
   test_initial_last_image_coverage_has_vlm_configured_key pins this.

Tests: pytest test/unit_test/deepdoc/parser/test_mineru_parser.py -v
      -> 57 passed (54 pre-existing + 3 new).
      The 3 pre-existing failures (RagTokenizer.set_language /
      grpcio-status) are unrelated to this change.
Annabelle0726 added a commit to Annabelle0726/wenruo-rag that referenced this pull request Oct 1, 2026
…ing and authorization, source tests executed

Readiness validation only: no U1 product code, no UI, no API, no migration, and no fix for any U0 finding (all sealed and carried forward).

- U1 V1 metrics mapped ONLY to workspace_usage, workspace_usage_ledger, workspace_budget and user_tenant; provider / key-instance / workload attribution and reconstructed history excluded; unknown stays unknown.

- reserved/settled/unsettled decision table frozen with effective_tokens = CASE WHEN status='settled' THEN tokens ELSE reserved_tokens END; counters are budget occupancy, not settled actuals; unsettled has two distinct causes.

- Monetary term frozen to 'Estimated model cost'; a zero-cost row with non-zero tokens renders as unknown/partial, never \.00.

- Authorization matrix frozen: NORMAL reads own rows only; OWNER/ADMIN reads the current workspace aggregate and member breakdown; live membership re-checked per request; refusals are HTTP 200 code=108.

- Source tests executed in the checkout's uv-managed .venv: collected 50, 48 passed, 2 skipped (Redis-gated, TEST_REDIS_URL deliberately unset to avoid a Redis mutation), 0 collection errors.

- U1_IMPLEMENTATION_READY stays NO: the no-secret production shape check is not authorized (U0 open decision infiniflow#2 unanswered).

Files: docs/key-usage/workspace-ai-usage-provider-reliability-u0-5.md (new), docs/key-usage/workspace-ai-usage-provider-reliability-u0.md (new), docs/key-usage/ROADMAP.md (new), AGENTS.md (milestone + pending decision).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants