diff --git a/assets/js/admin-ai-seo.js b/assets/js/admin-ai-seo.js index b587ec0d..42da9a97 100644 --- a/assets/js/admin-ai-seo.js +++ b/assets/js/admin-ai-seo.js @@ -78,8 +78,7 @@ function getEditorContent() { var content = ''; - var ta = document.getElementById('content'); - if (ta && ta.value) content = ta.value; + // Block editor first (post-new.php uses Gutenberg). try { if (window.wp && wp.data && wp.data.select) { var ed = wp.data.select('core/editor'); @@ -89,10 +88,27 @@ } } } catch (e) { /* ignore */ } - // Strip tags for length check / API + + if (!content) { + var ta = document.getElementById('content'); + if (ta && ta.value) content = ta.value; + } + + // TinyMCE classic. + try { + if (!content && window.tinymce && tinymce.get) { + var editor = tinymce.get('content'); + if (editor && editor.getContent) { + content = editor.getContent({ format: 'text' }) || editor.getContent() || ''; + } + } + } catch (e2) { /* ignore */ } + + // Strip tags for API plain-text summary. var div = document.createElement('div'); div.innerHTML = content || ''; - return (div.textContent || div.innerText || content || '').trim(); + var plain = (div.textContent || div.innerText || content || '').replace(/\u00a0/g, ' ').trim(); + return plain; } function setExcerptValue(summary) { @@ -238,23 +254,34 @@ .then(function (res) { setLoading(sumBtn, false, sumOriginal); if (!res.ok || !res.json || res.json.success === false) { + var j = res.json || {}; var msg = - (res.json && (res.json.message || (res.json.data && res.json.data.message))) || + j.message || + (j.data && (j.data.message || (Array.isArray(j.data) && j.data[0] && j.data[0].message))) || I18N.failed || '生成失败'; + if (res.status === 401 || res.status === 403) { + msg = I18N.needLogin || '登录已失效或权限不足,请刷新页面后重试'; + } notify(sumBtn, msg, 'error'); return; } - var summary = (res.json.data && res.json.data.summary) || ''; + var payload = res.json.data || {}; + var summary = payload.summary || (payload.data && payload.data.summary) || ''; + if (!summary) { + notify(sumBtn, I18N.failed || '生成失败:返回摘要为空', 'error'); + return; + } if (!setExcerptValue(summary)) { notify(sumBtn, I18N.noExcerptField || '未找到摘要字段,请展开「摘要」面板', 'error'); return; } notify(sumBtn, I18N.summarySuccess || '已填入摘要字段,请检查后更新保存', 'ok'); }) - .catch(function () { + .catch(function (err) { setLoading(sumBtn, false, sumOriginal); - notify(sumBtn, I18N.failed || '生成失败', 'error'); + notify(sumBtn, (err && err.message) || I18N.failed || '生成失败', 'error'); }); + }); })(); diff --git a/inc/classes/admin/class-aksrt-admin-ai-controller.php b/inc/classes/admin/class-aksrt-admin-ai-controller.php index 801f5716..f0efa162 100644 --- a/inc/classes/admin/class-aksrt-admin-ai-controller.php +++ b/inc/classes/admin/class-aksrt-admin-ai-controller.php @@ -204,24 +204,78 @@ class AKSRT_Admin_AI_Controller extends AKSRT_Admin_Controller_Base { } $params = $this->get_json_params($request); - $content = wp_kses_post((string) ($params['content'] ?? '')); - $max_len = max(50, min(500, (int) ($params['max_length'] ?? 200))); - - if (trim(wp_strip_all_tags($content)) === '') { - return $this->error(__('内容不能为空', 'aksrt')); + // Accept JSON body or form body (some admin contexts strip JSON). + if ($params === []) { + $params = $request->get_params(); + if (!is_array($params)) { + $params = []; + } } - $prompt = AKSRT_AI_Prompt::get_instance()->build_summary_prompt($content, $max_len); - $result = AKSRT_AI::get_instance()->generate_text($prompt, [ - 'max_tokens' => min(600, $max_len * 2), + $title = sanitize_text_field((string) ($params['title'] ?? '')); + $raw = (string) ($params['content'] ?? ''); + // Keep readable text; strip tags for emptiness / prompt length. + $plain = trim(wp_strip_all_tags(html_entity_decode($raw, ENT_QUOTES | ENT_HTML5, 'UTF-8'))); + $content = $plain !== '' ? $plain : trim(wp_strip_all_tags(wp_kses_post($raw))); + $max_len = max(50, min(500, (int) ($params['max_length'] ?? 200))); + + if ($content === '') { + return $this->error(__('内容不能为空,请先在编辑器填写正文后再生成摘要', 'aksrt'), 422); + } + + $ai = AKSRT_AI::get_instance(); + if (!$ai->is_available()) { + return $this->error( + __('AI 服务未启用或未配置。请到「扩展 → AI 辅助」启用并填写 API Key(或配置 WordPress AI Connectors)。', 'aksrt'), + 503 + ); + } + + // Prefer excerpt-oriented prompt when title is present. + $prompt_builder = AKSRT_AI_Prompt::get_instance(); + if ($title !== '' && method_exists($prompt_builder, 'build_excerpt_prompt')) { + $prompt = $prompt_builder->build_excerpt_prompt($title, $content); + } else { + $prompt = $prompt_builder->build_summary_prompt($content, $max_len); + } + + $result = $ai->generate_text($prompt, [ + 'max_tokens' => min(600, max(120, $max_len * 2)), 'temperature' => 0.5, + 'system_instruction' => __('你是中文内容编辑,只输出摘要正文,不要标题、前缀或 Markdown。', 'aksrt'), ]); if (!empty($result['success'])) { - return $this->success(['data' => ['summary' => $result['content']]]); + $summary = trim((string) ($result['content'] ?? '')); + if ($summary === '') { + return $this->error(__('AI 返回内容为空,请稍后重试或检查模型配置', 'aksrt'), 502); + } + // Soft trim to requested length (characters). + if (function_exists('mb_substr') && mb_strlen($summary) > $max_len + 20) { + $summary = mb_substr($summary, 0, $max_len); + } + return $this->success([ + 'data' => [ + 'summary' => $summary, + 'backend' => (string) ($result['backend'] ?? ''), + ], + ]); } - return $this->error((string) ($result['message'] ?? __('生成失败', 'aksrt'))); + $message = trim((string) ($result['message'] ?? '')); + if ($message === '') { + $message = __('生成失败', 'aksrt'); + } + + // Upstream/provider failures are not client validation errors. + $status = 502; + if (str_contains($message, '未启用') || str_contains($message, '未配置')) { + $status = 503; + } elseif (str_contains($message, '频繁')) { + $status = 429; + } + + return $this->error($message, $status); } public function tags_suggest(WP_REST_Request $request): WP_REST_Response { diff --git a/inc/classes/class-aksrt-ai.php b/inc/classes/class-aksrt-ai.php index f3402471..7906a0fd 100644 --- a/inc/classes/class-aksrt-ai.php +++ b/inc/classes/class-aksrt-ai.php @@ -111,16 +111,20 @@ class AKSRT_AI { } /** - * WordPress 核心 AI Client 是否可用。 + * WordPress 核心 AI Client 是否真正可用。 + * + * 仅有函数存根不够:没有 Connectors / wp_supports_ai=false 时不应抢占主题 provider。 */ public function is_wp_ai_available(): bool { if (!function_exists('wp_ai_client_prompt')) { return false; } - if (function_exists('wp_supports_ai') && !wp_supports_ai()) { - return false; + // Prefer the official capability gate when present. + if (function_exists('wp_supports_ai')) { + return (bool) wp_supports_ai(); } - return true; + // Without wp_supports_ai, do not claim availability (avoids false-positive 400s). + return false; } /** @@ -128,28 +132,37 @@ class AKSRT_AI { */ public function is_theme_provider_available(): bool { $config = $this->get_config(); + $provider = sanitize_key((string) ($config['provider'] ?? self::PROVIDER_NONE)); + $api_key = trim((string) ($config['api_key'] ?? '')); + $api_base = trim((string) ($config['api_base'] ?? '')); + return !empty($config['enabled']) - && ($config['provider'] ?? self::PROVIDER_NONE) !== self::PROVIDER_NONE - && !empty($config['api_key']); + && $provider !== self::PROVIDER_NONE + && $provider !== '' + && $api_key !== '' + && $api_base !== ''; } /** * 任一后端可用即可生成。 */ public function is_available(): bool { - return $this->is_wp_ai_available() || $this->is_theme_provider_available(); + return $this->is_theme_provider_available() || $this->is_wp_ai_available(); } /** * 当前优先后端标识。 + * + * Theme provider wins when explicitly configured — WP AI stubs often exist + * without a working connector and previously produced opaque 400 failures. */ public function resolve_backend(): string { - if ($this->is_wp_ai_available()) { - return 'wp_ai'; - } if ($this->is_theme_provider_available()) { return 'theme'; } + if ($this->is_wp_ai_available()) { + return 'wp_ai'; + } return 'none'; } @@ -205,28 +218,35 @@ class AKSRT_AI { ? (string) $options['system_instruction'] : __('你是一个内容助手,提供建议性内容。输出仅作为参考建议,不会自动应用到线上内容。', 'aksrt'); - // 1) Prefer WP AI Client + $last_error = [ + 'success' => false, + 'message' => __('AI 服务未启用或未配置。请配置 WordPress AI Connectors,或在「扩展 → AI 辅助」填写 API Key。', 'aksrt'), + ]; + + // 1) Prefer explicitly configured theme OpenAI-compatible provider. + if ($this->is_theme_provider_available()) { + $theme_result = $this->generate_via_theme($prompt, $system, $options); + $this->record_call(); + if (!empty($theme_result['success'])) { + $theme_result['backend'] = 'theme'; + return $theme_result; + } + $last_error = $theme_result; + // Fall through to WP AI if available. + } + + // 2) WordPress AI Client (Connectors). if ($this->is_wp_ai_available()) { $wp_result = $this->generate_via_wp_ai($prompt, $system, $options); + $this->record_call(); if (!empty($wp_result['success'])) { - $this->record_call(); $wp_result['backend'] = 'wp_ai'; return $wp_result; } - // Fall through to theme if configured - if (!$this->is_theme_provider_available()) { - $this->record_call(); - return $wp_result; - } + $last_error = $wp_result; } - // 2) Theme OpenAI-compatible - $theme_result = $this->generate_via_theme($prompt, $system, $options); - $this->record_call(); - if (!empty($theme_result['success'])) { - $theme_result['backend'] = 'theme'; - } - return $theme_result; + return $last_error; } /**