@kangsicj/nexussync 1.6.20 → 1.6.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -8,7 +8,7 @@
8
8
  // @icon https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/assets/icon.svg
9
9
  // @updateURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.meta.js
10
10
  // @downloadURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.user.js
11
- // @version 1.6.20
11
+ // @version 1.6.21
12
12
  // @description Watch any web video together in perfect sync: cinema mode, live AI subtitles & translation, chat bubbles with auto-translation, quick ink, cover, go-together to the next episode.
13
13
  // @description:ko 어떤 웹 영상이든 완벽한 싱크로 함께 보기: 시네마 모드, 실시간 AI 자막·번역, 자동 번역 말풍선 채팅, 잠깐 그리기, 가리기, 다음 화도 함께.
14
14
  // @match *://*/*
@@ -8,7 +8,7 @@
8
8
  // @icon https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/assets/icon.svg
9
9
  // @updateURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.meta.js
10
10
  // @downloadURL https://cdn.jsdelivr.net/npm/@kangsicj/nexussync@latest/dist/NexusSync.user.js
11
- // @version 1.6.20
11
+ // @version 1.6.21
12
12
  // @description Watch any web video together in perfect sync: cinema mode, live AI subtitles & translation, chat bubbles with auto-translation, quick ink, cover, go-together to the next episode.
13
13
  // @description:ko 어떤 웹 영상이든 완벽한 싱크로 함께 보기: 시네마 모드, 실시간 AI 자막·번역, 자동 번역 말풍선 채팅, 잠깐 그리기, 가리기, 다음 화도 함께.
14
14
  // @match *://*/*
@@ -46,12 +46,12 @@
46
46
 
47
47
  // The version of the code that is actually running (the manager's metadata can lag
48
48
  // behind when an old copy is still installed).
49
- const NXU_VERSION = '1.6.20';
49
+ const NXU_VERSION = '1.6.21';
50
50
  // Rank used by the one-instance guard below and to tell newer builds apart in a room.
51
51
  // It is independent of the public version (1.0.0 is the first public release, after
52
52
  // private builds that reached ranks up to 10.2.0), so every older copy still installed
53
53
  // steps aside instead of this release.
54
- const NXU_RANK = '11.6.20';
54
+ const NXU_RANK = '11.6.21';
55
55
  const NXU_SESSION = Math.random().toString(36).slice(2, 10); // this page load // raise with every release
56
56
  // App icon (same artwork as assets/icon.svg / @icon), inlined so it shows offline too.
57
57
  const NXU_ICON = 'data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTYgMjU2IiByb2xlPSJpbWciIGFyaWEtbGFiZWw9Ik5leHVzU3luYyI+PGRlZnM+PGxpbmVhckdyYWRpZW50IGlkPSJueGJnIiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjNWIyZWZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmY0ZmEzIi8+PC9saW5lYXJHcmFkaWVudD48cmFkaWFsR3JhZGllbnQgaWQ9Im54Z2xvdyIgY3g9IjAuODIiIGN5PSIwLjE0IiByPSIwLjciPjxzdG9wIG9mZnNldD0iMCIgc3RvcC1jb2xvcj0iIzdjZjlmZiIgc3RvcC1vcGFjaXR5PSIwLjU1Ii8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjN2NmOWZmIiBzdG9wLW9wYWNpdHk9IjAiLz48L3JhZGlhbEdyYWRpZW50PjxsaW5lYXJHcmFkaWVudCBpZD0ibnhwbGF5IiB4MT0iMCIgeTE9IjAiIHgyPSIxIiB5Mj0iMSI+PHN0b3Agb2Zmc2V0PSIwIiBzdG9wLWNvbG9yPSIjZmZmZmZmIi8+PHN0b3Agb2Zmc2V0PSIxIiBzdG9wLWNvbG9yPSIjZmZlM2YxIi8+PC9saW5lYXJHcmFkaWVudD48Y2xpcFBhdGggaWQ9Im54ciI+PHJlY3Qgd2lkdGg9IjI1NiIgaGVpZ2h0PSIyNTYiIHJ4PSI1OCIvPjwvY2xpcFBhdGg+PC9kZWZzPjxnIGNsaXAtcGF0aD0idXJsKCNueHIpIj48cmVjdCB3aWR0aD0iMjU2IiBoZWlnaHQ9IjI1NiIgZmlsbD0idXJsKCNueGJnKSIvPjxyZWN0IHdpZHRoPSIyNTYiIGhlaWdodD0iMjU2IiBmaWxsPSJ1cmwoI254Z2xvdykiLz48ZyBmaWxsPSJub25lIiBzdHJva2U9IiNmZmZmZmYiIHN0cm9rZS13aWR0aD0iMTUiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCI+PHBhdGggZD0iTTYwIDExNiBBNzAgNzAgMCAwIDEgMTc4IDcyIi8+PHBhdGggZD0iTTE5NiAxNDAgQTcwIDcwIDAgMCAxIDc4IDE4NCIvPjwvZz48cGF0aCBkPSJNMTg2IDUwIEwyMDAgOTIgTDE1NyA4NiBaIiBmaWxsPSIjZmZmZmZmIi8+PHBhdGggZD0iTTcwIDIwNiBMNTYgMTY0IEw5OSAxNzAgWiIgZmlsbD0iI2ZmZmZmZiIvPjxwYXRoIGQ9Ik0xMTAgOTIgUTEwNCA4OCAxMDQgOTYgTDEwNCAxNjAgUTEwNCAxNjggMTEwIDE2NCBMMTYyIDEzMiBRMTY4IDEyOCAxNjIgMTI0IFoiIGZpbGw9InVybCgjbnhwbGF5KSIvPjwvZz48L3N2Zz4=';
@@ -122,6 +122,7 @@ async function handle(m) {
122
122
  if (m.cmd === 'status') send({ type: 'status', id: m.id, cached: await cacheHas(m.urls || []), gpu: !!navigator.gpu, f16: navigator.gpu ? await navigator.gpu.requestAdapter().then(a => !!a && a.features.has('shader-f16')).catch(() => false) : false });
123
123
  else if (m.cmd === 'load') getWorker().postMessage({ type: 'load', id: m.id, lib: LIB, ort: '1.31.0-dev.20260914-8d85527a0', repo: m.repo, device: m.device, dtype: m.dtype });
124
124
  else if (m.cmd === 'run') getWorker().postMessage({ type: 'run', id: m.id, audio: m.audio, lang: m.lang }, [m.audio.buffer]);
125
+ else if (m.cmd === 'recycle') { if (worker) { worker.terminate(); worker = null; } send({ type: 'recycled', id: m.id }); }
125
126
  else if (m.cmd === 'remove') {
126
127
  const c = await caches.open('transformers-cache');
127
128
  for (const req of await c.keys()) if (req.url.includes('/' + m.repo + '/')) await c.delete(req);
@@ -702,13 +703,18 @@ async function handle(m) {
702
703
  // ───────────────────────── UI language (Korean / English)
703
704
  const I18N = {
704
705
  en: {
705
- asrEngine: 'Speech recognition engine', asrBrowser: 'Browser built-in (free)', asrOpenAI: 'OpenAI gpt-4o-mini-transcribe (fast, accurate)', asrOpenAIHQ: 'OpenAI gpt-4o-transcribe (best accuracy)',
706
- asrLocal: 'Whisper offline (on this device, free, no key)', whisperModel_base: 'Whisper base · fast · {mb} MB', whisperModel_small: 'Whisper small · more accurate, slower · {mb} MB', whisperModel_turbo: 'Whisper large-v3 turbo · best · {mb} MB · needs a graphics card (WebGPU)', whisperDownload: 'Download ({mb} MB)', whisperRemove: 'Remove', whisperChecking: 'Checking…', whisperReady: 'Ready (offline)', whisperDownloading: 'Downloading the model — only this once on this site, then it works offline.', whisperDone: 'Offline Whisper is ready', whisperFailed: 'The Whisper download failed — check the connection and try again', whisperHelp: 'Open-source speech recognition that runs on this device: nothing is sent anywhere, no key needed. Downloaded once per site, then it works offline.', whisperReadyHelp: 'Recognition runs on this device. Bigger models are more accurate but slower.', whisperNeedsGpu: 'Needs a graphics card', whisperGpuHelp: 'This model needs WebGPU with 16-bit support, which this browser or PC does not offer. Pick base or small.', whisperBlocked: 'Not available here', whisperBlockedHelp: 'The helper NexusSync needs could not start here (blocked by the site, or the userscript manager does not run in frames). Allow it to run in frames, or use another site.', whisperBlockedHere: '⚠️ Offline Whisper cannot start on this site — using the browser engine.',
706
+ asrEngine: 'Speech recognition engine', asrBrowser: 'Browser built-in (online, free)', secAsr: 'Speech recognition', secTx: 'Translation', secView: 'Display',
707
+ asrHelp_browser: 'Your browser\'s own recognition (Chrome/Edge send the sound to their speech service). Fast; quality varies with noise and accents.',
708
+ asrHelp_local: 'Open-source Whisper runs inside this browser — nothing is sent anywhere, no key. Downloaded once (below); uses the processor, so a slower computer lags behind.',
709
+ asrHelp_openai: 'OpenAI recognises the sound in the cloud with your key. Very accurate, also with background noise. Billed to your account.',
710
+ asrHelp_groq: 'Groq runs Whisper large-v3 turbo in the cloud with your key. Very fast and accurate; generous free tier.', asrOpenAI: 'OpenAI gpt-4o-mini-transcribe (fast, accurate)', asrOpenAIHQ: 'OpenAI gpt-4o-transcribe (best accuracy)',
711
+ asrLocal: 'Whisper (on this device, offline, no key)', whisperModel_base: 'Whisper base · fast · {mb} MB', whisperModel_small: 'Whisper small · more accurate, slower · {mb} MB', whisperModel_turbo: 'Whisper large-v3 turbo · best · {mb} MB · needs a graphics card (WebGPU)', whisperDownload: 'Download ({mb} MB)', whisperRemove: 'Remove', whisperChecking: 'Checking…', whisperReady: 'Ready (offline)', whisperDownloading: 'Downloading the model — only this once on this site, then it works offline.', whisperDone: 'Offline Whisper is ready', whisperFailed: 'The Whisper download failed — check the connection and try again', whisperHelp: 'Open-source speech recognition that runs on this device: nothing is sent anywhere, no key needed. Downloaded once per site, then it works offline.', whisperReadyHelp: 'Recognition runs on this device. Bigger models are more accurate but slower.', whisperNeedsGpu: 'Needs a graphics card', whisperGpuHelp: 'This model needs WebGPU with 16-bit support, which this browser or PC does not offer. Pick base or small.', whisperBlocked: 'Not available here', whisperBlockedHelp: 'The helper NexusSync needs could not start here (blocked by the site, or the userscript manager does not run in frames). Allow it to run in frames, or use another site.', whisperBlockedHere: '⚠️ Offline Whisper cannot start on this site — using the browser engine.',
707
712
  asrGroq: 'Groq Whisper large-v3 turbo (very fast)', providerClaude: 'Claude (context-aware, most natural)', providerGPT: 'GPT (context-aware)', providerDeepL: 'DeepL',
708
713
  engineHelp: 'AI engines (OpenAI, Claude, Groq, DeepL) use your own API key and give the best accuracy; without a key the free engines are used.',
709
714
  aiNeedKey: 'Enter the {names} API key under Advanced — until then the free engine is used.', aiKeys: 'API keys', aiTest: 'Test',
710
715
  aiKeysHelp: 'Keys are saved only in your userscript manager and sent only to that provider. Usage is billed to your account.',
711
716
  modelHelp: 'Optional: override the model name (leave empty for the recommended default).', aiNoKey: 'No API key entered.', aiKeyOk: 'Key works ✓',
717
+ subHearing: 'Recognising…', aiKeyFormat: '🔑 That does not look like a {name} key (it starts with {ph}). Not saved.', aiKeyAutofill: '🔑 The browser filled in a saved password — ignored. Paste the {name} key yourself.',
712
718
  aiKeyInvalid: '🔑 The AI API key was rejected — check it in AI Sub → Advanced. Using the free engine.', cloudAsrFallback: '⚠️ Cloud speech recognition unavailable — switched to browser recognition.',
713
719
  ccSiteControls: "Use the site's own player controls", ccNexusControls: 'Use NexusSync cinema controls', ccModeSite: '🎬 Using the site player controls', ccModeNexus: '🎛 Using cinema controls', ccToSite: 'Site controls', ccToNexus: 'Cinema controls',
714
720
  ccSeek: 'Seek', ccPlay: 'Play (Space)', ccPause: 'Pause (Space)', ccBack: 'Back 10s (J / ←)', ccForward: 'Forward 10s (L / →)', ccMute: 'Mute (M)', ccVolume: 'Volume (↑/↓)',
@@ -740,7 +746,7 @@ async function handle(m) {
740
746
  you: 'You', roomBuffering: '⏳ {name} is loading… everyone waits', roomResume: '▶️ Everyone is ready — playing together', roomRate: '⏩ Speed {rate}x synced',
741
747
  youBuffering: '⏳ Your video is loading — the room waits for you', shieldResumeTitle: 'Tap to rejoin playback', shieldResumeText: 'The browser paused this video. Tap once to continue in sync with the room.',
742
748
  shieldResumeButton: 'RESUME ▶️', rateTitle: 'Playback speed (shared with the room)', rateSet: '⏩ Speed {rate}x', resynced: 'Re-synced with the room',
743
- offlineDownload: 'Download offline models', offlineHelp: 'Downloads on-device speech/translation for the selected languages (faster, private, no network needed later). Best done before watching.',
749
+ offlineDownload: 'Get browser language packs', offlineHelp: 'Chrome/Edge\'s own speech and translation packs for the chosen languages, used by the browser engine. This is not Whisper — Whisper downloads its own model when you choose it above.',
744
750
  offlineDownloading: '⬇️ Downloading offline models…', offlineReady: '✅ Offline models ready', offlineUnsupported: 'This browser has no downloadable offline models for these languages.',
745
751
  findMedia: 'Find Media', connect: 'Connect', disconnect: 'Disconnect', connecting: 'Connecting…', loading: 'Loading…', offline: 'Offline', sync: 'Sync',
746
752
  cinema: 'Cinema', cinemaTitle: 'Fill the window with the video (Alt+Shift+C, Esc to exit)', cinemaOn: '🍿 Cinema ON', cinemaOff: '🍿 Cinema OFF',
@@ -804,7 +810,7 @@ async function handle(m) {
804
810
  subPosition: 'Subtitle position', posVideo: 'Over the video', posScreen: 'Bottom of the screen', subSize: 'Size', subOpacity: 'Opacity',
805
811
  advanced: 'Advanced', translationEngine: 'Translation engine', providerAuto: 'Google first, on-device as backup (best quality)', providerBrowser: 'On-device only (private)',
806
812
  providerGoogle: 'Google only', providerHelp: 'Online translation reads whole sentences far better; the on-device model shows the live line and steps in when offline.',
807
- localFirst: 'Prefer on-device speech recognition', localFirstHelp: 'Uses the offline speech model when the browser has it installed.',
813
+ localFirst: 'Use the browser\'s on-device language pack', localFirstHelp: 'When the pack is installed the browser recognises speech on this device instead of its online service.',
808
814
  hotkeyHelp: 'Shortcuts: Alt+Shift+T subtitles · Alt+Shift+C cinema · Alt+Shift+N menu · in cinema: Space, ←/→, ↑/↓, M, F',
809
815
  subStart: 'Start subtitles', subStop: 'Stop subtitles', subStarting: 'Starting…', subStatusIdle: 'Ready. Choose the languages, then press Start.',
810
816
  subStatusStarting: 'Preparing audio input…', subListening: 'Listening', auto: 'Auto', inputMic: 'mic', inputMedia: 'video audio',
@@ -829,13 +835,18 @@ async function handle(m) {
829
835
  menuCinema: 'Toggle cinema mode', menuSubtitles: 'Start / stop AI subtitles', menuShowButton: 'Show / hide the NexusSync button on this site'
830
836
  },
831
837
  ko: {
832
- asrEngine: '음성 인식 엔진', asrBrowser: '브라우저 내장 (무료)', asrOpenAI: 'OpenAI gpt-4o-mini-transcribe (빠르고 정확)', asrOpenAIHQ: 'OpenAI gpt-4o-transcribe (최고 정확도)',
833
- asrLocal: 'Whisper 오프라인 (이 기기에서, 무료, 키 없음)', whisperModel_base: 'Whisper base · 빠름 · {mb}MB', whisperModel_small: 'Whisper small · 더 정확, 느림 · {mb}MB', whisperModel_turbo: 'Whisper large-v3 turbo · 최고 · {mb}MB · 그래픽카드(WebGPU) 필요', whisperDownload: '다운로드 ({mb}MB)', whisperRemove: '삭제', whisperChecking: '확인 중…', whisperReady: '준비됨 (오프라인)', whisperDownloading: '모델을 받는 중이에요 — 이 사이트에서는 이번 한 번만 받고, 이후엔 오프라인으로 동작해요.', whisperDone: '오프라인 Whisper 준비 완료', whisperFailed: 'Whisper 다운로드에 실패했어요 — 연결을 확인하고 다시 시도해 주세요', whisperHelp: '이 기기에서 직접 돌아가는 오픈소스 음성 인식이에요. 어디에도 보내지 않고 키도 필요 없어요. 사이트마다 한 번 받으면 이후엔 오프라인으로 동작해요.', whisperReadyHelp: '음성 인식이 이 기기에서 돌아가요. 큰 모델일수록 정확하지만 더 느려요.', whisperNeedsGpu: '그래픽카드 필요', whisperGpuHelp: '이 모델은 16비트를 지원하는 WebGPU가 필요한데, 이 브라우저나 PC에서는 쓸 수 없어요. base나 small을 골라 주세요.', whisperBlocked: '여기서는 쓸 수 없음', whisperBlockedHelp: 'NexusSync가 쓰는 도우미가 여기서 시작되지 못했어요 (사이트가 막았거나, 유저스크립트 관리자가 프레임 안에서 실행되지 않아요). 프레임 안 실행을 허용하거나 다른 사이트에서 써 주세요.', whisperBlockedHere: '⚠️ 이 사이트에서는 오프라인 Whisper를 시작할 수 없어 브라우저 엔진을 써요.',
838
+ asrEngine: '음성 인식 엔진', asrBrowser: '브라우저 내장 (온라인, 무료)', secAsr: '음성 인식', secTx: '번역', secView: '표시',
839
+ asrHelp_browser: '브라우저 자체 음성 인식이에요 (Chrome/Edge는 소리를 자사 음성 서비스로 보내 인식). 빠르지만 소음·억양에 따라 품질이 달라요.',
840
+ asrHelp_local: '오픈소스 Whisper가 이 브라우저 안에서 직접 돌아가요. 어디에도 보내지 않고 키도 필요 없어요. 아래에서 한 번 받으면 되고, 컴퓨터 성능(CPU)을 쓰기 때문에 느린 기기에선 밀릴 수 있어요.',
841
+ asrHelp_openai: 'OpenAI 클라우드가 키로 인식해요. 배경 소음이 있어도 매우 정확해요. 사용량은 본인 계정으로 청구돼요.',
842
+ asrHelp_groq: 'Groq 클라우드에서 Whisper large-v3 turbo로 키를 써서 인식해요. 매우 빠르고 정확하며 무료 사용량이 넉넉해요.', asrOpenAI: 'OpenAI gpt-4o-mini-transcribe (빠르고 정확)', asrOpenAIHQ: 'OpenAI gpt-4o-transcribe (최고 정확도)',
843
+ asrLocal: 'Whisper (이 기기에서, 오프라인, 키 없음)', whisperModel_base: 'Whisper base · 빠름 · {mb}MB', whisperModel_small: 'Whisper small · 더 정확, 느림 · {mb}MB', whisperModel_turbo: 'Whisper large-v3 turbo · 최고 · {mb}MB · 그래픽카드(WebGPU) 필요', whisperDownload: '다운로드 ({mb}MB)', whisperRemove: '삭제', whisperChecking: '확인 중…', whisperReady: '준비됨 (오프라인)', whisperDownloading: '모델을 받는 중이에요 — 이 사이트에서는 이번 한 번만 받고, 이후엔 오프라인으로 동작해요.', whisperDone: '오프라인 Whisper 준비 완료', whisperFailed: 'Whisper 다운로드에 실패했어요 — 연결을 확인하고 다시 시도해 주세요', whisperHelp: '이 기기에서 직접 돌아가는 오픈소스 음성 인식이에요. 어디에도 보내지 않고 키도 필요 없어요. 사이트마다 한 번 받으면 이후엔 오프라인으로 동작해요.', whisperReadyHelp: '음성 인식이 이 기기에서 돌아가요. 큰 모델일수록 정확하지만 더 느려요.', whisperNeedsGpu: '그래픽카드 필요', whisperGpuHelp: '이 모델은 16비트를 지원하는 WebGPU가 필요한데, 이 브라우저나 PC에서는 쓸 수 없어요. base나 small을 골라 주세요.', whisperBlocked: '여기서는 쓸 수 없음', whisperBlockedHelp: 'NexusSync가 쓰는 도우미가 여기서 시작되지 못했어요 (사이트가 막았거나, 유저스크립트 관리자가 프레임 안에서 실행되지 않아요). 프레임 안 실행을 허용하거나 다른 사이트에서 써 주세요.', whisperBlockedHere: '⚠️ 이 사이트에서는 오프라인 Whisper를 시작할 수 없어 브라우저 엔진을 써요.',
834
844
  asrGroq: 'Groq Whisper large-v3 turbo (매우 빠름)', providerClaude: 'Claude (문맥 이해, 가장 자연스러움)', providerGPT: 'GPT (문맥 이해)', providerDeepL: 'DeepL',
835
845
  engineHelp: 'AI 엔진(OpenAI·Claude·Groq·DeepL)은 본인 API 키로 동작하며 정확도가 가장 높습니다. 키가 없으면 무료 엔진을 사용합니다.',
836
846
  aiNeedKey: '고급 설정에서 {names} API 키를 입력하세요 — 그전까지는 무료 엔진을 사용합니다.', aiKeys: 'API 키', aiTest: '확인',
837
847
  aiKeysHelp: '키는 유저스크립트 관리자에만 저장되고 해당 회사로만 전송됩니다. 사용량은 본인 계정으로 청구됩니다.',
838
848
  modelHelp: '선택: 모델 이름을 직접 지정 (비워 두면 권장 기본값).', aiNoKey: 'API 키가 입력되지 않았습니다.', aiKeyOk: '키 정상 ✓',
849
+ subHearing: '인식 중…', aiKeyFormat: '🔑 {name} 키 형식이 아니에요 ({ph} 로 시작). 저장하지 않았어요.', aiKeyAutofill: '🔑 브라우저가 저장된 비밀번호를 자동으로 채웠어요 — 무시했어요. {name} 키를 직접 붙여넣어 주세요.',
839
850
  aiKeyInvalid: '🔑 AI API 키가 거부되었습니다 — AI 자막 → 고급에서 확인하세요. 무료 엔진으로 계속합니다.', cloudAsrFallback: '⚠️ 클라우드 음성 인식을 사용할 수 없어 브라우저 인식으로 전환했습니다.',
840
851
  ccSiteControls: '사이트 자체 플레이어 컨트롤 사용', ccNexusControls: 'NexusSync 시네마 컨트롤 사용', ccModeSite: '🎬 사이트 플레이어 컨트롤 사용 중', ccModeNexus: '🎛 시네마 컨트롤 사용 중', ccToSite: '사이트 컨트롤', ccToNexus: '시네마 컨트롤',
841
852
  ccSeek: '탐색', ccPlay: '재생 (Space)', ccPause: '일시정지 (Space)', ccBack: '10초 뒤로 (J / ←)', ccForward: '10초 앞으로 (L / →)', ccMute: '음소거 (M)', ccVolume: '볼륨 (↑/↓)',
@@ -867,7 +878,7 @@ async function handle(m) {
867
878
  you: '나', roomBuffering: '⏳ {name} 기기 로딩 중… 모두 잠시 대기', roomResume: '▶️ 모두 준비됨 — 함께 재생합니다', roomRate: '⏩ {rate}배속 동기화',
868
879
  youBuffering: '⏳ 이 기기 영상 로딩 중 — 방이 기다려 줍니다', shieldResumeTitle: '탭해서 다시 재생', shieldResumeText: '브라우저가 이 영상을 멈췄습니다. 한 번 탭하면 방과 맞춰 이어서 재생합니다.',
869
880
  shieldResumeButton: '이어서 재생 ▶️', rateTitle: '재생 속도 (방 전체와 공유)', rateSet: '⏩ {rate}배속', resynced: '방과 다시 맞췄습니다',
870
- offlineDownload: '오프라인 모델 다운로드', offlineHelp: '선택한 언어의 기기 내 음성 인식·번역 모델을 받습니다 (더 빠르고, 개인정보 보호, 이후 네트워크 불필요). 시청 전에 받아 두세요.',
881
+ offlineDownload: '브라우저 언어팩 받기', offlineHelp: '선택한 언어의 Chrome/Edge 자체 음성 인식·번역 언어팩이에요. 브라우저 내장 엔진이 사용해요. Whisper와는 다른 엔진이며, Whisper는 위에서 선택하면 자체 모델을 따로 받아요.',
871
882
  offlineDownloading: '⬇️ 오프라인 모델 다운로드 중…', offlineReady: '✅ 오프라인 모델 준비 완료', offlineUnsupported: '이 브라우저는 해당 언어의 오프라인 모델을 지원하지 않습니다.',
872
883
  findMedia: '미디어 찾기', connect: '연결', disconnect: '연결 해제', connecting: '연결 중…', loading: '불러오는 중…', offline: '오프라인', sync: '동기화',
873
884
  cinema: '시네마', cinemaTitle: '영상을 창 전체로 크게 보기 (Alt+Shift+C, Esc로 종료)', cinemaOn: '🍿 시네마 모드 켜짐', cinemaOff: '🍿 시네마 모드 꺼짐',
@@ -931,7 +942,7 @@ async function handle(m) {
931
942
  subPosition: '자막 위치', posVideo: '영상 위', posScreen: '화면 하단', subSize: '크기', subOpacity: '불투명도',
932
943
  advanced: '고급', translationEngine: '번역 엔진', providerAuto: 'Google 우선, 기기 내 번역 보조 (최고 품질)', providerBrowser: '기기 내 번역만 (개인정보 보호)',
933
944
  providerGoogle: 'Google만', providerHelp: '문장 번역 품질은 온라인(Google)이 훨씬 좋습니다. 기기 내 모델은 실시간 임시 줄과 오프라인 상황을 맡습니다.',
934
- localFirst: '기기 내 음성 인식 우선', localFirstHelp: '브라우저에 오프라인 음성 모델이 설치되어 있으면 사용합니다.',
945
+ localFirst: '브라우저 언어팩으로 기기 내 인식', localFirstHelp: '언어팩이 설치되어 있으면 브라우저가 온라인 서비스 대신 이 기기에서 인식해요.',
935
946
  hotkeyHelp: '단축키: Alt+Shift+T 자막 · Alt+Shift+C 시네마 · Alt+Shift+N 메뉴 · 시네마 중: Space, ←/→, ↑/↓, M, F',
936
947
  subStart: '자막 시작', subStop: '자막 중지', subStarting: '시작하는 중…', subStatusIdle: '준비됨. 언어를 고른 뒤 시작을 누르세요.',
937
948
  subStatusStarting: '오디오 입력 준비 중…', subListening: '듣는 중', auto: '자동', inputMic: '마이크', inputMedia: '영상 소리',
@@ -3360,7 +3371,7 @@ async function handle(m) {
3360
3371
  logDebug('AI Sub: the speech engine returns no words here (' + (this._diag.empty || 0) + ' empty results).', 'error');
3361
3372
  if (key && STORE.get('nxu_asr_provider', 'browser') === 'browser') {
3362
3373
  showToast(t('subNoWordsKey'));
3363
- STORE.set('nxu_asr_provider', AI.key('groq') ? 'groq' : 'openai');
3374
+ STORE.set('nxu_asr_provider', AI.key('groq') ? 'groq' : 'openai'); STORE.set('nxu_asr_auto', '1');
3364
3375
  this.restart('no words from the browser engine');
3365
3376
  } else showToast(t(/\bEdg\//.test(navigator.userAgent) ? 'subNoWordsEdge' : 'subNoWords'));
3366
3377
  }
@@ -3732,7 +3743,7 @@ async function handle(m) {
3732
3743
  this.stop(t(policy ? (cloudKey ? 'subSiteBlocksSpeechKey' : 'subSiteBlocksSpeech') : 'subMicDenied'));
3733
3744
  // With a key, cloud recognition does not need the browser's speech engine.
3734
3745
  if (policy && cloudKey && STORE.get('nxu_asr_provider', 'browser') === 'browser') {
3735
- STORE.set('nxu_asr_provider', AI.key('groq') ? 'groq' : 'openai');
3746
+ STORE.set('nxu_asr_provider', AI.key('groq') ? 'groq' : 'openai'); STORE.set('nxu_asr_auto', '1');
3736
3747
  setTimeout(() => this.start().catch(() => { }), 400);
3737
3748
  }
3738
3749
  return;
@@ -3772,7 +3783,7 @@ async function handle(m) {
3772
3783
  logDebug('AI Sub: the browser speech service is unreachable here.', 'error');
3773
3784
  this.stop(t(cloudKey ? 'subNoServiceKey' : 'subNoService'));
3774
3785
  if (cloudKey && STORE.get('nxu_asr_provider', 'browser') === 'browser') {
3775
- STORE.set('nxu_asr_provider', AI.key('groq') ? 'groq' : 'openai');
3786
+ STORE.set('nxu_asr_provider', AI.key('groq') ? 'groq' : 'openai'); STORE.set('nxu_asr_auto', '1');
3776
3787
  setTimeout(() => this.start().catch(() => { }), 400);
3777
3788
  }
3778
3789
  return;
@@ -3835,6 +3846,7 @@ async function handle(m) {
3835
3846
  this._openSentence = fragment ? { job, at: now } : null;
3836
3847
  this._lastCommitted = { text: job.text, at: now };
3837
3848
  this._queue.push(job);
3849
+ this._showPending(job);
3838
3850
  while (this._queue.length > 10) {
3839
3851
  const dropped = this._queue.shift();
3840
3852
  this._done.set(dropped.seq, null);
@@ -4131,9 +4143,11 @@ async function handle(m) {
4131
4143
  overlay.id = 'nxu-subtitle-overlay';
4132
4144
  const finalSlot = createEl('div', 'sub-slot');
4133
4145
  finalSlot.id = 'nxu-final-slot';
4146
+ const pendingSlot = createEl('div', 'sub-slot');
4147
+ pendingSlot.id = 'nxu-pending-slot';
4134
4148
  const interimSlot = createEl('div', 'sub-slot');
4135
4149
  interimSlot.id = 'nxu-interim-slot';
4136
- overlay.append(finalSlot, interimSlot);
4150
+ overlay.append(finalSlot, pendingSlot, interimSlot);
4137
4151
  getContainer()?.appendChild(overlay);
4138
4152
  applySubtitlePrefs();
4139
4153
  }
@@ -4188,6 +4202,48 @@ async function handle(m) {
4188
4202
  this._mirror({ mode: 'interim', text: this._interimTranslation ? this._interimTranslation + ' …' : value + ' …', original: this._interimTranslation ? value : '', color: meta.speakerColor });
4189
4203
  });
4190
4204
  },
4205
+ // ── live feedback: "hearing…" while a piece is being recognised, then the recognised
4206
+ // words at once (typed in) with a shimmer while the translation is made; the
4207
+ // translated line then lands in its place.
4208
+ _pendingSlot() { this.getOverlay(); return shadow?.getElementById('nxu-pending-slot') || null; },
4209
+ _showHeard() {
4210
+ if (!this.active || this._pendingInterim) return;
4211
+ const slot = this._pendingSlot();
4212
+ if (!slot || slot.firstElementChild) return;
4213
+ const meta = this._meta('interim');
4214
+ const card = createEl('div', 'sub-caption-card sub-caption-interim sub-pending sub-hearing');
4215
+ card.style.setProperty('--speaker-color', meta.speakerColor || '#00e676');
4216
+ const wave = createEl('span', 'sub-hear');
4217
+ for (let i = 0; i < 5; i++) wave.appendChild(document.createElement('i'));
4218
+ card.append(wave, createEl('span', 'sub-hear-label', t('subHearing')));
4219
+ slot.appendChild(card);
4220
+ slot.style.opacity = '1';
4221
+ clearTimeout(this._pendingTimer);
4222
+ this._pendingTimer = setTimeout(() => this._clearPending(), 7000);
4223
+ },
4224
+ _showPending(job) {
4225
+ if (!this.active || !job?.raw) return;
4226
+ const slot = this._pendingSlot();
4227
+ if (!slot) return;
4228
+ const card = this._buildCard('sub-caption-interim sub-pending', job.raw, '', job.meta || this._meta('final'));
4229
+ card.querySelector('.sub-caption-body')?.appendChild(createEl('div', 'sub-pending-bar'));
4230
+ card.dataset.seq = String(job.seq);
4231
+ slot.replaceChildren(card);
4232
+ slot.style.opacity = '1';
4233
+ this._pendingSeq = job.seq;
4234
+ if (!this._pendingInterim) this._mirror({ mode: 'interim', text: job.raw + ' …', original: '', color: (job.meta || {}).speakerColor || '#00e676' });
4235
+ clearTimeout(this._pendingTimer);
4236
+ this._pendingTimer = setTimeout(() => this._clearPending(), 12000);
4237
+ },
4238
+ _clearPending(upTo = Infinity) {
4239
+ const slot = shadow?.getElementById('nxu-pending-slot');
4240
+ const card = slot?.firstElementChild;
4241
+ if (!card) return;
4242
+ const seq = +(card.dataset.seq || 0);
4243
+ if (seq && seq > upTo) return;
4244
+ clearTimeout(this._pendingTimer);
4245
+ slot.replaceChildren();
4246
+ },
4191
4247
  _setInterimTranslation(text) {
4192
4248
  this._interimTranslation = this._normalize(text);
4193
4249
  if (this._pendingInterim) this._renderInterim(this._pendingInterim);
@@ -4246,6 +4302,7 @@ async function handle(m) {
4246
4302
  if (item) job.historyItems.push(item);
4247
4303
  this.getOverlay();
4248
4304
  const slot = shadow?.getElementById('nxu-final-slot');
4305
+ this._clearPending(job.seq);
4249
4306
  if (slot) {
4250
4307
  const card = this._buildCard('sub-caption-final text-morph', out, src, meta);
4251
4308
  const previous = slot.querySelector('.sub-caption-final:not(.prev)');
@@ -4436,6 +4493,8 @@ async function handle(m) {
4436
4493
  this._cloud = false;
4437
4494
  CLOUD_ASR.stop();
4438
4495
  const bad = err?.status === 401 || err?.status === 403;
4496
+ // A switch made automatically is undone when the key is refused.
4497
+ if (bad && STORE.get('nxu_asr_auto', '')) { STORE.set('nxu_asr_provider', 'browser'); STORE.set('nxu_asr_auto', ''); }
4439
4498
  showToast(t(err?.code === 'helper' ? 'whisperBlockedHere' : bad ? 'aiKeyInvalid' : 'cloudAsrFallback'));
4440
4499
  const SR = window.SpeechRecognition || window.webkitSpeechRecognition;
4441
4500
  if (SR && this.active && !this.recognizer) {
@@ -4459,6 +4518,9 @@ async function handle(m) {
4459
4518
  try { this._abortCtrl?.abort(); } catch (_) { }
4460
4519
  this._abortCtrl = null;
4461
4520
  CLOUD_ASR.stop();
4521
+ // Offline Whisper's memory is given back a while after AI Sub stops.
4522
+ clearTimeout(LOCAL_WHISPER._idleT);
4523
+ LOCAL_WHISPER._idleT = setTimeout(() => { if (!TRANSLATOR.active) LOCAL_WHISPER.release(); }, 120000);
4462
4524
  this._destroyRecognizer();
4463
4525
  this._stopAudioCapture();
4464
4526
  this._restoreAppleSession();
@@ -4471,6 +4533,7 @@ async function handle(m) {
4471
4533
  if (overlay) {
4472
4534
  overlay.style.opacity = '0';
4473
4535
  shadow.getElementById('nxu-final-slot')?.replaceChildren();
4536
+ shadow.getElementById('nxu-pending-slot')?.replaceChildren();
4474
4537
  shadow.getElementById('nxu-interim-slot')?.replaceChildren();
4475
4538
  }
4476
4539
  this._mirror({ mode: 'clear' });
@@ -4976,7 +5039,21 @@ async function handle(m) {
4976
5039
  ];
4977
5040
 
4978
5041
  const AI = {
4979
- key(name) { return String(STORE.get('nxu_key_' + name, '') || '').trim(); },
5042
+ // Each provider's keys have a recognisable shape. Anything else (most often the
5043
+ // browser's saved site password, autofilled into the key box) is never sent.
5044
+ KEY_FORMATS: { openai: /^sk-[A-Za-z0-9_-]{20,}$/, anthropic: /^sk-ant-[A-Za-z0-9_-]{20,}$/, groq: /^gsk_[A-Za-z0-9]{20,}$/, deepl: /^[0-9a-f][0-9a-f-]{30,}(:fx)?$/i },
5045
+ validKey(name, value) { const re = this.KEY_FORMATS[name]; return !!value && (!re || re.test(value)); },
5046
+ key(name) {
5047
+ const value = String(STORE.get('nxu_key_' + name, '') || '').trim();
5048
+ if (!value) return '';
5049
+ if (this.validKey(name, value)) return value;
5050
+ STORE.set('nxu_key_' + name, '');
5051
+ // A cloud engine that only had that bogus key goes back to the browser's engine.
5052
+ const asr = STORE.get('nxu_asr_provider', 'browser');
5053
+ if (((asr === 'openai' || asr === 'openai-hq') && !this.key('openai')) || (asr === 'groq' && !this.key('groq'))) { STORE.set('nxu_asr_provider', 'browser'); STORE.set('nxu_asr_auto', ''); }
5054
+ logDebug(`AI: the saved ${name} key is not an API key (probably filled in by the browser's password manager) — removed, never sent.`, 'warn');
5055
+ return '';
5056
+ },
4980
5057
  asrProvider() {
4981
5058
  const p = STORE.get('nxu_asr_provider', 'browser');
4982
5059
  if (p === 'local' && LOCAL_WHISPER.available() && STORE.get('nxu_whisper_ready_' + LOCAL_WHISPER.model(), false)) return p;
@@ -5253,14 +5330,61 @@ async function handle(m) {
5253
5330
  return true;
5254
5331
  },
5255
5332
  async remove(id = this.model()) { await this._call({ cmd: 'remove', repo: this.MODELS[id].repo }, { timeout: 20000 }); if (this._loaded === id) this._loaded = ''; },
5256
- async transcribe(samples, lang) {
5257
- if (this._queue > 3) { logDebug('AI Sub: offline Whisper is behind; skipping a line to catch up.', 'warn'); return ''; }
5258
- this._queue++;
5333
+ // One piece runs at a time. Pieces that arrive meanwhile wait and are joined into one
5334
+ // run (up to 28 s of audio), so a backlog is caught up instead of lines being dropped;
5335
+ // the joined text goes to the first of them, in speaking order.
5336
+ _waiting: [], _busy: false, _runs: 0,
5337
+ transcribe(samples, lang) {
5338
+ return new Promise((resolve, reject) => {
5339
+ this._waiting.push({ samples, lang: lang || '', resolve, reject });
5340
+ this._queue = this._waiting.length;
5341
+ this._drain();
5342
+ });
5343
+ },
5344
+ async _drain() {
5345
+ if (this._busy || !this._waiting.length) return;
5346
+ this._busy = true;
5347
+ const group = [this._waiting.shift()];
5348
+ let total = group[0].samples.length;
5349
+ while (this._waiting.length && this._waiting[0].lang === group[0].lang && total + this._waiting[0].samples.length <= 16000 * 28) {
5350
+ const next = this._waiting.shift();
5351
+ total += next.samples.length + 1600;
5352
+ group.push(next);
5353
+ }
5354
+ this._queue = this._waiting.length;
5355
+ let audio = group[0].samples;
5356
+ if (group.length > 1) {
5357
+ audio = new Float32Array(total);
5358
+ let o = 0;
5359
+ group.forEach((g, i) => { audio.set(g.samples, o); o += g.samples.length + (i < group.length - 1 ? 1600 : 0); });
5360
+ logDebug(`AI Sub: offline Whisper was behind; joined ${group.length} pieces into one run.`, 'info');
5361
+ }
5259
5362
  try {
5363
+ // A long session grows the model runtime's memory; start it afresh now and then.
5364
+ if (this._runs >= 150 && this._frame) { this._runs = 0; await this.recycle(); }
5260
5365
  await this.load();
5261
- const r = await this._call({ cmd: 'run', audio: samples, lang: lang || '' }, { transfer: [samples.buffer], timeout: 120000 });
5262
- return String(r.text || '').trim();
5263
- } finally { this._queue--; }
5366
+ const r = await this._call({ cmd: 'run', audio, lang: group[0].lang }, { transfer: [audio.buffer], timeout: 60000 });
5367
+ this._runs++;
5368
+ const text = String(r.text || '').trim();
5369
+ group.forEach((g, i) => g.resolve(i ? '' : text));
5370
+ } catch (err) {
5371
+ group.forEach(g => g.reject(err));
5372
+ } finally {
5373
+ this._busy = false;
5374
+ this._queue = this._waiting.length;
5375
+ if (this._waiting.length) this._drain();
5376
+ }
5377
+ },
5378
+ async recycle() {
5379
+ try { await this._call({ cmd: 'recycle' }, { timeout: 5000 }); } catch (_) { }
5380
+ this._loaded = '';
5381
+ logDebug('AI Sub: offline Whisper restarted to free memory.', 'info');
5382
+ },
5383
+ // Leaving AI Sub frees the model's memory (it loads again from the cache next time).
5384
+ release() {
5385
+ this._waiting.splice(0).forEach(g => g.resolve(''));
5386
+ this._queue = 0;
5387
+ if (this._frame && this._loaded) this.recycle();
5264
5388
  }
5265
5389
  };
5266
5390
 
@@ -5268,8 +5392,9 @@ async function handle(m) {
5268
5392
  RATE: 16000,
5269
5393
  FRAME: 320, // 20 ms
5270
5394
  PREROLL: 15, // 300 ms
5271
- END_SILENCE: 35, // 700 ms of quiet ends an utterance
5395
+ END_SILENCE: 24, // 480 ms of quiet ends an utterance
5272
5396
  MAX_FRAMES: 650, // 13 s hard cap (cut at the quietest recent moment)
5397
+ SOFT_FRAMES: 300, // after 6 s, the next short dip (≥ 160 ms) ends the piece
5273
5398
  MIN_VOICED: 18, // ≥ 360 ms of voiced audio, otherwise ignored
5274
5399
  node: null, sink: null, input: null,
5275
5400
  active: false,
@@ -5370,7 +5495,7 @@ async function handle(m) {
5370
5495
  this._seg.push(frame);
5371
5496
  if (rms > threshold * 0.8) { this._voiced++; this._silence = 0; } else this._silence++;
5372
5497
  if (this._silence >= this.END_SILENCE) this._cut('final');
5373
- else if (this._seg.length >= this.MAX_FRAMES) this._cut('streaming');
5498
+ else if (this._seg.length >= this.MAX_FRAMES || (this._seg.length >= this.SOFT_FRAMES && this._silence >= 8)) this._cut('streaming');
5374
5499
  },
5375
5500
  _cut(reason) {
5376
5501
  let frames = this._seg || [];
@@ -5411,6 +5536,7 @@ async function handle(m) {
5411
5536
  async _send(frames, reason) {
5412
5537
  const seq = ++this._seq;
5413
5538
  const meta = TRANSLATOR._meta(reason);
5539
+ TRANSLATOR._showHeard();
5414
5540
  const ctrl = new AbortController();
5415
5541
  this._inflight.add(ctrl);
5416
5542
  const seconds = (frames.length * 0.02).toFixed(1);
@@ -5427,7 +5553,10 @@ async function handle(m) {
5427
5553
  diag.lastMs = Date.now() - began;
5428
5554
  if (text) { diag.answered++; diag.lastText = text.slice(0, 40); } else diag.empty++;
5429
5555
  } catch (err) {
5430
- if (err?.name === 'AbortError' || !this.active) return;
5556
+ if (!this.active) return;
5557
+ // A timed-out piece still takes its place in the order (otherwise every later
5558
+ // line waited for it forever and piled up in memory).
5559
+ if (err?.name === 'AbortError') { this._release(seq, '', reason, meta); return; }
5431
5560
  this._failures++;
5432
5561
  diag.failed++; diag.lastErr = String(err?.message || err).slice(0, 60);
5433
5562
  logDebug(`AI Sub: cloud speech recognition failed (${err.message}${err.detail ? ': ' + err.detail : ''}).`, 'warn');
@@ -5437,7 +5566,13 @@ async function handle(m) {
5437
5566
  }
5438
5567
  if (!this.active) return;
5439
5568
  logDebug(`AI Sub: cloud ASR (${seconds}s, ${reason}) → "${text.slice(0, 90)}"`, text ? 'success' : 'info');
5440
- this._results.set(seq, { text, reason, meta });
5569
+ this._release(seq, text, reason, meta);
5570
+ },
5571
+ _release(seq, text, reason, meta) {
5572
+ this._results.set(seq, { text, reason, meta, at: Date.now() });
5573
+ // A piece that never answers must not hold back the ones after it for long.
5574
+ const head = Math.min(...this._results.keys());
5575
+ if (head > this._next && (this._results.size > 30 || Date.now() - (this._results.get(head)?.at || 0) > 9000)) this._next = head;
5441
5576
  while (this._results.has(this._next)) {
5442
5577
  const r = this._results.get(this._next);
5443
5578
  this._results.delete(this._next);
@@ -8451,13 +8586,32 @@ async function handle(m) {
8451
8586
  const keyRows = createEl('div', 'key-rows');
8452
8587
  [['openai', 'OpenAI', 'sk-…'], ['anthropic', 'Anthropic (Claude)', 'sk-ant-…'], ['groq', 'Groq', 'gsk_…'], ['deepl', 'DeepL', '…:fx']].forEach(([name, title, ph]) => {
8453
8588
  const row = createEl('div', 'key-row');
8454
- const input = createEl('input', 'key-input', '', { type: 'password', placeholder: ph, autocomplete: 'off', spellcheck: 'false', 'aria-label': title + ' API key' });
8589
+ // A text field drawn as dots: browsers' password managers fill password fields
8590
+ // with the site's saved password, which then looked like an entered key.
8591
+ const masked = typeof CSS !== 'undefined' && CSS.supports?.('-webkit-text-security', 'disc');
8592
+ const input = createEl('input', 'key-input' + (masked ? ' key-secret' : ''), '', { type: masked ? 'text' : 'password', placeholder: ph, autocomplete: masked ? 'off' : 'new-password',
8593
+ name: 'nxu-apikey-' + name + '-' + Math.random().toString(36).slice(2, 7), spellcheck: 'false', autocapitalize: 'off', 'data-lpignore': 'true', 'data-1p-ignore': 'true', 'data-bwignore': 'true', 'data-form-type': 'other', 'aria-label': title + ' API key' });
8455
8594
  input.value = AI.key(name);
8456
8595
  const test = createEl('button', 'btn subtle key-test', t('aiTest'));
8457
8596
  const status = createEl('span', 'key-status', AI.key(name) ? '•' : '');
8458
- input.addEventListener('change', () => { STORE.set('nxu_key_' + name, input.value.trim()); status.textContent = input.value.trim() ? '•' : ''; refreshEngineHint(); TRANSLATOR._cache.clear(); });
8597
+ const save = () => {
8598
+ const value = input.value.trim();
8599
+ let autofilled = false;
8600
+ try { autofilled = input.matches(':-webkit-autofill') || input.matches(':autofill'); } catch (_) { }
8601
+ if (value && (autofilled || !AI.validKey(name, value))) {
8602
+ input.value = AI.key(name);
8603
+ status.textContent = '⚠️';
8604
+ showToast(t(autofilled ? 'aiKeyAutofill' : 'aiKeyFormat', { name: title, ph }));
8605
+ return false;
8606
+ }
8607
+ STORE.set('nxu_key_' + name, value);
8608
+ if (value) STORE.set('nxu_asr_auto', '');
8609
+ status.textContent = value ? '•' : '';
8610
+ return true;
8611
+ };
8612
+ input.addEventListener('change', () => { save(); refreshEngineHint(); TRANSLATOR._cache.clear(); });
8459
8613
  test.onclick = async () => {
8460
- STORE.set('nxu_key_' + name, input.value.trim());
8614
+ if (!save()) return;
8461
8615
  status.textContent = '…';
8462
8616
  const res = await AI.test(name);
8463
8617
  status.textContent = res.ok ? '✅' : '❌';
@@ -8501,13 +8655,34 @@ async function handle(m) {
8501
8655
  };
8502
8656
  const details = createEl('details', 'ai-advanced');
8503
8657
  const advanced = createEl('div', 'ai-advanced-body');
8658
+ // Grouped by what each setting is for: recognition, translation, keys, display.
8659
+ // The browser's own language packs (Chrome/Edge) are a different engine from offline
8660
+ // Whisper, so they sit under the browser engine and are shown only when it is used.
8504
8661
  const offlineBtn = createEl('button', 'btn subtle', '⬇️ ' + t('offlineDownload'));
8505
8662
  offlineBtn.onclick = () => TRANSLATOR.downloadOfflineModels();
8506
- advanced.append(label(t('translationEngine')), providerSelect, engineHint,
8507
- label(t('asrEngine')), asrSelect, whisperBox,
8508
- label(t('subPosition')), positionSelect,
8509
- label(t('glossary')), glossaryInput, help(t('glossaryHelp')), label(t('aiKeys')), keyRows, help(t('aiKeysHelp')), modelRow('anthropic', 'claude-haiku-4-5'), modelRow('openai', 'gpt-4.1-mini'),
8510
- help(t('modelHelp')), localRow, help(t('localFirstHelp')), offlineBtn, help(t('offlineHelp')));
8663
+ const SRc = window.SpeechRecognition || window.webkitSpeechRecognition;
8664
+ const packBox = createEl('div', 'ai-pack');
8665
+ packBox.append(localRow, help(t('localFirstHelp')), offlineBtn, help(t('offlineHelp')));
8666
+ const hasPacks = !!(SRc && typeof SRc.install === 'function') || !!(self.Translator || window.Translator);
8667
+ const asrHelp = help('');
8668
+ const modelBox = createEl('div', 'ai-models');
8669
+ const claudeModel = modelRow('anthropic', 'claude-haiku-4-5'), gptModel = modelRow('openai', 'gpt-4.1-mini');
8670
+ const modelHelp = help(t('modelHelp'));
8671
+ modelBox.append(claudeModel, gptModel, modelHelp);
8672
+ const section = (icon, title) => createEl('div', 'ai-sec', icon + ' ' + title);
8673
+ const paintAdvanced = () => {
8674
+ const asr = asrSelect.value, tx = providerSelect.value;
8675
+ asrHelp.textContent = t('asrHelp_' + (asr === 'openai-hq' ? 'openai' : asr));
8676
+ packBox.style.display = asr === 'browser' && hasPacks ? '' : 'none';
8677
+ claudeModel.style.display = tx === 'anthropic' ? '' : 'none';
8678
+ gptModel.style.display = tx === 'openai' ? '' : 'none';
8679
+ modelBox.style.display = tx === 'anthropic' || tx === 'openai' ? '' : 'none';
8680
+ };
8681
+ advanced.append(
8682
+ section('🎧', t('secAsr')), asrSelect, asrHelp, whisperBox, packBox,
8683
+ section('🌐', t('secTx')), providerSelect, engineHint, modelBox, label(t('glossary')), glossaryInput, help(t('glossaryHelp')),
8684
+ section('🔑', t('aiKeys')), keyRows, help(t('aiKeysHelp')),
8685
+ section('🖥️', t('secView')), positionSelect);
8511
8686
  details.append(createEl('summary', '', t('advanced')), advanced);
8512
8687
 
8513
8688
  body.append(
@@ -8531,6 +8706,7 @@ async function handle(m) {
8531
8706
  if (!asrSelect.value) asrSelect.value = 'browser';
8532
8707
  paintWhisper();
8533
8708
  refreshEngineHint();
8709
+ paintAdvanced();
8534
8710
  localCheck.checked = STORE.get('nxu_stt_local_first', true) !== false;
8535
8711
  sizeSlider.value = SUB_PREFS.size; sizeVal.textContent = SUB_PREFS.size + 'px';
8536
8712
  opacitySlider.value = SUB_PREFS.opacity; opacityVal.textContent = SUB_PREFS.opacity + '%';
@@ -8543,8 +8719,8 @@ async function handle(m) {
8543
8719
  TRANSLATOR.setOutputLanguage(subtitleSelect.value);
8544
8720
  });
8545
8721
  positionSelect.addEventListener('change', () => { STORE.set('nxu_sub_position', positionSelect.value); SUB_LAYOUT.schedule(); });
8546
- providerSelect.addEventListener('change', () => { STORE.set('nxu_translation_provider', providerSelect.value); TRANSLATOR._cache.clear(); TRANSLATOR._llmHistory = []; refreshEngineHint(); });
8547
- asrSelect.addEventListener('change', () => { STORE.set('nxu_asr_provider', asrSelect.value); refreshEngineHint(); paintWhisper(); paintSource(); TRANSLATOR.restart('recognition engine changed'); });
8722
+ providerSelect.addEventListener('change', () => { STORE.set('nxu_translation_provider', providerSelect.value); TRANSLATOR._cache.clear(); TRANSLATOR._llmHistory = []; refreshEngineHint(); paintAdvanced(); });
8723
+ asrSelect.addEventListener('change', () => { STORE.set('nxu_asr_provider', asrSelect.value); STORE.set('nxu_asr_auto', ''); refreshEngineHint(); paintAdvanced(); paintWhisper(); paintSource(); TRANSLATOR.restart('recognition engine changed'); });
8548
8724
  localCheck.addEventListener('change', () => STORE.set('nxu_stt_local_first', !!localCheck.checked));
8549
8725
  sizeSlider.addEventListener('input', () => {
8550
8726
  STORE.set('nxu_sub_size', +sizeSlider.value);
@@ -8847,6 +9023,10 @@ async function handle(m) {
8847
9023
  .key-row { display:flex; align-items:center; gap:6px; }
8848
9024
  .key-name { flex:0 0 96px; font-size:11px; color:rgba(255,255,255,0.8); }
8849
9025
  .glossary-input { width:100%; box-sizing:border-box; resize:vertical; min-height:44px; background:rgba(0,0,0,0.35); color:#fff; border:1px solid rgba(255,255,255,0.2); border-radius:8px; padding:6px 8px; font:12.5px/1.4 inherit; font-family:inherit; outline:none; }
9026
+ .key-secret { -webkit-text-security:disc; }
9027
+ .ai-sec { margin:14px 0 6px; padding-top:10px; border-top:1px solid rgba(255,255,255,0.1); font-size:12.5px; font-weight:800; color:#fff; letter-spacing:0.01em; }
9028
+ .ai-advanced-body > .ai-sec:first-child { margin-top:4px; padding-top:0; border-top:0; }
9029
+ .ai-pack, .ai-models { margin-top:8px; padding:8px 10px; border-radius:10px; background:rgba(255,255,255,0.05); }
8850
9030
  .key-input { flex:1; min-width:0; background:rgba(0,0,0,0.35); color:#fff; border:1px solid rgba(255,255,255,0.2); border-radius:6px; padding:5px 7px; font:12px ui-monospace, monospace; outline:none; }
8851
9031
  .key-test { width:auto !important; flex:0 0 auto; padding:5px 8px !important; }
8852
9032
  .key-status { width:18px; text-align:center; font-size:12px; }
@@ -9076,8 +9256,23 @@ async function handle(m) {
9076
9256
  .sub-interim-translation { color:#fff; font-size:calc(var(--sub-size) * 0.92); line-height:1.4; font-weight:750; overflow-wrap:anywhere; text-shadow:0 2px 5px rgba(0,0,0,0.9); margin-bottom:2px; }
9077
9257
  .sub-interim-translation + .sub-interim-text { font-size:var(--sub-original-size); opacity:0.8; }
9078
9258
  .sub-interim-text { color:rgba(255,255,255,0.88); font-size:var(--sub-interim-size); line-height:1.38; font-style:italic; overflow-wrap:anywhere; text-shadow:0 2px 4px rgba(0,0,0,0.75); }
9079
- .text-morph { animation:textSmoothFade 0.3s cubic-bezier(0.2,0.8,0.2,1); }
9080
- @keyframes textSmoothFade { from { opacity:0.2; transform:translateY(4px); } to { opacity:var(--sub-opacity); transform:none; } }
9259
+ .text-morph { animation:subLand 0.42s cubic-bezier(0.2,0.8,0.2,1); }
9260
+ .text-morph .sub-final-text { animation:subInk 0.5s ease-out; }
9261
+ @keyframes subLand { from { opacity:0.15; transform:translateY(8px) scale(0.98); } to { opacity:var(--sub-opacity); transform:none; } }
9262
+ @keyframes subInk { from { filter:blur(5px); opacity:0; letter-spacing:0.02em; } to { filter:none; opacity:1; letter-spacing:normal; } }
9263
+ .sub-pending { background:rgba(8,10,14,0.55); animation:subPop 0.2s ease-out; }
9264
+ .sub-pending .sub-interim-text { animation:subType 0.55s steps(24, end); }
9265
+ .sub-pending-bar { height:2px; margin-top:6px; border-radius:2px; background:linear-gradient(90deg, transparent 0%, var(--speaker-color,#00e676) 50%, transparent 100%); background-size:50% 100%; background-repeat:no-repeat; animation:subShimmer 1.1s linear infinite; opacity:0.85; }
9266
+ .sub-hearing { align-items:center; gap:8px; padding:6px 14px 6px 16px; min-width:0; }
9267
+ .sub-hear { display:inline-flex; align-items:center; gap:3px; height:14px; }
9268
+ .sub-hear i { display:block; width:3px; height:100%; border-radius:2px; background:var(--speaker-color,#00e676); animation:subHear 0.9s ease-in-out infinite; transform-origin:center; }
9269
+ .sub-hear i:nth-child(2) { animation-delay:0.12s; } .sub-hear i:nth-child(3) { animation-delay:0.24s; } .sub-hear i:nth-child(4) { animation-delay:0.36s; } .sub-hear i:nth-child(5) { animation-delay:0.48s; }
9270
+ .sub-hear-label { color:rgba(255,255,255,0.75); font-size:11px; font-weight:700; }
9271
+ @keyframes subPop { from { opacity:0; transform:translateY(4px); } to { opacity:1; transform:none; } }
9272
+ @keyframes subType { from { clip-path:inset(0 100% 0 0); } to { clip-path:inset(0 0 0 0); } }
9273
+ @keyframes subShimmer { from { background-position:-60% 0; } to { background-position:160% 0; } }
9274
+ @keyframes subHear { 0%, 100% { transform:scaleY(0.3); } 50% { transform:scaleY(1); } }
9275
+ @media (prefers-reduced-motion: reduce) { .text-morph, .text-morph .sub-final-text, .sub-pending, .sub-pending .sub-interim-text, .sub-pending-bar, .sub-hear i { animation:none !important; } }
9081
9276
  /* reactions: edge lanes only */
9082
9277
  .rx { position:absolute; z-index:50; pointer-events:none !important; will-change:transform, opacity; line-height:1; user-select:none; -webkit-user-select:none; }
9083
9278
  .rx-emoji { filter:drop-shadow(0 3px 6px rgba(0,0,0,0.45)) drop-shadow(0 0 10px rgba(255,255,255,0.18)); opacity:0; }
@@ -10701,6 +10896,24 @@ async function handle(m) {
10701
10896
  this._kick();
10702
10897
  }
10703
10898
  };
10899
+ // Players with their own drag gestures (seek by dragging, swipe for volume…) listen on
10900
+ // the whole window in the capture phase and often stop the event there, so it never
10901
+ // reached the sketch layer: drawing did nothing on such sites. While the sketch layer is
10902
+ // open, pointer events aimed at it are taken first (this listener is registered at
10903
+ // start-up, before the page's) and handled directly; the page does not see them.
10904
+ if (IS_TOP) {
10905
+ const inkFirst = (e) => {
10906
+ const c = INK._catcher;
10907
+ if (!c || !c.isConnected) return;
10908
+ const path = e.composedPath ? e.composedPath() : [];
10909
+ if (!path.includes(c) || path.some(n => n?.classList?.contains?.('nx-ink-done') || n?.classList?.contains?.('nx-ink-hint'))) return;
10910
+ e.stopImmediatePropagation();
10911
+ if (e.type === 'pointerdown') { INK._wake(); INK._down(e); }
10912
+ else if (e.type === 'pointermove') { if (Date.now() - (INK._lastWake || 0) > 300) { INK._lastWake = Date.now(); INK._wake(); } INK._move(e); }
10913
+ else INK._up(e);
10914
+ };
10915
+ ['pointerdown', 'pointermove', 'pointerup', 'pointercancel'].forEach(type => window.addEventListener(type, inkFirst, { capture: true, passive: false }));
10916
+ }
10704
10917
 
10705
10918
  // ───────────────────────── Brightness (cinema, per device)
10706
10919
  // Web pages cannot change the screen's brightness, so the picture itself is made
@@ -11051,12 +11264,54 @@ async function handle(m) {
11051
11264
  // The text the site is showing in it right now. Lines the site keeps in the page but
11052
11265
  // hides (earlier cues left with display:none) are not read: innerText is what is
11053
11266
  // rendered. Only inside something this script hid itself is the raw text used.
11054
- _text(el) {
11267
+ //
11268
+ // The NexusSync controls hide the site's bar with a class rule ("…overlay", "…control",
11269
+ // "…mask" and the like). A player that draws its subtitles inside such a layer had them
11270
+ // hidden by that rule too, and innerText of hidden text is empty: with the NexusSync
11271
+ // controls the subtitles vanished, with the site's controls they came back. Text hidden
11272
+ // by this script is read as laid out (lines the site removed with display:none still skipped).
11273
+ _uiSel() {
11274
+ if (this._sel !== undefined) return this._sel;
11275
+ const m = CINEMA_CSS.match(/\.nxu-site-ui-off :is\(([\s\S]*?)\):not\(video\)/);
11276
+ this._sel = null;
11277
+ if (m) { try { document.createElement('i').matches(':is(' + m[1] + ')'); this._sel = ':is(' + m[1] + ')'; } catch (_) { } }
11278
+ return this._sel;
11279
+ },
11280
+ _hiddenByUs(el) {
11055
11281
  const mine = el.closest('.nxu-site-hide');
11282
+ if (mine) return mine;
11283
+ if (!el.closest('.nxu-site-ui-off')) return null;
11284
+ const win = el.ownerDocument.defaultView || window;
11285
+ if (win.getComputedStyle(el).visibility !== 'hidden') return null;
11286
+ let n = el;
11287
+ while (n.parentElement && !n.classList.contains('nxu-site-ui-off') && win.getComputedStyle(n.parentElement).visibility === 'hidden') n = n.parentElement;
11288
+ const sel = this._uiSel();
11289
+ return sel && n.matches(sel) ? n : null;
11290
+ },
11291
+ _laidOut(el) {
11292
+ let out = '';
11293
+ const win = el.ownerDocument.defaultView || window;
11294
+ const walk = (node, depth) => {
11295
+ for (const c of node.childNodes) {
11296
+ if (c.nodeType === 3) { out += c.nodeValue; continue; }
11297
+ if (c.nodeType !== 1 || depth > 8) continue;
11298
+ if (c.tagName === 'BR') { out += '\n'; continue; }
11299
+ if (!c.getClientRects().length || /^(SCRIPT|STYLE|TEMPLATE)$/.test(c.tagName)) continue;
11300
+ const block = !/^inline/.test(win.getComputedStyle(c).display);
11301
+ if (block && out && !out.endsWith('\n')) out += '\n';
11302
+ walk(c, depth + 1);
11303
+ if (block && out && !out.endsWith('\n')) out += '\n';
11304
+ }
11305
+ };
11306
+ walk(el, 0);
11307
+ return out;
11308
+ },
11309
+ _text(el) {
11310
+ const mine = this._hiddenByUs(el);
11056
11311
  // (An element the site took out of the layout reports all its text as innerText.)
11057
- if (!mine && !el.getClientRects().length) return '';
11058
- const raw = mine ? el.textContent : el.innerText ?? el.textContent;
11059
- return String(raw || '').replace(/[ \t]+/g, ' ').replace(/\n{2,}/g, '\n').trim().slice(0, 300);
11312
+ if (!el.getClientRects().length) return '';
11313
+ const raw = mine ? this._laidOut(el) : el.innerText ?? el.textContent;
11314
+ return String(raw || '').replace(/[ \t]+/g, ' ').replace(/ *\n */g, '\n').replace(/\n{2,}/g, '\n').trim().slice(0, 300);
11060
11315
  },
11061
11316
  scan() {
11062
11317
  const root = this._root;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kangsicj/nexussync",
3
- "version": "1.6.20",
3
+ "version": "1.6.21",
4
4
  "description": "Watch-together userscript: media sync, cinema mode, live AI subtitles, chat bubbles and quick ink for Violentmonkey, Tampermonkey and iOS Userscripts.",
5
5
  "keywords": [
6
6
  "userscript",