Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions extensions/FreeVideoTaskManager/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
__pycache__/
*.py[cod]
.pytest_cache/
node_modules/
.env
.env.*
*.log
59 changes: 59 additions & 0 deletions extensions/FreeVideoTaskManager/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
# FreeVideo Task Manager — v0.1.0 (preview)
Independent ComfyUI frontend extension targeting FreeVideo 0.6.8. No changes to upstream files or engine lifecycle.

## Installation
Place this folder in ComfyUI/custom_nodes/FreeVideoTaskManager. Restart ComfyUI **only when the queue and agent activity are idle**. Reload the browser; select Tasks in the main FreeVideo navigation. To remove, stop ComfyUI when idle, remove this folder, and start normally. Do not restart during a generation.

## Design
- Native top bars, Appearance settings and Tasks expose a shared reactive language selector. All three languages switch without reloading through a reversible, scoped UI adapter (web/native_pt.js) and the generated compatibility catalog (web/native_locales.js). The original startup locale is preserved internally, so native lazy-loaded modules remain consistent. Known navigation, Create controls and common settings labels are translated; specialized messages and views are not fully covered. Native palette language commands outside the shared selector still use the original reload behavior. No original source files, prompts or workflow data are changed. The Tasks header includes Creations, which opens the original library after leaving the dashboard.
- The sun/moon control follows the shared FreeVideo theme, via FreeVideoShell.setTheme and the native freevideo.theme preference. The dashboard no longer stores a separate theme.
- The extension also replaces the native Settings sun-like glyph with a cog and adds a separate theme toggle next to Settings. Existing Settings behavior is unchanged; no upstream files are edited.
- Local UI string catalog (web/i18n.js): Brazilian Portuguese, English and Simplified Chinese. The globe selector beside the theme icon changes the shared language immediately, saves the preference in the current tab's sessionStorage and preserves filters and task monitoring. A fresh launch (freevideo=launch) or new independent tab honors an explicit freevideo_lang parameter; otherwise detects browser locale and falls back to English. Refreshing the current tab retains its selection. Old global language preferences are ignored. Native job names and unknown engine diagnostic strings remain unchanged. The native application itself still supports only English and Chinese; the reactive adapter is a compatibility layer, not a complete upstream localization.
- Uses the original task_store singleton and task_float sources (idempotent startup), agent_tasks adapter for agent activity, and studio_queue seededPrompt to clone an original video workflow for explicit retry.
- Full-screen independent view; native views remain mounted. No changes to the original navigation controller.
- GET FreeVideo monitor, jobs, chains, queue and progress; local read-only host route samples psutil non-blockingly, plus disk. GPU readings come from FreeVideo itself. History stores up to 240 samples (within 24 h) in browser storage, captured every five seconds while the dashboard and browser tab are visible (about 20 minutes of continuous samples). No persistent background daemon.
- Agent records are distinct from engine generation records, so totals count records, not unique underlying jobs. MCP is shown only if the server client identifies MCP; CLI stays CLI.
- Cancel uses native task/agent actions or the targeted native prompt/node endpoint with confirmation. Agent-controlled underlying workflow cancellation should use its agent activity row. Chain resume uses native endpoint; simple video retry requeues its frozen workflow if still in ComfyUI history (not checkpoint resume). No automatic retries. Image and agent retries are not yet implemented.
- Compatibility: internal FreeVideo JS exports and DOM selectors can change in future releases. Update-safe folder separation, not a promise of cross-version API compatibility. If exports change, opening safely errors without modifying the engine.
- No prompts are persisted by this extension. Hardware data only in localStorage. No external network or new Python dependency beyond ComfyUI's psutil.
## Validation before upstream PR
From the ComfyUI directory, offline checks (no generation is created or cancelled):

```powershell
node --test custom_nodes/FreeVideoTaskManager/tests/tasks.test.cjs
.venv/Scripts/python.exe -B custom_nodes/FreeVideoTaskManager/tests/test_host.py
```

Verified on Windows 10 with an NVIDIA RTX 5060 Ti 16 GB and FreeVideo 0.6.8: the dashboard displayed live generation progress and hardware metrics, both themes rendered, and the user confirmed the dashboard language menu visually. The native Portuguese overlay and Creations shortcut still need a visual acceptance check. The offline checks do not replace the live-job acceptance tests below.

Upstream discussion: https://github.com/FlashML-org/FreeVideo/issues/1054. The prototype was developed with AI assistance. Upstream main and other platforms still require validation.

### Locale validation

The compatibility catalog is derived from FreeVideo's Apache-2.0 licensed UI
strings and the initial locale catalogs on the separate `feat/native-i18n` branch.
To regenerate it from matching source trees, run from the extension directory:

```sh
node scripts/build_native_locales.mjs <FreeVideo-web-directory> <native-locales-directory>
```

The optional Windows Chromium smoke test uses disposable profiles and the
running local server (port 8188), without submitting generation requests:

```powershell
node tests/browser_locale_smoke.cjs pt-BR en-US zh-CN
```

Verified first-launch navigation, locale badge and generation-button rendering
in fresh Chrome profiles for these three locales. Seventeen JavaScript
regression tests and one Python host test also passed. Full live switching
coverage across specialized views and destructive task-action acceptance
remain outstanding.

1. Idle restart and confirm Tasks appears in each native view; switch themes and back.
2. Generate a small video from UI and agent, verify progress, queue, ETA, origin and history.
3. Verify no interruptions when opening or closing Tasks.
4. Queue disposable jobs to verify confirmed targeted cancellation, chain resume, and video retry; never test on valuable jobs.
5. Compare hardware values to native monitor and Task Manager, and check browser console.
6. Assess upstream extension API, translations and cross-platform compatibility before proposing PR.
27 changes: 27 additions & 0 deletions extensions/FreeVideoTaskManager/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Independent FreeVideo Task Manager, no generation or model hooks."""
from pathlib import Path
import shutil
import psutil
from aiohttp import web
from server import PromptServer

NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
WEB_DIRECTORY = "./web"

# Prime the non-blocking counter. No sampling thread, no CUDA calls.
psutil.cpu_percent(interval=None)
ENGINE = Path(__file__).resolve().parents[2] / "FreeVideo-engine"

@PromptServer.instance.routes.get("/freevideo-task-manager/host")
async def task_manager_host(request):
memory = psutil.virtual_memory()
# Same volume as the engine, not necessarily the system drive.
disk = shutil.disk_usage(ENGINE if ENGINE.exists() else ENGINE.parent)
return web.json_response({
"cpu": psutil.cpu_percent(interval=None),
"ram_used": memory.total - memory.available,
"ram_total": memory.total,
"disk_used": disk.used,
"disk_total": disk.total,
}, headers={"Cache-Control": "no-store"})
29 changes: 29 additions & 0 deletions extensions/FreeVideoTaskManager/scripts/build_native_locales.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Regenerate the compatibility catalog from a matching FreeVideo source tree.
// Only literal UI pairs are collected; no prompts, workflows or user data.
import fs from 'node:fs';
import path from 'node:path';
const source=process.argv[2];
const upstreamCatalog=process.argv[3];
if(!source||!upstreamCatalog)throw Error('Usage: node scripts/build_native_locales.mjs <FreeVideo web directory> <native locale directory>');
const en=JSON.parse(fs.readFileSync(path.join(upstreamCatalog,'en.json'),'utf8'));
const zh=JSON.parse(fs.readFileSync(path.join(upstreamCatalog,'zh.json'),'utf8'));
const pt=JSON.parse(fs.readFileSync(path.join(upstreamCatalog,'pt-BR.json'),'utf8'));
const files=['view_navigation','topbar_state','topbar','studio','studio_console','result_actions','sampling_effort','settings_room','settings_words','settings_kit','library','context_menu','image_view','image_view_ui','editor','palette','task_float','tooltip_copy','monitor_panel','generation_progress'];
const literal=String.raw`(?:'(?:\\.|[^'\\\r\n])*'|"(?:\\.|[^"\\\r\n])*")`;
const pair=new RegExp(String.raw`(?:\b(?:t|text|t0|tt)\(\s*|\[\s*)(${literal})\s*,\s*(${literal})\s*(?:\)|\])`,'g');
const pairs=new Map();
function add(a,b){if(typeof a!=='string'||typeof b!=='string'||!a.trim()||!b.trim()||a.length>500||b.length>500||!/[\u3400-\u9fff]/.test(b))return;const key=JSON.stringify([a,b]);pairs.set(key,[a,b]);}
for(const file of files){const src=fs.readFileSync(path.join(source,file+'.js'),'utf8');for(const match of src.matchAll(pair)){
try{add(Function('return '+match[1])(),Function('return '+match[2])());}catch{}
}}
const translated={};
for(const key of Object.keys(en))if(!key.startsWith('progress.')&&!key.startsWith('theme.')&&!key.startsWith('quality.')){translated[en[key]]=pt[key];add(en[key],zh[key]);}
const overrides=[
['Create','创作面板'],['Images','图像视图'],['Nodes','节点视图'],['Edit','剪辑视图'],['Autopilot','AI 全自动'],
['Creations','作品库'],['Ready','就绪'],['Light','轻量'],['Light','浅色'],['Dark','深色'],['Enhance','增强'],
['Media','素材'],['Generate video','生成视频'],['Generate preview','生成预览'],['Extend','接着生成'],
['Share','分享'],['Reuse settings','复用设置'],['Download video','下载视频'],['Settings','设置']
];overrides.forEach(([a,b])=>add(a,b));
const output='// Generated compatibility catalog for FreeVideo 0.6.8. See scripts/build_native_locales.mjs.\nexport const nativePairs = '+JSON.stringify([...pairs.values()].sort((a,b)=>a[0].localeCompare(b[0],'en')||a[1].localeCompare(b[1],'zh'))) + ';\nexport const nativePortugueseLabels = '+JSON.stringify(translated)+';\n';
fs.writeFileSync('web/native_locales.js',output);
console.log('Pairs:',pairs.size,'Portuguese labels:',Object.keys(translated).length);
38 changes: 38 additions & 0 deletions extensions/FreeVideoTaskManager/tests/browser_locale_smoke.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Optional browser smoke test: disposable Chromium profile, no generation.
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
const {spawn}=require('node:child_process');
const chrome=process.env.CHROME_PATH || 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe';
const delay=ms=>new Promise(r=>setTimeout(r,ms));
async function run(locale){
const dir=fs.mkdtempSync(path.join(os.tmpdir(),'fv-locale-test-'));
fs.mkdirSync(path.join(dir,'Default'));
fs.writeFileSync(path.join(dir,'Default','Preferences'),JSON.stringify({intl:{accept_languages:locale}}));
const proc=spawn(chrome,['--headless=new','--disable-gpu','--no-first-run','--no-default-browser-check','--remote-debugging-port=0','--user-data-dir='+dir,'--lang='+locale,'about:blank'],{stdio:'ignore'});
let ws;
try{
const endpoint=path.join(dir,'DevToolsActivePort');
for(let i=0;i<100&&!fs.existsSync(endpoint);i++)await delay(100);
const port=fs.readFileSync(endpoint,'utf8').split(/\r?\n/)[0];
const tabs=await (await fetch('http://127.0.0.1:'+port+'/json/list')).json();
ws=new WebSocket(tabs.find(x=>x.type==='page').webSocketDebuggerUrl);
await new Promise((r,j)=>{ws.onopen=r;ws.onerror=j});
let seq=0;const calls=new Map();
ws.onmessage=e=>{const obj=JSON.parse(e.data);if(obj.id&&calls.has(obj.id)){const [r,j]=calls.get(obj.id);calls.delete(obj.id);obj.error?j(Error(JSON.stringify(obj.error))):r(obj.result);}};
const call=(method,params={})=>new Promise((r,j)=>{let id=++seq;calls.set(id,[r,j]);ws.send(JSON.stringify({id,method,params}));});
await call('Page.enable');
await call('Runtime.enable');
await call('Page.navigate',{url:'http://127.0.0.1:8188/?freevideo=launch'});
let state;
for(let i=0;i<100;i++){
await delay(300);
const r=await call('Runtime.evaluate',{expression:`JSON.stringify({browser:navigator.language, languages:navigator.languages, tabs:[...document.querySelectorAll('.fv-view-switch [data-view=studio]')].map(b=>b.textContent.trim()), code:document.querySelector('.ftm-native-language .language-code')?.textContent, saved:sessionStorage.getItem('freevideo-task-manager.tab-language'), generate:[...document.querySelectorAll('.fvs-key-label')].map(e=>e.textContent.trim())})`,returnByValue:true});
if(!r.result.value)continue;
state=JSON.parse(r.result.value);
if(state.code&&state.tabs.length&&state.generate.length)break;
}
console.log(JSON.stringify({requested:locale,...state}));
const expected=locale.startsWith('pt')?'PT-BR':locale.startsWith('zh')?'中文':'EN';
if(state?.code!==expected||!state.tabs.includes(expected==='PT-BR'?'Criar':expected==='EN'?'Create':'创作面板'))throw Error('First-visit check failed '+JSON.stringify(state));
} finally {ws?.close();proc.kill();await delay(500);try{fs.rmSync(dir,{recursive:true,force:true,maxRetries:2})}catch{}}
}
(async()=>{for(const lang of process.argv.slice(2))await run(lang)})().catch(e=>{console.error(e);process.exitCode=1});
Loading