feat: AI 任务同步执行、评论垃圾管理、会员导航分组、多 AI 配置
Build and Deploy / verify (push) Successful in 10s
Build and Deploy / deploy (push) Successful in 20s

- 评论 AI 审核/文章润色改为同步执行(站点无 queue worker,任务曾永久卡队列,
  导致垃圾评论滞留待审核、润色毫无效果);审核在响应结束后经 terminating 触发
- 评论表:修复 approve 闭包里误嵌入 recordUrl 的坏链;新增「非垃圾」恢复发布、
  批量「标为垃圾」、工具栏「清空垃圾评论」;各操作补充通知反馈
- 会员套餐/订阅/订单移入新导航组「会员」
- LlmClient 支持多服务商 profile;AI 设置页可添加多个 AI 并为审核/润色/封面
  分别指定服务商(不指定用默认配置);封面生成同步支持 profile
- AI 设置页:润色改同步并即时展示结果,按钮加 loading;删除无 workerman 的
  WebSocket 进度区块
This commit is contained in:
2026-10-15 00:06:55 +00:00
parent ddbf259e93
commit 2e052498a5
14 changed files with 221 additions and 83 deletions
+2 -1
View File
@@ -8,7 +8,8 @@ namespace App\Blog\Jobs;
use App\Blog\Services\LlmClient;
/**
* 由 Workerman 消费者执行的 AI 任务统一接口。
* AI 任务统一接口。站点无常驻 queue worker,任务在响应结束后同步执行
* (comment.created 钩子经 app()->terminating 触发,后台操作直接 dispatchSync)。
*/
interface AiJob
{
+19 -5
View File
@@ -18,17 +18,29 @@ class CoverGenerator
public function isConfigured(): bool
{
return $this->llm->isConfigured();
return $this->llm()->isConfigured();
}
public function model(?string $override = null): string
{
return $override ?: (string) blog_setting('llm_image_model', 'image-01');
// 优先级:命令行参数 > llm_image_model 设置 > 图片 profile 的模型 > image-01
$profileModel = blog_setting('llm_profile_image') ? $this->llm()->model() : null;
return $override
?: (string) (blog_setting('llm_image_model') ?: $profileModel ?: 'image-01');
}
/**
* 封面生成使用的 LLM 配置(可在 AI 设置里指定独立的服务商)。
*/
private function llm(): LlmClient
{
return $this->llm->forProfile((string) blog_setting('llm_profile_image', ''));
}
public function generateFor(Post $post, ?string $model = null, ?string $style = null): void
{
if (! $this->llm->isConfigured()) {
if (! $this->llm()->isConfigured()) {
throw new \RuntimeException('LLM 未配置:请先在后台「AI 设置」配置 Base URL / API Key');
}
@@ -102,9 +114,11 @@ class CoverGenerator
private function requestImage(string $prompt, ?string $model = null): \Illuminate\Http\Client\Response
{
$llm = $this->llm();
return Http::timeout(120)
->withToken($this->llm->apiKey())
->post($this->llm->baseUrl().'/image_generation', [
->withToken($llm->apiKey())
->post($llm->baseUrl().'/image_generation', [
'model' => $this->model($model),
'prompt' => $prompt,
'aspect_ratio' => '16:9',
+44 -3
View File
@@ -10,22 +10,26 @@ use Illuminate\Support\Facades\Log;
/**
* OpenAI 兼容 LLM 客户端(支持 OpenAI / DeepSeek / 通义 / 自建代理)。
* 支持多服务商:后台「AI 设置」可配置 llm_profiles,用 forProfile('名称') 切换。
*/
class LlmClient
{
/** @var array{base_url?: string, api_key?: string, model?: string} */
private array $overrides = [];
public function baseUrl(): string
{
return rtrim((string) blog_setting('llm_base_url', config('services.llm.base_url', env('LLM_BASE_URL'))), '/');
return rtrim((string) ($this->overrides['base_url'] ?? blog_setting('llm_base_url', config('services.llm.base_url', env('LLM_BASE_URL')))), '/');
}
public function apiKey(): string
{
return (string) blog_setting('llm_api_key', config('services.llm.api_key', env('LLM_API_KEY')));
return (string) ($this->overrides['api_key'] ?? blog_setting('llm_api_key', config('services.llm.api_key', env('LLM_API_KEY'))));
}
public function model(): string
{
return (string) blog_setting('llm_model', config('services.llm.model', env('LLM_MODEL', 'gpt-4o-mini')));
return (string) ($this->overrides['model'] ?? blog_setting('llm_model', config('services.llm.model', env('LLM_MODEL', 'gpt-4o-mini'))));
}
public function isConfigured(): bool
@@ -33,6 +37,43 @@ class LlmClient
return $this->baseUrl() !== '' && $this->apiKey() !== '';
}
/**
* 已配置的额外 AI 服务商列表(后台 AI 设置维护)。
*
* @return list<array{name?: string, base_url?: string, api_key?: string, model?: string}>
*/
public static function profiles(): array
{
$profiles = json_decode((string) blog_setting('llm_profiles', '[]'), true);
return is_array($profiles) ? $profiles : [];
}
/**
* 切换到指定名称的服务商配置;名称为空或不存在时返回默认配置。
*/
public function forProfile(?string $name): static
{
if (! $name) {
return $this;
}
foreach (self::profiles() as $profile) {
if (($profile['name'] ?? '') === $name) {
$clone = clone $this;
$clone->overrides = array_filter([
'base_url' => $profile['base_url'] ?? null,
'api_key' => $profile['api_key'] ?? null,
'model' => $profile['model'] ?? null,
], fn ($value) => filled($value));
return $clone;
}
}
return $this;
}
/**
* 简单的聊天补全。
*
@@ -7,12 +7,15 @@ namespace App\Filament\Resources\Comments\Tables;
use App\Models\Comment;
use Filament\Actions\Action;
use Filament\Actions\BulkAction;
use Filament\Actions\BulkActionGroup;
use Filament\Actions\DeleteBulkAction;
use Filament\Actions\EditAction;
use Filament\Notifications\Notification;
use Filament\Tables\Columns\TextColumn;
use Filament\Tables\Filters\SelectFilter;
use Filament\Tables\Table;
use Illuminate\Support\Collection;
class CommentsTable
{
@@ -74,21 +77,68 @@ class CommentsTable
->color('success')
->visible(fn (Comment $record) => $record->status !== 'published')
->action(function (Comment $record): void {
$record->update(['status' => 'published'])
->recordUrl(null)
->recordAction(null);
$record->update(['status' => 'published']);
$record->post?->increment('comment_count');
Notification::make()->title('评论已通过')->success()->send();
}),
Action::make('spam')
->label('垃圾')
->icon('heroicon-o-x-mark')
->color('danger')
->visible(fn (Comment $record) => $record->status !== 'spam')
->action(fn (Comment $record) => $record->update(['status' => 'spam'])),
->action(function (Comment $record): void {
if ($record->status === 'published') {
$record->post?->decrement('comment_count');
}
$record->update(['status' => 'spam']);
Notification::make()->title('已标记为垃圾评论')->success()->send();
}),
Action::make('notSpam')
->label('非垃圾')
->icon('heroicon-o-check-badge')
->color('success')
->requiresConfirmation()
->modalHeading('标记为非垃圾')
->modalDescription('该评论将恢复为已发布状态。')
->visible(fn (Comment $record) => $record->status === 'spam')
->action(function (Comment $record): void {
$record->update(['status' => 'published']);
$record->post?->increment('comment_count');
Notification::make()->title('已恢复发布')->success()->send();
}),
EditAction::make(),
])
->recordUrl(null)
->recordAction(null)
->toolbarActions([
Action::make('purgeSpam')
->label('清空垃圾评论')
->icon('heroicon-o-trash')
->color('danger')
->requiresConfirmation()
->modalHeading('清空垃圾评论')
->modalDescription(fn (): string => '将永久删除全部 '.Comment::query()->where('status', 'spam')->count().' 条垃圾评论,不可恢复。')
->visible(fn (): bool => Comment::query()->where('status', 'spam')->exists())
->action(function (): void {
$count = Comment::query()->where('status', 'spam')->count();
Comment::query()->where('status', 'spam')->delete();
Notification::make()->title("已删除 {$count} 条垃圾评论")->success()->send();
}),
BulkActionGroup::make([
BulkAction::make('markSpam')
->label('标为垃圾')
->icon('heroicon-o-x-mark')
->color('danger')
->requiresConfirmation()
->action(function (Collection $records): void {
$records->each(function (Comment $record): void {
if ($record->status === 'published') {
$record->post?->decrement('comment_count');
}
$record->update(['status' => 'spam']);
});
Notification::make()->title('已标记 '.$records->count().' 条为垃圾评论')->success()->send();
}),
DeleteBulkAction::make(),
]),
])
@@ -83,6 +83,7 @@ class AdminPanelProvider extends PanelProvider
)
->navigationGroups([
NavigationGroup::make('内容'),
NavigationGroup::make('会员'),
NavigationGroup::make('管理'),
NavigationGroup::make('插件'),
])
@@ -5,9 +5,11 @@ declare(strict_types=1);
namespace Plugins\Neatstudio\AiModeration\Filament\Pages;
use App\Blog\Services\LlmClient;
use App\Models\Post;
use App\Models\Setting;
use Filament\Actions\Action;
use Filament\Forms\Components\Repeater;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\Textarea;
use Filament\Forms\Components\TextInput;
@@ -46,9 +48,24 @@ class AiSettings extends Page
'cover_prompt_style' => Setting::get('cover_prompt_style', '扁平插画风格,色调柔和,构图简洁'),
'ai_moderation_enabled' => (int) Setting::get('ai_moderation_enabled', 1) === 1,
'ai_moderation_system_prompt' => Setting::get('ai_moderation_system_prompt', '你是博客评论审核员。判断评论是否包含:广告/垃圾、人身攻击、违法内容、无关灌水。只回复 JSON:{"verdict":"approved|rejected|spam","reason":"简短理由"}'),
'llm_profiles' => LlmClient::profiles(),
'llm_profile_moderation' => Setting::get('llm_profile_moderation'),
'llm_profile_polish' => Setting::get('llm_profile_polish'),
'llm_profile_image' => Setting::get('llm_profile_image'),
]);
}
/**
* @return array<string, string>
*/
private function profileOptions(): array
{
return collect(LlmClient::profiles())
->pluck('name', 'name')
->filter()
->toArray();
}
public function form(Schema $schema): Schema
{
return $schema
@@ -63,6 +80,34 @@ class AiSettings extends Page
->helperText('供 php artisan covers:generate 批量生成封面使用(接口:{Base URL}/image_generation)'),
TextInput::make('cover_prompt_style')->label('封面风格')->default('扁平插画风格,色调柔和,构图简洁'),
]),
\Filament\Schemas\Components\Section::make('多 AI 配置')
->description('可配置多个 AI 服务商,并给不同任务指定独立的服务商;不指定则统一使用上方默认配置')
->schema([
Repeater::make('llm_profiles')
->label('AI 服务商')
->schema([
TextInput::make('name')->label('名称')->required()->placeholder('deepseek'),
TextInput::make('base_url')->label('Base URL')->required()->placeholder('https://api.deepseek.com/v1'),
TextInput::make('api_key')->label('API Key')->password()->required(),
TextInput::make('model')->label('模型')->placeholder('deepseek-chat'),
])
->columns(4)
->addActionLabel('添加 AI 服务商')
->defaultItems(0)
->columnSpanFull(),
Select::make('llm_profile_moderation')
->label('评论审核使用')
->options(fn (): array => $this->profileOptions())
->placeholder('默认配置'),
Select::make('llm_profile_polish')
->label('文章润色使用')
->options(fn (): array => $this->profileOptions())
->placeholder('默认配置'),
Select::make('llm_profile_image')
->label('封面生成使用')
->options(fn (): array => $this->profileOptions())
->placeholder('默认配置'),
]),
\Filament\Schemas\Components\Section::make('评论审核')
->schema([
Toggle::make('ai_moderation_enabled')->label('新评论启用 AI 自动审核'),
@@ -77,7 +122,17 @@ class AiSettings extends Page
$data = $this->form->getState();
foreach ($data as $key => $value) {
Setting::set($key, is_bool($value) ? (string) (int) $value : (string) $value);
if (is_bool($value)) {
$value = (string) (int) $value;
} elseif (is_array($value)) {
// Repeater(llm_profiles)等数组配置存 JSON,丢弃未填名称的行
$value = json_encode(
array_values(array_filter($value, fn ($row) => filled($row['name'] ?? null))),
JSON_UNESCAPED_UNICODE
);
}
Setting::set($key, (string) $value);
}
Notification::make()->title('AI 设置已保存')->success()->send();
@@ -93,8 +148,18 @@ class AiSettings extends Page
return;
}
dispatch(new AiPolishContentJob($post->id))->onQueue('ai');
Notification::make()->title('润色任务已提交(由 Workerman 异步执行)')->info()->send();
// 同步执行(站点无常驻 queue worker),几十秒内出结果并直接展示
try {
AiPolishContentJob::dispatchSync($post->id);
$this->polishResult = $post->fresh()->meta['ai_polished'] ?? null;
Notification::make()
->title($this->polishResult ? '润色完成,下方预览后可采纳' : '润色未返回结果')
->{$this->polishResult ? 'success' : 'warning'}()
->send();
} catch (\Throwable $e) {
Notification::make()->title('润色失败')->body($e->getMessage())->danger()->send();
}
}
public function acceptPolish(Post $post): void
@@ -29,6 +29,8 @@ class AiModerateCommentJob implements AiJob, ShouldQueue
return;
}
$llm = $llm->forProfile((string) blog_setting('llm_profile_moderation', ''));
WorkermanBroadcaster::send('ai.moderation.started', ['comment_id' => $this->commentId]);
$system = (string) blog_setting('ai_moderation_system_prompt', '你是博客评论审核员。判断评论是否包含:广告/垃圾、人身攻击、违法内容、无关灌水。只回复 JSON:{"verdict":"approved|rejected|spam","reason":"简短理由"}');
@@ -32,6 +32,8 @@ class AiPolishContentJob implements AiJob, ShouldQueue
? $post->content
: (new \League\HTMLToMarkdown\HtmlConverter())->convert($post->content);
$llm = $llm->forProfile((string) blog_setting('llm_profile_polish', ''));
$polished = $llm->chat([
['role' => 'system', 'content' => '你是中文博客编辑。润色下面的文章,保持原意、事实、Markdown 结构不变,改进表达、语法、可读性。直接输出润色后的完整 Markdown。'],
['role' => 'user', 'content' => $source],
@@ -28,7 +28,14 @@ class ServiceProvider extends PluginServiceProvider
return;
}
dispatch(new Jobs\AiModerateCommentJob($comment->id))->onQueue('ai');
// 站点无常驻 queue worker:响应结束后同步执行审核,避免任务永远卡在队列里
$job = fn () => Jobs\AiModerateCommentJob::dispatchSync($comment->id);
if (app()->runningInConsole()) {
$job();
} else {
app()->terminating($job);
}
}, 10);
}
}
@@ -6,13 +6,16 @@
</div>
</form>
<x-filament::section heading="AI 润色文章">
<x-filament::section heading="AI 润色文章" description="同步执行,约 10~60 秒出结果;结果先暂存,确认后点「采纳」写回文章。">
<div class="space-y-2">
@foreach(\App\Models\Post::query()->latest()->limit(20)->get(['id','title']) as $post)
<div class="flex items-center justify-between rounded-lg border border-gray-200 p-3 dark:border-white/10">
<span class="text-sm">{{ $post->title }}</span>
<div class="flex gap-2">
<x-filament::button size="sm" color="primary" wire:click="polish({{ $post->id }})">AI 润色</x-filament::button>
<div class="flex items-center gap-2">
<x-filament::button size="sm" color="primary" wire:click="polish({{ $post->id }})" wire:loading.attr="disabled" wire:target="polish({{ $post->id }})">
<x-filament::loading-indicator class="h-4 w-4" wire:loading wire:target="polish({{ $post->id }})" />
AI 润色
</x-filament::button>
@if($post->meta['ai_polished'] ?? null)
<x-filament::button size="sm" color="success" wire:click="acceptPolish({{ $post->id }})">采纳</x-filament::button>
@endif
@@ -28,60 +31,4 @@
</div>
@endif
</x-filament::section>
<x-filament::section heading="AI 审核实时进度"
:description="'WebSocket :'.config('workerman.websocket_port', 8787).'(需 workerman:serve 运行;未连接时结果仍会落库,可在评论列表查看)'">
<div id="ai-moderation-feed" class="space-y-1 text-sm" style="max-height:260px;overflow-y:auto;">
<p class="text-gray-500">等待事件…</p>
</div>
</x-filament::section>
</x-filament-panels::page>
<script>
document.addEventListener('DOMContentLoaded', function () {
var port = {{ (int) config('workerman.websocket_port', 8787) }};
var host = location.hostname || 'localhost';
var feed = document.getElementById('ai-moderation-feed');
if (! feed) return;
var ws;
try {
ws = new WebSocket('ws://' + host + ':' + port);
} catch (e) { return; }
ws.onopen = function () {
feed.innerHTML = '<p class="text-gray-400">已连接,等待 AI 审核事件…</p>';
};
ws.onclose = function () {
feed.innerHTML = '<p class="text-gray-500">WebSocket 未连接(workerman 未运行或端口不通)</p>';
};
ws.onmessage = function (e) {
var msg;
try { msg = JSON.parse(e.data); } catch (err) { return; }
if (! msg.event || msg.event.indexOf('ai.moderation') !== 0) return;
var d = msg.data || {};
var item = document.createElement('div');
var text = '[' + new Date().toLocaleTimeString() + '] 评论 #' + (d.comment_id || '?') + ' ';
var cls = 'border-gray-300 bg-gray-50 dark:border-white/10';
if (msg.event === 'ai.moderation.started') {
text += '开始审核…';
cls = 'border-blue-300 bg-blue-50 dark:border-blue-500/30';
} else if (msg.event === 'ai.moderation.finished') {
var labels = { approved: '已通过', rejected: '已拒绝', spam: '垃圾评论' };
text += '审核完成:' + (labels[d.verdict] || d.verdict);
cls = d.verdict === 'approved' ? 'border-green-300 bg-green-50 dark:border-green-500/30'
: (d.verdict === 'spam' ? 'border-red-300 bg-red-50 dark:border-red-500/30'
: 'border-amber-300 bg-amber-50 dark:border-amber-500/30');
} else if (msg.event === 'ai.moderation.failed') {
text += '审核失败:' + (d.error || '未知错误');
cls = 'border-red-300 bg-red-50 dark:border-red-500/30';
}
item.className = 'rounded-md border px-2 py-1 ' + cls;
item.textContent = text;
feed.prepend(item);
};
});
</script>
@@ -21,7 +21,7 @@ use Plugins\Neatstudio\Membership\Models\MembershipPlan;
class MembershipPlanResource extends Resource
{
protected static \UnitEnum|string|null $navigationGroup = '管理';
protected static \UnitEnum|string|null $navigationGroup = '会员';
protected static ?string $model = MembershipPlan::class;
@@ -17,7 +17,7 @@ use Plugins\Neatstudio\Membership\Models\Subscription;
class SubscriptionResource extends Resource
{
protected static \UnitEnum|string|null $navigationGroup = '管理';
protected static \UnitEnum|string|null $navigationGroup = '会员';
protected static ?string $model = Subscription::class;
@@ -15,7 +15,7 @@ use Plugins\Neatstudio\Payment\Models\Payment;
class PaymentResource extends Resource
{
protected static \UnitEnum|string|null $navigationGroup = '管理';
protected static \UnitEnum|string|null $navigationGroup = '会员';
protected static ?string $model = Payment::class;
+12 -4
View File
@@ -27,10 +27,8 @@ class AiModerationTest extends TestCase
Setting::set('llm_model', 'test-model');
}
public function test_comment_created_dispatches_moderation_job(): void
public function test_comment_created_runs_moderation_after_response(): void
{
\Illuminate\Support\Facades\Queue::fake();
$post = Post::create([
'title' => '评论审核',
'slug' => 'ai-comment',
@@ -40,12 +38,20 @@ class AiModerationTest extends TestCase
'published_at' => now(),
]);
$llm = $this->mock(LlmClient::class);
$llm->shouldReceive('isConfigured')->andReturn(true);
$llm->shouldReceive('forProfile')->andReturnSelf();
$llm->shouldReceive('chat')->andReturn('{"verdict":"approved","reason":"正常"}');
$this->post('/posts/'.$post->id.'/comments', [
'author_name' => '访客',
'content' => '这是一条需要审核的评论',
]);
\Illuminate\Support\Facades\Queue::assertPushed(AiModerateCommentJob::class);
// 审核在响应结束后同步执行(app()->terminating),测试请求周期内即完成
$comment = Comment::query()->latest('id')->first();
$this->assertSame('published', $comment->status);
$this->assertStringContainsString('approved', $comment->ai_review['raw'] ?? '');
}
public function test_moderation_job_approves_comment(): void
@@ -68,6 +74,7 @@ class AiModerationTest extends TestCase
]);
$llm = $this->mock(LlmClient::class);
$llm->shouldReceive('forProfile')->andReturnSelf();
$llm->shouldReceive('chat')->once()->andReturn('{"verdict":"approved","reason":"正常"}');
(new AiModerateCommentJob($comment->id))->handle($llm);
@@ -97,6 +104,7 @@ class AiModerationTest extends TestCase
]);
$llm = $this->mock(LlmClient::class);
$llm->shouldReceive('forProfile')->andReturnSelf();
$llm->shouldReceive('chat')->once()->andReturn('{"verdict":"spam","reason":"广告"}');
(new AiModerateCommentJob($comment->id))->handle($llm);