Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
fix(feishu): surface permission errors clearly and keep users on page (#3032)
xierfloatcd9add7a27e7
diff --git a/openviking/parse/accessors/feishu_accessor.py b/openviking/parse/accessors/feishu_accessor.pyindex ac97ebd0d..e65f13f71 100644--- a/openviking/parse/accessors/feishu_accessor.py+++ b/openviking/parse/accessors/feishu_accessor.py@@ -16,9 +16,11 @@ import reimport tempfilefrom dataclasses import dataclassfrom pathlib import Path-from typing import Any, Dict, Optional, Tuple, Union+from typing import Any, Dict, NoReturn, Optional, Tuple, Unionfrom urllib.parse import urlparse+from openviking.utils.exceptions import error_code_from_http_status+from openviking_cli.exceptions import OpenVikingErrorfrom openviking_cli.utils.logger import get_loggerfrom .base import DataAccessor, LocalResource, SourceType@@ -27,6 +29,7 @@ from .mime_types import get_preferred_extensionlogger = get_logger(__name__)_FEISHU_IMAGE_RE = re.compile(r"!\[([^\]]*)\]\(feishu://image/([^)]+)\)")+_FEISHU_DOCUMENT_FORBIDDEN = 1770032def _getattr_safe(obj, key: str, default=None):@@ -36,6 +39,47 @@ def _getattr_safe(obj, key: str, default=None):return getattr(obj, key, default)+def _response_http_status(response: Any) -> int | None:+ status = getattr(getattr(response, "raw", None), "status_code", None)+ return status if isinstance(status, int) else None+++def _raise_from_lark_response(+ response: Any,+ *,+ operation: str,+ resource: str | None = None,+) -> NoReturn:+ code = getattr(response, "code", None)+ msg = getattr(response, "msg", None) or "Feishu API request failed"+ http_status = _response_http_status(response)+ details: dict[str, Any] = {+ "operation": operation,+ "feishu_code": code,+ "feishu_msg": msg,+ "http_status": http_status,+ }+ if resource:+ details["resource"] = resource++ logger.error(+ "[FeishuAPI] %s failed: code=%s msg=%s http=%s",+ operation,+ code,+ msg,+ http_status,+ )+ raise OpenVikingError(+ f"Feishu {operation} failed: code={code}, msg={msg}",+ code=(+ "PERMISSION_DENIED"+ if code == _FEISHU_DOCUMENT_FORBIDDEN or "forbidden" in msg.lower()+ else error_code_from_http_status(http_status)+ ),+ details=details,+ )++@dataclassclass FeishuDocument:"""Result from fetching a Feishu document."""@@ -344,8 +388,8 @@ class FeishuAccessor(DataAccessor):import lark_oapi as larkexcept ImportError:raise ImportError(- "lark-oapi is required for Feishu document parsing. "- "Install it with: pip install lark-oapi>=1.0.0"+ "lark-oapi is required for Feishu document parsing. "+ "Install it with: pip install lark-oapi>=1.0.0")config = self._get_config()app_id = config.app_id or os.getenv("FEISHU_APP_ID", "")@@ -396,8 +440,10 @@ class FeishuAccessor(DataAccessor):else:response = client.wiki.v2.space.get_node(request, option)if not response.success():- raise RuntimeError(- f"Failed to resolve wiki node {token}: code={response.code}, msg={response.msg}"+ _raise_from_lark_response(+ response,+ operation=f"resolve wiki node {token}",+ resource=token,)node = response.data.nodeobj_type = node.obj_type or ""@@ -492,9 +538,10 @@ class FeishuAccessor(DataAccessor):response = client.docx.v1.document_block.list(request, option)if not response.success():- raise RuntimeError(- f"Failed to fetch blocks for {document_id}: "- f"code={response.code}, msg={response.msg}"+ _raise_from_lark_response(+ response,+ operation=f"fetch blocks for {document_id}",+ resource=document_id,)items = response.data.items or []@@ -674,9 +721,7 @@ class FeishuAccessor(DataAccessor):# injects it (see lark_oapi.core.token.auth.verify) and the download# silently fails — dropping images from user-token imports.token_type = (- lark.AccessTokenType.USER- if feishu_access_token- else lark.AccessTokenType.TENANT+ lark.AccessTokenType.USER if feishu_access_token else lark.AccessTokenType.TENANT)raw_req = (lark.BaseRequest.builder()@@ -688,7 +733,9 @@ class FeishuAccessor(DataAccessor):option = self._user_request_option(feishu_access_token)try:- raw_resp = client.request(raw_req) if option is None else client.request(raw_req, option)+ raw_resp = (+ client.request(raw_req) if option is None else client.request(raw_req, option)+ )except Exception as exc:logger.warning("[FeishuAccessor] Error downloading image %s: %s", file_token, exc)return None@@ -698,9 +745,7 @@ class FeishuAccessor(DataAccessor):http_status = getattr(raw, "status_code", None)detail = getattr(raw_resp, "msg", "") or f"HTTP {http_status}"if http_status == 403:- detail = (- f"{detail} (missing Feishu permission docs:document.media:download)"- )+ detail = f"{detail} (missing Feishu permission docs:document.media:download)"logger.warning("[FeishuAccessor] Failed to download image %s: code=%s, http=%s, msg=%s",file_token,diff --git a/openviking/server/error_mapping.py b/openviking/server/error_mapping.pyindex da166e064..d969f0ece 100644--- a/openviking/server/error_mapping.py+++ b/openviking/server/error_mapping.py@@ -28,6 +28,7 @@ from openviking.pyagfs.exceptions import (GitConcurrentCommitError,)from openviking.storage.errors import LockAcquisitionError, ResourceBusyError+from openviking.utils.exceptions import HTTP_STATUS_TO_ERROR_CODE, error_code_from_http_statusfrom openviking_cli.exceptions import (ConflictError,FailedPreconditionError,@@ -39,23 +40,7 @@ from openviking_cli.exceptions import (UnavailableError,)-_UPSTREAM_HTTP_STATUS_TO_ERROR_CODE = {- 400: "INVALID_ARGUMENT",- 401: "UNAUTHENTICATED",- 402: "RESOURCE_EXHAUSTED",- 403: "PERMISSION_DENIED",- 404: "NOT_FOUND",- 408: "DEADLINE_EXCEEDED",- 409: "CONFLICT",- 422: "INVALID_ARGUMENT",- 429: "RESOURCE_EXHAUSTED",- 500: "UNAVAILABLE",- 502: "UNAVAILABLE",- 503: "UNAVAILABLE",- 504: "DEADLINE_EXCEEDED",-}--_KNOWN_HTTP_STATUS_CODES = frozenset(_UPSTREAM_HTTP_STATUS_TO_ERROR_CODE)+_KNOWN_HTTP_STATUS_CODES = frozenset(HTTP_STATUS_TO_ERROR_CODE)_UPSTREAM_ERROR_MARKERS = ("api error","apierror",@@ -288,16 +273,6 @@ def _extract_text_http_status(exc: Exception) -> int | None:return None-def _upstream_code_for_status(status: int) -> str:- if status in _UPSTREAM_HTTP_STATUS_TO_ERROR_CODE:- return _UPSTREAM_HTTP_STATUS_TO_ERROR_CODE[status]- if 400 <= status < 500:- return "INVALID_ARGUMENT"- if 500 <= status < 600:- return "UNAVAILABLE"- return "UNKNOWN"--def _extract_vlm_info(exc: Exception | None) -> tuple[str | None, str | None]:"""Extract model name and api_base from the exception chain, if annotated."""if exc is None:@@ -365,7 +340,7 @@ def _map_upstream_api_error(exc: Exception) -> OpenVikingError | None:if status is None:status = _extract_text_http_status(exc)if status is not None:- code = _upstream_code_for_status(status)+ code = error_code_from_http_status(status, default="UNKNOWN")if code == "UNKNOWN":return Nonereturn _build_upstream_error(diff --git a/openviking/utils/exceptions.py b/openviking/utils/exceptions.pyindex a7bdb037e..d3b8444b2 100644--- a/openviking/utils/exceptions.py+++ b/openviking/utils/exceptions.py@@ -1,6 +1,34 @@# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.# SPDX-License-Identifier: AGPL-3.0-"""Common exceptions for credential failover functionality."""+"""Common exception helpers."""++HTTP_STATUS_TO_ERROR_CODE = {+ 400: "INVALID_ARGUMENT",+ 401: "UNAUTHENTICATED",+ 402: "RESOURCE_EXHAUSTED",+ 403: "PERMISSION_DENIED",+ 404: "NOT_FOUND",+ 408: "DEADLINE_EXCEEDED",+ 409: "CONFLICT",+ 422: "INVALID_ARGUMENT",+ 429: "RESOURCE_EXHAUSTED",+ 500: "UNAVAILABLE",+ 502: "UNAVAILABLE",+ 503: "UNAVAILABLE",+ 504: "DEADLINE_EXCEEDED",+}+++def error_code_from_http_status(status: int | None, default: str = "INVALID_ARGUMENT") -> str:+ if status is None:+ return default+ if status in HTTP_STATUS_TO_ERROR_CODE:+ return HTTP_STATUS_TO_ERROR_CODE[status]+ if 400 <= status < 500:+ return "INVALID_ARGUMENT"+ if 500 <= status < 600:+ return "UNAVAILABLE"+ return defaultclass AllCredentialsFailedError(Exception):diff --git a/tests/parse/test_feishu_errors.py b/tests/parse/test_feishu_errors.pynew file mode 100644index 000000000..2f705ff24--- /dev/null+++ b/tests/parse/test_feishu_errors.py@@ -0,0 +1,69 @@+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.+# SPDX-License-Identifier: AGPL-3.0+"""Tests for Feishu OpenAPI error mapping."""++from types import SimpleNamespace++import pytest++from openviking.parse.accessors.feishu_accessor import _raise_from_lark_response+from openviking_cli.exceptions import OpenVikingError+++def _fake_response(+ *,+ code: int,+ msg: str,+ http_status: int = 400,+):+ return SimpleNamespace(+ code=code,+ msg=msg,+ raw=SimpleNamespace(status_code=http_status),+ )+++def _raised_error(response, *, operation="resolve wiki node", resource=None):+ with pytest.raises(OpenVikingError) as exc_info:+ _raise_from_lark_response(response, operation=operation, resource=resource)+ return exc_info.value+++def test_maps_feishu_forbidden_to_permission_denied_and_keeps_details():+ response = _fake_response(+ code=1770032,+ msg="forBidden",+ http_status=400,+ )+ exc = _raised_error(+ response,+ operation="fetch document blocks",+ resource="doc_token",+ )++ assert exc.code == "PERMISSION_DENIED"+ assert "code=1770032, msg=forBidden" in exc.message+ assert exc.details["feishu_code"] == 1770032+ assert exc.details["feishu_msg"] == "forBidden"+ assert exc.details["http_status"] == 400+ assert exc.details["resource"] == "doc_token"+++ ("http_status", "error_code"),+ [+ (401, "UNAUTHENTICATED"),+ (404, "NOT_FOUND"),+ (429, "RESOURCE_EXHAUSTED"),+ (500, "UNAVAILABLE"),+ (400, "INVALID_ARGUMENT"),+ ],+)+def test_maps_http_status_to_openviking_error(http_status, error_code):+ response = _fake_response(code=123, msg="failed", http_status=http_status)++ exc = _raised_error(response)++ assert exc.code == error_code+ assert exc.details["feishu_code"] == 123+ assert exc.details["http_status"] == http_statusdiff --git a/web-studio/src/hooks/use-app-connection.test.ts b/web-studio/src/hooks/use-app-connection.test.tsindex 6a16e6c83..cdd40ee09 100644--- a/web-studio/src/hooks/use-app-connection.test.ts+++ b/web-studio/src/hooks/use-app-connection.test.ts@@ -3,8 +3,11 @@ import { describe, expect, it } from 'vitest'import {resolveConnectionRoleProbeState,resolveInitialApiKey,+ shouldRedirectToLoginOnApiError,} from './use-app-connection'+const acceptClientError = () => true+describe('resolveInitialApiKey', () => {it('keeps the stored connection key paired with the stored account and user', () => {expect(@@ -80,3 +83,36 @@ describe('resolveConnectionRoleProbeState', () => {})})})++describe('shouldRedirectToLoginOnApiError', () => {+ it('redirects on HTTP 401 session failures', () => {+ expect(+ shouldRedirectToLoginOnApiError(+ { statusCode: 401, code: 'UNAUTHENTICATED' },+ acceptClientError,+ ),+ ).toBe(true)+ })++ it('does not redirect on HTTP 403 business permission errors', () => {+ expect(+ shouldRedirectToLoginOnApiError(+ {+ statusCode: 403,+ code: 'PERMISSION_DENIED',+ details: { feishu_code: 1770032 },+ },+ acceptClientError,+ ),+ ).toBe(false)+ })++ it('does not redirect on other HTTP 403 permission denials', () => {+ expect(+ shouldRedirectToLoginOnApiError(+ { statusCode: 403, code: 'PERMISSION_DENIED' },+ acceptClientError,+ ),+ ).toBe(false)+ })+})diff --git a/web-studio/src/hooks/use-app-connection.tsx b/web-studio/src/hooks/use-app-connection.tsxindex 942e20f2c..4232b532c 100644--- a/web-studio/src/hooks/use-app-connection.tsx+++ b/web-studio/src/hooks/use-app-connection.tsx@@ -180,6 +180,20 @@ export function resolveConnectionRoleProbeState({return { isLoading: true, role: 'unknown', shouldProbe: true }}+export function shouldRedirectToLoginOnApiError(+ error: unknown,+ isClientError: (value: unknown) => boolean = isOvClientError,+): boolean {+ if (!isClientError(error)) {+ return false+ }++ const clientError = error as { code?: string; statusCode?: number }+ return (+ clientError.statusCode === 401 || clientError.code === 'UNAUTHENTICATED'+ )+}+function applyConnection(connection: ConnectionDraft,serverMode: ServerMode,@@ -420,8 +434,7 @@ export function AppConnectionProvider({(response) => response,(error) => {if (- isOvClientError(error) &&- (error.statusCode === 401 || error.statusCode === 403) &&+ shouldRedirectToLoginOnApiError(error) &&Date.now() >= authPromptSuppressedUntilRef.current) {openConnectionSettings()