🎬 Open-source, self-hosted AI agent that runs a YouTube channel end to end: researches topics, writes scripts, generates narration, visuals and video, optimizes SEO, and publishes after your approval, then learns from analytics. Works with Gemini, OpenAI, OpenRouter, DeepSeek and more.
JavaScript ai-agentsautomationcontent-automationcontent-creationcontent-strategygoogle-geminijavascriptnodejsopenaiself-hostedseo-optimizationsocial-media-automationthumbnail-generatorvideo-generationyoutube-apiyoutube-automationyoutube-botyoutube-channelyoutube-shortsyoutube-uploader
fix: address final review findings for engagement studio
darkzOGx9e4c2996395b
diff --git a/dashboard/app.js b/dashboard/app.jsindex 854d878..a019432 100644--- a/dashboard/app.js+++ b/dashboard/app.js@@ -454,7 +454,9 @@ function renderEngagementDetail() {const commentsById = new Map((detail.comments || []).map(comment => [comment.commentId, comment]));const postingEnabled = ui.state?.engagement?.postingEnabled === true;const drafts = (detail.drafts || []).filter(draft => draft.status !== 'discarded');- $('#engagement-drafts').innerHTML = drafts.length ? drafts.map(draft => {+ const draftsContainer = $('#engagement-drafts');+ // The 8s poll must not wipe a reply the operator is actively editing.+ const draftsHTML = drafts.length ? drafts.map(draft => {const comment = commentsById.get(draft.commentId) || {};const locked = draft.status === 'posted';return `@@ -470,6 +472,7 @@ function renderEngagementDetail() {</div></article>`;}).join('') : empty('No reply drafts for this video yet.');+ if (!draftsContainer.contains(document.activeElement)) draftsContainer.innerHTML = draftsHTML;const attention = Array.isArray(insight.attentionFlags) ? insight.attentionFlags : [];$('#engagement-attention').innerHTML = attention.length ? attention.map(flag => {@@ -478,7 +481,7 @@ function renderEngagementDetail() {<article class="comment-card"><div class="learning-card-heading"><strong>${escapeHTML((flag.categories || []).join(', '))}</strong></div><p class="comment-original">${escapeHTML(comment.text || '')}</p>- <a class="text-button" href="${escapeHTML(flag.permalink || '#')}" target="_blank" rel="noopener noreferrer">Open in YouTube Studio</a>+ <a class="text-button" href="${escapeHTML(flag.permalink || '#')}" target="_blank" rel="noopener noreferrer">Open on YouTube</a></article>`;}).join('') : empty('Nothing flagged as spam, scam, or toxic.');}@@ -1154,6 +1157,7 @@ document.addEventListener('click', async event => {if (replyApprove) {const card = replyApprove.closest('[data-reply-card]');const text = card?.querySelector('[data-reply-text]')?.value || '';+ if (!text.trim()) return showToast('Reply text is empty.', 'error');if (confirm(`Post this reply to YouTube?\n\n${text}`)) {await mutate(`/api/engagement/replies/${encodeURIComponent(replyApprove.dataset.replyApprove)}/approve`, 'POST', { confirmed: true, editedText: text }, 'Reply posted to YouTube.').catch(() => {});ui.engagementDetail = null;diff --git a/index.js b/index.jsindex acb5f07..8cee69c 100644--- a/index.js+++ b/index.js@@ -107,7 +107,7 @@ class YouTubeAutomationAgent {this.engagement = new AudienceEngagementService(this.db,this.credentials,- new AITextService(this.credentials),+ new AITextService(this.credentials?.credentials || {}),{ logger: this.logger });@@ -948,10 +948,12 @@ class YouTubeAutomationAgent {}});+ const ENGAGEMENT_VIDEO_ID = /^[A-Za-z0-9_-]{1,100}$/;+this.app.get('/api/engagement/:videoId', async (req, res) => {try {const videoId = String(req.params.videoId || '').trim();- if (!/^[A-Za-z0-9_-]{1,100}$/.test(videoId)) {+ if (!ENGAGEMENT_VIDEO_ID.test(videoId)) {return res.status(400).json({ error: 'A valid YouTube video ID is required' });}const [insight, comments, drafts] = await Promise.all([@@ -969,7 +971,7 @@ class YouTubeAutomationAgent {try {if (!this.engagement) return res.status(503).json({ error: 'Audience engagement requires completed setup' });const videoId = String(req.params.videoId || '').trim();- if (!/^[A-Za-z0-9_-]{1,100}$/.test(videoId)) {+ if (!ENGAGEMENT_VIDEO_ID.test(videoId)) {return res.status(400).json({ error: 'A valid YouTube video ID is required' });}const sync = await this.engagement.syncVideoComments(videoId, req.body || {});@@ -985,7 +987,11 @@ class YouTubeAutomationAgent {this.app.post('/api/engagement/:videoId/draft-replies', protect, async (req, res) => {try {if (!this.engagement) return res.status(503).json({ error: 'Audience engagement requires completed setup' });- const result = await this.engagement.draftReplies(String(req.params.videoId || '').trim(), req.body || {});+ const videoId = String(req.params.videoId || '').trim();+ if (!ENGAGEMENT_VIDEO_ID.test(videoId)) {+ return res.status(400).json({ error: 'A valid YouTube video ID is required' });+ }+ const result = await this.engagement.draftReplies(videoId, req.body || {});return res.json({ success: true, result });} catch (error) {return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code });@@ -1006,13 +1012,18 @@ class YouTubeAutomationAgent {try {if (!this.engagement) return res.status(503).json({ error: 'Audience engagement requires completed setup' });const result = await this.engagement.approveReplyDraft(req.params.draftId, req.body || {});- await this.operator.notify({- type: 'audience_reply_posted',- level: 'success',- title: 'Audience reply posted',- message: `A reply was posted on video ${result.videoId}`,- data: { draftId: result.id, videoId: result.videoId, postedCommentId: result.postedCommentId }- });+ // The reply is already live on YouTube; a notification failure must not report an error.+ try {+ await this.operator.notify({+ type: 'audience_reply_posted',+ level: 'success',+ title: 'Audience reply posted',+ message: `A reply was posted on video ${result.videoId}`,+ data: { draftId: result.id, videoId: result.videoId, postedCommentId: result.postedCommentId }+ });+ } catch (notifyError) {+ this.logger.warn(`Posted reply notification failed: ${notifyError.message}`);+ }return res.json({ success: true, result });} catch (error) {return res.status(error.status || 400).json({ success: false, error: error.message, code: error.code });diff --git a/test.js b/test.jsindex a165577..b657e13 100644--- a/test.js+++ b/test.js@@ -58,6 +58,7 @@ class SystemTest {{ name: 'Audience Idea Mining', test: () => this.testAudienceIdeaMining() },{ name: 'Reply Drafting', test: () => this.testReplyDrafting() },{ name: 'Reply Approval and Posting', test: () => this.testReplyApprovalAndPosting() },+ { name: 'Engagement AI Provider Wiring', test: () => this.testEngagementAIProviderWiring() },{ name: 'Engagement Sync Schedule', test: () => this.testEngagementSyncSchedule() }];@@ -2789,6 +2790,35 @@ class SystemTest {}}+ async testEngagementAIProviderWiring() {+ const { AITextService } = require('./utils/ai-text-service');++ // Regression: index.js must hand AITextService the unwrapped credentials object+ // (manager.credentials), the shape the walkthrough writes to credentials.json.+ // Passing the CredentialManager itself leaves the engagement studio permanently+ // in fallback mode on installs with no provider environment variables.+ const savedEnv = process.env.OPENAI_API_KEY;+ delete process.env.OPENAI_API_KEY;+ try {+ const configured = new AITextService({+ aiProvider: { provider: 'openai', apiKey: 'test-key', model: 'gpt-5.6' }+ });+ if (!configured.isAvailable()) {+ throw new Error('AITextService must initialize from a credentials-file aiProvider config');+ }++ const wrapped = new AITextService({+ credentials: { aiProvider: { provider: 'openai', apiKey: 'test-key', model: 'gpt-5.6' } }+ });+ if (wrapped.isAvailable()) {+ throw new Error('A CredentialManager-shaped argument must not look configured; index.js has to unwrap it');+ }+ } finally {+ if (savedEnv === undefined) delete process.env.OPENAI_API_KEY;+ else process.env.OPENAI_API_KEY = savedEnv;+ }+ }+async testEngagementSyncSchedule() {let captured = null;const events = [];diff --git a/utils/audience-engagement-service.js b/utils/audience-engagement-service.jsindex e53fe24..ff64790 100644--- a/utils/audience-engagement-service.js+++ b/utils/audience-engagement-service.js@@ -16,6 +16,7 @@ class AudienceEngagementService {this.maxCommentsPerAnalysis = Number(options.maxCommentsPerAnalysis || 200);this.maxDraftsPerRun = Number(options.maxDraftsPerRun || 10);this.dailyReplyCap = Number(options.dailyReplyCap || process.env.ENGAGEMENT_DAILY_REPLY_CAP || 50);+ this.syncDelayMs = Number(options.syncDelayMs ?? 2000);this.listCommentThreads = options.listCommentThreads || (params => this.defaultListCommentThreads(params));this.insertComment = options.insertComment || (params => this.defaultInsertComment(params));this.getChannelId = options.getChannelId || (() => this.defaultGetChannelId());@@ -113,6 +114,9 @@ class AudienceEngagementService {// Watermark is keyed on top-level publish time (order=time is newest-first);// new replies inside old threads are only picked up when their thread re-enters a page.+ // A first sync of a video with more comments than maxCommentsPerSync stops at the cap but+ // still records the newest comment as the watermark, so the older backlog beyond that cap is+ // never backfilled by later runs.async syncVideoComments(videoId, meta = {}) {const existing = await this.db.getEngagementInsight(videoId);const watermark = existing?.newestCommentAt ? new Date(existing.newestCommentAt) : null;@@ -206,9 +210,11 @@ Comments: ${JSON.stringify(payload)}`;title: String(theme?.title || '').slice(0, 120).trim(),summary: String(theme?.summary || '').slice(0, 300).trim(),kind: THEME_KINDS.includes(theme?.kind) ? theme.kind : 'feedback',- commentIds: (Array.isArray(theme?.commentIds) ? theme.commentIds : [])- .filter(id => known.has(id))- .filter(id => !(perComment.get(id)?.flags || []).some(flag => QUARANTINE_FLAGS.includes(flag)))+ commentIds: [...new Set(+ (Array.isArray(theme?.commentIds) ? theme.commentIds : [])+ .filter(id => known.has(id))+ .filter(id => !(perComment.get(id)?.flags || []).some(flag => QUARANTINE_FLAGS.includes(flag)))+ )]})).filter(theme => theme.title && theme.commentIds.length >= 2).slice(0, 8)@@ -226,8 +232,17 @@ Comments: ${JSON.stringify(payload)}`;}async analyzeVideo(videoId) {- const comments = (await this.db.listAudienceComments({ videoId, limit: this.maxCommentsPerAnalysis }))- .filter(comment => !comment.isChannelOwner);+ // Top-level comments claim the analysis budget first; replies fill any remaining room.+ const selected = await this.db.listAudienceComments({ videoId, topLevelOnly: true, limit: this.maxCommentsPerAnalysis });+ if (selected.length < this.maxCommentsPerAnalysis) {+ const seen = new Set(selected.map(comment => comment.commentId));+ const all = await this.db.listAudienceComments({ videoId, limit: this.maxCommentsPerAnalysis });+ for (const comment of all) {+ if (selected.length >= this.maxCommentsPerAnalysis) break;+ if (!seen.has(comment.commentId)) selected.push(comment);+ }+ }+ const comments = selected.filter(comment => !comment.isChannelOwner);if (!comments.length) return this.db.getEngagementInsight(videoId);let analysis;@@ -345,6 +360,10 @@ Comments: ${JSON.stringify(payload)}`;results.skipped++;continue;}+ // Space out API calls once a sweep is already underway, matching the analytics sweep.+ if (results.synced + results.failed > 0 && this.syncDelayMs > 0) {+ await new Promise(resolve => setTimeout(resolve, this.syncDelayMs));+ }try {const outcome = await this.syncVideoComments(videoId, video);results.synced++;@@ -422,7 +441,7 @@ Comments: ${JSON.stringify(payload)}`;for (const entry of Array.isArray(entries) ? entries : []) {const target = byId.get(entry?.commentId);const text = String(entry?.reply || '').trim().slice(0, 1000);- if (!target || !text || /https?:\/\//i.test(text)) continue;+ if (!target || !text || /(https?:\/\/|www\.)/i.test(text)) continue;drafts.push(await this.db.saveReplyDraft({commentId: target.commentId,videoId,