Compare commits

..

3 Commits

Author SHA1 Message Date
Julian Freeman
a04b0f4be1 fix logging style 2025-12-02 10:50:15 -04:00
Julian Freeman
d2cafc328f add logging 2025-12-02 10:44:14 -04:00
Julian Freeman
068bc1c79e trying parse different url, but failed 2025-12-02 10:29:39 -04:00
10 changed files with 536 additions and 52 deletions

58
spec/logging_feature.md Normal file
View File

@@ -0,0 +1,58 @@
# Feature Request: Real-time Logging & UI Refinement
## 1. Context & Objective
Users currently experience download failures without sufficient context or error details, making troubleshooting difficult.
The objective is to introduce a dedicated **Logs System** within the application to capture, display, and persist detailed execution logs from the `yt-dlp` process.
Additionally, the application's sidebar layout requires balancing for better UX.
## 2. Requirements
### 2.1. Backend (Rust) - Logging Infrastructure
* **Stream Capture**: The `downloader` module must capture both `STDOUT` (progress) and `STDERR` (errors/warnings) from the `yt-dlp` process.
* **Event Emission**: Emit a new Tauri event `download-log` to the frontend in real-time.
* Payload: `{ id: String, message: String, level: 'info' | 'error' | 'debug' }`
* **Persistence (Optional but Recommended)**: Ideally, write logs to a local file (e.g., `logs/{date}.log` or `logs/{task_id}.log`) for post-mortem analysis. *For this iteration, real-time event emission is priority.*
### 2.2. Frontend - Logs View
* **New Route**: `/logs`
* **UI Layout**:
* A dedicated **Logs Tab** in the main navigation.
* A console-like view displaying a stream of log messages.
* Filters: Filter by "Task ID" or "Level" (Error/Info).
* **Real-time**: The view must update automatically as new log events arrive.
* **Detail**: Failed downloads must show the specific error message returned by `yt-dlp` (e.g., "Sign in required", "Video unavailable").
### 2.3. UI/UX - Sidebar Refactoring
* **Reordering**:
* **Top Section**: Home (Downloader), History.
* **Bottom Section**: Logs, Settings.
* **Removal**: Remove the "Version Number" text from the bottom of the sidebar (it can be moved to the Settings page if needed, or just removed as requested).
## 3. Implementation Steps
### Step 1: Rust Backend Updates
* Modify `src-tauri/src/downloader.rs`:
* Update `download_video` to spawn the process with `Stdio::piped()` for both stdout and stderr.
* Use `tokio::select!` or separate tasks to read both streams concurrently.
* Emit `download-log` events for every line read.
* Ensure the final error message (if exit code != 0) is explicitly captured and returned/logged.
### Step 2: Frontend Store & Logic
* Create `src/stores/logs.ts`:
* State: `logs: LogEntry[]`.
* Action: `addLog(entry)`.
* Listener: Listen for `download-log` events globally.
### Step 3: Frontend UI
* Create `src/views/Logs.vue`:
* Display logs in a scrollable container.
* Style error logs in red, info in gray/white.
* Update `src/App.vue`:
* Add the `FileText` (or similar) icon for Logs.
* Refactor the sidebar Flexbox layout to push Logs and Settings to the bottom.
* Remove the version footer.
* Update `src/router/index.ts` to include the new route.
## 4. Success Criteria
* When a download fails, the user can go to the "Logs" tab and see the exact error output from `yt-dlp`.
* The sidebar looks balanced with navigation items split between top and bottom.

111
spec/url_parsing.md Normal file
View File

@@ -0,0 +1,111 @@
# Feature Request: Advanced Playlist Parsing & Mix Handling
## Context
We are upgrading the **StreamCapture** application. Currently, the app only supports parsing standard single video URLs.
We need to implement robust support for **Standard Playlists** and **YouTube Mixes (Radio)**, while solving performance issues and thumbnail loading errors.
## Problem Statement
1. **Playlists (`/playlist?list=...`)**: Fails to parse entries or hangs because it attempts to resolve full metadata for every video. Thumbnails are missing.
2. **Mixes (`/watch?v=...&list=RD...`)**: Currently fails or behaves unpredictably.
3. **UI/UX**: Users need a specific choice when encountering a "Mix" link:
* **Option A (Default):** Treat it as a single video (ignore the list).
* **Option B:** Parse the Mix as a playlist (limit to top 20 items).
## Technical Requirements
### 1. Rust Backend Refactoring (`src-tauri/src/ytdlp.rs`)
Refactor the `fetch_metadata` command to use a unified, efficient parsing strategy.
#### A. Command Construction
For **ALL** metadata fetching, use the `--flat-playlist` flag to prevent deep extraction (which causes the hang).
**Base Command:**
```bash
yt-dlp --dump-single-json --flat-playlist --no-warnings [URL]
```
#### B. Handling Different URL Types
1. Single Video:
- `yt-dlp` returns a single JSON object with `_type: "video"` (or no type).
- Action: Wrap it in a list of 1.
2. Standard Playlist:
- `yt-dlp` returns `_type: "playlist"` with an `entries` array.
- Action: Map the `entries` to our `Video` struct.
3. Mix / Radio (Infinite List):
- Condition: If the frontend flags this request as a "Mix Playlist scan".
- Modification: Add flag --playlist-end 20 to the command.
- Reason: Mixes are infinite; we must cap them.
#### C. Data Normalization & Thumbnail Fallback
When using `--flat-playlist`, the `entries` often lack full `thumbnail` URLs or return webp formats that might not render immediately.
- Logic: If the `thumbnail` field is missing or empty in an entry, construct it manually using the ID:
- https://i.ytimg.com/vi/{video_id}/mqdefault.jpg
### 2. Frontend Logic (`src/views/Home.vue` & Stores)
#### A. URL Detection & User Choice
Before sending the URL to Rust, analyze the string:
1. Regex Check: Detect if the URL contains both `v=` AND `list=` (typical for Mixes).
2. New UI Element:
- If a Mix link is detected, show a **Checkbox** or **Toggle** near the "Analyze" button.
- Label: "Scan Playlist (Max 20)"
- Default State: Unchecked (Off).
3. Submission Logic:
- If Unchecked (Default): Strip the `&list=...` parameter from the URL string before calling Rust. Treat it as a pure single video.
- If Checked: Keep the full URL and pass a flag (e.g., `is_mix: true`) to the Rust backend (or handle the logic to request the top 20).
#### B. Displaying Results
- Ensure the "Selection Area" can render a list of cards whether it contains 1 video or 20 videos.
- If it's a playlist, show a "Select All" / "Deselect All" control.
## Implementation Plan
### Step 1: Rust Structs Update
Update the Serde structs in `ytdlp.rs` to handle the `flat-playlist` JSON structure.
```rust
// Example structure hint
struct YtDlpResponse {
_type: Option<String>,
entries: Option<Vec<VideoEntry>>,
// ... fields for single video fallback
id: Option<String>,
title: Option<String>,
}
struct VideoEntry {
id: String,
title: String,
duration: Option<f64>,
thumbnail: Option<String>, // Might be missing
}
```
### Step 2: Rust Logic Update
Modify `command::fetch_metadata`.
- Accept an optional argument `parse_mix_playlist: bool`.
- If `true`, append `--playlist-end 20`.
- Implement the thumbnail fallback logic (if `thumbnail` is None, use `i.ytimg.com`).
### Step 3: Frontend Update
- Add the "Mix Detected" logic in `Home.vue`.
- Add the toggle UI.
- Update the `analyze` function to handle URL stripping vs. passing through based on the toggle.
## Deliverables
Please rewrite the necessary parts of `src-tauri/src/ytdlp.rs`, `src-tauri/src/commands.rs`, and `src/views/Home.vue` to implement this logic.

View File

@@ -30,8 +30,8 @@ pub fn get_ytdlp_version(app: AppHandle) -> Result<String, String> {
}
#[tauri::command]
pub async fn fetch_metadata(app: AppHandle, url: String) -> Result<downloader::MetadataResult, String> {
downloader::fetch_metadata(&app, &url).await.map_err(|e| e.to_string())
pub async fn fetch_metadata(app: AppHandle, url: String, parse_mix_playlist: bool) -> Result<downloader::MetadataResult, String> {
downloader::fetch_metadata(&app, &url, parse_mix_playlist).await.map_err(|e| e.to_string())
}
#[tauri::command]

View File

@@ -46,18 +46,29 @@ pub struct ProgressEvent {
pub status: String, // "downloading", "processing", "finished", "error"
}
pub async fn fetch_metadata(app: &AppHandle, url: &str) -> Result<MetadataResult> {
#[derive(Serialize, Clone, Debug)]
pub struct LogEvent {
pub id: String,
pub message: String,
pub level: String, // "info", "error"
}
pub async fn fetch_metadata(app: &AppHandle, url: &str, parse_mix_playlist: bool) -> Result<MetadataResult> {
let ytdlp_path = ytdlp::get_ytdlp_path(app)?;
// Use std::process for simple output capture if it's short, but tokio is safer for async.
let output = Command::new(ytdlp_path)
.arg("--dump-single-json")
.arg("--flat-playlist")
.arg(url)
// Stop errors from cluttering
.stderr(Stdio::piped())
.output()
.await?;
let mut cmd = Command::new(ytdlp_path);
cmd.arg("--dump-single-json")
.arg("--flat-playlist")
.arg("--no-warnings");
if parse_mix_playlist {
cmd.arg("--playlist-end").arg("20");
}
cmd.arg(url);
cmd.stderr(Stdio::piped());
let output = cmd.output().await?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -90,10 +101,18 @@ pub async fn fetch_metadata(app: &AppHandle, url: &str) -> Result<MetadataResult
}
fn parse_video_metadata(json: &serde_json::Value) -> VideoMetadata {
let id = json["id"].as_str().unwrap_or("").to_string();
// Thumbnail fallback logic
let thumbnail = match json.get("thumbnail").and_then(|t| t.as_str()) {
Some(t) if !t.is_empty() => t.to_string(),
_ => format!("https://i.ytimg.com/vi/{}/mqdefault.jpg", id),
};
VideoMetadata {
id: json["id"].as_str().unwrap_or("").to_string(),
id,
title: json["title"].as_str().unwrap_or("Unknown Title").to_string(),
thumbnail: json["thumbnail"].as_str().unwrap_or("").to_string(), // Note: thumbnails might be an array sometimes, usually string in flat-playlist
thumbnail,
duration: json["duration"].as_f64(),
uploader: json["uploader"].as_str().map(|s| s.to_string()),
}
@@ -136,31 +155,60 @@ pub async fn download_video(
let mut child = Command::new(ytdlp_path)
.args(&args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.stderr(Stdio::piped()) // Capture stderr for logs
.spawn()?;
let stdout = child.stdout.take().ok_or(anyhow!("Failed to open stdout"))?;
let mut reader = BufReader::new(stdout);
let mut line = String::new();
let stderr = child.stderr.take().ok_or(anyhow!("Failed to open stderr"))?;
let mut stdout_reader = BufReader::new(stdout);
let mut stderr_reader = BufReader::new(stderr);
// Regex for progress: [download] 42.5% of 10.00MiB at 2.00MiB/s ETA 00:05
let re = Regex::new(r"\[download\]\s+(\d+\.?\d*)%").unwrap();
while reader.read_line(&mut line).await? > 0 {
if let Some(caps) = re.captures(&line) {
if let Some(pct_match) = caps.get(1) {
if let Ok(pct) = pct_match.as_str().parse::<f64>() {
// Emit event
app.emit("download-progress", ProgressEvent {
id: id.clone(),
progress: pct,
speed: "TODO".to_string(), // Speed parsing is a bit more complex, skipping for MVP or adding regex for it
status: "downloading".to_string(),
}).ok();
// Loop to read both streams
loop {
let mut out_line = String::new();
let mut err_line = String::new();
tokio::select! {
res = stdout_reader.read_line(&mut out_line) => {
if res.unwrap_or(0) == 0 {
break; // EOF
}
// Log info
app.emit("download-log", LogEvent {
id: id.clone(),
message: out_line.trim().to_string(),
level: "info".to_string(),
}).ok();
// Parse progress
if let Some(caps) = re.captures(&out_line) {
if let Some(pct_match) = caps.get(1) {
if let Ok(pct) = pct_match.as_str().parse::<f64>() {
app.emit("download-progress", ProgressEvent {
id: id.clone(),
progress: pct,
speed: "TODO".to_string(),
status: "downloading".to_string(),
}).ok();
}
}
}
}
res = stderr_reader.read_line(&mut err_line) => {
if res.unwrap_or(0) > 0 {
// Log error
app.emit("download-log", LogEvent {
id: id.clone(),
message: err_line.trim().to_string(),
level: "error".to_string(),
}).ok();
}
}
}
line.clear();
}
let status = child.wait().await?;

View File

@@ -2,18 +2,21 @@
<script setup lang="ts">
import { onMounted } from 'vue'
import { RouterView, RouterLink, useRoute } from 'vue-router'
import { Home, History, Settings as SettingsIcon, Download } from 'lucide-vue-next'
import { Home, History, Settings as SettingsIcon, Download, FileText } from 'lucide-vue-next'
import { useSettingsStore } from './stores/settings'
import { useQueueStore } from './stores/queue'
import { useLogsStore } from './stores/logs'
const settingsStore = useSettingsStore()
const queueStore = useQueueStore()
const logsStore = useLogsStore()
const route = useRoute()
onMounted(async () => {
await settingsStore.loadSettings()
await settingsStore.initYtdlp()
await queueStore.initListener()
await logsStore.initListener()
})
</script>
@@ -28,7 +31,8 @@ onMounted(async () => {
<span class="font-bold text-lg hidden lg:block">StreamCapture</span>
</div>
<nav class="flex-1 px-4 space-y-2 mt-4">
<nav class="flex-1 px-4 space-y-2 mt-4 flex flex-col">
<!-- Top Section -->
<RouterLink to="/"
class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors"
:class="route.path === '/' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'"
@@ -45,21 +49,25 @@ onMounted(async () => {
<span class="hidden lg:block font-medium">History</span>
</RouterLink>
<RouterLink to="/settings"
<div class="flex-1"></div>
<!-- Bottom Section -->
<RouterLink to="/logs"
class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors"
:class="route.path === '/logs' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'"
>
<FileText class="w-5 h-5 shrink-0" />
<span class="hidden lg:block font-medium">Logs</span>
</RouterLink>
<RouterLink to="/settings"
class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors mb-4"
:class="route.path === '/settings' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'"
>
<SettingsIcon class="w-5 h-5 shrink-0" />
<span class="hidden lg:block font-medium">Settings</span>
</RouterLink>
</nav>
<div class="p-4 border-t border-gray-200 dark:border-zinc-800">
<div class="text-xs text-gray-400 text-center lg:text-left truncate">
<p v-if="settingsStore.isInitializing">Initializing...</p>
<p v-else>v{{ settingsStore.ytdlpVersion }}</p>
</div>
</div>
</aside>
<!-- Main Content -->

View File

@@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
import History from '../views/History.vue'
import Settings from '../views/Settings.vue'
import Logs from '../views/Logs.vue'
const router = createRouter({
history: createWebHistory(),
@@ -16,6 +17,11 @@ const router = createRouter({
name: 'history',
component: History
},
{
path: '/logs',
name: 'logs',
component: Logs
},
{
path: '/settings',
name: 'settings',

View File

@@ -8,6 +8,10 @@ export const useAnalysisStore = defineStore('analysis', () => {
const error = ref('')
const metadata = ref<any>(null)
// New state for mix detection
const isMix = ref(false)
const scanMix = ref(false)
const options = ref({
is_audio_only: false,
quality: 'best',
@@ -19,10 +23,9 @@ export const useAnalysisStore = defineStore('analysis', () => {
loading.value = false
error.value = ''
metadata.value = null
// We keep options as is, or reset them?
// Usually keeping user preference for "Audio Only" is nice,
// but let's just reset the content-related stuff.
isMix.value = false
scanMix.value = false
}
return { url, loading, error, metadata, options, reset }
return { url, loading, error, metadata, options, isMix, scanMix, reset }
})

54
src/stores/logs.ts Normal file
View File

@@ -0,0 +1,54 @@
// filepath: src/stores/logs.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { listen } from '@tauri-apps/api/event'
export interface LogEntry {
id: string
taskId: string
message: string
level: 'info' | 'error'
timestamp: number
}
interface LogEvent {
id: string
message: string
level: string
}
export const useLogsStore = defineStore('logs', () => {
const logs = ref<LogEntry[]>([])
const isListening = ref(false)
function addLog(taskId: string, message: string, level: 'info' | 'error') {
logs.value.push({
id: crypto.randomUUID(),
taskId,
message,
level,
timestamp: Date.now()
})
// Optional: Limit log size to avoid memory issues
if (logs.value.length > 5000) {
logs.value = logs.value.slice(-5000)
}
}
async function initListener() {
if (isListening.value) return
isListening.value = true
await listen<LogEvent>('download-log', (event) => {
const { id, message, level } = event.payload
addLog(id, message, level as 'info' | 'error')
})
}
function clearLogs() {
logs.value = []
}
return { logs, addLog, initListener, clearLogs }
})

View File

@@ -26,6 +26,17 @@ watch(() => settingsStore.settings.download_path, (newPath) => {
}
}, { immediate: true })
// Detect Mix URL
watch(() => analysisStore.url, (newUrl) => {
if (newUrl && newUrl.includes('v=') && newUrl.includes('list=')) {
analysisStore.isMix = true
} else {
analysisStore.isMix = false
// Reset scanMix if URL changes to non-mix
analysisStore.scanMix = false
}
})
async function analyze() {
if (!analysisStore.url) return
analysisStore.loading = true
@@ -33,7 +44,29 @@ async function analyze() {
analysisStore.metadata = null
try {
const res = await invoke('fetch_metadata', { url: analysisStore.url })
let urlToScan = analysisStore.url;
let parseMix = false;
if (analysisStore.isMix) {
if (analysisStore.scanMix) {
// Keep URL as is, tell backend to limit scan
parseMix = true;
} else {
// Strip list param
try {
const u = new URL(urlToScan);
u.searchParams.delete('list');
u.searchParams.delete('index');
u.searchParams.delete('start_radio');
urlToScan = u.toString();
} catch (e) {
// Fallback regex if URL parsing fails
urlToScan = urlToScan.replace(/&list=[^&]+/, '');
}
}
}
const res = await invoke('fetch_metadata', { url: urlToScan, parseMixPlaylist: parseMix })
analysisStore.metadata = res
} catch (e: any) {
analysisStore.error = e.toString()
@@ -55,8 +88,28 @@ async function startDownload() {
{ title: analysisStore.metadata.title, thumbnail: "", id: analysisStore.metadata.id } :
analysisStore.metadata;
// Note: We might want to pass the *cleaned* URL if it was cleaned during analyze
// But for now we pass the original URL or whatever was scanned.
// Actually, if we scanned as a single video (unchecked), we should probably download as single video.
// The user might expect the same result as analysis.
// Let's reconstruct the URL logic or just use what `analyze` used?
// Since `start_download` just takes a URL string, we should probably use the same logic.
let urlToDownload = analysisStore.url;
if (analysisStore.isMix && !analysisStore.scanMix) {
try {
const u = new URL(urlToDownload);
u.searchParams.delete('list');
u.searchParams.delete('index');
u.searchParams.delete('start_radio');
urlToDownload = u.toString();
} catch (e) {
urlToDownload = urlToDownload.replace(/&list=[^&]+/, '');
}
}
const id = await invoke<string>('start_download', {
url: analysisStore.url,
url: urlToDownload,
options: analysisStore.options,
metadata: metaToSend
})
@@ -104,6 +157,22 @@ async function startDownload() {
<span v-else>Analyze</span>
</button>
</div>
<!-- Mix Toggle -->
<div v-if="analysisStore.isMix" class="mt-4 flex items-center gap-3">
<button
@click="analysisStore.scanMix = !analysisStore.scanMix"
class="w-12 h-6 rounded-full relative transition-colors duration-200 ease-in-out flex-shrink-0"
:class="analysisStore.scanMix ? 'bg-blue-600' : 'bg-gray-300 dark:bg-zinc-600'"
>
<span
class="absolute top-1 left-1 w-4 h-4 bg-white rounded-full transition-transform duration-200"
:class="analysisStore.scanMix ? 'translate-x-6' : 'translate-x-0'"
/>
</button>
<span class="text-sm font-medium text-zinc-700 dark:text-gray-300">Scan Playlist (Max 20)</span>
</div>
<p v-if="analysisStore.error" class="mt-3 text-red-500 text-sm">{{ analysisStore.error }}</p>
</div>

127
src/views/Logs.vue Normal file
View File

@@ -0,0 +1,127 @@
// filepath: src/views/Logs.vue
<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import { useLogsStore } from '../stores/logs'
import { Trash2, Search } from 'lucide-vue-next'
const logsStore = useLogsStore()
const logsContainer = ref<HTMLElement | null>(null)
const autoScroll = ref(true)
const filterLevel = ref<'all' | 'info' | 'error'>('all')
const searchQuery = ref('')
const filteredLogs = computed(() => {
return logsStore.logs.filter(log => {
if (filterLevel.value !== 'all' && log.level !== filterLevel.value) return false
if (searchQuery.value && !log.message.toLowerCase().includes(searchQuery.value.toLowerCase()) && !log.taskId.includes(searchQuery.value)) return false
return true
})
})
// Auto-scroll
watch(() => logsStore.logs.length, () => {
if (autoScroll.value) {
nextTick(() => {
if (logsContainer.value) {
logsContainer.value.scrollTop = logsContainer.value.scrollHeight
}
})
}
})
function formatTime(ts: number) {
const d = new Date(ts)
const year = d.getFullYear()
const month = String(d.getMonth() + 1).padStart(2, '0')
const day = String(d.getDate()).padStart(2, '0')
const hours = String(d.getHours()).padStart(2, '0')
const minutes = String(d.getMinutes()).padStart(2, '0')
const seconds = String(d.getSeconds()).padStart(2, '0')
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
</script>
<template>
<div class="flex flex-col h-full p-6">
<!-- Header -->
<div class="flex justify-between items-center mb-6">
<div>
<h1 class="text-3xl font-bold text-zinc-900 dark:text-white">Execution Logs</h1>
<p class="text-gray-500 dark:text-gray-400 mt-2">Real-time output from download processes.</p>
</div>
<div class="flex items-center gap-3">
<!-- Search -->
<div class="relative">
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<input
v-model="searchQuery"
type="text"
placeholder="Search logs..."
class="pl-9 pr-4 py-2 bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-xl text-sm outline-none focus:ring-2 focus:ring-blue-500 text-zinc-900 dark:text-white w-48"
/>
</div>
<!-- Level Filter -->
<div class="flex bg-white dark:bg-zinc-900 border border-gray-200 dark:border-zinc-800 rounded-xl p-1">
<button
@click="filterLevel = 'all'"
class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
:class="filterLevel === 'all' ? 'bg-gray-100 dark:bg-zinc-800 text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
>All</button>
<button
@click="filterLevel = 'info'"
class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
:class="filterLevel === 'info' ? 'bg-gray-100 dark:bg-zinc-800 text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
>Info</button>
<button
@click="filterLevel = 'error'"
class="px-3 py-1.5 rounded-lg text-xs font-medium transition-colors"
:class="filterLevel === 'error' ? 'bg-gray-100 dark:bg-zinc-800 text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
>Error</button>
</div>
<button
@click="logsStore.clearLogs"
class="p-2 text-gray-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20 rounded-xl transition-colors border border-gray-200 dark:border-zinc-800 bg-white dark:bg-zinc-900"
title="Clear Logs"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
<!-- Logs Console -->
<div class="flex-1 overflow-hidden relative bg-white dark:bg-zinc-900 rounded-2xl shadow-sm border border-gray-200 dark:border-zinc-800 font-mono text-xs md:text-sm">
<div
ref="logsContainer"
class="absolute inset-0 overflow-auto p-4 space-y-1"
@scroll="(e) => {
const target = e.target as HTMLElement;
autoScroll = target.scrollTop + target.clientHeight >= target.scrollHeight - 10;
}"
>
<div v-if="filteredLogs.length === 0" class="h-full flex items-center justify-center text-gray-400 dark:text-gray-600">
No logs to display
</div>
<div v-for="log in filteredLogs" :key="log.id" class="flex gap-4 hover:bg-gray-50 dark:hover:bg-zinc-800/50 px-2 py-1 rounded transition-colors">
<span class="text-gray-400 dark:text-zinc-600 shrink-0 select-none w-36">{{ formatTime(log.timestamp) }}</span>
<span
class="break-all whitespace-pre-wrap"
:class="log.level === 'error' ? 'text-red-500 dark:text-red-400' : 'text-zinc-700 dark:text-gray-300'"
>{{ log.message }}</span>
</div>
</div>
<!-- Auto-scroll indicator -->
<div v-if="!autoScroll" class="absolute bottom-4 right-4">
<button
@click="() => { if(logsContainer) logsContainer.scrollTop = logsContainer.scrollHeight }"
class="bg-blue-600 hover:bg-blue-700 text-white text-xs px-3 py-1.5 rounded-full shadow-lg transition-colors"
>
Resume Auto-scroll
</button>
</div>
</div>
</div>
</template>