Luca448 commited on
Commit
c0f1db4
·
1 Parent(s): 4ef8fce

Feat: News UI top tab bar and AI Model fallback cascade logic with simulation

Browse files
Files changed (2) hide show
  1. server/news-service.js +65 -24
  2. src/views/news/news-view.js +38 -8
server/news-service.js CHANGED
@@ -87,7 +87,7 @@ async function searchDDG(query) {
87
  }
88
 
89
  // Call Gemini
90
- async function generateArticleWithGemini(topic, searchResults) {
91
  const apiKey = process.env.GEMINI_API_KEY;
92
  if (!apiKey) {
93
  throw new Error('GEMINI_API_KEY is not set on the server.');
@@ -120,24 +120,64 @@ Antworte nur mit dem Markdown-Text des Artikels, oder "SKIP".`;
120
  }
121
  };
122
 
123
- const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`, {
124
- method: 'POST',
125
- headers: { 'Content-Type': 'application/json' },
126
- body: JSON.stringify(body)
127
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
128
 
129
- if (!response.ok) {
130
- const errText = await response.text();
131
- throw new Error(`Gemini API Error: ${errText}`);
 
 
 
 
 
132
  }
133
 
134
- const resJson = await response.json();
135
- const text = resJson.candidates?.[0]?.content?.parts?.[0]?.text;
136
- return text?.trim() || 'SKIP';
137
  }
138
 
139
  // Generate for all topics
140
- async function runGenerationCycle() {
141
  console.log('[NewsService] Starting generation cycle...');
142
  const apiKey = process.env.GEMINI_API_KEY;
143
  if (!apiKey) {
@@ -158,7 +198,7 @@ async function runGenerationCycle() {
158
  continue;
159
  }
160
 
161
- const content = await generateArticleWithGemini(topic, results);
162
 
163
  if (content && content !== 'SKIP' && !content.startsWith('SKIP')) {
164
  // Find best image logic? We don't have image search easily.
@@ -169,8 +209,8 @@ async function runGenerationCycle() {
169
 
170
  // Generate a catchy title
171
  const lines = content.split('\n').filter(l => l.trim().length > 0);
172
- let title = lines.find(l => l.startsWith('#')) || \`Neuigkeiten zu \${topic}\`;
173
- title = title.replace(/^#+\\s*/, '').trim(); // Remove markdown headers
174
 
175
  // Find a short description (first non-header paragraph)
176
  let snippet = lines.find(l => !l.startsWith('#') && l.length > 20) || 'Aktuelle Informationen aus dem Web...';
@@ -183,22 +223,22 @@ async function runGenerationCycle() {
183
  snippet: snippet,
184
  content: content,
185
  sources: results,
186
- imageUrl: \`https://images.unsplash.com/photo-1503676260728-1c00da094a0b?q=80&w=800&auto=format&fit=crop\`, // Default school image
187
  timestamp: Date.now()
188
  };
189
 
190
  // Add to beginning
191
  data.articles.unshift(article);
192
  newArticles++;
193
- console.log(\`[NewsService] Successfully generated article for \${topic}.\`);
194
  } else {
195
- console.log(\`[NewsService] AI skipped topic: \${topic}\`);
196
  }
197
 
198
  // Sleep to avoid rate limits
199
  await new Promise(r => setTimeout(r, 2000));
200
  } catch (e) {
201
- console.error(\`[NewsService] Error processing topic \${topic}:\`, e);
202
  }
203
  }
204
 
@@ -206,7 +246,7 @@ async function runGenerationCycle() {
206
  data.lastRun = Date.now();
207
  saveData();
208
  }
209
- console.log(\`[NewsService] Generation cycle complete. Added \${newArticles} articles.\`);
210
  }
211
 
212
  // Start up
@@ -256,9 +296,10 @@ export function registerNewsRoutes(app) {
256
  res.json({ success: true, topics: data.topics });
257
  });
258
 
259
- app.post('/api/news/generate', async (req, res) => {
 
260
  // Manual trigger
261
- runGenerationCycle(); // async
262
- res.json({ success: true, message: 'Generation started in background' });
263
  });
264
  }
 
87
  }
88
 
89
  // Call Gemini
90
+ async function generateArticleWithGemini(topic, searchResults, simulateError = false) {
91
  const apiKey = process.env.GEMINI_API_KEY;
92
  if (!apiKey) {
93
  throw new Error('GEMINI_API_KEY is not set on the server.');
 
120
  }
121
  };
122
 
123
+ const cascade = [
124
+ { name: 'gemini-3.5-flash', shouldSimulateError: simulateError },
125
+ { name: 'gemini-3.5-flash', isRetry: true, delayMs: 10000, shouldSimulateError: simulateError },
126
+ { name: 'gemini-2.5-flash', shouldSimulateError: false },
127
+ { name: 'gemini-3.1-flash-lite', shouldSimulateError: false }
128
+ ];
129
+
130
+ for (const step of cascade) {
131
+ console.log(`[NewsService] Trying model: ${step.name}${step.isRetry ? ' (Retry)' : ''}...`);
132
+
133
+ if (step.delayMs) {
134
+ console.log(`[NewsService] Waiting ${step.delayMs / 1000} seconds before retry...`);
135
+ await new Promise(r => setTimeout(r, step.delayMs));
136
+ }
137
+
138
+ try {
139
+ if (step.shouldSimulateError) {
140
+ throw new Error('Simulated 503 Overloaded Error');
141
+ }
142
+
143
+ const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${step.name}:generateContent?key=${apiKey}`, {
144
+ method: 'POST',
145
+ headers: { 'Content-Type': 'application/json' },
146
+ body: JSON.stringify(body)
147
+ });
148
+
149
+ if (!response.ok) {
150
+ if (response.status === 404) {
151
+ // If fake future model 3.5 doesn't exist, we fallback to 1.5-flash to keep it working
152
+ console.log(`[NewsService] Model ${step.name} not found (404), falling back to gemini-1.5-flash`);
153
+ const fbResponse = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key=${apiKey}`, {
154
+ method: 'POST',
155
+ headers: { 'Content-Type': 'application/json' },
156
+ body: JSON.stringify(body)
157
+ });
158
+ if (!fbResponse.ok) throw new Error(`Fallback Error: ${await fbResponse.text()}`);
159
+ const fbJson = await fbResponse.json();
160
+ return fbJson.candidates?.[0]?.content?.parts?.[0]?.text?.trim() || 'SKIP';
161
+ }
162
+ const errText = await response.text();
163
+ throw new Error(`API Error ${response.status}: ${errText}`);
164
+ }
165
 
166
+ const resJson = await response.json();
167
+ const text = resJson.candidates?.[0]?.content?.parts?.[0]?.text;
168
+ console.log(`[NewsService] Successfully generated with ${step.name}`);
169
+ return text?.trim() || 'SKIP';
170
+ } catch (e) {
171
+ console.error(`[NewsService] Failed with ${step.name}: ${e.message}`);
172
+ // Continue to next model in cascade
173
+ }
174
  }
175
 
176
+ throw new Error('All models in the fallback cascade failed.');
 
 
177
  }
178
 
179
  // Generate for all topics
180
+ async function runGenerationCycle(simulateError = false) {
181
  console.log('[NewsService] Starting generation cycle...');
182
  const apiKey = process.env.GEMINI_API_KEY;
183
  if (!apiKey) {
 
198
  continue;
199
  }
200
 
201
+ const content = await generateArticleWithGemini(topic, results, simulateError);
202
 
203
  if (content && content !== 'SKIP' && !content.startsWith('SKIP')) {
204
  // Find best image logic? We don't have image search easily.
 
209
 
210
  // Generate a catchy title
211
  const lines = content.split('\n').filter(l => l.trim().length > 0);
212
+ let title = lines.find(l => l.startsWith('#')) || `Neuigkeiten zu ${topic}`;
213
+ title = title.replace(/^#+\s*/, '').trim(); // Remove markdown headers
214
 
215
  // Find a short description (first non-header paragraph)
216
  let snippet = lines.find(l => !l.startsWith('#') && l.length > 20) || 'Aktuelle Informationen aus dem Web...';
 
223
  snippet: snippet,
224
  content: content,
225
  sources: results,
226
+ imageUrl: `https://images.unsplash.com/photo-1503676260728-1c00da094a0b?q=80&w=800&auto=format&fit=crop`, // Default school image
227
  timestamp: Date.now()
228
  };
229
 
230
  // Add to beginning
231
  data.articles.unshift(article);
232
  newArticles++;
233
+ console.log(`[NewsService] Successfully generated article for ${topic}.`);
234
  } else {
235
+ console.log(`[NewsService] AI skipped topic: ${topic}`);
236
  }
237
 
238
  // Sleep to avoid rate limits
239
  await new Promise(r => setTimeout(r, 2000));
240
  } catch (e) {
241
+ console.error(`[NewsService] Error processing topic ${topic}:`, e);
242
  }
243
  }
244
 
 
246
  data.lastRun = Date.now();
247
  saveData();
248
  }
249
+ console.log(`[NewsService] Generation cycle complete. Added ${newArticles} articles.`);
250
  }
251
 
252
  // Start up
 
296
  res.json({ success: true, topics: data.topics });
297
  });
298
 
299
+ app.post('/api/news/generate', express.json(), async (req, res) => {
300
+ const simulateError = req.body && req.body.simulateError === true;
301
  // Manual trigger
302
+ runGenerationCycle(simulateError); // async
303
+ res.json({ success: true, message: simulateError ? 'Simulated fallback generation started' : 'Generation started in background' });
304
  });
305
  }
src/views/news/news-view.js CHANGED
@@ -8,6 +8,7 @@ export class NewsView {
8
  this.isLoading = true;
9
  this.activeArticle = null;
10
  this.chatHistory = [];
 
11
  }
12
 
13
  async init() {
@@ -49,10 +50,15 @@ export class NewsView {
49
  </button>
50
  </div>
51
 
52
- <!-- Topics Scroller -->
53
- <div style="padding: 0 24px; margin-bottom: 24px; display: flex; gap: 8px; overflow-x: auto; scrollbar-width: none;">
54
- ${this.topics.map(t => `<div style="background: rgba(255,255,255,0.1); padding: 6px 12px; border-radius: 16px; font-size: 13px; white-space: nowrap;">${t}</div>`).join('')}
55
- ${this.topics.length === 0 && !this.isLoading ? '<div style="color: var(--text-secondary); font-size: 14px;">Keine Themen konfiguriert.</div>' : ''}
 
 
 
 
 
56
  </div>
57
 
58
  <div class="news-feed" style="padding: 0 16px; display: flex; flex-direction: column; gap: 20px;">
@@ -173,18 +179,24 @@ export class NewsView {
173
  }
174
 
175
  renderArticles() {
176
- if (this.articles.length === 0) {
 
 
 
 
 
177
  return `
178
  <div style="text-align: center; padding: 40px 20px; color: var(--text-secondary);">
179
  <svg viewBox="0 0 24 24" width="48" height="48" fill="none" stroke="currentColor" stroke-width="1" style="opacity: 0.5; margin-bottom: 16px;"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>
180
  <h3>Noch keine Artikel</h3>
181
- <p style="font-size: 14px; margin-top: 8px;">Die KI hat noch keine Artikel für deine Themen generiert. Füge Themen hinzu oder warte auf den nächsten Durchlauf.</p>
182
  <button id="trigger-generation-btn" class="liquid-glass" style="margin-top: 16px; padding: 10px 20px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.1); color: white;">Jetzt generieren</button>
 
183
  </div>
184
  `;
185
  }
186
 
187
- return this.articles.map((article, index) => `
188
  <div class="news-card" data-id="${article.id}">
189
  <div class="news-image" style="background-image: url('${article.imageUrl || 'https://images.unsplash.com/photo-1503676260728-1c00da094a0b?q=80&w=600&auto=format&fit=crop'}');">
190
  ${index === 0 ? '<div class="news-tag highlight-tag">Neu</div>' : ''}
@@ -363,11 +375,29 @@ export class NewsView {
363
  if (triggerBtn) {
364
  triggerBtn.addEventListener('click', async () => {
365
  triggerBtn.textContent = 'Generiere...';
366
- await fetch('/api/news/generate', { method: 'POST' });
367
  setTimeout(() => this.fetchData(), 5000); // Poll after 5s
368
  });
369
  }
370
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
371
  // Open Article
372
  document.querySelectorAll('.news-card').forEach(card => {
373
  card.addEventListener('click', (e) => {
 
8
  this.isLoading = true;
9
  this.activeArticle = null;
10
  this.chatHistory = [];
11
+ this.activeTopic = 'Alle';
12
  }
13
 
14
  async init() {
 
50
  </button>
51
  </div>
52
 
53
+ <!-- Top Tab Bar (TikTok/Perplexity style) -->
54
+ <div style="padding: 0 24px; margin-bottom: 24px; display: flex; gap: 16px; overflow-x: auto; scrollbar-width: none; border-bottom: 1px solid rgba(255,255,255,0.05);">
55
+ ${['Alle', ...this.topics].map(t => `
56
+ <div class="topic-tab ${this.activeTopic === t ? 'active' : ''}" data-topic="${t}" style="padding-bottom: 12px; font-size: 15px; font-weight: ${this.activeTopic === t ? '600' : '500'}; color: ${this.activeTopic === t ? '#fff' : 'var(--text-secondary)'}; cursor: pointer; position: relative; white-space: nowrap;">
57
+ ${t}
58
+ ${this.activeTopic === t ? '<div style="position: absolute; bottom: 0; left: 0; right: 0; height: 2px; background: #c183f0; border-radius: 2px 2px 0 0;"></div>' : ''}
59
+ </div>
60
+ `).join('')}
61
+ ${this.topics.length === 0 && !this.isLoading ? '<div style="color: var(--text-secondary); font-size: 14px; padding-bottom: 12px;">Keine Themen konfiguriert.</div>' : ''}
62
  </div>
63
 
64
  <div class="news-feed" style="padding: 0 16px; display: flex; flex-direction: column; gap: 20px;">
 
179
  }
180
 
181
  renderArticles() {
182
+ let filteredArticles = this.articles;
183
+ if (this.activeTopic !== 'Alle') {
184
+ filteredArticles = this.articles.filter(a => a.topic === this.activeTopic);
185
+ }
186
+
187
+ if (filteredArticles.length === 0) {
188
  return `
189
  <div style="text-align: center; padding: 40px 20px; color: var(--text-secondary);">
190
  <svg viewBox="0 0 24 24" width="48" height="48" fill="none" stroke="currentColor" stroke-width="1" style="opacity: 0.5; margin-bottom: 16px;"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"></path><polyline points="14 2 14 8 20 8"></polyline><line x1="16" y1="13" x2="8" y2="13"></line><line x1="16" y1="17" x2="8" y2="17"></line><polyline points="10 9 9 9 8 9"></polyline></svg>
191
  <h3>Noch keine Artikel</h3>
192
+ <p style="font-size: 14px; margin-top: 8px;">Die KI hat noch keine Artikel für dieses Thema generiert. Füge Themen hinzu oder warte auf den nächsten Durchlauf.</p>
193
  <button id="trigger-generation-btn" class="liquid-glass" style="margin-top: 16px; padding: 10px 20px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.1); color: white;">Jetzt generieren</button>
194
+ <button id="trigger-simulation-btn" class="liquid-glass" style="margin-top: 8px; padding: 10px 20px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.1); color: var(--text-secondary); background: transparent;">Simulation testen</button>
195
  </div>
196
  `;
197
  }
198
 
199
+ return filteredArticles.map((article, index) => `
200
  <div class="news-card" data-id="${article.id}">
201
  <div class="news-image" style="background-image: url('${article.imageUrl || 'https://images.unsplash.com/photo-1503676260728-1c00da094a0b?q=80&w=600&auto=format&fit=crop'}');">
202
  ${index === 0 ? '<div class="news-tag highlight-tag">Neu</div>' : ''}
 
375
  if (triggerBtn) {
376
  triggerBtn.addEventListener('click', async () => {
377
  triggerBtn.textContent = 'Generiere...';
378
+ await fetch('/api/news/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ simulateError: false }) });
379
  setTimeout(() => this.fetchData(), 5000); // Poll after 5s
380
  });
381
  }
382
 
383
+ const simBtn = document.getElementById('trigger-simulation-btn');
384
+ if (simBtn) {
385
+ simBtn.addEventListener('click', async () => {
386
+ simBtn.textContent = 'Generiere... (Simulated Error)';
387
+ await fetch('/api/news/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ simulateError: true }) });
388
+ setTimeout(() => this.fetchData(), 12000); // Poll after 12s (because 10s wait)
389
+ });
390
+ }
391
+
392
+ // Top Tabs
393
+ document.querySelectorAll('.topic-tab').forEach(tab => {
394
+ tab.addEventListener('click', (e) => {
395
+ const t = e.currentTarget.dataset.topic;
396
+ this.activeTopic = t;
397
+ this.render();
398
+ });
399
+ });
400
+
401
  // Open Article
402
  document.querySelectorAll('.news-card').forEach(card => {
403
  card.addEventListener('click', (e) => {