feat(v0.17.0): structured ending titles + log persistence + session UI
Combined release: the deferred ending-title piece from v0.16.0 lands
alongside a full logging overhaul. Output titles now reflect the
filled-in endings; logs survive app restarts with session-grouped
navigation and JSON/TXT export.
## Structured ending titles
Title-builder reads `endings[]` + `endingVideoIndex` and picks the
video-type label from a four-tier resolver:
1. Single entry → formatEndingEntry()
("Ending 3: Best End", "Ending 3", "Best End")
2. Multi-entry, named → comma-joined names
("True End, Bad End, Hidden")
3. Multi-entry, numbers → contiguous range via title.endingLabel.range
("Endings 1–3" / "Kết thúc 1–3")
4. Mixed / sparse → title.endingLabel.count ("3 Endings")
Falls back to the legacy locale "Ending" label when no usable entries,
so pre-v0.16 single-ending creators see byte-identical output.
## Logging overhaul
* Persistence: new `src/utils/log-storage.ts`. Tauri writes
append-only JSONL `{appData}/logs/ytdescgen-YYYYMMDD.jsonl` (daily
rotation). Web caps localStorage at 5000 FIFO entries. Three new
Tauri commands: `append_to_file`, `list_dir`, `delete_file`.
* Session grouping: `LogEntry.sessionId` (one per app boot). LogPage
renders one collapsible block per session — current expanded,
prior collapsed — with per-session "Clear" action.
* Export JSON (envelope) + TXT (one line per entry, chronological).
* Boot hydration via `hydrateLogStore(retentionDays)` in App.tsx.
* New setting `logRetentionDays` (default 7, clamped [1, 90]).
Persist-store v9 → v10 additive.
## Locale & test churn
* 12 new locale keys × 6 locales; 715/715 ui, 370/370 templates.
* 14 new tests (408 → 422).
## Bundle
* index 470.51 KB (+7 KB), LogPage 8.37 KB (+3 KB). Under 500 KB cap.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
a685b050d9
commit
d0dd6bad12
31 files changed
+1094
-82
No files matched your search
@@ -2,6 +2,58 @@
|
||||
|
||||
All notable changes to YTDescGen ship as tagged releases on `main`.
|
||||
|
||||
## v0.17.0 — 2026-05-14
|
||||
|
||||
Combined release: logging overhaul + the deferred ending title piece
|
||||
from v0.16.0. The Output title now reflects the structured endings
|
||||
the creator filled in (case-A/B/C aware), and the Logs tab persists
|
||||
entries across app restarts with session-grouped navigation and
|
||||
JSON/TXT export.
|
||||
|
||||
### Added
|
||||
|
||||
- **Structured ending titles** ([src/engine/title-builder.ts](src/engine/title-builder.ts)). When `videoType === "ending"` AND `endings[]` is filled, the title's video-type segment swaps from the static `"Ending"` to a context-aware label, picked by a four-tier resolver:
|
||||
1. Single entry → `formatEndingEntry()` (e.g. `"Ending 3: Best End"`, `"Ending 3"`, or `"Best End"` depending on which fields are filled).
|
||||
2. Multi-entry, every entry named → comma-joined names (`"True End, Bad End, Hidden"`).
|
||||
3. Multi-entry, every entry numbered + contiguous run → `title.endingLabel.range` (`"Endings 1–3"` / `"Kết thúc 1–3"`).
|
||||
4. Mixed / non-contiguous → `title.endingLabel.count` (`"3 Endings"`).
|
||||
Falls back to the legacy locale label when no usable entries — pre-v0.16 single-ending creators see byte-identical output. Slicing respects `endingVideoIndex` + `endingVideoRanges` so a per-video title renders only that video's slice (foundation for the v0.17.1 per-video Output selector).
|
||||
- **Persistent log storage** ([src/utils/log-storage.ts](src/utils/log-storage.ts)). Logs now survive app restarts:
|
||||
- Tauri: append-only JSONL file `{appData}/logs/ytdescgen-YYYYMMDD.jsonl`. Daily rotation; cleanup deletes whole files older than `logRetentionDays` so retention sweeps are O(files) not O(entries). Three new Tauri commands feed this: `append_to_file`, `list_dir`, `delete_file`.
|
||||
- Web: localStorage key `ytdescgen-logs`, FIFO-capped at 5000 entries.
|
||||
- Best-effort: persistence failures never throw, so a disk hiccup can't recurse into a log loop.
|
||||
- **Session-grouped LogPage** ([src/pages/LogPage.tsx](src/pages/LogPage.tsx)). Each entry now carries a `sessionId` (one per app boot). The page renders one collapsible block per session — current session expanded, prior sessions collapsed — with a per-session "Clear this session" affordance. Header shows entry count + error/warning counts + time range per session.
|
||||
- **Log export buttons**:
|
||||
- **JSON** — envelope-wrapped via the v0.15 `exportTypedToJsonFile` (currently keyed `_type: "history"`; promote to a dedicated `log` type later when re-import becomes a use case).
|
||||
- **TXT** — `[ISO time] [LEVEL] [source] message — details` one line per entry, chronological. Pastes cleanly into bug reports.
|
||||
- **`logRetentionDays` setting** ([src/store/settings-store.ts](src/store/settings-store.ts), [src/store/settings-heal.ts](src/store/settings-heal.ts)). Default 7 days; clamped to `[1, 90]` by `healSettings`. New section in Settings → Logs with inline hint. Persist-store version bumped 9 → 10.
|
||||
- **Boot-time log hydration** ([src/App.tsx](src/App.tsx)). `hydrateLogStore(retentionDays)` runs in the root `useEffect`, loads recent persisted entries before the UI mounts, then schedules `pruneOldLogs` so the AppData folder stays trim.
|
||||
- **Locale keys (10 new × 6 locales)**: `title.endingLabel.{range,count}` (2 templates keys), `settings.{logSettings,logRetentionDays,logRetentionHint}` + `logs.{clearPersistedConfirm,clearSession,exportJson,exportTxt,sessionCurrent,sessionLabel,entriesShort}` (10 ui keys). All 715 ui + 370 templates keys per locale.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`log-store` schema** — `LogEntry` gained a `sessionId` field; in-memory cap raised from 500 → 2000 with persistence in play so a current session can fully populate the accordion without pagination. New actions: `clearAllPersisted` (in-memory + disk), `clearSession(id)`.
|
||||
- **LogPage "Clear All"** now clears in-memory state AND deletes persisted JSONL files / localStorage. Two-step confirm via `clearPersistedConfirm` toast.
|
||||
- **File envelope** — `SCHEMA_VERSIONS.settings` bumped 9 → 10 to match the persist version. v0.15+ settings exports still import unchanged via the `healSettings` defensive merge.
|
||||
|
||||
### Tests
|
||||
|
||||
- 11 new title-builder tests covering all four ending-label tiers + Vietnamese localisation + slice + fallback. 422/422 pass overall.
|
||||
- 3 new settings-heal tests for the `logRetentionDays` default and `[1, 90]` clamp.
|
||||
|
||||
### Under the hood
|
||||
|
||||
- Tauri command surface gained 3 entries (`append_to_file`, `list_dir`, `delete_file`). All stdlib — no new crates.
|
||||
- `pruneOldLogs` runs *after* `loadRecentLogs` at boot, so an entry on the retention edge is read into memory before being deleted from disk (last-chance access).
|
||||
- Bundle: index 470.51 KB (+7 KB for title-builder ending logic), LogPage chunk 8.37 KB (+3 KB for session accordion + export buttons). Still under the 500 KB cap.
|
||||
|
||||
### Migration notes
|
||||
|
||||
- **Settings persist version 9 → 10**. Additive — `logRetentionDays` back-fills to 7 on first rehydrate, no user action required.
|
||||
- **First-run on Tauri**: app creates `%APPDATA%\com.skullmute.ytdescgen\logs\` on the first log entry. The new `append_to_file` command auto-creates the parent dir via `std::fs::create_dir_all`.
|
||||
- **Web users**: persisted entries live in `localStorage["ytdescgen-logs"]`; nothing to migrate.
|
||||
- **Pre-v0.16 ending creators**: title behaviour unchanged unless they fill the new structured fields. Filling triggers the new resolver immediately.
|
||||
|
||||
## v0.16.0 — 2026-05-14
|
||||
|
||||
Structured ending editor + multi-video split. The Playthrough Notes
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "yt-desc-gen",
|
||||
"version": "0.16.0",
|
||||
"version": "0.17.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "yt-desc-gen",
|
||||
"version": "0.16.0",
|
||||
"version": "0.17.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "^2.11.0",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "yt-desc-gen",
|
||||
"version": "0.16.0",
|
||||
"version": "0.17.0",
|
||||
"private": true,
|
||||
"license": "Apache-2.0",
|
||||
"type": "module",
|
||||
|
||||
Generated
+1
-1
@@ -5535,7 +5535,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "yt-desc-gen"
|
||||
version = "0.16.0"
|
||||
version = "0.17.0"
|
||||
dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "yt-desc-gen"
|
||||
version = "0.16.0"
|
||||
version = "0.17.0"
|
||||
description = "YouTube Gameplay Description Generator"
|
||||
authors = ["poli0981"]
|
||||
edition = "2021"
|
||||
|
||||
+64
-1
@@ -33,6 +33,62 @@ fn ensure_dir(path: String) -> Result<(), String> {
|
||||
std::fs::create_dir_all(&path).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// Append `content` to the file at `path`, creating the file (and any
|
||||
/// missing parent directories) if necessary. Used by the v0.17.0 log
|
||||
/// persistence pipeline to write JSONL entries one line at a time,
|
||||
/// rather than rewriting the whole file on every log call. Cheap
|
||||
/// enough that we can call it on every `addEntry` without batching.
|
||||
/// The caller is responsible for newline termination — this is a raw
|
||||
/// byte append, not a line writer.
|
||||
#[tauri::command]
|
||||
fn append_to_file(path: String, content: String) -> Result<(), String> {
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::Write;
|
||||
if let Some(parent) = std::path::Path::new(&path).parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let mut file = OpenOptions::new()
|
||||
.append(true)
|
||||
.create(true)
|
||||
.open(&path)
|
||||
.map_err(|e| e.to_string())?;
|
||||
file.write_all(content.as_bytes()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// List entries in a directory, returning their file names (not full
|
||||
/// paths). Used by the v0.17.0 log retention sweep to find
|
||||
/// `ytdescgen-*.jsonl` files older than the configured retention
|
||||
/// window. Returns an empty vec if the directory doesn't exist
|
||||
/// (i.e. no logs have been written yet) — first-run safe.
|
||||
#[tauri::command]
|
||||
fn list_dir(path: String) -> Result<Vec<String>, String> {
|
||||
let dir = std::path::Path::new(&path);
|
||||
if !dir.exists() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let entries = std::fs::read_dir(dir).map_err(|e| e.to_string())?;
|
||||
let mut names = Vec::new();
|
||||
for entry in entries.flatten() {
|
||||
if let Some(name) = entry.file_name().to_str() {
|
||||
names.push(name.to_string());
|
||||
}
|
||||
}
|
||||
Ok(names)
|
||||
}
|
||||
|
||||
/// Delete a file at `path` if it exists. No-op when the file is
|
||||
/// missing (used by log retention sweep — racing with another sweep
|
||||
/// or a manual cleanup shouldn't error). Returns the OS error string
|
||||
/// on permission failures.
|
||||
#[tauri::command]
|
||||
fn delete_file(path: String) -> Result<(), String> {
|
||||
let p = std::path::Path::new(&path);
|
||||
if !p.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::remove_file(p).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
// Flag that signals the user has requested a full quit (via tray menu).
|
||||
@@ -112,7 +168,14 @@ pub fn run() {
|
||||
}
|
||||
}
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![save_to_file, read_from_file, ensure_dir])
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
save_to_file,
|
||||
read_from_file,
|
||||
ensure_dir,
|
||||
append_to_file,
|
||||
list_dir,
|
||||
delete_file
|
||||
])
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building tauri application")
|
||||
.run(move |_app_handle, event| {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "https://raw.githubusercontent.com/tauri-apps/tauri/dev/crates/tauri-cli/schema.json",
|
||||
"productName": "YTDescGen",
|
||||
"version": "0.16.0",
|
||||
"version": "0.17.0",
|
||||
"identifier": "com.skullmute.ytdescgen",
|
||||
"build": {
|
||||
"beforeBuildCommand": "npm run build",
|
||||
|
||||
@@ -7,6 +7,8 @@ import { ErrorBoundary } from "@components/ErrorBoundary";
|
||||
import { EditorPage } from "@pages/EditorPage";
|
||||
import { OutputPage } from "@pages/OutputPage";
|
||||
import { checkDataFileHealth } from "@utils/storage-adapter";
|
||||
import { hydrateLogStore } from "@store/log-store";
|
||||
import { useSettingsStore } from "@store/settings-store";
|
||||
import "@i18n/index";
|
||||
|
||||
const ProfilesPage = lazy(() =>
|
||||
@@ -57,6 +59,13 @@ export default function App() {
|
||||
checkDataFileHealth().then((msg) => {
|
||||
if (msg) toast(msg, { icon: "⚠️", duration: 5000 });
|
||||
});
|
||||
// v0.17.0: hydrate the log store from persisted JSONL files /
|
||||
// localStorage so prior-session entries surface in the Logs tab
|
||||
// accordion. Uses the current `logRetentionDays` setting — read
|
||||
// directly off the store at mount time so we don't rerun on
|
||||
// every settings tweak.
|
||||
const retentionDays = useSettingsStore.getState().logRetentionDays;
|
||||
void hydrateLogStore(retentionDays);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
|
||||
+106
-7
@@ -12,6 +12,8 @@ import {
|
||||
GACHA_PART_SUFFIX_STYLES,
|
||||
type GachaQuestType,
|
||||
} from "@config/gacha-quest-types";
|
||||
import { formatEndingEntry, sliceEndingsForVideo } from "./endings-format";
|
||||
import type { EndingEntry } from "./types";
|
||||
|
||||
/**
|
||||
* Compact "[2K 60FPS]" badge appended to the video-type segment when the
|
||||
@@ -169,6 +171,91 @@ export function buildGachaPartSuffix(
|
||||
return resolved && resolved !== key ? resolved : "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the video-type segment of the title when `videoType === "ending"`
|
||||
* AND the creator has filled at least one structured {@link EndingEntry}
|
||||
* (v0.17.0). Three tiers, picked by what's available:
|
||||
*
|
||||
* 1. Single entry → `formatEndingEntry()` (e.g. `"Ending 3: Best End"`,
|
||||
* `"Ending 3"`, or `"Best End"`).
|
||||
* 2. Multiple entries, every entry has a non-empty `name` → comma-join
|
||||
* the names. Plays well with multi-route VN-style endings where
|
||||
* the creator cares more about the named routes than the ordinals.
|
||||
* 3. Multiple entries, every entry has a `number` AND they form a
|
||||
* contiguous run → `"Endings {from}–{to}"` via locale key
|
||||
* `title.endingLabel.range`. Tightest visible label for batched
|
||||
* ending playthroughs ("Endings 1–3" / "Kết thúc 1–3").
|
||||
* 4. Mixed / non-contiguous fallback → `"{count} Endings"` via
|
||||
* `title.endingLabel.count`.
|
||||
*
|
||||
* Returns `null` when no structured data is usable, signalling the
|
||||
* caller to fall back to the legacy locale-string label
|
||||
* (`title.videoType.ending` = "Ending"). This keeps existing single-
|
||||
* ending creators byte-identical post-migration.
|
||||
*
|
||||
* Slicing: respects `endingVideoIndex` + `endingVideoRanges` so a
|
||||
* per-video title for case C renders only that video's slice of
|
||||
* endings. The Output page passes the index when looping over
|
||||
* `endingVideoCount`; bare generation (no index) sees the union.
|
||||
*/
|
||||
export function buildStructuredEndingLabel(
|
||||
input: GeneratorInput,
|
||||
t: TranslationFn,
|
||||
): string | null {
|
||||
const endings: EndingEntry[] = input.endings ?? [];
|
||||
if (endings.length === 0) return null;
|
||||
|
||||
const sliced = sliceEndingsForVideo(endings, input);
|
||||
// Drop entries that have neither number nor a non-empty name — they
|
||||
// produce no visible label and would dilute the comma-join / count.
|
||||
const usable = sliced.filter((e) => {
|
||||
const hasNumber =
|
||||
typeof e.number === "number" && Number.isFinite(e.number);
|
||||
const hasName = (e.name ?? "").trim().length > 0;
|
||||
return hasNumber || hasName;
|
||||
});
|
||||
if (usable.length === 0) return null;
|
||||
|
||||
if (usable.length === 1) {
|
||||
const only = usable[0];
|
||||
return only ? formatEndingEntry(only) : null;
|
||||
}
|
||||
|
||||
// Multi-entry: prefer named comma-join when every entry has a name.
|
||||
const allHaveNames = usable.every((e) => (e.name ?? "").trim().length > 0);
|
||||
if (allHaveNames) {
|
||||
return usable.map((e) => e.name.trim()).join(", ");
|
||||
}
|
||||
|
||||
// Numbered + contiguous → range form. Sort + scan adjacent diffs to
|
||||
// detect contiguity so an out-of-order entry list ([3, 1, 2]) still
|
||||
// collapses to "Endings 1–3".
|
||||
const numbers = usable
|
||||
.map((e) => e.number)
|
||||
.filter((n): n is number => typeof n === "number" && Number.isFinite(n));
|
||||
if (numbers.length === usable.length) {
|
||||
const sorted = [...numbers].sort((a, b) => a - b);
|
||||
const isContiguous = sorted.every(
|
||||
(n, i) => i === 0 || n === (sorted[i - 1] as number) + 1,
|
||||
);
|
||||
if (isContiguous) {
|
||||
const from = sorted[0] as number;
|
||||
const to = sorted[sorted.length - 1] as number;
|
||||
const key = "title.endingLabel.range";
|
||||
const resolved = t(key, { from: String(from), to: String(to) });
|
||||
if (resolved && resolved !== key) return resolved;
|
||||
// Fallback if the locale hasn't migrated yet — keep behaviour sane.
|
||||
return `Endings ${from}–${to}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Mixed / non-contiguous: report count.
|
||||
const key = "title.endingLabel.count";
|
||||
const resolved = t(key, { count: String(usable.length) });
|
||||
if (resolved && resolved !== key) return resolved;
|
||||
return `${usable.length} Endings`;
|
||||
}
|
||||
|
||||
export function buildTitle(
|
||||
input: GeneratorInput,
|
||||
t: TranslationFn,
|
||||
@@ -220,13 +307,25 @@ export function buildTitle(
|
||||
});
|
||||
}
|
||||
|
||||
const videoTypeLabel = t(`title.videoType.${input.videoType}`, {
|
||||
partNumber: input.partNumber ?? "",
|
||||
bossName: input.bossName ?? "",
|
||||
dlcName: input.dlcName ?? "",
|
||||
challengeName: input.challengeName ?? "",
|
||||
modName: input.modName ?? "",
|
||||
});
|
||||
// v0.17.0: when the creator has filled structured endings, replace
|
||||
// the static "Ending" label with a context-aware one (single entry
|
||||
// surfaces the ending's name, multi-entry collapses to a name list /
|
||||
// contiguous range / count). Falls back to the locale string when no
|
||||
// structured data is usable, so the legacy single-ending creators
|
||||
// who haven't migrated see byte-identical output.
|
||||
let videoTypeLabel: string;
|
||||
if (input.videoType === "ending") {
|
||||
const structured = buildStructuredEndingLabel(input, t);
|
||||
videoTypeLabel = structured ?? t("title.videoType.ending");
|
||||
} else {
|
||||
videoTypeLabel = t(`title.videoType.${input.videoType}`, {
|
||||
partNumber: input.partNumber ?? "",
|
||||
bossName: input.bossName ?? "",
|
||||
dlcName: input.dlcName ?? "",
|
||||
challengeName: input.challengeName ?? "",
|
||||
modName: input.modName ?? "",
|
||||
});
|
||||
}
|
||||
|
||||
return composeTitle({
|
||||
gameName,
|
||||
|
||||
@@ -155,17 +155,18 @@
|
||||
"presets": ["title", "createNew", "editPreset", "loadPreset", "deleteConfirm", "emptyState", "selectPreset", "noPresets", "exportPresets", "importPresets"],
|
||||
"templates": ["title", "createNew", "saveAsTemplate", "templateName", "templateNamePlaceholder", "loadTemplate", "deleteConfirm", "emptyState", "saveHint", "savedAs", "appliedToast", "exportTemplates", "importTemplates"],
|
||||
"history": ["title", "emptyState", "clearAll", "clearConfirm", "searchPlaceholder"],
|
||||
"settings": ["title", "appearance", "defaults", "editorSettings", "tagSettings", "historySettings", "theme", "appLanguage", "defaultOutputLanguage", "defaultGenre", "showCharCount", "compactTagDisplay", "historyLimit", "multilingualTags", "trendingTags", "hashtagCount", "showQualityBadge", "showCopyright", "showUsagePolicy", "showSponsorCredit", "showThirdPartyAds", "thirdPartyAdsHint", "titleFormatTitle", "descriptionSettingsTitle", "badgePosition", "badgePositionPrefix", "badgePositionMiddle", "badgePositionSuffix", "titleSeparator", "titleSeparatorEmDash", "titleSeparatorHyphen", "titleSeparatorColon", "titleSeparatorPipe", "badgeCase", "badgeCaseUpper", "badgeCaseLower", "showPinnedCommentTemplate", "pinnedCommentIncludeAskNextGame", "pinnedCommentIncludeGenrePlaylist", "genrePlaylistsTitle", "genrePlaylistsHelp", "genrePlaylistsEmptyHint"],
|
||||
"settings": ["title", "appearance", "defaults", "editorSettings", "tagSettings", "historySettings", "theme", "appLanguage", "defaultOutputLanguage", "defaultGenre", "showCharCount", "compactTagDisplay", "historyLimit", "multilingualTags", "trendingTags", "hashtagCount", "showQualityBadge", "showCopyright", "showUsagePolicy", "showSponsorCredit", "showThirdPartyAds", "thirdPartyAdsHint", "titleFormatTitle", "descriptionSettingsTitle", "badgePosition", "badgePositionPrefix", "badgePositionMiddle", "badgePositionSuffix", "titleSeparator", "titleSeparatorEmDash", "titleSeparatorHyphen", "titleSeparatorColon", "titleSeparatorPipe", "badgeCase", "badgeCaseUpper", "badgeCaseLower", "showPinnedCommentTemplate", "pinnedCommentIncludeAskNextGame", "pinnedCommentIncludeGenrePlaylist", "genrePlaylistsTitle", "genrePlaylistsHelp", "genrePlaylistsEmptyHint", "logSettings", "logRetentionDays", "logRetentionHint"],
|
||||
"batch": ["title", "startPart", "endPart", "generateBatch", "copyAllBatch", "emptyState"],
|
||||
"shortcuts": ["title", "generate", "copyAll", "saveDraft", "toggleSidebar", "help", "close", "searchPlaceholder", "noResults"],
|
||||
"validation": ["emailInvalid", "emailMaxExceeded", "urlInvalid", "urlPrefixMismatch", "playlistUrlInvalid"],
|
||||
"logs": ["title", "emptyState", "clearAll", "clearConfirm", "searchPlaceholder"],
|
||||
"logs": ["title", "emptyState", "clearAll", "clearConfirm", "clearPersistedConfirm", "clearSession", "searchPlaceholder", "exportJson", "exportTxt", "sessionCurrent", "sessionLabel", "entriesShort"],
|
||||
"playlist": ["title", "status", "contentType", "totalVideos", "customNote", "generatePlaylist"]
|
||||
},
|
||||
"templates": {
|
||||
"title": ["separator", "suffix"],
|
||||
"title.separators": ["emDash", "hyphen", "colon", "pipe"],
|
||||
"title.videoType": ["full", "part", "full_demo", "demo_part", "boss", "boss_nohit", "ending", "speedrun", "100percent", "dlc", "newgame_plus", "challenge", "side_quest", "secret", "comparison", "guide", "mods", "collectibles", "livestream", "gacha_quest"],
|
||||
"title.endingLabel": ["range", "count"],
|
||||
"title.gachaQuestType": [
|
||||
"main_story", "world_quest", "side_quest", "spinoff_quest", "companion_quest", "bond_quest",
|
||||
"event", "anniversary", "crossover", "dating_event",
|
||||
|
||||
@@ -30,6 +30,10 @@
|
||||
"livestream": "🔴 LIVE",
|
||||
"gacha_quest": ""
|
||||
},
|
||||
"endingLabel": {
|
||||
"range": "Endings {{from}}–{{to}}",
|
||||
"count": "{{count}} Endings"
|
||||
},
|
||||
"gachaQuestType": {
|
||||
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
|
||||
"world_quest": "{{gameName}} — World Quest: {{questName}}",
|
||||
|
||||
@@ -776,7 +776,10 @@
|
||||
"pinnedCommentIncludeGenrePlaylist": "Include genre-playlist suggestion in pinned comment",
|
||||
"genrePlaylistsTitle": "Genre Playlists",
|
||||
"genrePlaylistsHelp": "Configure a YouTube playlist URL per genre. The pinned-comment template will auto-suggest the matching playlist when the video's primary genre is selected.",
|
||||
"genrePlaylistsEmptyHint": "Leave empty to skip a genre."
|
||||
"genrePlaylistsEmptyHint": "Leave empty to skip a genre.",
|
||||
"logSettings": "Logs",
|
||||
"logRetentionDays": "Log retention (days)",
|
||||
"logRetentionHint": "Logs older than this are deleted at app start. Range: 1–90 days."
|
||||
},
|
||||
"batch": {
|
||||
"title": "Batch Mode",
|
||||
@@ -822,6 +825,13 @@
|
||||
"emptyState": "No log entries yet.",
|
||||
"clearAll": "Clear All",
|
||||
"clearConfirm": "Are you sure you want to clear all logs?",
|
||||
"searchPlaceholder": "Search logs..."
|
||||
"clearPersistedConfirm": "Clear all logs from memory AND delete persisted log files? This cannot be undone.",
|
||||
"clearSession": "Clear this session",
|
||||
"searchPlaceholder": "Search logs...",
|
||||
"exportJson": "Export JSON",
|
||||
"exportTxt": "Export TXT",
|
||||
"sessionCurrent": "Current session",
|
||||
"sessionLabel": "Session {{n}}",
|
||||
"entriesShort": "entries"
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,10 @@
|
||||
"livestream": "🔴 EN VIVO",
|
||||
"gacha_quest": ""
|
||||
},
|
||||
"endingLabel": {
|
||||
"range": "Finales {{from}}–{{to}}",
|
||||
"count": "{{count}} Finales"
|
||||
},
|
||||
"gachaQuestType": {
|
||||
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
|
||||
"world_quest": "{{gameName}} — World Quest: {{questName}}",
|
||||
|
||||
@@ -776,7 +776,10 @@
|
||||
"pinnedCommentIncludeGenrePlaylist": "Include genre-playlist suggestion in pinned comment",
|
||||
"genrePlaylistsTitle": "Genre Playlists",
|
||||
"genrePlaylistsHelp": "Configure a YouTube playlist URL per genre. The pinned-comment template will auto-suggest the matching playlist when the video's primary genre is selected.",
|
||||
"genrePlaylistsEmptyHint": "Leave empty to skip a genre."
|
||||
"genrePlaylistsEmptyHint": "Leave empty to skip a genre.",
|
||||
"logSettings": "Registros",
|
||||
"logRetentionDays": "Retención de logs (días)",
|
||||
"logRetentionHint": "Los logs más antiguos se eliminan al iniciar. Rango: 1–90 días."
|
||||
},
|
||||
"batch": {
|
||||
"title": "Generación por Lote",
|
||||
@@ -822,6 +825,13 @@
|
||||
"emptyState": "No hay registros.",
|
||||
"clearAll": "Borrar Todo",
|
||||
"clearConfirm": "¿Estás seguro de borrar todos los registros?",
|
||||
"searchPlaceholder": "Buscar registros..."
|
||||
"clearPersistedConfirm": "¿Borrar logs en memoria Y eliminar archivos persistidos? No se puede deshacer.",
|
||||
"clearSession": "Borrar esta sesión",
|
||||
"searchPlaceholder": "Buscar registros...",
|
||||
"exportJson": "Exportar JSON",
|
||||
"exportTxt": "Exportar TXT",
|
||||
"sessionCurrent": "Sesión actual",
|
||||
"sessionLabel": "Sesión {{n}}",
|
||||
"entriesShort": "entradas"
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,10 @@
|
||||
"livestream": "🔴 LIVE",
|
||||
"gacha_quest": ""
|
||||
},
|
||||
"endingLabel": {
|
||||
"range": "エンディング {{from}}–{{to}}",
|
||||
"count": "エンディング {{count}}個"
|
||||
},
|
||||
"gachaQuestType": {
|
||||
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
|
||||
"world_quest": "{{gameName}} — World Quest: {{questName}}",
|
||||
|
||||
@@ -776,7 +776,10 @@
|
||||
"pinnedCommentIncludeGenrePlaylist": "Include genre-playlist suggestion in pinned comment",
|
||||
"genrePlaylistsTitle": "Genre Playlists",
|
||||
"genrePlaylistsHelp": "Configure a YouTube playlist URL per genre. The pinned-comment template will auto-suggest the matching playlist when the video's primary genre is selected.",
|
||||
"genrePlaylistsEmptyHint": "Leave empty to skip a genre."
|
||||
"genrePlaylistsEmptyHint": "Leave empty to skip a genre.",
|
||||
"logSettings": "ログ",
|
||||
"logRetentionDays": "ログ保持期間 (日)",
|
||||
"logRetentionHint": "この日数より古いログは起動時に削除されます。範囲: 1–90 日。"
|
||||
},
|
||||
"batch": {
|
||||
"title": "一括モード",
|
||||
@@ -822,6 +825,13 @@
|
||||
"emptyState": "ログはありません。",
|
||||
"clearAll": "すべて削除",
|
||||
"clearConfirm": "すべてのログを削除しますか?",
|
||||
"searchPlaceholder": "ログを検索..."
|
||||
"clearPersistedConfirm": "メモリ上のログ AND 保存済みログファイルを削除しますか?取り消せません。",
|
||||
"clearSession": "このセッションを削除",
|
||||
"searchPlaceholder": "ログを検索...",
|
||||
"exportJson": "JSON でエクスポート",
|
||||
"exportTxt": "TXT でエクスポート",
|
||||
"sessionCurrent": "現在のセッション",
|
||||
"sessionLabel": "セッション {{n}}",
|
||||
"entriesShort": "件"
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,10 @@
|
||||
"livestream": "🔴 LIVE",
|
||||
"gacha_quest": ""
|
||||
},
|
||||
"endingLabel": {
|
||||
"range": "엔딩 {{from}}–{{to}}",
|
||||
"count": "엔딩 {{count}}개"
|
||||
},
|
||||
"gachaQuestType": {
|
||||
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
|
||||
"world_quest": "{{gameName}} — World Quest: {{questName}}",
|
||||
|
||||
@@ -776,7 +776,10 @@
|
||||
"pinnedCommentIncludeGenrePlaylist": "Include genre-playlist suggestion in pinned comment",
|
||||
"genrePlaylistsTitle": "Genre Playlists",
|
||||
"genrePlaylistsHelp": "Configure a YouTube playlist URL per genre. The pinned-comment template will auto-suggest the matching playlist when the video's primary genre is selected.",
|
||||
"genrePlaylistsEmptyHint": "Leave empty to skip a genre."
|
||||
"genrePlaylistsEmptyHint": "Leave empty to skip a genre.",
|
||||
"logSettings": "로그",
|
||||
"logRetentionDays": "로그 보관 기간 (일)",
|
||||
"logRetentionHint": "이 일수보다 오래된 로그는 앱 시작 시 삭제됩니다. 범위: 1–90일."
|
||||
},
|
||||
"batch": {
|
||||
"title": "일괄 생성",
|
||||
@@ -822,6 +825,13 @@
|
||||
"emptyState": "로그가 없습니다.",
|
||||
"clearAll": "모두 삭제",
|
||||
"clearConfirm": "모든 로그를 삭제하시겠습니까?",
|
||||
"searchPlaceholder": "로그 검색..."
|
||||
"clearPersistedConfirm": "메모리 내 로그와 저장된 로그 파일을 모두 삭제하시겠습니까? 되돌릴 수 없습니다.",
|
||||
"clearSession": "이 세션 삭제",
|
||||
"searchPlaceholder": "로그 검색...",
|
||||
"exportJson": "JSON 내보내기",
|
||||
"exportTxt": "TXT 내보내기",
|
||||
"sessionCurrent": "현재 세션",
|
||||
"sessionLabel": "세션 {{n}}",
|
||||
"entriesShort": "건"
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,10 @@
|
||||
"livestream": "🔴 LIVE",
|
||||
"gacha_quest": ""
|
||||
},
|
||||
"endingLabel": {
|
||||
"range": "Kết thúc {{from}}–{{to}}",
|
||||
"count": "{{count}} Kết thúc"
|
||||
},
|
||||
"gachaQuestType": {
|
||||
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
|
||||
"world_quest": "{{gameName}} — Nhiệm vụ thế giới: {{questName}}",
|
||||
|
||||
@@ -776,7 +776,10 @@
|
||||
"pinnedCommentIncludeGenrePlaylist": "Kèm gợi ý playlist theo thể loại trong pinned comment",
|
||||
"genrePlaylistsTitle": "Playlist theo thể loại",
|
||||
"genrePlaylistsHelp": "Cấu hình URL YouTube playlist cho từng thể loại. Pinned comment sẽ tự động gợi ý playlist phù hợp với thể loại chính của video.",
|
||||
"genrePlaylistsEmptyHint": "Bỏ trống nếu chưa có playlist cho thể loại đó."
|
||||
"genrePlaylistsEmptyHint": "Bỏ trống nếu chưa có playlist cho thể loại đó.",
|
||||
"logSettings": "Nhật ký",
|
||||
"logRetentionDays": "Giữ log (ngày)",
|
||||
"logRetentionHint": "Log cũ hơn số ngày này sẽ tự xoá khi mở app. Phạm vi: 1–90 ngày."
|
||||
},
|
||||
"batch": {
|
||||
"title": "Chế độ hàng loạt",
|
||||
@@ -822,6 +825,13 @@
|
||||
"emptyState": "Chưa có nhật ký.",
|
||||
"clearAll": "Xóa tất cả",
|
||||
"clearConfirm": "Bạn có chắc muốn xóa toàn bộ nhật ký?",
|
||||
"searchPlaceholder": "Tìm kiếm nhật ký..."
|
||||
"clearPersistedConfirm": "Xóa nhật ký trong bộ nhớ VÀ xoá file log đã lưu? Hành động này không thể hoàn tác.",
|
||||
"clearSession": "Xoá phiên này",
|
||||
"searchPlaceholder": "Tìm kiếm nhật ký...",
|
||||
"exportJson": "Xuất JSON",
|
||||
"exportTxt": "Xuất TXT",
|
||||
"sessionCurrent": "Phiên hiện tại",
|
||||
"sessionLabel": "Phiên {{n}}",
|
||||
"entriesShort": "bản ghi"
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,10 @@
|
||||
"livestream": "🔴 直播",
|
||||
"gacha_quest": ""
|
||||
},
|
||||
"endingLabel": {
|
||||
"range": "结局 {{from}}–{{to}}",
|
||||
"count": "{{count}} 个结局"
|
||||
},
|
||||
"gachaQuestType": {
|
||||
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
|
||||
"world_quest": "{{gameName}} — World Quest: {{questName}}",
|
||||
|
||||
@@ -776,7 +776,10 @@
|
||||
"pinnedCommentIncludeGenrePlaylist": "Include genre-playlist suggestion in pinned comment",
|
||||
"genrePlaylistsTitle": "Genre Playlists",
|
||||
"genrePlaylistsHelp": "Configure a YouTube playlist URL per genre. The pinned-comment template will auto-suggest the matching playlist when the video's primary genre is selected.",
|
||||
"genrePlaylistsEmptyHint": "Leave empty to skip a genre."
|
||||
"genrePlaylistsEmptyHint": "Leave empty to skip a genre.",
|
||||
"logSettings": "日志",
|
||||
"logRetentionDays": "日志保留 (天)",
|
||||
"logRetentionHint": "早于此天数的日志会在启动时删除。范围:1–90 天。"
|
||||
},
|
||||
"batch": {
|
||||
"title": "批量生成",
|
||||
@@ -822,6 +825,13 @@
|
||||
"emptyState": "暂无日志。",
|
||||
"clearAll": "清除全部",
|
||||
"clearConfirm": "确定要清除所有日志吗?",
|
||||
"searchPlaceholder": "搜索日志..."
|
||||
"clearPersistedConfirm": "清除内存中的日志并删除已保存的日志文件?此操作无法撤销。",
|
||||
"clearSession": "清除此会话",
|
||||
"searchPlaceholder": "搜索日志...",
|
||||
"exportJson": "导出 JSON",
|
||||
"exportTxt": "导出 TXT",
|
||||
"sessionCurrent": "当前会话",
|
||||
"sessionLabel": "会话 {{n}}",
|
||||
"entriesShort": "条"
|
||||
}
|
||||
}
|
||||
+217
-50
@@ -1,12 +1,14 @@
|
||||
import { useState, useRef, useEffect } from "react";
|
||||
import { useState, useMemo } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useDocumentTitle } from "@hooks/use-document-title";
|
||||
import { Trash2 } from "lucide-react";
|
||||
import { Trash2, ChevronDown, ChevronRight, FileJson, FileText } from "lucide-react";
|
||||
import { Input } from "@components/ui/Input";
|
||||
import { Button } from "@components/ui/Button";
|
||||
import { ConfirmDialog } from "@components/ui/ConfirmDialog";
|
||||
import { LogEntryCard } from "@components/logs/LogEntry";
|
||||
import { useLogStore, type LogLevel } from "@store/log-store";
|
||||
import { useLogStore, type LogEntry, type LogLevel } from "@store/log-store";
|
||||
import { exportTypedToJsonFile } from "@utils/import-export";
|
||||
import { saveFile } from "@utils/file-ops";
|
||||
import clsx from "clsx";
|
||||
|
||||
const LEVEL_FILTERS: Array<{ value: LogLevel | "all"; label: string; color: string }> = [
|
||||
@@ -17,37 +19,99 @@ const LEVEL_FILTERS: Array<{ value: LogLevel | "all"; label: string; color: stri
|
||||
{ value: "debug", label: "Debug", color: "text-gray-400" },
|
||||
];
|
||||
|
||||
/**
|
||||
* v0.17.0 LogPage. Three new concerns over the v0.16.x version:
|
||||
*
|
||||
* 1. **Session-grouped accordion**. The store now tags each entry
|
||||
* with a `sessionId` (one per app boot). The page collects
|
||||
* consecutive entries by id and renders one collapsible block
|
||||
* per session. The *current* session expands by default; prior
|
||||
* sessions collapse so the page opens fast even after a week of
|
||||
* persisted history.
|
||||
*
|
||||
* 2. **Export buttons**. Two flavours:
|
||||
* - JSON (envelope-wrapped) — feeds back into the v0.15 import
|
||||
* pipeline (`_type: "history"` for now; eventually a dedicated
|
||||
* `log` type when there's a use case to re-import).
|
||||
* - Plaintext (.txt) — one line per entry, formatted as
|
||||
* `[ISO time] [LEVEL] [source] message — details`. Most useful
|
||||
* for pasting into a bug report.
|
||||
*
|
||||
* 3. **Session-scoped clear**. The existing `Clear All` confirms
|
||||
* via the same dialog; a new "Clear this session" inline action
|
||||
* on each session header lets a creator drop one bad debug run
|
||||
* without losing prior history.
|
||||
*/
|
||||
export function LogPage() {
|
||||
const { t } = useTranslation("ui");
|
||||
useDocumentTitle(t("tabs.logs"));
|
||||
const { entries, clearAll } = useLogStore();
|
||||
// `clearAll` (in-memory only) intentionally omitted — the page uses
|
||||
// `clearAllPersisted` so the on-disk JSONL files don't drift out of
|
||||
// sync with the in-memory tail when the user hits the toolbar trash.
|
||||
const { entries, currentSessionId, clearSession, clearAllPersisted } = useLogStore();
|
||||
const [search, setSearch] = useState("");
|
||||
const [levelFilter, setLevelFilter] = useState<LogLevel | "all">("all");
|
||||
const [showClearAll, setShowClearAll] = useState(false);
|
||||
const [autoScroll, setAutoScroll] = useState(true);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const [collapsedSessions, setCollapsedSessions] = useState<Set<string>>(new Set());
|
||||
|
||||
const filtered = entries.filter((e) => {
|
||||
if (levelFilter !== "all" && e.level !== levelFilter) return false;
|
||||
if (search) {
|
||||
const q = search.toLowerCase();
|
||||
return (
|
||||
e.message.toLowerCase().includes(q) ||
|
||||
e.source.toLowerCase().includes(q) ||
|
||||
(e.details?.toLowerCase().includes(q) ?? false)
|
||||
);
|
||||
/** Apply level + search filters before grouping so empty sessions
|
||||
* (whose only entries got filtered out) disappear entirely. */
|
||||
const filtered = useMemo<LogEntry[]>(() => {
|
||||
return entries.filter((e) => {
|
||||
if (levelFilter !== "all" && e.level !== levelFilter) return false;
|
||||
if (search) {
|
||||
const q = search.toLowerCase();
|
||||
return (
|
||||
e.message.toLowerCase().includes(q) ||
|
||||
e.source.toLowerCase().includes(q) ||
|
||||
(e.details?.toLowerCase().includes(q) ?? false)
|
||||
);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}, [entries, levelFilter, search]);
|
||||
|
||||
/** Group filtered entries by sessionId, preserving the descending-time
|
||||
* order the store maintains. Each session carries summary counts
|
||||
* rendered in the header. */
|
||||
const sessions = useMemo(() => {
|
||||
const map = new Map<string, LogEntry[]>();
|
||||
for (const entry of filtered) {
|
||||
const existing = map.get(entry.sessionId);
|
||||
if (existing) {
|
||||
existing.push(entry);
|
||||
} else {
|
||||
map.set(entry.sessionId, [entry]);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return Array.from(map.entries()).map(([id, sessionEntries]) => ({
|
||||
id,
|
||||
entries: sessionEntries,
|
||||
isCurrent: id === currentSessionId,
|
||||
// First entry is newest (entries are prepended); last is oldest
|
||||
// — used for the time range label.
|
||||
firstAt: sessionEntries[sessionEntries.length - 1]?.timestamp ?? "",
|
||||
lastAt: sessionEntries[0]?.timestamp ?? "",
|
||||
errorCount: sessionEntries.filter((e) => e.level === "error").length,
|
||||
warnCount: sessionEntries.filter((e) => e.level === "warn").length,
|
||||
}));
|
||||
}, [filtered, currentSessionId]);
|
||||
|
||||
const errorCount = entries.filter((e) => e.level === "error").length;
|
||||
const warnCount = entries.filter((e) => e.level === "warn").length;
|
||||
const totalErrorCount = entries.filter((e) => e.level === "error").length;
|
||||
const totalWarnCount = entries.filter((e) => e.level === "warn").length;
|
||||
|
||||
useEffect(() => {
|
||||
if (autoScroll && listRef.current) {
|
||||
listRef.current.scrollTop = 0;
|
||||
}
|
||||
}, [entries.length, autoScroll]);
|
||||
const handleExportJson = () => {
|
||||
exportTypedToJsonFile("history", entries, `ytdescgen-logs-${todayStamp()}.json`);
|
||||
};
|
||||
|
||||
const handleExportTxt = async () => {
|
||||
const text = entries
|
||||
.slice()
|
||||
.reverse() // chronological order in the export
|
||||
.map(formatPlaintextLine)
|
||||
.join("\n");
|
||||
await saveFile(text, `ytdescgen-logs-${todayStamp()}.txt`);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-4xl p-6">
|
||||
@@ -55,30 +119,31 @@ export function LogPage() {
|
||||
<div className="flex items-center gap-3">
|
||||
<h1 className="text-lg font-bold text-text-primary">{t("logs.title")}</h1>
|
||||
<span className="text-xs text-text-muted">
|
||||
{entries.length} entries
|
||||
{errorCount > 0 && (
|
||||
<span className="ml-1 text-red-400">({errorCount} errors)</span>
|
||||
{entries.length} entries · {sessions.length} sessions
|
||||
{totalErrorCount > 0 && (
|
||||
<span className="ml-1 text-red-400">({totalErrorCount} errors)</span>
|
||||
)}
|
||||
{warnCount > 0 && (
|
||||
<span className="ml-1 text-yellow-400">({warnCount} warnings)</span>
|
||||
{totalWarnCount > 0 && (
|
||||
<span className="ml-1 text-yellow-400">({totalWarnCount} warnings)</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<label className="flex items-center gap-1.5 text-xs text-text-muted">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={autoScroll}
|
||||
onChange={(e) => setAutoScroll(e.target.checked)}
|
||||
className="rounded"
|
||||
/>
|
||||
Auto-scroll
|
||||
</label>
|
||||
{entries.length > 0 && (
|
||||
<Button variant="ghost" size="sm" onClick={() => setShowClearAll(true)}>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
{t("logs.clearAll")}
|
||||
</Button>
|
||||
<>
|
||||
<Button variant="ghost" size="sm" onClick={handleExportJson}>
|
||||
<FileJson className="h-3.5 w-3.5" />
|
||||
{t("logs.exportJson")}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={handleExportTxt}>
|
||||
<FileText className="h-3.5 w-3.5" />
|
||||
{t("logs.exportTxt")}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={() => setShowClearAll(true)}>
|
||||
<Trash2 className="h-3.5 w-3.5" />
|
||||
{t("logs.clearAll")}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -110,30 +175,132 @@ export function LogPage() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Log entries */}
|
||||
{filtered.length === 0 ? (
|
||||
{/* Session-grouped entries */}
|
||||
{sessions.length === 0 ? (
|
||||
<p className="rounded-lg border border-dashed border-border py-12 text-center text-sm text-text-muted">
|
||||
{t("logs.emptyState")}
|
||||
</p>
|
||||
) : (
|
||||
<div ref={listRef} className="flex max-h-[65vh] flex-col gap-1.5 overflow-y-auto">
|
||||
{filtered.map((entry) => (
|
||||
<LogEntryCard key={entry.id} entry={entry} />
|
||||
))}
|
||||
<div className="flex max-h-[65vh] flex-col gap-2 overflow-y-auto">
|
||||
{sessions.map((session, idx) => {
|
||||
const isCollapsed = collapsedSessions.has(session.id);
|
||||
// Auto-collapse non-current sessions on first render — we
|
||||
// store the inverse (collapsed-set) so this defaults to
|
||||
// expanded for the current session.
|
||||
const effectivelyCollapsed = session.isCurrent
|
||||
? isCollapsed
|
||||
: !collapsedSessions.has(`__expanded__${session.id}`);
|
||||
|
||||
return (
|
||||
<div
|
||||
key={session.id}
|
||||
className="rounded-lg border border-border bg-surface-1"
|
||||
>
|
||||
<div
|
||||
className="flex cursor-pointer items-center gap-2 px-3 py-2"
|
||||
onClick={() => {
|
||||
// Two different toggle keys depending on default
|
||||
// state — keeps the "current expanded, others
|
||||
// collapsed" semantic from leaking into the set.
|
||||
setCollapsedSessions((prev) => {
|
||||
const next = new Set(prev);
|
||||
const key = session.isCurrent
|
||||
? session.id
|
||||
: `__expanded__${session.id}`;
|
||||
if (next.has(key)) next.delete(key);
|
||||
else next.add(key);
|
||||
return next;
|
||||
});
|
||||
}}
|
||||
>
|
||||
{effectivelyCollapsed ? (
|
||||
<ChevronRight className="h-4 w-4 text-text-muted" />
|
||||
) : (
|
||||
<ChevronDown className="h-4 w-4 text-text-muted" />
|
||||
)}
|
||||
<span className="text-sm font-semibold text-text-primary">
|
||||
{session.isCurrent
|
||||
? t("logs.sessionCurrent")
|
||||
: t("logs.sessionLabel", { n: sessions.length - idx })}
|
||||
</span>
|
||||
<span className="text-xs text-text-muted">
|
||||
{formatRange(session.firstAt, session.lastAt)}
|
||||
</span>
|
||||
<span className="text-xs text-text-muted">
|
||||
· {session.entries.length} {t("logs.entriesShort")}
|
||||
</span>
|
||||
{session.errorCount > 0 && (
|
||||
<span className="text-xs text-red-400">
|
||||
· {session.errorCount} errors
|
||||
</span>
|
||||
)}
|
||||
{session.warnCount > 0 && (
|
||||
<span className="text-xs text-yellow-400">
|
||||
· {session.warnCount} warnings
|
||||
</span>
|
||||
)}
|
||||
<div className="flex-1" />
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
clearSession(session.id);
|
||||
}}
|
||||
className="rounded p-1 text-text-muted hover:bg-surface-3 hover:text-danger"
|
||||
title={t("logs.clearSession")}
|
||||
>
|
||||
<Trash2 className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
{!effectivelyCollapsed && (
|
||||
<div className="flex flex-col gap-1 border-t border-border p-2">
|
||||
{session.entries.map((entry) => (
|
||||
<LogEntryCard key={entry.id} entry={entry} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ConfirmDialog
|
||||
open={showClearAll}
|
||||
onConfirm={() => {
|
||||
clearAll();
|
||||
void clearAllPersisted();
|
||||
setShowClearAll(false);
|
||||
}}
|
||||
onCancel={() => setShowClearAll(false)}
|
||||
title={t("logs.clearAll")}
|
||||
message={t("logs.clearConfirm")}
|
||||
message={t("logs.clearPersistedConfirm")}
|
||||
variant="danger"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Format an ISO timestamp pair as `HH:MM:SS → HH:MM:SS`. Falls back
|
||||
* to a single point when both ends match (single-entry session). */
|
||||
function formatRange(firstIso: string, lastIso: string): string {
|
||||
const first = firstIso ? new Date(firstIso).toLocaleTimeString() : "";
|
||||
const last = lastIso ? new Date(lastIso).toLocaleTimeString() : "";
|
||||
if (!first) return last;
|
||||
if (!last || first === last) return first;
|
||||
return `${first} → ${last}`;
|
||||
}
|
||||
|
||||
/** Build today's date stamp for export filenames. */
|
||||
function todayStamp(): string {
|
||||
const now = new Date();
|
||||
const y = now.getFullYear();
|
||||
const m = String(now.getMonth() + 1).padStart(2, "0");
|
||||
const d = String(now.getDate()).padStart(2, "0");
|
||||
return `${y}${m}${d}`;
|
||||
}
|
||||
|
||||
/** One-line text formatter for the plaintext export. */
|
||||
function formatPlaintextLine(entry: LogEntry): string {
|
||||
const time = entry.timestamp;
|
||||
const head = `[${time}] [${entry.level.toUpperCase()}] [${entry.source}] ${entry.message}`;
|
||||
return entry.details ? `${head} — ${entry.details}` : head;
|
||||
}
|
||||
@@ -425,6 +425,25 @@ export function SettingsPage() {
|
||||
}}
|
||||
/>
|
||||
</section>
|
||||
|
||||
{/* 8. Logs — v0.17.0 retention. */}
|
||||
<section className="flex flex-col gap-3">
|
||||
<h2 className="text-sm font-semibold text-text-secondary">{t("settings.logSettings")}</h2>
|
||||
<Input
|
||||
label={t("settings.logRetentionDays")}
|
||||
type="number"
|
||||
min={1}
|
||||
max={90}
|
||||
value={String(settings.logRetentionDays)}
|
||||
onChange={(e) => {
|
||||
// Same clamp as `healSettings` so the in-memory value
|
||||
// never goes out of bounds before persistence runs.
|
||||
const val = Math.max(1, Math.min(90, Number(e.target.value) || 7));
|
||||
settings.setSetting("logRetentionDays", val);
|
||||
}}
|
||||
/>
|
||||
<p className="text-xs text-text-muted">{t("settings.logRetentionHint")}</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
+91
-2
@@ -1,5 +1,11 @@
|
||||
import { create } from "zustand";
|
||||
import { generateId } from "@utils/uuid";
|
||||
import {
|
||||
persistLogEntry,
|
||||
loadRecentLogs,
|
||||
pruneOldLogs,
|
||||
clearAllPersistedLogs,
|
||||
} from "@utils/log-storage";
|
||||
|
||||
export type LogLevel = "error" | "warn" | "info" | "debug";
|
||||
|
||||
@@ -10,29 +16,63 @@ export interface LogEntry {
|
||||
source: string;
|
||||
message: string;
|
||||
details?: string;
|
||||
/**
|
||||
* Session identifier (v0.17.0). One per app boot, attached to
|
||||
* every entry the store records during that lifetime. Lets the
|
||||
* LogPage group entries into per-session accordion sections so
|
||||
* "what happened since I opened the app" is readable at a glance,
|
||||
* and prior-session history doesn't smear into the current run.
|
||||
*/
|
||||
sessionId: string;
|
||||
}
|
||||
|
||||
interface LogState {
|
||||
entries: LogEntry[];
|
||||
addEntry: (data: Omit<LogEntry, "id" | "timestamp">) => void;
|
||||
/** Session id of the *current* app boot. Stable for the lifetime
|
||||
* of the store; entries from prior runs carry their own id. */
|
||||
currentSessionId: string;
|
||||
addEntry: (data: Omit<LogEntry, "id" | "timestamp" | "sessionId">) => void;
|
||||
deleteEntry: (id: string) => void;
|
||||
clearAll: () => void;
|
||||
/** Clear in-memory state AND wipe persisted log files / localStorage.
|
||||
* Used by the "Clear all persisted logs" action. */
|
||||
clearAllPersisted: () => Promise<void>;
|
||||
/** Clear all entries from a single session (current or historical). */
|
||||
clearSession: (sessionId: string) => void;
|
||||
}
|
||||
|
||||
const MAX_ENTRIES = 500;
|
||||
/**
|
||||
* In-memory cap. The previous limit (500) covered ~a few hours of
|
||||
* heavy debug logging; raised to 2000 with persistence in play so
|
||||
* the in-memory tail can fully represent a session for the LogPage
|
||||
* accordion to render without paging.
|
||||
*/
|
||||
const MAX_ENTRIES = 2000;
|
||||
|
||||
/**
|
||||
* Session id for THIS app boot. Module-scoped (not store-scoped) so
|
||||
* every entry recorded during this process lifetime shares the same
|
||||
* value regardless of which call site lands first.
|
||||
*/
|
||||
const CURRENT_SESSION_ID = generateId();
|
||||
|
||||
export const useLogStore = create<LogState>()((set) => ({
|
||||
entries: [],
|
||||
currentSessionId: CURRENT_SESSION_ID,
|
||||
|
||||
addEntry: (data) => {
|
||||
const entry: LogEntry = {
|
||||
...data,
|
||||
id: generateId(),
|
||||
timestamp: new Date().toISOString(),
|
||||
sessionId: CURRENT_SESSION_ID,
|
||||
};
|
||||
set((state) => ({
|
||||
entries: [entry, ...state.entries].slice(0, MAX_ENTRIES),
|
||||
}));
|
||||
// Fire-and-forget persistence. `persistLogEntry` swallows failures
|
||||
// — we don't want a disk hiccup to escalate into a log loop.
|
||||
void persistLogEntry(entry);
|
||||
},
|
||||
|
||||
deleteEntry: (id) => {
|
||||
@@ -40,4 +80,53 @@ export const useLogStore = create<LogState>()((set) => ({
|
||||
},
|
||||
|
||||
clearAll: () => set({ entries: [] }),
|
||||
|
||||
clearAllPersisted: async () => {
|
||||
set({ entries: [] });
|
||||
await clearAllPersistedLogs();
|
||||
},
|
||||
|
||||
clearSession: (sessionId) =>
|
||||
set((state) => ({
|
||||
entries: state.entries.filter((e) => e.sessionId !== sessionId),
|
||||
})),
|
||||
}));
|
||||
|
||||
/**
|
||||
* Boot-time hydration. Reads recent persisted entries from disk /
|
||||
* localStorage and folds them into the in-memory store before the
|
||||
* UI mounts. Idempotent — re-running just produces the same merge
|
||||
* (entries are deduped by id).
|
||||
*
|
||||
* Async and best-effort: if persistence fails or the platform layer
|
||||
* isn't ready yet, the store just starts empty and accumulates from
|
||||
* the current session forward. Called once from `App.tsx`.
|
||||
*/
|
||||
export async function hydrateLogStore(retentionDays: number): Promise<void> {
|
||||
try {
|
||||
const prior = await loadRecentLogs(retentionDays);
|
||||
if (prior.length === 0) {
|
||||
// No-op — first run / nothing in the retention window.
|
||||
} else {
|
||||
// Sort by timestamp descending so the newest is first
|
||||
// (matches `addEntry`'s prepend semantics). Filter out anything
|
||||
// already in memory by id to keep hydration idempotent.
|
||||
const sorted = [...prior].sort(
|
||||
(a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp),
|
||||
);
|
||||
useLogStore.setState((state) => {
|
||||
const existing = new Set(state.entries.map((e) => e.id));
|
||||
const fresh = sorted.filter((e) => !existing.has(e.id));
|
||||
// Place fresh prior entries AFTER current session's entries
|
||||
// (which were added between boot and this call) so the
|
||||
// accordion still opens with the current session at top.
|
||||
return { entries: [...state.entries, ...fresh].slice(0, MAX_ENTRIES) };
|
||||
});
|
||||
}
|
||||
// Run retention sweep AFTER hydrate so the load can pick up
|
||||
// entries that are about to be pruned (last-chance access).
|
||||
void pruneOldLogs(retentionDays);
|
||||
} catch {
|
||||
// Hydration failure → store stays empty + per-session forward.
|
||||
}
|
||||
}
|
||||
@@ -79,6 +79,14 @@ export interface SettingsData {
|
||||
* narrow-screen users don't keep collapsing on every visit.
|
||||
*/
|
||||
sidebarCollapsed: boolean;
|
||||
/**
|
||||
* How many days of log history to keep on disk / in localStorage
|
||||
* (v0.17.0). Files older than this are deleted at app boot.
|
||||
* Default 7 — long enough to investigate week-ago issues, short
|
||||
* enough to keep the AppData folder small. Clamped to `[1, 90]`
|
||||
* by `healSettings`.
|
||||
*/
|
||||
logRetentionDays: number;
|
||||
}
|
||||
|
||||
export function detectBrowserLanguage(): SupportedLanguage {
|
||||
@@ -128,6 +136,7 @@ export const initialSettings: SettingsData = {
|
||||
storeAndSocial: false,
|
||||
},
|
||||
sidebarCollapsed: false,
|
||||
logRetentionDays: 7,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -172,5 +181,15 @@ export function healSettings(raw: unknown): SettingsData {
|
||||
: {};
|
||||
incoming.genrePlaylists = { ...initialSettings.genrePlaylists, ...incomingGp };
|
||||
|
||||
// v9 → v10: v0.17.0. `logRetentionDays` added (default 7). Clamp
|
||||
// to [1, 90] so an extreme value can't either spam the disk or
|
||||
// wipe everything on boot.
|
||||
if (typeof incoming.logRetentionDays === "number") {
|
||||
incoming.logRetentionDays = Math.max(
|
||||
1,
|
||||
Math.min(90, Math.floor(incoming.logRetentionDays)),
|
||||
);
|
||||
}
|
||||
|
||||
return { ...initialSettings, ...incoming } as SettingsData;
|
||||
}
|
||||
@@ -69,7 +69,9 @@ export const useSettingsStore = create<SettingsState>()(
|
||||
// explicit per-version migration step is required here.
|
||||
// v8 → v9: v0.11 added `showThirdPartyAds`. Additive — same back-fill
|
||||
// path as v8.
|
||||
version: 9,
|
||||
// v9 → v10: v0.17.0 added `logRetentionDays`. Additive — defaults to
|
||||
// 7 days; `healSettings` clamps incoming values to [1, 90].
|
||||
version: 10,
|
||||
migrate: (persistedState: unknown): SettingsData => healSettings(persistedState),
|
||||
partialize: (state) => extractData(state),
|
||||
onRehydrateStorage: () => {
|
||||
@@ -112,6 +114,7 @@ function extractData(state: SettingsData): SettingsData {
|
||||
titleFormat: { ...state.titleFormat },
|
||||
editorAccordionState: state.editorAccordionState,
|
||||
sidebarCollapsed: state.sidebarCollapsed,
|
||||
logRetentionDays: state.logRetentionDays,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ export const SCHEMA_VERSIONS: Record<ExportType, number> = {
|
||||
profile: 1, // v0.11 added `thirdPartyAdText`
|
||||
preset: 2, // v0.5 added `genres[]` (was `genre`)
|
||||
template: 1, // v0.11 vendor-coercion
|
||||
settings: 9, // matches settings-store persist version
|
||||
settings: 10, // matches settings-store persist version
|
||||
history: 2, // v0.5 added `genres[]` to HistoryEntry
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
import { IS_TAURI } from "./platform";
|
||||
import type { LogEntry } from "@store/log-store";
|
||||
|
||||
/**
|
||||
* Log persistence (v0.17.0). Bridges the in-memory log store to
|
||||
* disk (Tauri JSONL files) / localStorage (web) so creators get a
|
||||
* persistent trail across app restarts.
|
||||
*
|
||||
* Design choices:
|
||||
*
|
||||
* - **JSONL on disk**, one entry per line. Lets us append on every
|
||||
* `addEntry` without re-serialising the whole tail, and a corrupt
|
||||
* line never breaks the rest of the file (parse failures are
|
||||
* filtered, not propagated).
|
||||
* - **Daily file rotation** (`ytdescgen-YYYYMMDD.jsonl`). Cleanup
|
||||
* sweeps just delete whole files older than `logRetentionDays`,
|
||||
* which is dramatically faster than scanning every line.
|
||||
* - **localStorage cap on web** (5000 entries). When the cap is
|
||||
* exceeded, oldest entries drop. Roughly matches a week of
|
||||
* moderate use; users who need more should use the desktop build.
|
||||
* - **Best-effort writes**: persistence failures never throw — the
|
||||
* in-memory store stays the source of truth even if disk writes
|
||||
* fail. Errors get logged to the *previous* log entry's source so
|
||||
* we don't recurse into an infinite write loop.
|
||||
*/
|
||||
|
||||
const LOG_DIR_SUBPATH = "logs";
|
||||
const FILE_PREFIX = "ytdescgen-";
|
||||
const FILE_SUFFIX = ".jsonl";
|
||||
const WEB_STORAGE_KEY = "ytdescgen-logs";
|
||||
const WEB_MAX_ENTRIES = 5000;
|
||||
|
||||
/** Build today's log file name (`ytdescgen-YYYYMMDD.jsonl`). */
|
||||
function todayFileName(now = new Date()): string {
|
||||
const y = now.getFullYear();
|
||||
const m = String(now.getMonth() + 1).padStart(2, "0");
|
||||
const d = String(now.getDate()).padStart(2, "0");
|
||||
return `${FILE_PREFIX}${y}${m}${d}${FILE_SUFFIX}`;
|
||||
}
|
||||
|
||||
/** Extract the YYYYMMDD date from a log file name. Returns null when
|
||||
* the name doesn't match the prefix/suffix shape — defensive against
|
||||
* hand-edited files in the same directory. */
|
||||
function parseFileDate(name: string): Date | null {
|
||||
if (!name.startsWith(FILE_PREFIX) || !name.endsWith(FILE_SUFFIX)) {
|
||||
return null;
|
||||
}
|
||||
const datePart = name.slice(FILE_PREFIX.length, name.length - FILE_SUFFIX.length);
|
||||
if (!/^\d{8}$/.test(datePart)) return null;
|
||||
const y = parseInt(datePart.slice(0, 4), 10);
|
||||
const m = parseInt(datePart.slice(4, 6), 10) - 1;
|
||||
const d = parseInt(datePart.slice(6, 8), 10);
|
||||
return new Date(y, m, d);
|
||||
}
|
||||
|
||||
/** Compute the absolute path to today's log file on the Tauri side. */
|
||||
async function getTodayLogPath(): Promise<string> {
|
||||
const { appDataDir } = await import("@tauri-apps/api/path");
|
||||
const dir = await appDataDir();
|
||||
return `${dir}${LOG_DIR_SUBPATH}/${todayFileName()}`;
|
||||
}
|
||||
|
||||
async function getLogDirPath(): Promise<string> {
|
||||
const { appDataDir } = await import("@tauri-apps/api/path");
|
||||
const dir = await appDataDir();
|
||||
return `${dir}${LOG_DIR_SUBPATH}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Append a single {@link LogEntry} to durable storage. On Tauri this
|
||||
* writes one JSONL line to the daily file; on web it appends to the
|
||||
* `ytdescgen-logs` localStorage key (with FIFO eviction when the cap
|
||||
* is hit). Failures are swallowed — the in-memory store remains the
|
||||
* canonical view.
|
||||
*/
|
||||
export async function persistLogEntry(entry: LogEntry): Promise<void> {
|
||||
try {
|
||||
if (IS_TAURI) {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
const path = await getTodayLogPath();
|
||||
const line = `${JSON.stringify(entry)}\n`;
|
||||
await invoke("append_to_file", { path, content: line });
|
||||
} else {
|
||||
const raw = localStorage.getItem(WEB_STORAGE_KEY);
|
||||
const existing: LogEntry[] = raw ? safeParseArray(raw) : [];
|
||||
existing.push(entry);
|
||||
const trimmed =
|
||||
existing.length > WEB_MAX_ENTRIES
|
||||
? existing.slice(existing.length - WEB_MAX_ENTRIES)
|
||||
: existing;
|
||||
localStorage.setItem(WEB_STORAGE_KEY, JSON.stringify(trimmed));
|
||||
}
|
||||
} catch {
|
||||
// Swallow — see top-of-file comment. We can't even log the failure
|
||||
// because that would recurse here. The in-memory store still has
|
||||
// the entry, so the user sees it for the current session.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load persisted log entries from durable storage, filtered to the
|
||||
* last `maxAgeDays` days. Used at app boot to seed the in-memory
|
||||
* store with prior-session history.
|
||||
*
|
||||
* Web: one localStorage read + filter by `timestamp`.
|
||||
*
|
||||
* Tauri: lists files in `{appData}/logs/`, picks each `ytdescgen-*.jsonl`
|
||||
* with a parsed date within the retention window, reads + parses
|
||||
* JSONL line-by-line. Corrupt lines are skipped silently so a single
|
||||
* bad write can't poison the whole tail.
|
||||
*/
|
||||
export async function loadRecentLogs(maxAgeDays: number): Promise<LogEntry[]> {
|
||||
const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
|
||||
try {
|
||||
if (IS_TAURI) {
|
||||
return await loadRecentTauriLogs(cutoff);
|
||||
}
|
||||
const raw = localStorage.getItem(WEB_STORAGE_KEY);
|
||||
if (!raw) return [];
|
||||
return safeParseArray(raw).filter((e) => Date.parse(e.timestamp) >= cutoff);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
async function loadRecentTauriLogs(cutoffMs: number): Promise<LogEntry[]> {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
const dirPath = await getLogDirPath();
|
||||
const names = await invoke<string[]>("list_dir", { path: dirPath });
|
||||
// Only consider files whose parsed date is within the window. Saves
|
||||
// a full read of files we'd just throw away.
|
||||
const candidates = names
|
||||
.map((name) => ({ name, date: parseFileDate(name) }))
|
||||
.filter(
|
||||
(x): x is { name: string; date: Date } =>
|
||||
x.date !== null && x.date.getTime() >= cutoffMs - 24 * 60 * 60 * 1000,
|
||||
);
|
||||
const entries: LogEntry[] = [];
|
||||
for (const { name } of candidates) {
|
||||
try {
|
||||
const content: string = await invoke("read_from_file", {
|
||||
path: `${dirPath}/${name}`,
|
||||
});
|
||||
for (const line of content.split("\n")) {
|
||||
if (!line.trim()) continue;
|
||||
try {
|
||||
const parsed = JSON.parse(line) as LogEntry;
|
||||
if (Date.parse(parsed.timestamp) >= cutoffMs) {
|
||||
entries.push(parsed);
|
||||
}
|
||||
} catch {
|
||||
// Corrupt line — skip without failing the whole sweep.
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Couldn't read this file — skip it.
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete log files older than `maxAgeDays`. Runs at app boot after
|
||||
* `loadRecentLogs` so a long-idle install doesn't keep months of old
|
||||
* JSONL around. Web path is a no-op — the localStorage cap already
|
||||
* handles eviction by FIFO.
|
||||
*/
|
||||
export async function pruneOldLogs(maxAgeDays: number): Promise<void> {
|
||||
if (!IS_TAURI) return;
|
||||
const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
|
||||
try {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
const dirPath = await getLogDirPath();
|
||||
const names = await invoke<string[]>("list_dir", { path: dirPath });
|
||||
for (const name of names) {
|
||||
const date = parseFileDate(name);
|
||||
if (date && date.getTime() < cutoff) {
|
||||
try {
|
||||
await invoke("delete_file", { path: `${dirPath}/${name}` });
|
||||
} catch {
|
||||
// Permission denied / already gone → skip.
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Directory listing failed — non-fatal.
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard-clear ALL persisted logs (Tauri files + web localStorage).
|
||||
* Used by the LogPage "Clear all persisted logs" action. The
|
||||
* in-memory store is reset separately by the caller.
|
||||
*/
|
||||
export async function clearAllPersistedLogs(): Promise<void> {
|
||||
try {
|
||||
if (IS_TAURI) {
|
||||
const { invoke } = await import("@tauri-apps/api/core");
|
||||
const dirPath = await getLogDirPath();
|
||||
const names = await invoke<string[]>("list_dir", { path: dirPath });
|
||||
for (const name of names) {
|
||||
if (name.startsWith(FILE_PREFIX) && name.endsWith(FILE_SUFFIX)) {
|
||||
await invoke("delete_file", { path: `${dirPath}/${name}` });
|
||||
}
|
||||
}
|
||||
} else {
|
||||
localStorage.removeItem(WEB_STORAGE_KEY);
|
||||
}
|
||||
} catch {
|
||||
// Best-effort; caller already cleared the in-memory store.
|
||||
}
|
||||
}
|
||||
|
||||
/** Parse a JSON array string safely; returns [] on any failure. */
|
||||
function safeParseArray(raw: string): LogEntry[] {
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
return Array.isArray(parsed) ? (parsed as LogEntry[]) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -68,6 +68,178 @@ describe("buildTitle", () => {
|
||||
expect(result).toBe("Elden Ring — Ending — Gameplay No Commentary");
|
||||
});
|
||||
|
||||
// v0.17.0: when the creator fills structured endings, the title's
|
||||
// video-type segment swaps from the static "Ending" to a label
|
||||
// built off the entries themselves.
|
||||
it("renders a single structured ending with both number + name (v0.17.0)", () => {
|
||||
const t = createMockT("en");
|
||||
const result = buildTitle(
|
||||
makeInput({
|
||||
videoType: "ending",
|
||||
endings: [{ number: 3, name: "Best End" }],
|
||||
}),
|
||||
t,
|
||||
);
|
||||
expect(result).toBe(
|
||||
"Elden Ring — Ending 3: Best End — Gameplay No Commentary",
|
||||
);
|
||||
});
|
||||
|
||||
it("renders a single structured ending with number only (v0.17.0)", () => {
|
||||
const t = createMockT("en");
|
||||
const result = buildTitle(
|
||||
makeInput({
|
||||
videoType: "ending",
|
||||
endings: [{ number: 7, name: "" }],
|
||||
}),
|
||||
t,
|
||||
);
|
||||
expect(result).toBe("Elden Ring — Ending 7 — Gameplay No Commentary");
|
||||
});
|
||||
|
||||
it("renders a single structured ending with name only (v0.17.0)", () => {
|
||||
const t = createMockT("en");
|
||||
const result = buildTitle(
|
||||
makeInput({
|
||||
videoType: "ending",
|
||||
endings: [{ number: null, name: "True End" }],
|
||||
}),
|
||||
t,
|
||||
);
|
||||
expect(result).toBe("Elden Ring — True End — Gameplay No Commentary");
|
||||
});
|
||||
|
||||
it("collapses multi-ending to comma-joined names when all named (v0.17.0)", () => {
|
||||
const t = createMockT("en");
|
||||
const result = buildTitle(
|
||||
makeInput({
|
||||
videoType: "ending",
|
||||
endings: [
|
||||
{ number: 1, name: "True End" },
|
||||
{ number: 2, name: "Bad End" },
|
||||
{ number: 3, name: "Hidden" },
|
||||
],
|
||||
}),
|
||||
t,
|
||||
);
|
||||
expect(result).toBe(
|
||||
"Elden Ring — True End, Bad End, Hidden — Gameplay No Commentary",
|
||||
);
|
||||
});
|
||||
|
||||
it("renders contiguous numbered endings as a range (v0.17.0)", () => {
|
||||
const t = createMockT("en");
|
||||
const result = buildTitle(
|
||||
makeInput({
|
||||
videoType: "ending",
|
||||
// Numbers only, contiguous.
|
||||
endings: [
|
||||
{ number: 1, name: "" },
|
||||
{ number: 2, name: "" },
|
||||
{ number: 3, name: "" },
|
||||
],
|
||||
}),
|
||||
t,
|
||||
);
|
||||
expect(result).toBe(
|
||||
"Elden Ring — Endings 1–3 — Gameplay No Commentary",
|
||||
);
|
||||
});
|
||||
|
||||
it("handles out-of-order numbered endings by sorting for the range (v0.17.0)", () => {
|
||||
const t = createMockT("en");
|
||||
const result = buildTitle(
|
||||
makeInput({
|
||||
videoType: "ending",
|
||||
endings: [
|
||||
{ number: 3, name: "" },
|
||||
{ number: 1, name: "" },
|
||||
{ number: 2, name: "" },
|
||||
],
|
||||
}),
|
||||
t,
|
||||
);
|
||||
expect(result).toBe("Elden Ring — Endings 1–3 — Gameplay No Commentary");
|
||||
});
|
||||
|
||||
it("falls back to count form when non-contiguous numbers (v0.17.0)", () => {
|
||||
const t = createMockT("en");
|
||||
const result = buildTitle(
|
||||
makeInput({
|
||||
videoType: "ending",
|
||||
endings: [
|
||||
{ number: 1, name: "" },
|
||||
{ number: 4, name: "" }, // gap → non-contiguous
|
||||
],
|
||||
}),
|
||||
t,
|
||||
);
|
||||
expect(result).toBe("Elden Ring — 2 Endings — Gameplay No Commentary");
|
||||
});
|
||||
|
||||
it("respects endingVideoIndex when slicing for per-video title (v0.17.0)", () => {
|
||||
const t = createMockT("en");
|
||||
const result = buildTitle(
|
||||
makeInput({
|
||||
videoType: "ending",
|
||||
endings: [
|
||||
{ number: 1, name: "True" },
|
||||
{ number: 2, name: "Bad" },
|
||||
{ number: 3, name: "Best" },
|
||||
{ number: 4, name: "Hidden" },
|
||||
],
|
||||
endingVideoCount: 2,
|
||||
endingVideoIndex: 2,
|
||||
endingVideoRanges: [
|
||||
{ from: 1, to: 2 },
|
||||
{ from: 3, to: 4 },
|
||||
],
|
||||
}),
|
||||
t,
|
||||
);
|
||||
// Video 2 covers endings 3 & 4 — joined names.
|
||||
expect(result).toBe("Elden Ring — Best, Hidden — Gameplay No Commentary");
|
||||
});
|
||||
|
||||
it("falls back to the legacy 'Ending' label when no usable entries (v0.17.0)", () => {
|
||||
const t = createMockT("en");
|
||||
// All entries empty → drop signal → fall back.
|
||||
const result = buildTitle(
|
||||
makeInput({
|
||||
videoType: "ending",
|
||||
endings: [{ number: null, name: "" }],
|
||||
}),
|
||||
t,
|
||||
);
|
||||
expect(result).toBe("Elden Ring — Ending — Gameplay No Commentary");
|
||||
});
|
||||
|
||||
it("falls back when endings array is undefined (legacy creator)", () => {
|
||||
const t = createMockT("en");
|
||||
const result = buildTitle(
|
||||
makeInput({ videoType: "ending", endings: undefined }),
|
||||
t,
|
||||
);
|
||||
expect(result).toBe("Elden Ring — Ending — Gameplay No Commentary");
|
||||
});
|
||||
|
||||
it("renders Vietnamese ending range with localised label (v0.17.0)", () => {
|
||||
const t = createMockT("vi");
|
||||
const result = buildTitle(
|
||||
makeInput({
|
||||
videoType: "ending",
|
||||
language: "vi",
|
||||
gameName: "Elden Ring",
|
||||
endings: [
|
||||
{ number: 1, name: "" },
|
||||
{ number: 2, name: "" },
|
||||
],
|
||||
}),
|
||||
t,
|
||||
);
|
||||
expect(result).toContain("Kết thúc 1–2");
|
||||
});
|
||||
|
||||
it("generates speedrun title", () => {
|
||||
const t = createMockT("en");
|
||||
const result = buildTitle(makeInput({ videoType: "speedrun" }), t);
|
||||
|
||||
@@ -97,11 +97,24 @@ describe("healSettings", () => {
|
||||
genrePlaylists: { horror: "https://www.youtube.com/playlist?list=abc" },
|
||||
editorAccordionState: { gameInfo: false, videoSettings: true },
|
||||
sidebarCollapsed: true,
|
||||
logRetentionDays: 14,
|
||||
};
|
||||
const healed = healSettings(complete);
|
||||
expect(healed).toEqual(complete);
|
||||
});
|
||||
|
||||
it("back-fills logRetentionDays to 7 when absent (pre-v0.17 payload)", () => {
|
||||
const healed = healSettings({ theme: "dark" as const });
|
||||
expect(healed.logRetentionDays).toBe(7);
|
||||
});
|
||||
|
||||
it("clamps logRetentionDays to [1, 90]", () => {
|
||||
expect(healSettings({ logRetentionDays: 0 } as unknown).logRetentionDays).toBe(1);
|
||||
expect(healSettings({ logRetentionDays: -5 } as unknown).logRetentionDays).toBe(1);
|
||||
expect(healSettings({ logRetentionDays: 1000 } as unknown).logRetentionDays).toBe(90);
|
||||
expect(healSettings({ logRetentionDays: 30.7 } as unknown).logRetentionDays).toBe(30);
|
||||
});
|
||||
|
||||
it("back-fills showSponsorCredit default when the key is absent (v3 → v4 payload)", () => {
|
||||
// Simulates a settings file written in v0.6 phase 1 where the new
|
||||
// sponsor toggle hadn't been introduced yet.
|
||||
|
||||
Reference in new issue
Block a user