Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Add phone pages and a LAN access entry for chat and generation monitoring
Bowen Xue03ca5edd2842
diff --git a/freevideo_engine/access_proxy.py b/freevideo_engine/access_proxy.pyindex 8369a2d..1040bf6 100644--- a/freevideo_engine/access_proxy.py+++ b/freevideo_engine/access_proxy.py@@ -26,9 +26,14 @@ from . import proxy_identity, lan_passwordfrom .lan_auth import PasswordAuth, DEVICE_COOKIE, REMEMBER_SECONDS, LOGIN_DELAYPHONE_WEB = Path(__file__).resolve().parents[1] / 'web'-PHONE_FILE = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.-]*\.(?:js|css|html)')+PHONE_FILE = re.compile(r'[A-Za-z0-9_][A-Za-z0-9_.-]*\.(?:js|css)')PHONE_ASSETS = ('assets/freevideo.svg', 'assets/freevideo-light.svg')-PHONE_TYPES = {'.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html', '.svg': 'image/svg+xml'}+PHONE_TYPES = {'.js': 'text/javascript', '.css': 'text/css', '.svg': 'image/svg+xml'}+# Inline like the password page: installed packages only carry .js/.css/.svg under web/.+PHONE_PAGE = (+ '<!doctype html>'+ '<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"><meta name="referrer" content="same-origin"><title>FreeVideo</title><link rel="stylesheet" href="./theme.css"><link rel="stylesheet" href="./phone.css"></head><body class="fv-phone"><div id="phone"></div><script type="module" src="./phone.js"></script></body></html>')+COOKIE = 'freevideo_access'DAYS = 30LOGIN_PATH = '/m/login'@@ -60,9 +65,9 @@ def password_page(*, error='', retry_after=0, status=401):def phone_file(path, root=None):- """The page file /m/<name> stands for: .js/.css/.html directly inside web/ and the two wordmark SVGs."""+ """The page file /m/<name> stands for: .js/.css directly inside web/ and the two wordmark SVGs (/m/ itself is PHONE_PAGE)."""root = (root or PHONE_WEB).resolve()- name = 'phone.html' if path == '/m/' else path[len('/m/'):]+ name = path[len('/m/'):]if not (PHONE_FILE.fullmatch(name) or name in PHONE_ASSETS):return Nonetry:@@ -303,6 +308,8 @@ def create(upstream, token, engine=None):return web.Response(status=403)if request.path == '/m/csrf':response = web.json_response(dict(csrf=proxy_identity.csrf(hop_secret, request['lan_device'])))+ elif request.path == '/m/':+ response = web.Response(text=PHONE_PAGE if request.method == 'GET' else '', content_type='text/html', charset='utf-8')else:found = phone_file(request.path)if found is None:diff --git a/web/autopilot.js b/web/autopilot.jsindex c64145b..ee9302f 100644--- a/web/autopilot.js+++ b/web/autopilot.js@@ -1,3 +1,4 @@+import {createLanAccess} from './lan_access.js';// The Agent's own page, beside the studio and the editing view: the card that connects one, then the conversation with it.import { api } from '../../scripts/api.js';import { agentConnectCard, connectionLabel } from './agent_connect.js';@@ -35,7 +36,8 @@ export function openAutopilotView(node, {studio = null, initialPrompt = '', initgo.type = halt.type = 'button'; go.append(ring, name, more, percent, eta); now.append(go, halt);halt.title = t('Stop all', '全部停止'); halt.setAttribute('aria-label', halt.title);const line = el('i', 'fv-autopilot-line');- tools.append(now, lamp, feedbackButton(t), settings);+ const phoneAccess = createLanAccess(t, api);+ tools.append(now, lamp, phoneAccess.element, feedbackButton(t), settings);// The view chosen next takes over once this page has closed; Escape goes back to what is underneath.let next = () => studio?.open ? viewChanged('studio', node) : viewChanged('nodes', node);const leave = action => { next = action; closeDialog(dialog); };@@ -77,6 +79,7 @@ export function openAutopilotView(node, {studio = null, initialPrompt = '', initif (arrived) chat.input.focus();lamp.hidden = !ready; lamp.dataset.color = label.color; lampText.textContent = lamp.title = label.text; lamp.setAttribute('aria-label', label.text); lamp.disabled = connected || !last.any;const job = talking ? last.current : null;+ phoneAccess.observe(job);now.hidden = !job; line.dataset.on = String(!!job);halt.disabled = !!last.stopping;halt.setAttribute('aria-busy', String(!!last.stopping));@@ -100,7 +103,7 @@ export function openAutopilotView(node, {studio = null, initialPrompt = '', initdialog.append(header, body);dialog.addEventListener('cancel', event => { event.preventDefault(); closeDialog(dialog); });dialog.onclose = () => {- card.stop(); chat.stop(); assets.dispose(); dialog.remove();+ phoneAccess.dispose(); card.stop(); chat.stop(); assets.dispose(); dialog.remove();if (current === dialog) current = null;next();};diff --git a/web/autopilot_chat.js b/web/autopilot_chat.jsindex 78e5a80..e9e2168 100644--- a/web/autopilot_chat.js+++ b/web/autopilot_chat.js@@ -2,6 +2,8 @@// cards at the place they happened. Reads and sends use the page session; the agent's token never enters the page.import {agentGet, agentPost, retryAgentPost} from './agent_session.js';import {SCENE_TEXT, sceneList, startScene, watchScene} from './whitebox_scenes.js';+import {chatData, chatDelay, chatReadRequest, emptyChat, chatMerge, chatEntries, canSend, newId, SEND_ATTEMPTS, WAIT_FOR_AGENT, sendRefused, sendError} from './chat_data.js';+export {emptyChat, chatMerge, chatEntries, canSend} from './chat_data.js';import {isolateDialogKeys, routeDialogKey} from './dialog_keys.js';import {closeDialog} from './motion.js';import { estimatedFraction, remainingAbove, remainingShown, createDiagnosticReportControl } from './generation_progress.js';@@ -40,33 +42,7 @@ const WHITEBOX = {play: ['Play', '播放'], pause: ['Pause', '暂停'], seconds: ['s', '秒'],failure: ['Could not start: ', '无法开始生成:'],};-const SEND_ATTEMPTS = 3, WAIT_FOR_AGENT = ['not_connected', 'not_listening'];const GENERIC_FAILURE_ZH = '没有完成';-// A listening/connection race is queued; other 4xx refusals never repeat automatically.-const sendRefused = (error, response) => error?.code === 'session_full' || error?.retryable === false- || response?.status >= 400 && response.status < 500 && !WAIT_FOR_AGENT.includes(error?.code);-async function sendError(response) {- if (!response) return null;- try { return (await (response.clone?.() || response).json())?.error || null; }- catch { return null; }-}-// Only an explicit field-validation refusal is safe to resend without the optional field.-// An older backend that ignores it already succeeds; unrelated errors keep the existing retry policy.-async function previewUnsupported(response) {- if (![400, 422].includes(response?.status)) return false;- try {- const value = await response.clone().json(), error = value.error;- // The current server redacts unknown field names. The only boolean true we add is this flag.- const detail = error?.details?.[0];- if (error?.code === 'invalid_request' && error.details?.length === 1 && detail?.path === '/<unknown>'- && detail.allowed === 'absent (unknown field)' && detail.got === 'True') return true;- if (Array.isArray(value.detail) && value.detail.some(item => item.type === 'extra_forbidden'- && item.loc?.includes(WHITEBOX_PREVIEW.field))) return true;- const named = error?.field === WHITEBOX_PREVIEW.field || error?.message?.includes(WHITEBOX_PREVIEW.field);- return !!named && (['unknown_field', 'unsupported_field', 'unsupported_parameter', 'extra_forbidden'].includes(error?.code)- || /unknown|unsupported|unexpected|unrecognized|not supported|extra field/i.test(error?.message || ''));- } catch { return false; }-}// Sends and failure cards use the same public reason, including the engine's Chinese mapping.function failureReason(value, t) {const error = value.error, reason = error?.error_zh || value.error_zh;@@ -163,33 +139,6 @@ export function jobParts(job) {return Array.from({length: block.total}, (_, i) => i < (block.done || 0) ? 1 : i === block.index - 1 ? inside : 0);}-export const emptyChat = () => ({session: undefined, items: new Map(), jobs: {}, failures: {}, confirms: {}, last: 0, read: 0, agent: {}, current: null, active: 0});-// One answer from the server folded into what the page already has: entries add up by their number, jobs are-// replaced by id (a card keeps its last state after the server stops listing its job), and so are the answers to its questions.-export function chatMerge(state, data) {- const items = new Map(state.items);- for (const item of data.items || []) if (['message', 'job', 'confirm', 'production', 'cast'].includes(item.type) && Number.isFinite(item.seq)) items.set(item.seq, item);- const read = Math.max(state.read, Number(data.read_seq) || 0, ...(data.items || []).filter(item => item.read === true).map(item => item.seq));- return {session: data.session ?? null, items, jobs: {...state.jobs, ...(data.jobs || {})}, failures: data.failures || {}, confirms: {...state.confirms, ...(data.confirms || {})}, read,- last: Math.max(state.last, Number(data.last_seq) || 0, ...items.keys()), agent: data.agent || {},- current: data.current || null, active: Number(data.active) || 0};-}-// The entries in order. A user's sentence counts as taken once the agent has read it or has said or done anything after it.-export function chatEntries(state) {- const list = [...state.items.values()].sort((a, b) => a.seq - b.seq);- let answered = 0;- for (const item of list) if (item.type !== 'message' || item.role !== 'user') answered = item.seq;- return list.map(item => item.type === 'message' && item.role === 'user'- ? {...item, taken: item.read === true || item.seq <= state.read || item.seq < answered} : item);-}-// Whether a sentence sent now reaches anyone: the agent is waiting for one, or is at work and will come back for it.-export const canSend = state => state.agent?.connected === true && (state.agent.listening !== false || state.active > 0);--function newId() {- const bytes = crypto.getRandomValues(new Uint8Array(12));- return 'm-' + [...bytes].map(b => b.toString(36).padStart(2, '0')).join('').slice(0, 20);-}-// A picture is viewed here, independently of the video library. The image stays within reach while zoomed.function imageViewer(t, src, name, opener, failed) {const dialog = el('dialog', 'fv-studio fv-chat-image-viewer'), actions = el('div', 'fv-chat-actions');@@ -267,6 +216,7 @@ function imageViewer(t, src, name, opener, failed) {// user can see the conversation; the page calls sync() whenever that may have changed. changed(view) follows every// answer: {known, agent, current, active, any}.export function agentChat(t, api, {open, edit, shown = () => true, changed = () => {}, interval = 1500, productVersion = () => null, initialPrompt = '', initialWhiteboxPreview = false, initialScene = '', hint = null} = {}) {+ const dataLayer = chatData(api);const element = el('section', 'fv-chat'), main = el('div', 'fv-chat-main'), scroller = el('div', 'fv-chat-scroll'), log = el('ol', 'fv-chat-log');log.setAttribute('role', 'log'); log.setAttribute('aria-label', t('Conversation', '对话'));const down = press('fv-chat-down', null, () => { scroller.scrollTo({top: scroller.scrollHeight, behavior: 'smooth'}); });@@ -537,7 +487,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()// A disabled focused button can lose native focus. Keep it on the origin while awaiting the request.menuOrigin()?.focus({preventScroll: true}); updateMenu();try {- const response = await agentPost(api, '/freevideo/agent/chat/delete', stop ? {session, stop: true} : {session});+ const response = await dataLayer.remove(session, stop);if (stopped) return;const data = await response.json().catch(() => ({}));if (stopped) return;@@ -587,7 +537,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()if (creating || !active() || conversations.supported !== true) return;creating = true; newError.hidden = newIssue.hidden = true; renderConversations(); render();try {- const response = await agentPost(api, '/freevideo/agent/chat/new', {});+ const response = await dataLayer.create();if (stopped) return;if (response.ok) {const data = await response.json();@@ -608,7 +558,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()if (!force && performance.now() - listAt < listInterval) return;listBusy = true; listAt = performance.now();try {- const response = await agentGet(api, '/freevideo/agent/chat/list', {signal: closed.signal});+ const response = await dataLayer.list({signal: closed.signal});if (stopped) return;// The body is awaited first: a conversation chosen meanwhile must stay the current one.const data = response.ok ? await response.json() : null;@@ -693,7 +643,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()if (!ids.length) return;say(t('Stopping…', '正在停止…'));ids.forEach(id => stopping.add(id)); render(); report();- const results = await Promise.all(ids.map(id => retryAgentPost(api, '/freevideo/agent/activity/cancel', {id})));+ const results = await Promise.all(ids.map(id => dataLayer.cancel(id)));results.forEach((response, index) => { if (!response?.ok) stopping.delete(ids[index]); });if (results.some(response => !response?.ok)) say(t('Could not stop. Click again.', '没能停止,请再点一次。'), true);else say('');@@ -1005,7 +955,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()item.querySelectorAll('button').forEach(button => { button.disabled = true; });confirming.add(key); confirmErrors.delete(key); render();try {- const response = await agentPost(api, '/freevideo/agent/chat/confirm', {id: entry.id, approve, session});+ const response = await dataLayer.confirm({id: entry.id, approve, session});if (!response.ok) throw await requestError(response);answers.set(key, (await response.json()).state || (approve ? 'approved' : 'declined'));} catch (error) { confirmErrors.set(key, t('Could not start shooting: ', '没有开始拍摄:') + reason(error)); }@@ -1110,8 +1060,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()if (!row) { away = null; return; }try {// Past the last message: only that conversation's jobs come back.- const query = new URLSearchParams({session: row.id, after: String(Number.MAX_SAFE_INTEGER)});- const response = await agentGet(api, `/freevideo/agent/chat?${query}`, {signal: closed.signal});+ const response = await dataLayer.read({session: row.id, after: Number.MAX_SAFE_INTEGER, signal: closed.signal});if (!response.ok) { away = null; return; }const data = await response.json(), jobs = Object.values(data.jobs || {}).filter(job => WORKING.includes(job?.status));const job = data.jobs?.[data.current] || jobs[0];@@ -1158,18 +1107,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()const whiteboxes = [...state.items.values()].filter(card => card.type === 'confirm' && card.whitebox && whiteboxState(card) === 'asked');entry.sending = true; entry.retried = !!original; entry.error = null; entry.automatic = false; render(true); report();try {- const body = {id: entry.id, text: entry.text};- if (conversations.supported === true && entry.session) body.session = entry.session;- if (entry.whiteboxPreview) body[WHITEBOX_PREVIEW.field] = true;- entry.attempts++;- const response = await retryAgentPost(api, '/freevideo/agent/chat', body, {retry: async response => {- if (!stopped && !entry.acknowledged && entry.whiteboxPreview && entry.attempts < SEND_ATTEMPTS && await previewUnsupported(response)) {- entry.whiteboxPreview = false; delete body[WHITEBOX_PREVIEW.field];- entry.attempts++; return body;- }- if (stopped || entry.acknowledged || sendRefused(await sendError(response), response) || entry.attempts >= SEND_ATTEMPTS) return null;- entry.attempts++; return body;- }});+ const response = await dataLayer.sendMessage(entry, {sessionSupported: conversations.supported === true, stopped: () => stopped, previewField: WHITEBOX_PREVIEW.field});if (entry.acknowledged) return true;if (response?.ok) {const value = await response.json().catch(() => ({}));@@ -1249,11 +1187,8 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()const readSelection = selection, requested = selectedSession;let again = false;try {- const after = state.session && (!requested || requested === state.session) ? state.last : 0;- const query = new URLSearchParams();- if (requested) query.set('session', requested);- if (after) query.set('after', String(after));- const response = await agentGet(api, '/freevideo/agent/chat' + (query.size ? `?${query}` : ''), {signal: closed.signal});+ const {after} = chatReadRequest(state, requested);+ const response = await dataLayer.read({session: requested, after, signal: closed.signal});if (stopped) return;if (readSelection !== selection) again = true;else if (response.ok) {@@ -1296,7 +1231,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()known = true;// The next read is booked before the page hears of this one, so the page's sync() does not start another.const idle = state.agent.connected !== true && !state.active;- timer = setTimeout(poll, (idle ? Math.max(interval, 3000) : interval) * Math.min(4, 1 + failures));+ timer = setTimeout(poll, chatDelay({idle, interval, failures}));render(); report();if (sendingAllowed()) for (const entry of [...pending]) {if (entry.session !== state.session || !entry.automatic || entry.sending || entry.acknowledged) continue;diff --git a/web/chat_data.js b/web/chat_data.jsnew file mode 100644index 0000000..fe7fec7--- /dev/null+++ b/web/chat_data.js@@ -0,0 +1,119 @@+import {agentGet, agentPost, retryAgentPost} from './agent_session.js';+export const SEND_ATTEMPTS = 3, WAIT_FOR_AGENT = ['not_connected', 'not_listening'];+// A listening/connection race is queued; other 4xx refusals never repeat automatically.+export const sendRefused = (error, response) => error?.code === 'session_full' || error?.retryable === false+ || response?.status >= 400 && response.status < 500 && !WAIT_FOR_AGENT.includes(error?.code);+export async function sendError(response) {+ if (!response) return null;+ try { return (await (response.clone?.() || response).json())?.error || null; }+ catch { return null; }+}+export const emptyChat = () => ({session: undefined, items: new Map(), jobs: {}, failures: {}, confirms: {}, last: 0, read: 0, agent: {}, current: null, active: 0});+// One answer from the server folded into what the page already has: entries add up by their number, jobs are+// replaced by id (a card keeps its last state after the server stops listing its job), and so are the answers to its questions.+export function chatMerge(state, data) {+ const items = new Map(state.items);+ for (const item of data.items || []) if (['message', 'job', 'confirm', 'production', 'cast'].includes(item.type) && Number.isFinite(item.seq)) items.set(item.seq, item);+ const read = Math.max(state.read, Number(data.read_seq) || 0, ...(data.items || []).filter(item => item.read === true).map(item => item.seq));+ return {session: data.session ?? null, items, jobs: {...state.jobs, ...(data.jobs || {})}, failures: data.failures || {}, confirms: {...state.confirms, ...(data.confirms || {})}, read,+ last: Math.max(state.last, Number(data.last_seq) || 0, ...items.keys()), agent: data.agent || {},+ current: data.current || null, active: Number(data.active) || 0};+}+// The entries in order. A user's sentence counts as taken once the agent has read it or has said or done anything after it.+export function chatEntries(state) {+ const list = [...state.items.values()].sort((a, b) => a.seq - b.seq);+ let answered = 0;+ for (const item of list) if (item.type !== 'message' || item.role !== 'user') answered = item.seq;+ return list.map(item => item.type === 'message' && item.role === 'user'+ ? {...item, taken: item.read === true || item.seq <= state.read || item.seq < answered} : item);+}+// Whether a sentence sent now reaches anyone: the agent is waiting for one, or is at work and will come back for it.+export const canSend = state => state.agent?.connected === true && (state.agent.listening !== false || state.active > 0);++export function newId() {+ const bytes = crypto.getRandomValues(new Uint8Array(12));+ return 'm-' + [...bytes].map(b => b.toString(36).padStart(2, '0')).join('').slice(0, 20);+}++++// The cursor is scoped to its conversation; switching always starts at zero.+export function chatReadRequest(state, session) {+ return {session, after: state.session && (!session || session === state.session) ? state.last : 0};+}+// A send's id and attempt budget survive an uncertain response. Presentation can+// acknowledge the same entry from a concurrent poll before this request returns.+// Only an explicit field-validation refusal is safe to resend without the optional field.+// An older backend that ignores it already succeeds; unrelated errors keep the existing retry policy.+export async function previewUnsupported(response, field) {+ if (!field || ![400, 422].includes(response?.status)) return false;+ try {+ const value = await response.clone().json(), error = value.error;+ // The current server redacts unknown field names. The only boolean true we add is this flag.+ const detail = error?.details?.[0];+ if (error?.code === 'invalid_request' && error.details?.length === 1 && detail?.path === '/<unknown>'+ && detail.allowed === 'absent (unknown field)' && detail.got === 'True') return true;+ if (Array.isArray(value.detail) && value.detail.some(item => item.type === 'extra_forbidden'+ && item.loc?.includes(field))) return true;+ const named = error?.field === field || error?.message?.includes(field);+ return !!named && (['unknown_field', 'unsupported_field', 'unsupported_parameter', 'extra_forbidden'].includes(error?.code)+ || /unknown|unsupported|unexpected|unrecognized|not supported|extra field/i.test(error?.message || ''));+ } catch { return false; }+}+export async function sendChatMessage(api, entry, {sessionSupported = true, stopped = () => false, previewField = null} = {}) {+ const body = {id: entry.id, text: entry.text};+ if (sessionSupported && entry.session) body.session = entry.session;+ if (entry.whiteboxPreview && previewField) body[previewField] = true;+ entry.attempts = (entry.attempts || 0) + 1;+ return retryAgentPost(api, '/freevideo/agent/chat', body, {retry: async response => {+ if (!stopped() && !entry.acknowledged && entry.whiteboxPreview && entry.attempts < SEND_ATTEMPTS && await previewUnsupported(response, previewField)) {+ entry.whiteboxPreview = false; delete body[previewField];+ entry.attempts++; return body;+ }+ if (stopped() || entry.acknowledged || sendRefused(await sendError(response), response) || entry.attempts >= SEND_ATTEMPTS) return null;+ entry.attempts++; return body;+ }});+}++// DOM-free transport and state folds shared by desktop and phone. Rendering,+// drafts and visibility decisions remain with the owning view.+export function chatData(api) {+ const read = (path, options) => agentGet(api, path, options);+ return {+ read({session, after, signal} = {}) {+ const query = new URLSearchParams();+ if (session) query.set('session', session);+ if (after) query.set('after', String(after));+ return read('/freevideo/agent/chat' + (query.size ? `?${query}` : ''), {signal});+ },+ now: options => read('/freevideo/agent/chat/now', options),+ list: options => read('/freevideo/agent/chat/list', options),+ create: () => agentPost(api, '/freevideo/agent/chat/new', {}),+ remove: (session, stop = false) => agentPost(api, '/freevideo/agent/chat/delete', stop ? {session, stop: true} : {session}),+ confirm: body => agentPost(api, '/freevideo/agent/chat/confirm', body),+ cancel: id => retryAgentPost(api, '/freevideo/agent/activity/cancel', {id}),+ activity: (cursor, options) => read('/freevideo/agent/activity' + (cursor ? '?cursor=' + encodeURIComponent(cursor) : ''), options),+ sendMessage: (entry, options) => sendChatMessage(api, entry, options),+ send: (body, options) => retryAgentPost(api, '/freevideo/agent/chat', body, options),+ video: work => '/freevideo/agent/chat/video?id=' + encodeURIComponent(work),+ };+}+export function chatDelay({hidden = false, phone = false, idle = false, interval = 1500, failures = 0} = {}) {+ return phone ? (hidden ? 10000 : 2000) : (idle ? Math.max(interval, 3000) : interval) * Math.min(4, 1 + failures);+}+// Serial polling, visibility rescheduling and disposal work without a browser.+export function chatPoller(read, {delay = () => 2000, error = () => {}, clock = globalThis} = {}) {+ let timer = null, running = null, disposed = false, again = false;+ function poll() {+ clock.clearTimeout(timer); timer = null;+ if (disposed) return Promise.resolve();+ if (running) { again = true; return running; }+ running = Promise.resolve().then(read).catch(error).finally(() => {+ running = null;+ if (!disposed) { const ms = again ? 0 : delay(); again = false; timer = clock.setTimeout(poll, ms); }+ });+ return running;+ }+ return {poll, reschedule() { clock.clearTimeout(timer); if (!disposed && !running) timer = clock.setTimeout(poll, delay()); },+ dispose() { disposed = true; clock.clearTimeout(timer); }};+}diff --git a/web/editor.css b/web/editor.cssindex 1cb0606..fa1681a 100644--- a/web/editor.css+++ b/web/editor.css@@ -209,6 +209,7 @@/* editor_header_fit.js: when the project name would not stay readable beside a centred view switch, the logo takes its phone size, then leaves, then the switch takes a second row. */.fv-studio.fv-editor .fv-header[data-fit~=compact] .fv-wordmark{width:90px}.fv-studio.fv-editor .fv-header[data-fit~=bare] .fv-wordmark{display:none}+.fv-studio.fv-editor .fv-header[data-fit~=tight] .fv-lan{display:none}.fv-studio.fv-editor .fv-header[data-fit~=wrap]{height:auto;min-height:98px;grid-template-columns:minmax(0,1fr) auto;padding-block:10px}.fv-studio.fv-editor .fv-header[data-fit~=wrap]>.fv-view-switch{grid-column:1/-1;grid-row:2;justify-self:center}.fv-studio.fv-editor .fv-header[data-fit~=wrap]>.fv-header-actions{grid-column:2;grid-row:1}diff --git a/web/editor.js b/web/editor.jsindex 5835991..05d1f18 100644--- a/web/editor.js+++ b/web/editor.js@@ -1,3 +1,4 @@+import {createLanAccess} from './lan_access.js';import {createEditorText} from './editor_text.js';import {isNetworkTypeError, connectionLostText} from './browser_extension.js';import {createToolbarMore} from './editor_toolbar_more.js';@@ -198,7 +199,9 @@ export function openEditor({api, app, from = null, panel = {}, components: given}, 'fv-primary fv-ed-export-main');const exportCancel = button('', () => store.cancelExport(exportStatus.id).catch(error)); exportCancel.hidden = true; exportCancel.append(icon('m4 4 8 8M12 4l-8 8')); exportCancel.setAttribute('aria-label', t('Cancel', '取消'));exportBox.append(exportHint, exportButton, exportCancel); brand.append(wordmark(), title);- headerActions.append(exportBox, feedbackButton(t), button(t('Settings', '设置'), openSetup, 'fv-quiet'));+ const phoneAccess = createLanAccess(t, api);+ listeners.push(phoneAccess.dispose);+ headerActions.append(exportBox, phoneAccess.element, feedbackButton(t), button(t('Settings', '设置'), openSetup, 'fv-quiet'));top.append(brand, navigation, headerActions);const headerFit = fitEditorHeader(top, brand, title, navigation, headerActions);const menu = el('div', 'fv-ed-name-menu'); menu.hidden = true; menu.setAttribute('role', 'menu');@@ -255,6 +258,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given}}function receiveProgress(message) {+ phoneAccess.observe(message);if (disposed || !message.chain?.id || !message.chain.block) return false;const job = jobStatuses.get(message.chain.id);if (!job || String(job.node ?? panel.node?.id ?? panel.node ?? message.node) !== String(message.node)) return false;diff --git a/web/editor_header_fit.js b/web/editor_header_fit.jsindex 5552eb1..b446821 100644--- a/web/editor_header_fit.js+++ b/web/editor_header_fit.js@@ -17,9 +17,9 @@ export function fitEditorHeader(header, brand, title, navigation, actions) {const own = getComputedStyle(title), chevron = span.nextElementSibling, text = document.createRange(); text.selectNodeContents(span);const frame = px(own.paddingLeft) + px(own.paddingRight) + px(own.borderLeftWidth) + px(own.borderRightWidth) + (chevron ? chevron.getBoundingClientRect().width + px(own.columnGap) : 0);const wanted = Math.min(READABLE, text.getBoundingClientRect().width) + frame;- // The actions' own width: the box itself may already be squeezed below its buttons.+ // The actions' own width: the box itself, and the buttons in it, may already be squeezed below their content.const shown = [...actions.children].filter(child => child.offsetWidth > 0), apart = px(getComputedStyle(actions).columnGap);- const need = Math.max(actions.offsetWidth, shown.reduce((sum, child) => sum + child.getBoundingClientRect().width, 0) + apart * Math.max(0, shown.length - 1));+ const need = Math.max(actions.offsetWidth, shown.reduce((sum, child) => sum + Math.max(child.getBoundingClientRect().width, child.scrollWidth), 0) + apart * Math.max(0, shown.length - 1));const fits = markWidth => side >= need && side - markWidth - spacing >= wanted;const compact = Math.min(COMPACT_MARK, mark.offsetWidth);// On two rows the name shares the first row with the actions only; the logo shrinks too when that is still tight.@@ -28,7 +28,11 @@ export function fitEditorHeader(header, brand, title, navigation, actions) {const feedback = actions.querySelector('.fv-feedback-entry'), spare = feedback ? feedback.offsetWidth + apart : 0;// From 681 px up the switch has one place in every view, so the logo, then the feedback entry, leave before the switch moves down.const wide = !matchMedia('(max-width:680px)').matches, bare = room => wide && side >= room && side >= wanted;- const fit = fits(mark.offsetWidth) ? '' : fits(compact) ? 'compact' : bare(need) ? 'bare' : spare && bare(need - spare) ? 'bare lean'+ // Before the feedback entry, the phone entry steps aside.+ const lan = actions.querySelector('.fv-lan'), away = lan ? lan.offsetWidth + apart : 0;+ // The phone entry also steps aside rather than let the view switch drop to a second row.+ const fitsWithout = markWidth => side >= need - away && side - markWidth - spacing >= wanted;+ const fit = fits(mark.offsetWidth) ? '' : fits(compact) ? 'compact' : away && fitsWithout(mark.offsetWidth) ? 'tight' : away && fitsWithout(compact) ? 'compact tight' : bare(need) ? 'bare' : away && bare(need - away) ? 'bare tight' : away && spare && bare(need - away - spare) ? 'bare tight lean' : spare && bare(need - spare) ? 'bare lean': row(mark.offsetWidth) >= wanted ? 'wrap' : row(compact) >= wanted || !spare ? 'wrap compact' : 'wrap compact lean';if (fit) header.dataset.fit = fit;}diff --git a/web/health.js b/web/health.jsindex e1bf094..81add2c 100644--- a/web/health.js+++ b/web/health.js@@ -13,7 +13,7 @@ const t = (en, zh) => cn ? zh : en;// launcher.js removes this flag during setup; read it before that.const launchVisit = query.get('freevideo') === 'launch';// Every script this folder ships; a test keeps the list in step with web/*.js.-export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'capability_view.js', 'cast_generate.js', 'cast_mention.js', 'cast_overlay.js', 'cast_source.js', 'compatibility.js', 'entry_showcase.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',+export const MODULES = ['chat_data.js', 'phone_model.js', 'phone.js', 'lan_access.js', 'qrcodegen.js', 'agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'capability_view.js', 'cast_generate.js', 'cast_mention.js', 'cast_overlay.js', 'cast_source.js', 'compatibility.js', 'entry_showcase.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js','editor.js', 'editor_actions.js', 'editor_lifecycle.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_expand.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_media_references.js', 'editor_references.js', 'editor_genbar.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_speed.js', 'editor_speed_model.js', 'editor_failure.js', 'editor_header_fit.js','editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_toolbar_more.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'done_notify.js', 'failure_issue.js', 'feedback.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'launch_visit.js', 'launcher.js', 'length_plan.js', 'lora_triggers.js', 'lora_check.js', 'library.js', 'motion.js', 'native_errors.js', 'translate_guard.js', 'output_download.js', 'port_notice.js', 'preview_scene.js','progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'prompt_terms.js', 'request_assets.js', 'repair_hint.js', 'report_issue.js', 'issue_button.js', 'studio_recent.js',diff --git a/web/lan_access.css b/web/lan_access.cssnew file mode 100644index 0000000..3732cce--- /dev/null+++ b/web/lan_access.css@@ -0,0 +1,8 @@+.fv-lan.fv-lan{position:relative;display:inline-flex;flex:none;font-size:var(--fv-body);color:var(--fv-ink)}.fv-lan.fv-lan [hidden]{display:none!important}.fv-lan.fv-lan button{font:inherit;cursor:pointer;color:inherit;border:0;touch-action:manipulation}.fv-lan.fv-lan button:disabled{opacity:.45;cursor:default}.fv-lan.fv-lan .fv-lan-trigger{position:relative;width:32px;height:32px;min-width:32px;padding:7px;border-radius:6px;background:transparent;color:var(--fv-muted)}.fv-lan-trigger:hover,.fv-lan-trigger[aria-expanded=true]{background:var(--fv-hover)!important;color:var(--fv-ink)!important}.fv-lan.fv-lan svg{width:18px;height:18px;fill:none;stroke:currentColor;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round;display:block}.fv-lan-dot{position:absolute;right:1px;top:1px;width:7px;height:7px;background:var(--fv-accent);border:2px solid var(--fv-bg);box-sizing:content-box;border-radius:50%}.fv-lan-panel{position:fixed;z-index:1000;box-sizing:border-box;width:264px;max-width:calc(100vw - 16px);padding:16px;background:var(--fv-card);border:1px solid var(--fv-border);border-radius:var(--fv-r-md);box-shadow:0 12px 36px #0006;text-align:left;max-height:calc(100dvh - 80px);overflow:auto}.fv-lan-heading{display:flex;align-items:center;justify-content:space-between;gap:8px}.fv-lan-heading strong{font-size:calc(var(--fv-body) + 1px);font-weight:var(--fv-semibold)}.fv-lan.fv-lan .fv-lan-switch{height:32px;width:44px;padding:0;position:relative;border-radius:99px;background:transparent}.fv-lan-switch:before{content:'';position:absolute;inset:5px 3px;background:var(--fv-hover);border-radius:99px}.fv-lan-switch:after{content:'';position:absolute;left:6px;top:8px;width:16px;height:16px;border-radius:50%;background:var(--fv-ink)}.fv-lan-switch[aria-checked=true]:before{background:var(--fv-accent)}.fv-lan-switch[aria-checked=true]:after{left:22px}.fv-lan-content{display:flex;flex-direction:column;align-items:stretch}.fv-lan-qr{width:168px;height:168px;border-radius:8px;background:#fff;align-self:center;margin-top:14px;image-rendering:pixelated}.fv-lan-scan{text-align:center;font-size:var(--fv-micro);color:var(--fv-muted);margin:10px 0 8px;line-height:1.5}.fv-lan.fv-lan .fv-lan-copy{height:36px;background:var(--fv-raised);border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);font-weight:var(--fv-semibold)}.fv-lan-password{display:flex;align-items:center;justify-content:space-between;border-top:1px solid var(--fv-border);margin-top:14px;padding-top:10px;color:var(--fv-muted)}.fv-lan.fv-lan .fv-lan-set{color:var(--fv-accent);background:none;height:32px;padding:0 4px}.fv-lan-starting{font-size:var(--fv-body);color:var(--fv-muted);line-height:1.65;margin:12px 0 0}.fv-lan-starting span{white-space:nowrap}.fv-lan-form{width:100%;margin-top:10px}.fv-lan-field{display:flex;background:var(--fv-raised);border:1px solid var(--fv-border);border-radius:8px;overflow:hidden}.fv-lan-field input{font:inherit;font-size:var(--fv-strong);color:var(--fv-ink);width:100%;min-width:0;background:none;border:0;padding:8px}.fv-lan.fv-lan .fv-lan-eye{width:44px;min-height:44px;flex:none;background:none;display:flex;align-items:center;justify-content:center}.fv-lan-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:8px}.fv-lan-actions button{min-height:36px;padding:0 12px;border-radius:8px;background:var(--fv-raised)}.fv-lan-actions .fv-lan-save{background:var(--fv-accent);color:var(--fv-bg)}.fv-lan-error{font-size:var(--fv-body);color:var(--fv-danger);margin:8px 0 0}.fv-lan.fv-lan :focus-visible{outline:2px solid var(--fv-accent);outline-offset:2px}+@media(pointer:coarse){.fv-lan.fv-lan .fv-lan-trigger{width:44px;height:44px;padding:13px}.fv-lan-panel button{min-height:44px}}++@media(max-width:480px){.fv-studio .fv-header .fv-version-info{display:none}}++.fv-lan-tip{position:fixed;z-index:1001;background:var(--fv-raised);color:var(--fv-ink);font-size:var(--fv-micro);padding:6px 10px;border:1px solid var(--fv-border);border-radius:6px;white-space:nowrap;pointer-events:none;box-shadow:0 4px 12px #0004}+/* The extra tool must not take the readable project name out of a narrow editor. */+@media(max-width:680px){.fv-studio.fv-editor .fv-header[data-fit~=wrap][data-fit~=compact] .fv-wordmark{display:none}}diff --git a/web/lan_access.js b/web/lan_access.jsnew file mode 100644index 0000000..a3b2607--- /dev/null+++ b/web/lan_access.js@@ -0,0 +1,106 @@+import {longGeneration} from './phone_model.js';+import {agentGet, agentPost} from './agent_session.js';+import {qrcodegen} from './qrcodegen.js';+const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./lan_access.css', import.meta.url).href; document.head.append(css);+const seenKey = 'freevideo.phone.opened';+export function qrMatrix(link) { return qrcodegen.QrCode.encodeText(link, qrcodegen.QrCode.Ecc.MEDIUM); }+function drawQr(canvas, link) {+ const qr = qrMatrix(link), scale = Math.max(2, Math.floor(336 / (qr.size + 8))), size = (qr.size + 8) * scale;+ canvas.width = canvas.height = size; const ctx = canvas.getContext('2d'); ctx.fillStyle = '#fff'; ctx.fillRect(0, 0, size, size); ctx.fillStyle = '#000';+ for (let y = 0; y < qr.size; y++) for (let x = 0; x < qr.size; x++) if (qr.getModule(x, y)) ctx.fillRect((x + 4) * scale, (y + 4) * scale, scale, scale);+}+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };+const button = (cls, label, action) => { const b = el('button', cls, label); b.type = 'button'; b.onclick = action; return b; };+export function createLanAccess(t, api) {+ const element = el('div', 'fv-lan'), trigger = button('fv-lan-trigger', '', toggle), panel = el('section', 'fv-lan-panel');+ const label = t('Phone access', '手机连接'); trigger.setAttribute('aria-label', label); trigger.setAttribute('aria-expanded', 'false'); trigger.setAttribute('aria-haspopup', 'dialog');+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true');+ const path = document.createElementNS(svg.namespaceURI || 'http://www.w3.org/2000/svg', 'path'); path.setAttribute('d', 'M7 2h10a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V3a1 1 0 0 1 1-1zM10 18h4'); svg.append(path); trigger.append(svg);+ const dot = el('i', 'fv-lan-dot'); dot.hidden = true; dot.setAttribute('aria-hidden', 'true'); trigger.append(dot);+ panel.hidden = true; panel.setAttribute('role', 'dialog'); panel.setAttribute('aria-label', label);+ const head = el('div', 'fv-lan-heading'), toggleButton = button('fv-lan-switch', '', changeEnabled);+ toggleButton.setAttribute('role', 'switch'); toggleButton.setAttribute('aria-label', label); toggleButton.setAttribute('aria-checked', 'false'); toggleButton.disabled = true;+ head.append(el('strong', '', label), toggleButton);+ const starting = el('p', 'fv-lan-starting'), content = el('div', 'fv-lan-content'), qr = el('canvas', 'fv-lan-qr'); qr.setAttribute('role', 'img'); qr.setAttribute('aria-label', t('Phone access QR code', '手机连接二维码'));+ const copy = button('fv-lan-copy', t('Copy link', '复制链接'), async () => {+ try {+ if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(state.link);+ else { const area = el('textarea'); area.value = state.link; panel.append(area); area.select(); const ok = document.execCommand('copy'); area.remove(); if (!ok) throw new Error(); }+ copy.textContent = t('Copied', '已复制'); clearTimeout(copied); copied = setTimeout(() => { copy.textContent = t('Copy link', '复制链接'); }, 1500);+ } catch { fail(); }+ });+ const passwordRow = el('div', 'fv-lan-password'), passwordState = el('span'), set = button('fv-lan-set', t('Set', '设置'), () => { form.hidden = false; password.focus(); });+ passwordRow.append(passwordState, set);+ const form = el('form', 'fv-lan-form'), field = el('div', 'fv-lan-field'), password = el('input'); password.type = 'password'; password.autocomplete = 'new-password'; password.setAttribute('aria-label', t('New password', '新密码'));+ const eye = button('fv-lan-eye', '', () => { password.type = password.type === 'password' ? 'text' : 'password'; eye.setAttribute('aria-label', password.type === 'password' ? t('Show password', '显示密码') : t('Hide password', '隐藏密码')); }); eye.setAttribute('aria-label', t('Show password', '显示密码'));+ const eyeSvg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), eyePath = document.createElementNS('http://www.w3.org/2000/svg', 'path'); eyeSvg.setAttribute('viewBox', '0 0 24 24'); eyeSvg.setAttribute('aria-hidden', 'true'); eyePath.setAttribute('d', 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zm10 3a3 3 0 1 0 0-6 3 3 0 0 0 0 6z'); eyeSvg.append(eyePath); eye.append(eyeSvg); field.append(password, eye);+ const actions = el('div', 'fv-lan-actions'), cancel = button('', t('Cancel', '取消'), () => { form.hidden = true; password.value = ''; set.focus(); }), save = button('fv-lan-save', t('Save', '保存'), () => form.requestSubmit()); save.disabled = true;+ password.oninput = () => { save.disabled = [...password.value].length < (state.password_min_length || 6) || writing; };+ actions.append(cancel, save); form.append(field, actions); form.hidden = true;+ const error = el('p', 'fv-lan-error', t('Please try again.', '请重试。')); error.hidden = true; error.setAttribute('role', 'status');+ content.append(qr, el('p', 'fv-lan-scan', t('Connect to the same Wi-Fi, then scan', '手机连同一个 Wi-Fi 后扫码')), copy, passwordRow, form);+ const tip = el('span', 'fv-lan-tip', label); tip.setAttribute('role', 'tooltip'); tip.hidden = true;+ panel.append(head, starting, content, error); element.append(trigger, panel, tip);+ let state = {enabled: false, link: '', password_set: false}, seen = false, disposed = false, writing = false, desired = null, reading = false, timer = null, copied = null, drawn = '';+ try { seen = localStorage.getItem(seenKey) === '1'; } catch {}+ const windows = /Win/i.test(globalThis.navigator?.platform || globalThis.navigator?.userAgent || '');+ function fail() { error.hidden = false; }+ function position() {+ if (panel.hidden) return;+ const box = trigger.getBoundingClientRect(); panel.style.top = `${box.bottom + 8}px`;+ panel.style.left = `${Math.max(8, Math.min(box.right - 264, window.innerWidth - 272))}px`;+ }+ function render() {+ const on = desired ?? state.enabled, pending = on && (!state.enabled || !state.link);+ toggleButton.setAttribute('aria-checked', String(!!on)); toggleButton.disabled = writing || desired != null;+ content.hidden = !on || pending; starting.hidden = !pending;+ starting.replaceChildren();+ if (pending && windows) {+ if (t('en', 'zh') === 'zh') { starting.append(document.createTextNode('Windows 会弹出确认框,'), el('br'), el('span', '', '请勾选“专用网络”,再点“允许访问”。')); }+ else starting.textContent = 'Windows will ask for permission. Check "Private networks", then click "Allow access".';+ } else if (pending) starting.textContent = t('Opening…', '正在打开…');+ passwordState.textContent = state.password_set ? t('Password: on', '密码:已设置') : t('Password: not set', '密码:未设置');+ set.textContent = state.password_set ? t('Change', '修改') : t('Set', '设置');+ if (on && !pending && state.link !== drawn) { try { drawQr(qr, state.link); drawn = state.link; } catch { fail(); } }+ position();+ }+ async function read() {+ clearTimeout(timer); if (disposed || panel.hidden || reading) return; reading = true;+ try {+ const response = await agentGet(api, '/freevideo/lan', {signal: AbortSignal.timeout(10000)});+ if (!response.ok) throw new Error(); const value = await response.json(); if (disposed || writing) return;+ state = value; if (desired === state.enabled && (!desired || state.link)) desired = null;+ error.hidden = true; render();+ } catch { if (!disposed) fail(); }+ finally { reading = false; if (!disposed && !panel.hidden) timer = setTimeout(read, document.hidden ? 10000 : 2000); }+ }+ trigger.onpointerenter = trigger.onfocus = () => { if (!panel.hidden) return; const box = trigger.getBoundingClientRect(); tip.style.top = `${box.bottom + 8}px`; tip.style.right = `${Math.max(8, window.innerWidth - box.right)}px`; tip.hidden = false; };+ trigger.onpointerleave = trigger.onblur = () => { tip.hidden = true; };+ function close() { tip.hidden = true; panel.hidden = true; trigger.setAttribute('aria-expanded', 'false'); clearTimeout(timer); form.hidden = true; password.value = ''; }+ function toggle() {+ tip.hidden = true;+ if (!panel.hidden) { close(); return; }+ panel.hidden = false; trigger.setAttribute('aria-expanded', 'true'); seen = true; dot.hidden = true;+ try { localStorage.setItem(seenKey, '1'); } catch {}+ window.dispatchEvent(new Event('freevideo-phone-opened'));+ render(); read();+ }+ async function write(body) {+ writing = true; error.hidden = true; render();+ try {+ const response = await agentPost(api, '/freevideo/lan', body); if (!response.ok) throw new Error();+ const value = await response.json(); if (disposed) return false;+ if (typeof value.enabled === 'boolean') state = {...state, ...value}; return true;+ } catch { if (!disposed) fail(); return false; }+ finally { writing = false; if (!disposed) render(); }+ }+ async function changeEnabled() { desired = !state.enabled; if (!await write({enabled: desired})) desired = null; render(); read(); }+ form.onsubmit = async event => { event.preventDefault(); if (save.disabled || writing) return; save.disabled = true; if (await write({password: password.value})) { password.value = ''; form.hidden = true; set.focus(); read(); } else password.oninput(); };+ function observe(value) { if (!seen && longGeneration(value)) dot.hidden = false; }+ const opened = () => { seen = true; dot.hidden = true; };+ const storage = event => { if (event.key === seenKey && event.newValue === '1') opened(); };+ window.addEventListener('freevideo-phone-opened', opened); window.addEventListener('storage', storage);+ const progress = event => observe(event.detail), outside = event => { if (!element.contains(event.target)) close(); }, keys = event => { if (!panel.hidden && event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); close(); trigger.focus(); } };+ api.addEventListener?.('freevideo_progress', progress); document.addEventListener('pointerdown', outside, true); document.addEventListener('keydown', keys, true); window.addEventListener('resize', position);+ return {element, observe, dispose() { disposed = true; close(); clearTimeout(copied); api.removeEventListener?.('freevideo_progress', progress); document.removeEventListener('pointerdown', outside, true); document.removeEventListener('keydown', keys, true); window.removeEventListener('resize', position); window.removeEventListener('freevideo-phone-opened', opened); window.removeEventListener('storage', storage); }};+}diff --git a/web/phone.css b/web/phone.cssnew file mode 100644index 0000000..9436884--- /dev/null+++ b/web/phone.css@@ -0,0 +1,13 @@+.fv-phone{margin:0;background:var(--fv-bg);color:var(--fv-ink);font-size:var(--fv-strong);line-height:1.5;-webkit-font-smoothing:antialiased}+.fv-phone *{box-sizing:border-box}.fv-phone [hidden]{display:none!important}.fv-phone button,.fv-phone input,.fv-phone textarea,.fv-phone select{font:inherit;color:inherit}.fv-phone button{border:0;cursor:pointer;background:none;min-height:44px;touch-action:manipulation}.fv-phone button:disabled{opacity:.45;cursor:default}.fv-phone :focus-visible{outline:2px solid var(--fv-accent);outline-offset:2px}+#phone{height:100vh;height:100dvh;display:flex;flex-direction:column;overflow:hidden;position:relative}.phone-top{height:52px;flex:none;display:flex;align-items:center;justify-content:space-between;padding:0 16px;border-bottom:1px solid var(--fv-border)}.phone-top .fv-wordmark{height:20px;width:auto}.phone-offline{padding:8px 16px;background:var(--fv-raised);font-size:var(--fv-body);flex:none}.phone-main{flex:1;min-height:0;overflow:auto;padding:16px;overscroll-behavior:contain}.phone-log{display:flex;flex-direction:column;gap:14px;margin:0;padding:0;list-style:none}.phone-message{text-wrap:pretty;white-space:pre-wrap;overflow-wrap:anywhere;max-width:92%}.phone-message.user{align-self:flex-end;max-width:82%;padding:10px 14px;background:var(--fv-selected);border-radius:16px 16px 4px 16px}+.phone-compose{display:flex;gap:8px;align-items:flex-end;padding:8px 12px;border-top:1px solid var(--fv-border)}.phone-compose textarea{resize:none;flex:1;min-width:0;min-height:44px;max-height:134px;line-height:22px;background:var(--fv-raised);border:1px solid var(--fv-border);border-radius:22px;padding:10px 16px}.phone-compose textarea::placeholder{color:var(--fv-disabled)}.phone-send{height:44px;width:44px;border-radius:50%;background:var(--fv-accent)!important;color:var(--fv-bg)!important;flex:none}.phone-tabs{flex:none;display:flex;border-top:1px solid var(--fv-border);background:var(--fv-canvas);padding-bottom:env(safe-area-inset-bottom,0px)}.phone-tab{flex:1;height:56px;display:flex;align-items:center;justify-content:center;flex-direction:column;gap:2px;font-size:var(--fv-micro)!important;color:var(--fv-muted)!important}.phone-tab[aria-selected=true]{color:var(--fv-accent)!important}.fv-phone svg{width:22px;height:22px;stroke:currentColor;fill:none;stroke-width:1.6;stroke-linecap:round;stroke-linejoin:round;vertical-align:middle}+.phone-mini{display:flex;text-align:left;gap:12px;align-items:center;width:300px;max-width:100%;padding:8px;background:var(--fv-card)!important;border:1px solid var(--fv-border)!important;border-radius:var(--fv-r-md)}.phone-mini .phone-picture{width:44px;height:78px;border-radius:6px;flex:none}.phone-mini-body{min-width:0;flex:1;display:flex;flex-direction:column;gap:6px}.phone-mini-title{font-size:var(--fv-body);color:var(--fv-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.phone-mini-meta{display:flex;justify-content:space-between;font-size:var(--fv-body)}.phone-link{color:var(--fv-accent)!important;font-weight:var(--fv-semibold)}.phone-bar{height:4px;background:var(--fv-raised);border-radius:99px;overflow:hidden}.phone-bar i{height:100%;display:block;background:var(--fv-accent);border-radius:99px}.phone-picture{overflow:hidden;background:var(--fv-raised);position:relative}.phone-picture img{display:block;width:100%;height:100%;object-fit:cover}.phone-picture.strip img{max-width:none;object-fit:fill}+.phone-section{margin:4px 0 8px;font-size:var(--fv-body);font-weight:var(--fv-semibold);color:var(--fv-muted)}.phone-running{border:1px solid var(--fv-border);border-radius:var(--fv-r-lg);overflow:hidden;background:var(--fv-card);margin-bottom:20px}.phone-frame{height:232px;background:#0b0f15;display:flex;align-items:center;justify-content:center}.phone-frame .phone-picture{height:100%;max-width:100%;aspect-ratio:9/16}.phone-frame.no-frame .phone-picture{display:none}.phone-frame .phone-frame-pct{font-size:var(--fv-section)}.phone-info{padding:12px 14px 14px;display:flex;flex-direction:column;gap:10px}.phone-prompt{font-size:calc(var(--fv-body) + 1px);display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden;margin:0}.phone-job-row{display:flex;justify-content:space-between;align-items:center;gap:8px}.phone-pct{font-size:var(--fv-section);font-weight:var(--fv-semibold)}.phone-eta{font-size:var(--fv-body);color:var(--fv-muted)}.phone-quiet{padding:0 12px;border-radius:var(--fv-r-sm);background:var(--fv-raised)!important;font-size:var(--fv-body)!important}.phone-queue{display:flex;gap:12px;align-items:center;min-height:54px;border-bottom:1px solid var(--fv-border);margin-bottom:12px;touch-action:pan-y}.phone-queue .ph{width:28px;height:28px;background:var(--fv-raised);border-radius:6px;flex:none}.phone-queue .name{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:calc(var(--fv-body) + 1px);flex:1}.phone-queue .position{color:var(--fv-muted);font-size:var(--fv-body)}.phone-grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;margin-bottom:16px}.phone-grid.landscape{grid-template-columns:repeat(2,minmax(0,1fr))}.phone-done{padding:0;text-align:left;min-width:0}.phone-done .phone-picture{aspect-ratio:9/16;border-radius:var(--fv-r-sm)}.landscape .phone-done .phone-picture{aspect-ratio:16/9}.phone-caption{font-size:var(--fv-micro);color:var(--fv-muted);margin-top:4px;display:block}.phone-empty{color:var(--fv-muted);margin:28px 0}.phone-toast{position:relative;flex:none;margin:8px 12px;background:var(--fv-raised);border:1px solid var(--fv-border);border-radius:var(--fv-r-md);padding:10px 12px;box-shadow:0 8px 24px #0006;display:flex;gap:12px;align-items:center;font-size:calc(var(--fv-body) + 1px)}.phone-toast .phone-picture{width:28px;height:50px;flex:none;border-radius:4px}.phone-toast span{flex:1}+.phone-result{flex:1;min-height:0;display:flex;flex-direction:column}.phone-viewer{flex:1;min-height:0;background:#000;display:flex;align-items:center;justify-content:center}.phone-viewer video{width:100%;max-height:100%;object-fit:contain}.phone-result-actions{padding:12px 16px 28px;display:flex;flex-direction:column;gap:12px}.phone-result-actions .phone-prompt{color:var(--fv-muted)}.fv-phone .phone-primary{min-height:44px;background:var(--fv-accent)!important;color:var(--fv-bg)!important;border-radius:10px;font-weight:var(--fv-semibold);width:100%}.phone-back{width:44px;margin-left:-12px}.phone-password{flex:1;display:flex;flex-direction:column;justify-content:center;padding:0 28px 120px;gap:16px}.phone-password .fv-wordmark{height:26px;width:auto;align-self:flex-start;margin-bottom:24px}.phone-password h1{font-size:calc(var(--fv-section) + 2px);font-weight:var(--fv-semibold);margin:0}.phone-password-field{display:flex;min-height:48px;border-radius:10px;background:var(--fv-raised);border:1px solid var(--fv-border);padding:0 2px 0 16px}.phone-password-field:focus-within{border-color:var(--fv-accent)}.phone-password-field.bad,.phone-password-field.bad:focus-within{border-color:var(--fv-danger)}.phone-password-field input{background:none;border:0;outline:none!important;min-width:0;flex:1;font-size:var(--fv-strong)}.phone-eye{width:44px;flex:none;color:var(--fv-muted)!important}.phone-error{font-size:var(--fv-body);color:var(--fv-danger);margin:0}.phone-password .phone-error{margin-top:-8px}.phone-confirm{background:var(--fv-card);border:1px solid var(--fv-border);border-radius:var(--fv-r-md);padding:16px;color:var(--fv-ink);max-width:calc(100vw - 32px)}.phone-confirm::backdrop{background:#0008}.phone-confirm p{margin:0 0 16px}.phone-confirm-actions{display:flex;gap:12px}.phone-chat-tools{display:flex;gap:8px;justify-content:flex-end;margin-bottom:12px}.phone-chat-tools select{max-width:250px;min-height:44px;background:var(--fv-card);border:1px solid var(--fv-border);border-radius:8px}.phone-chat-tools button{width:44px}.phone-notice{margin:0;padding:4px 16px;font-size:var(--fv-body);color:var(--fv-danger)}++.phone-viewer{position:relative}.phone-viewer video{max-height:min(100%,560px);padding-bottom:48px;background:#000}++.fv-phone .phone-chats{width:40px;height:40px;min-height:40px;margin-right:-8px;display:flex;align-items:center;justify-content:center;color:var(--fv-muted)}.phone-chats svg{width:22px;height:22px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}+.phone-sheet{position:absolute;inset:0;z-index:20;background:#0008;display:flex;align-items:flex-end}.phone-sheet-panel{width:100%;max-height:70%;overflow:auto;background:var(--fv-card);border-top:1px solid var(--fv-border);border-radius:16px 16px 0 0;padding:10px 0 calc(16px + env(safe-area-inset-bottom))}+.fv-phone .phone-sheet-new{width:100%;text-align:left;padding:0 20px;color:var(--fv-accent);font-weight:var(--fv-semibold)}.phone-sheet-list{list-style:none;margin:0;padding:0}.fv-phone .phone-sheet-row{width:100%;display:flex;align-items:center;gap:12px;padding:0 20px;text-align:left}.phone-sheet-check{width:16px;flex:none;color:var(--fv-accent)}.phone-sheet-title{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.phone-sheet-time{flex:none;color:var(--fv-muted);font-size:13px}.phone-sheet-grip{width:36px;height:4px;border-radius:2px;margin:0 auto 8px;background:color-mix(in srgb,var(--fv-muted) 30%,transparent)}diff --git a/web/phone.js b/web/phone.jsnew file mode 100644index 0000000..48438fd--- /dev/null+++ b/web/phone.js@@ -0,0 +1,290 @@+import {chatData, chatPoller, chatDelay, chatReadRequest, emptyChat, chatMerge, chatEntries, newId} from './chat_data.js';+import {phoneText, jobGroups, mergePhoneJobs, retryWords, queueWords, remainingWords, mediaPath, saveVideo, applyPhoneChain, phonePartWords, phoneJobKey} from './phone_model.js';+import {wordmark} from './wordmark.js';++export function mountPhone(root) {+const t = phoneText(navigator.language);+document.documentElement.lang = t('en', 'zh-CN');+const el = (tag, cls = '', text) => { const e = document.createElement(tag); e.className = cls; if (text != null) e.textContent = text; return e; };+const button = (cls, label, run) => { const b = el('button', cls, label); b.type = 'button'; b.onclick = run; return b; };+const icon = path => { const s = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); s.setAttribute('viewBox', '0 0 24 24'); s.setAttribute('aria-hidden', 'true'); const p = document.createElementNS(s.namespaceURI, 'path'); p.setAttribute('d', path); s.append(p); return s; };+const closed = new AbortController();+let locked = false, stopped = false, sending = false, retryUntil = 0, countdown = null;+let chat = emptyChat(), jobs = {}, selected, revision = 0, cursor = null, historyStarted = false, limit = 30, loadingMore = false, tab = location.hash === '#jobs' ? 'jobs' : 'chat', result = null;+let lastSend = null, toastTimer = null, flash = null, toastJob = null, permissionAsked = false;+try { permissionAsked = localStorage.getItem('freevideo.phone.notification-asked') === '1'; } catch {}+const drafts = new Map(), rows = new Map(), scrollPositions = {chat: 0, jobs: 0};+const top = el('header', 'phone-top'), offline = el('div', 'phone-offline', t('Connection lost. Reconnecting…', '连接断了,正在重新连接…'));+offline.hidden = true; offline.setAttribute('role', 'status');+const main = el('main', 'phone-main'), log = el('ol', 'phone-log'); log.setAttribute('role', 'log'); log.setAttribute('aria-label', t('Chat', '对话'));+let convRows = [], convCurrent = '';+const chatsButton = button('phone-chats', '', () => openSheet()); chatsButton.setAttribute('aria-label', t('Chats', '对话')); chatsButton.setAttribute('aria-haspopup', 'dialog'); chatsButton.append(icon('M4 4h16v12H9l-5 4V4zM12 7v6M9 10h6'));+const sheet = el('div', 'phone-sheet'), sheetPanel = el('section', 'phone-sheet-panel'); sheet.hidden = true; sheetPanel.setAttribute('role', 'dialog'); sheetPanel.setAttribute('aria-label', t('Chats', '对话')); sheet.append(sheetPanel);+const clock = seconds => { const d = new Date(Number(seconds) * 1000); if (!Number.isFinite(d.getTime()) || !seconds) return ''; const now = new Date(); return d.toDateString() === now.toDateString() ? d.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hour12: false}) : d.toLocaleDateString(t('en-US', 'zh-CN'), {month: 'long', day: 'numeric'}); };+function closeSheet() { sheet.hidden = true; chatsButton.setAttribute('aria-expanded', 'false'); chatsButton.focus(); }+function renderSheet() {+ const fresh = button('phone-sheet-new', t('New chat', '新对话'), async () => {+ fresh.disabled = true;+ try { const data = await json(await dataLayer.create()); if (!data.session) throw new Error(); closeSheet(); choose(data.session); }+ catch { closeSheet(); notice(t('Could not start a new chat. Try again.', '没有新建成功,请重试。')); }+ });+ const list = el('ul', 'phone-sheet-list');+ for (const row of convRows.some(row => row.id === convCurrent) || !convCurrent ? convRows : [{id: convCurrent}, ...convRows]) {+ const item = button('phone-sheet-row', '', () => { closeSheet(); if (row.id !== convCurrent) choose(row.id); });+ const check = el('span', 'phone-sheet-check', row.id === convCurrent ? '✓' : ''); check.setAttribute('aria-hidden', 'true');+ if (row.id === convCurrent) item.setAttribute('aria-current', 'true');+ item.append(check, el('span', 'phone-sheet-title', row.title || t('New chat', '新对话')), el('span', 'phone-sheet-time', clock(row.updated_at)));+ const li = el('li'); li.append(item); list.append(li);+ }+ const grip = el('div', 'phone-sheet-grip'); grip.setAttribute('aria-hidden', 'true');+ sheetPanel.replaceChildren(grip, fresh, list);+}+function openSheet() { renderSheet(); sheet.hidden = false; chatsButton.setAttribute('aria-expanded', 'true'); sheetPanel.querySelector('button').focus(); }+top.append(wordmark(), chatsButton);+sheet.addEventListener('pointerdown', event => { if (event.target === sheet) closeSheet(); });+let dragFrom = null;+sheetPanel.addEventListener('touchstart', event => { dragFrom = sheetPanel.scrollTop <= 0 ? event.touches[0].clientY : null; }, {passive: true});+sheetPanel.addEventListener('touchend', event => { if (dragFrom !== null && event.changedTouches[0].clientY - dragFrom > 60) closeSheet(); dragFrom = null; }, {passive: true});+sheet.addEventListener('keydown', event => { if (event.key === 'Escape') { event.preventDefault(); closeSheet(); } });+const generations = el('div', 'phone-generations');+main.append(log, generations);+const compose = el('form', 'phone-compose'), input = el('textarea'), send = button('phone-send', '', () => compose.requestSubmit());+input.rows = 1; input.maxLength = 8000; input.placeholder = t('What would you like to make?', '想做什么视频?'); input.setAttribute('aria-label', input.placeholder);+send.append(icon('M12 19V5M5 12l7-7 7 7')); send.setAttribute('aria-label', t('Send', '发送')); send.disabled = true; compose.append(input, send);+const warning = el('p', 'phone-notice'); warning.hidden = true; warning.setAttribute('role', 'status');+const tabs = el('nav', 'phone-tabs'); tabs.setAttribute('aria-label', t('Pages', '页面'));+const chatTab = button('phone-tab', '', () => show('chat')), jobsTab = button('phone-tab', '', () => show('jobs'));+for (const [b, label, path] of [[chatTab, t('Chat', '对话'), 'M4 4h16v12H9l-5 4V4z'], [jobsTab, t('Generations', '生成'), 'M4 7h11v11H4zM15 11l6-4v11l-6-4']]) { b.append(icon(path), el('span', '', label)); b.setAttribute('role', 'tab'); tabs.append(b); }+tabs.setAttribute('role', 'tablist');+const viewer = el('section', 'phone-result'), toast = el('div', 'phone-toast'); toast.hidden = viewer.hidden = true; toast.setAttribute('role', 'status');+const pw = el('form', 'phone-password'), field = el('div', 'phone-password-field'), password = el('input'), pwError = el('p', 'phone-error');+password.type = 'password'; password.autocomplete = 'current-password'; password.setAttribute('aria-label', t('Password', '密码'));+const eye = button('phone-eye', '', () => { password.type = password.type === 'password' ? 'text' : 'password'; eye.setAttribute('aria-label', password.type === 'password' ? t('Show password', '显示密码') : t('Hide password', '隐藏密码')); });+eye.append(icon('M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zm10 3a3 3 0 1 0 0-6 3 3 0 0 0 0 6z')); eye.setAttribute('aria-label', t('Show password', '显示密码'));+const enter = button('phone-primary', t('Open', '进入'), () => pw.requestSubmit()); enter.disabled = true;+field.append(password, eye); pwError.hidden = true; pwError.setAttribute('role', 'alert'); pw.append(wordmark(), el('h1', '', t('Enter password', '输入密码')), field, pwError, enter); pw.hidden = true;+root.append(top, offline, main, warning, compose, viewer, toast, tabs, pw, sheet);+function notice(text = '') { warning.textContent = text; warning.hidden = !text; }+function connection(ok) { offline.hidden = ok || locked; }+function requirePassword() { if (locked) return; locked = true; document.querySelectorAll('dialog.phone-confirm').forEach(dialog => dialog.close()); viewer.querySelector('video')?.pause(); renderShell(); password.focus(); }+const api = {apiURL: path => path, async fetchApi(path, options = {}) {+ const signals = [closed.signal, options.signal, AbortSignal.timeout(10000)].filter(Boolean);+ // The proxy hands each signed-in device its write proof at /m/csrf; the desktop page asks the agent route.+ const response = await fetch(path === '/freevideo/agent/session' ? '/m/csrf' : path, {...options, signal: AbortSignal.any(signals), credentials: 'same-origin'});+ // Without a valid device cookie the proxy answers every request with its password page, never JSON.+ if ([401, 429].includes(response.status) && (response.headers.get('Content-Type') || '').startsWith('text/html')) {+ requirePassword(); const wait = Number(response.headers.get('X-FreeVideo-Retry-After')); if (wait > 0) lockFor(wait);+ }+ return response;+}};+const dataLayer = chatData(api);+async function json(response) { const data = await response.json(); if (!response.ok) throw Object.assign(new Error(), {data, status: response.status}); return data; }+function lockFor(seconds) { retryUntil = Date.now() + Math.max(0, Number(seconds) || 0) * 1000; clearInterval(countdown); tickPassword(); countdown = setInterval(tickPassword, 250); }+function tickPassword() {+ const remaining = Math.ceil((retryUntil - Date.now()) / 1000);+ enter.disabled = remaining > 0 || !password.value || pw.dataset.busy === 'true';+ if (remaining > 0) { pwError.textContent = retryWords(remaining, t); pwError.hidden = false; field.classList.add('bad'); }+ else if (retryUntil) { retryUntil = 0; clearInterval(countdown); pwError.hidden = true; field.classList.remove('bad'); }+}+password.oninput = tickPassword;+pw.onsubmit = async event => {+ event.preventDefault(); if (enter.disabled) return; pw.dataset.busy = 'true'; tickPassword();+ try {+ // The proxy owns the sign-in: a form post, answered by a redirect that sets the device cookie.+ const response = await api.fetchApi('/m/login', {method: 'POST', headers: {'Content-Type': 'application/x-www-form-urlencoded'}, body: new URLSearchParams({password: password.value, remember: '1'}).toString()});+ const wait = Number(response.headers.get('X-FreeVideo-Retry-After'));+ if (response.ok) { locked = false; password.value = ''; pwError.hidden = true; field.classList.remove('bad'); renderShell(); await poller.poll(); }+ else if (response.status === 429 && wait > 0) lockFor(wait);+ else if (response.status === 401) { pwError.textContent = t('Wrong password. Please try again.', '密码不对,请再输一次。'); pwError.hidden = false; field.classList.add('bad'); password.focus(); password.select(); }+ else { pwError.textContent = t('Connection lost. Reconnecting…', '连接断了,正在重新连接…'); pwError.hidden = false; }+ } catch { pwError.textContent = t('Connection lost. Reconnecting…', '连接断了,正在重新连接…'); pwError.hidden = false; }+ finally { pw.dataset.busy = 'false'; tickPassword(); }+};+function renderShell() {+ pw.hidden = !locked; top.hidden = main.hidden = tabs.hidden = locked;+ compose.hidden = warning.hidden = locked || result != null || tab !== 'chat'; warning.hidden ||= !warning.textContent;+ viewer.hidden = locked || !result; main.hidden ||= !!result; tabs.hidden ||= !!result;+ offline.hidden ||= locked; toast.hidden = locked || !!result || !toastJob;+ chatsButton.hidden = log.hidden = tab !== 'chat'; generations.hidden = tab !== 'jobs';+ chatTab.setAttribute('aria-selected', String(tab === 'chat')); jobsTab.setAttribute('aria-selected', String(tab === 'jobs'));+}+function show(value) { if (!result) scrollPositions[tab] = main.scrollTop; viewer.querySelector('video')?.pause(); result = null; top.replaceChildren(wordmark(), chatsButton); tab = value; renderShell(); if (value === 'jobs') renderJobs(); main.scrollTop = scrollPositions[value]; }+function choose(session) { drafts.set(selected ?? chat.session, input.value); selected = session; revision++; chat = emptyChat(); input.value = drafts.get(session) || ''; lastSend = null; rows.clear(); log.replaceChildren(); grow(); poller.poll(); }+function grow() { input.style.height = 'auto'; input.style.height = `${Math.min(input.scrollHeight, 134)}px`; send.disabled = sending || !input.value.trim(); }+input.oninput = () => { if (lastSend?.text !== input.value.trim()) lastSend = null; grow(); notice(); };+input.onkeydown = event => { if (event.key === 'Enter' && !event.shiftKey && !event.isComposing && event.keyCode !== 229) { event.preventDefault(); compose.requestSubmit(); } };+compose.onsubmit = async event => {+ event.preventDefault(); const text = input.value.trim(); if (sending || !text) return;+ const body = lastSend?.text === text && lastSend.session === (chat.session ?? null) ? lastSend : {id: newId(), text, session: chat.session ?? null};+ lastSend = body; sending = true; const version = revision; grow(); notice();+ try {+ body.attempts = 0;+ const response = await dataLayer.sendMessage(body, {stopped: () => locked || stopped});+ if (!response?.ok) throw new Error();+ if (version === revision && input.value.trim() === text) { input.value = ''; lastSend = null; }+ await poller.poll();+ } catch { notice(t('Could not send. Please try again.', '没有发送成功,请重试。')); }+ finally { sending = false; grow(); }+};+function picture(job, preview = false) {+ const box = el('div', 'phone-picture');+ const p = job.progress || {}, frame = p.frame_preview;+ const path = preview && frame?.serial > 0 && frame.frames > 0 && frame.frames <= 8 && job.node != null+ ? `/freevideo/frame-preview/${encodeURIComponent(job.node)}?serial=${frame.serial}` : mediaPath(job.thumbnail, 'image');+ if (path) {+ const img = el('img'); img.alt = ''; img.loading = 'lazy'; img.src = path; box.append(img);+ if (preview && frame?.frames > 0) { box.classList.add('strip'); img.style.width = `${frame.frames * 100}%`; img.style.transform = `translateX(-${(frame.frames - 1) * 100 / frame.frames}%)`; }+ img.onerror = () => { img.remove(); box.closest('.phone-frame')?.classList.add('no-frame'); };+ }+ return box;+}+const fraction = job => Math.max(0, Math.min(1, Number(job.progress?.fraction) || 0));+function bar(job) { const b = el('div', 'phone-bar'), fill = el('i'); fill.style.width = `${fraction(job) * 100}%`; b.append(fill); b.setAttribute('role', 'progressbar'); b.setAttribute('aria-valuenow', String(Math.floor(fraction(job) * 100))); b.setAttribute('aria-label', job.label || t('Generating', '正在生成')); return b; }+function openJob(job) { if (job.status === 'succeeded') openResult(job); else { show('jobs'); generations.querySelector(`[data-job="${CSS.escape(job.id)}"]`)?.scrollIntoView({block: 'center'}); } }+function mini(job) {+ const b = button('phone-mini', '', () => openJob(jobs[job.id] || job)), body = el('div', 'phone-mini-body');+ body.append(el('div', 'phone-mini-title', job.label || t('Video', '视频')));+ if (job.status === 'succeeded') body.append(el('span', 'phone-link', t('View', '查看')));+ else if (['waiting', 'queued'].includes(job.status)) body.append(el('span', 'phone-mini-meta', t('Queued', '排队中')));+ else if (['failed', 'cancelled'].includes(job.status)) body.append(el('span', 'phone-mini-meta', job.status === 'failed' ? t('Failed', '失败') : t('Stopped', '已停止')));+ else { const meta = el('div', 'phone-mini-meta'); meta.append(el('b', '', `${Math.floor(fraction(job) * 100)}%`), el('span', 'phone-eta', remainingWords(job.progress?.remaining_seconds, t))); body.append(bar(job), meta); }+ b.append(picture(job, true), body); return b;+}+function renderChat() {+ const pinned = main.scrollHeight - main.clientHeight - main.scrollTop < 60;+ for (const entry of chatEntries(chat)) {+ if (lastSend && entry.id === lastSend.id) { lastSend.acknowledged = true; if (input.value.trim() === lastSend.text) { input.value = ''; grow(); } lastSend = null; notice(); }+ const job = jobs[entry.job], key = String(entry.seq), signature = JSON.stringify([entry, phoneJobKey(job), chat.confirms[entry.id]]);+ if (rows.get(key)?.signature === signature) continue;+ const row = el('li');+ if (entry.type === 'message') { row.className = 'phone-message ' + (entry.role === 'user' ? 'user' : 'agent'); row.textContent = entry.text; }+ else if (entry.type === 'job' && job) row.append(mini(job));+ else if (entry.type === 'confirm') {+ row.className = 'phone-confirm'; row.append(el('p', '', entry.question));+ const state = chat.confirms[entry.id] || entry.state;+ if (state === 'approved' || state === 'declined') row.append(el('span', '', state === 'approved' ? t('Approved', '已同意') : t('Declined', '已拒绝')));+ else for (const approve of [true, false]) {+ const b = button('phone-quiet', approve ? t('Start', '开始') : t('Cancel', '取消'), async () => {+ const version = revision, session = chat.session; row.querySelectorAll('button').forEach(e => e.disabled = true);+ try { const answer = await json(await dataLayer.confirm({id: entry.id, approve, ...(session ? {session} : {})})); if (revision === version) { chat.confirms[entry.id] = answer.state; renderChat(); } await poller.poll(); }+ catch { row.querySelectorAll('button').forEach(e => e.disabled = false); notice(t('Please try again.', '请重试。')); }+ }); row.append(b);+ }+ } else continue;+ const old = rows.get(key); if (old) old.element.replaceWith(row); else log.append(row); rows.set(key, {element: row, signature});+ }+ if (pinned && tab === 'chat') main.scrollTop = main.scrollHeight;+}+async function cancel(job, confirm) {+ if (confirm) {+ const dialog = el('dialog', 'fv-phone phone-confirm'); dialog.append(el('p', '', t('Stop this generation?', '停止这个生成?')));+ const actions = el('div', 'phone-confirm-actions');+ const yes = button('phone-quiet', t('Stop', '停止'), async () => { yes.disabled = true; if (await cancel(job, false)) dialog.close(); else yes.disabled = false; });+ const no = button('phone-quiet', t('Keep generating', '继续生成'), () => dialog.close()); actions.append(yes, no); dialog.append(actions); document.body.append(dialog); dialog.onclose = () => dialog.remove(); dialog.showModal(); no.focus(); return;+ }+ try { await json(await dataLayer.cancel(job.id)); await poller.poll(); return true; }+ catch { connection(false); return false; }+}+let jobsSignature = '';+function renderJobs() {+ const signature = JSON.stringify([Object.values(jobs).map(phoneJobKey), limit]); if (signature === jobsSignature) return; jobsSignature = signature;+ const active = document.activeElement?.dataset.action;+ const {running, queued, done} = jobGroups(jobs); generations.replaceChildren();+ if (!running.length && !queued.length && !done.length) generations.append(el('p', 'phone-empty', t('Nothing yet. Tell the Agent what to make in Chat.', '还没有作品,在对话里说想做什么。')));+ if (running.length) generations.append(el('h2', 'phone-section', t('Generating', '正在生成')));+ for (const job of running) {+ const card = el('article', 'phone-running'), frame = el('div', 'phone-frame'), info = el('div', 'phone-info'); card.dataset.job = job.id;+ const img = picture(job, true); img.style.aspectRatio = `${job.width || 9}/${job.height || 16}`; frame.append(img); frame.classList.toggle('no-frame', !img.firstChild);+ if (!img.firstChild) frame.append(el('span', 'phone-frame-pct', `${Math.floor(fraction(job) * 100)}%`));+ const row = el('div', 'phone-job-row'), numbers = el('div'); numbers.append(el('span', 'phone-pct', `${Math.floor(fraction(job) * 100)}%`), document.createTextNode(' '), el('span', 'phone-eta', remainingWords(job.progress?.remaining_seconds, t)));+ const stop = button('phone-quiet', t('Stop', '停止'), () => cancel(job, true)); stop.disabled = job.status === 'cancelling'; stop.dataset.action = 'stop-' + job.id; row.append(numbers, stop);+ info.append(el('p', 'phone-prompt', job.label)); if (phonePartWords(job, t)) info.append(el('span', 'phone-eta', phonePartWords(job, t))); info.append(bar(job), row); card.append(frame, info); generations.append(card);+ }+ if (queued.length) generations.append(el('h2', 'phone-section', t('Queued', '排队中')));+ queued.forEach((job, index) => {+ const row = el('div', 'phone-queue'), remove = button('phone-quiet', t('Remove', '移除'), async () => { remove.disabled = true; if (!await cancel(job, false)) remove.disabled = false; }); remove.hidden = true;+ row.tabIndex = 0; row.setAttribute('aria-label', `${job.label}, ${queueWords(index, t)}`); row.dataset.job = job.id;+ row.append(el('i', 'ph'), el('span', 'name', job.label), el('span', 'position', queueWords(index, t)), remove);+ let hold, x, y; const reveal = () => { remove.hidden = false; };+ row.onpointerdown = event => { x = event.clientX; y = event.clientY; hold = setTimeout(reveal, 500); };+ row.onpointermove = event => { if (Math.abs(event.clientY - y) > 12) clearTimeout(hold); if (x - event.clientX > 40 && Math.abs(event.clientY - y) < 25) { clearTimeout(hold); reveal(); } };+ row.onpointerup = row.onpointercancel = row.onlostpointercapture = () => clearTimeout(hold);+ row.oncontextmenu = event => { event.preventDefault(); reveal(); };+ row.onkeydown = event => { if (['Delete', 'Enter', ' '].includes(event.key)) { event.preventDefault(); reveal(); remove.focus(); } };+ generations.append(row);+ });+ if (done.length) generations.append(el('h2', 'phone-section', t('Done', '已完成')));+ // Keep chronological order, grouping only adjacent works of the same orientation.+ let grid, landscape;+ for (const job of done.slice(0, limit)) {+ const wide = job.width > job.height; if (!grid || landscape !== wide) { landscape = wide; grid = el('div', 'phone-grid' + (wide ? ' landscape' : '')); generations.append(grid); }+ const card = button('phone-done', '', () => openResult(job)); card.setAttribute('aria-label', job.label || t('View', '查看')); card.dataset.job = job.id;+ const time = job.finished_at ? new Date(job.finished_at * 1000).toLocaleTimeString([], {hour: '2-digit', minute: '2-digit', hour12: false}) : '';+ card.append(picture(job), el('span', 'phone-caption', [job.seconds > 0 ? `${job.seconds} s` : '', time].filter(Boolean).join(' · '))); grid.append(card);+ }+ if (active) generations.querySelector(`[data-action="${CSS.escape(active)}"]`)?.focus({preventScroll: true});+}+function openResult(job) {+ scrollPositions[tab] = main.scrollTop; result = job; toastJob = null; clearTimeout(toastTimer); const back = button('phone-back', '', () => show('jobs')); back.setAttribute('aria-label', t('Back', '返回')); back.append(icon('M15 5l-7 7 7 7')); top.replaceChildren(back);+ viewer.replaceChildren(); const stage = el('div', 'phone-viewer'), video = el('video'); video.controls = true; video.playsInline = true; video.preload = 'metadata'; video.src = mediaPath(job.play); const poster = mediaPath(job.thumbnail, 'image'); if (poster) video.poster = poster; stage.append(video);+ const actions = el('div', 'phone-result-actions'), error = el('p', 'phone-error'); error.hidden = true;+ const download = button('phone-primary', t('Download', '下载'), async () => {+ download.disabled = true; error.hidden = true;+ try { await saveVideo(job, {fetch: api.fetchApi, download(path, filename) { const a = el('a'); a.href = path; a.download = filename; document.body.append(a); a.click(); a.remove(); }}); }+ catch { error.textContent = t('Please try again.', '请重试。'); error.hidden = false; }+ finally { download.disabled = false; }+ });+ actions.append(el('p', 'phone-prompt', job.label), download, error); viewer.append(stage, actions); renderShell();+}+function completed(job) {+ toastJob = job; toast.replaceChildren(picture(job), el('span', '', t('Your video is ready', '生成好了')), button('phone-link', t('View', '查看'), () => { show('jobs'); openResult(job); }));+ main.classList.add('toast-space'); renderShell(); clearTimeout(toastTimer);+ toastTimer = setTimeout(() => { toastJob = null; toast.hidden = true; main.classList.remove('toast-space'); }, 6000);+ clearInterval(flash); let lit = false; flash = setInterval(() => { document.title = (lit = !lit) ? t('Your video is ready', '生成好了') : 'FreeVideo'; }, 1000);+ setTimeout(() => { clearInterval(flash); document.title = 'FreeVideo'; }, 6000);+ if ('Notification' in window) {+ if (document.hidden && Notification.permission === 'granted') { try { const n = new Notification(t('Your video is ready', '生成好了')); n.onclick = () => { window.focus(); show('jobs'); openResult(job); n.close(); }; } catch {} }+ if (!permissionAsked && Notification.permission === 'default') { permissionAsked = true; try { localStorage.setItem('freevideo.phone.notification-asked', '1'); } catch {} Notification.requestPermission().catch(() => {}); }+ }+}+async function refresh() {+ if (stopped || locked) return;+ const version = revision, {after} = chatReadRequest(chat, selected);+ try {+ const [data, activity, progress, now] = await Promise.all([dataLayer.read({session: selected, after}).then(json), dataLayer.activity().then(json), api.fetchApi('/freevideo/progress', {cache: 'no-store'}).then(json), dataLayer.now().then(json)]);+ if (stopped || locked || version !== revision) return;+ if (after && data.session !== chat.session) { drafts.set(chat.session, input.value); input.value = drafts.get(data.session) || ''; grow(); chat = emptyChat(); rows.clear(); log.replaceChildren(); await refresh(); return; }+ if (data.session !== chat.session) { chat = emptyChat(); rows.clear(); log.replaceChildren(); }+ chat = chatMerge(chat, data); const previous = jobs;+ jobs = mergePhoneJobs(jobs, {...chat.jobs, ...(now.current?.id ? {[now.current.id]: now.current} : {})}, activity.jobs || [], progress.progress || []);+ if (!historyStarted) cursor = activity.next_cursor ?? null;+ const running = jobGroups(jobs).running;+ await Promise.all(running.filter(job => job.chain_id).map(async job => {+ const {chain} = await json(await api.fetchApi('/freevideo/chain/' + encodeURIComponent(job.chain_id), {cache: 'no-store'}));+ if (stopped || version !== revision || !chain) return;+ jobs[job.id] = applyPhoneChain(job, chain);+ }));+ if (stopped || version !== revision) return;+ for (const job of Object.values(jobs)) if (job.status === 'succeeded' && previous[job.id] && ['running', 'queued', 'waiting', 'cancelling'].includes(previous[job.id].status)) completed(job);+ connection(true); renderChat(); if (tab === 'jobs') renderJobs();+ const response = await dataLayer.list();+ if (response.ok) { const list = await response.json(); if (version !== revision || stopped) return; convRows = list.conversations || []; convCurrent = selected || chat.session || list.here || ''; if (!sheet.hidden) renderSheet(); }+ } catch { if (!stopped) connection(false); }+}+const poller = chatPoller(refresh, {delay: () => chatDelay({phone: true, hidden: document.hidden})});+main.addEventListener('scroll', async () => {+ if (tab !== 'jobs' || main.scrollTop + main.clientHeight < main.scrollHeight - 150 || loadingMore) return;+ if (jobGroups(jobs).done.length > limit) { limit += 30; renderJobs(); return; }+ if (!cursor) return;+ loadingMore = true;+ try { const data = await json(await dataLayer.activity(cursor)); jobs = mergePhoneJobs(jobs, {}, data.jobs || []); cursor = data.next_cursor ?? null; historyStarted = true; limit += 30; renderJobs(); }+ catch { connection(false); } finally { loadingMore = false; }+}, {passive: true});+document.addEventListener('visibilitychange', () => { if (!document.hidden) { clearInterval(flash); document.title = 'FreeVideo'; poller.poll(); } else poller.reschedule(); });+window.addEventListener('pagehide', event => { if (!event.persisted) { stopped = true; closed.abort(); poller.dispose(); clearInterval(countdown); clearInterval(flash); clearTimeout(toastTimer); } });+window.addEventListener('pageshow', event => { if (event.persisted) poller.poll(); });+renderShell(); poller.poll();++return {refresh: () => poller.poll()};+}+if (document.querySelector('#phone')) mountPhone(document.querySelector('#phone'));diff --git a/web/phone_model.js b/web/phone_model.jsnew file mode 100644index 0000000..450acee--- /dev/null+++ b/web/phone_model.js@@ -0,0 +1,88 @@+import {chainPosition} from './studio_chain.js';+// Data shaping only. Backend identifiers are never guessed from the current job.+export const phoneText = (language = '') => String(language).toLowerCase().startsWith('zh') ? (en, zh) => zh : en => en;+export const activeJob = job => ['running', 'cancelling'].includes(job.status);+export const queuedJob = job => ['waiting', 'queued'].includes(job.status);+export function jobGroups(jobs) {+ const rows = Object.values(jobs).filter(job => ['generate', 'assemble'].includes(job.kind));+ return {running: rows.filter(activeJob), queued: rows.filter(queuedJob).sort((a, b) => (a.progress?.queue_position ?? Infinity) - (b.progress?.queue_position ?? Infinity) || a.created_at - b.created_at),+ done: rows.filter(job => job.status === 'succeeded').sort((a, b) => b.finished_at - a.finished_at || b.created_at - a.created_at)};+}+export function mergePhoneJobs(previous, chat, activity, snapshots = []) {+ const jobs = {...previous};+ for (const row of [...Object.values(chat), ...activity]) {+ const old = jobs[row.id] || {};+ jobs[row.id] = {...old, ...row, progress: {...old.progress, ...row.progress}};+ }+ for (const job of Object.values(jobs)) {+ if (!activeJob(job)) continue;+ const message = snapshots.find(m => m.job_id === job.id || (job.node != null && job.prompt_id && String(m.node) === String(job.node) && m.prompt_id === job.prompt_id));+ if (message) job.progress = {...job.progress, ...message,+ fraction: message.overall?.fraction ?? job.progress?.fraction,+ remaining_seconds: message.overall?.remaining_seconds ?? job.progress?.remaining_seconds};+ }+ return jobs;+}+export function retryWords(seconds, t) {+ const count = Math.ceil(Math.max(0, seconds));+ return count > 90 ? t(`Too many tries. Please try again in ${Math.ceil(count / 60)} min.`, `试错次数太多,请 ${Math.ceil(count / 60)} 分钟后再试。`)+ : t(`Too many tries. Please try again in ${count} s.`, `试错次数太多,请 ${count} 秒后再试。`);+}+export function queueWords(index, t) {+ const n = index + 1, mod = n % 100;+ const suffix = mod >= 11 && mod <= 13 ? 'th' : ({1: 'st', 2: 'nd', 3: 'rd'}[n % 10] || 'th');+ return t(index === 0 ? 'Next' : `${n}${suffix}`, `第 ${n} 个`);+}+export function remainingWords(seconds, t) {+ if (!(seconds > 0)) return '';+ return seconds >= 60 ? t(`About ${Math.ceil(seconds / 60)} min left`, `还要约 ${Math.ceil(seconds / 60)} 分钟`) : t('Under 1 min', '不到 1 分钟');+}+export function mediaPath(value, kind = 'video') {+ if (typeof value !== 'string' || !value.startsWith('/') || value.startsWith('//')) return '';+ const path = value.split('?')[0];+ return (kind === 'video' ? path === '/freevideo/agent/chat/video' : path === '/view' || /^\/freevideo\/frame-preview\/[^/]+$/.test(path)) ? value : '';+}+export const isIOS = navigator => /iPad|iPhone|iPod/.test(navigator.userAgent || '') || navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1;+export async function saveVideo(job, {navigator: nav = globalThis.navigator, fetch: get = globalThis.fetch, download, File: FileType = globalThis.File} = {}) {+ const path = mediaPath(job.play); if (!path) throw new Error('Video unavailable');+ if (isIOS(nav) && nav.share && FileType) {+ const response = await get(path, {credentials: 'same-origin'});+ if (!response.ok) throw new Error('Video unavailable');+ const file = new FileType([await response.blob()], 'FreeVideo.mp4', {type: 'video/mp4'});+ if (!nav.canShare || nav.canShare({files: [file]})) {+ try { await nav.share({files: [file]}); return 'shared'; }+ catch (error) { if (error.name === 'AbortError') return 'cancelled'; throw error; }+ }+ }+ download(path, 'FreeVideo.mp4'); return 'downloaded';+}++export function applyPhoneChain(job, chain) {+ if (!chain) return job;+ const position = chainPosition(chain), overall = chain.overall || {};+ return {...job, status: chain.state === 'queued' || chain.waiting === true ? 'waiting' : job.status,+ progress: {...job.progress, ...(Number.isFinite(overall.fraction) ? {fraction: overall.fraction} : {}),+ ...(Number.isFinite(overall.remaining_seconds) ? {remaining_seconds: overall.remaining_seconds} : {}),+ block: {index: position.index + 1, total: position.count}, waiting: chain.waiting === true}};+}+export function phonePartWords(job, t) {+ const b = job.progress?.block;+ if (!(b?.total > 1)) return '';+ return job.progress.waiting ? t(`Waiting in queue · Part ${b.index} of ${b.total}`, `正在排队 · 第 ${b.index} 段,共 ${b.total} 段`)+ : t(`Part ${b.index} of ${b.total}`, `第 ${b.index} 段,共 ${b.total} 段`);+}++// Ignore heartbeat-only fields when deciding whether a card needs repainting.+export function phoneJobKey(job = {}) {+ const p = job.progress || {};+ return [job.id, job.kind, job.status, job.label, job.play, job.thumbnail, job.width, job.height, job.node,+ job.seconds, job.finished_at, p.fraction, p.remaining_seconds, p.queue_position, p.block, p.waiting,+ p.frame_preview?.serial, p.frame_preview?.frames];+}++export function longGeneration(value) {+ if (!value || ['succeeded', 'failed', 'cancelled', 'complete'].includes(value.status || value.phase)) return false;+ if (value.status && value.status !== 'running' || ['queued', 'waiting'].includes(value.phase)) return false;+ const p = value.progress || value;+ return Number(p.remaining_seconds ?? p.overall?.remaining_seconds) > 120 || Number(p.elapsed_seconds ?? p.overall?.elapsed_seconds) >= 120;+}diff --git a/web/qrcodegen.js b/web/qrcodegen.jsnew file mode 100644index 0000000..e69adc5--- /dev/null+++ b/web/qrcodegen.js@@ -0,0 +1,840 @@+/*+ * QR Code generator library (compiled from TypeScript)+ *+ * Copyright (c) Project Nayuki. (MIT License)+ * https://www.nayuki.io/page/qr-code-generator-library+ *+ * Permission is hereby granted, free of charge, to any person obtaining a copy of+ * this software and associated documentation files (the "Software"), to deal in+ * the Software without restriction, including without limitation the rights to+ * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of+ * the Software, and to permit persons to whom the Software is furnished to do so,+ * subject to the following conditions:+ * - The above copyright notice and this permission notice shall be included in+ * all copies or substantial portions of the Software.+ * - The Software is provided "as is", without warranty of any kind, express or+ * implied, including but not limited to the warranties of merchantability,+ * fitness for a particular purpose and noninfringement. In no event shall the+ * authors or copyright holders be liable for any claim, damages or other+ * liability, whether in an action of contract, tort or otherwise, arising from,+ * out of or in connection with the Software or the use or other dealings in the+ * Software.+ */+"use strict";+var qrcodegen;+(function (qrcodegen) {+ /*---- QR Code symbol class ----*/+ /*+ * A QR Code symbol, which is a type of two-dimension barcode.+ * Invented by Denso Wave and described in the ISO/IEC 18004 standard.+ * Instances of this class represent an immutable square grid of dark and light cells.+ * The class provides static factory functions to create a QR Code from text or binary data.+ * The class covers the QR Code Model 2 specification, supporting all versions (sizes)+ * from 1 to 40, all 4 error correction levels, and 4 character encoding modes.+ *+ * Ways to create a QR Code object:+ * - High level: Take the payload data and call QrCode.encodeText() or QrCode.encodeBinary().+ * - Mid level: Custom-make the list of segments and call QrCode.encodeSegments().+ * - Low level: Custom-make the array of data codeword bytes (including+ * segment headers and final padding, excluding error correction codewords),+ * supply the appropriate version number, and call the QrCode() constructor.+ * (Note that all ways require supplying the desired error correction level.)+ */+ class QrCode {+ /*-- Constructor (low level) and fields --*/+ // Creates a new QR Code with the given version number,+ // error correction level, data codeword bytes, and mask number.+ // This is a low-level API that most users should not use directly.+ // A mid-level API is the encodeSegments() function.+ constructor(+ // The version number of this QR Code, which is between 1 and 40 (inclusive).+ // This determines the size of this barcode.+ version,+ // The error correction level used in this QR Code.+ errorCorrectionLevel, dataCodewords, msk) {+ this.version = version;+ this.errorCorrectionLevel = errorCorrectionLevel;+ // The modules of this QR Code (false = light, true = dark).+ // Immutable after constructor finishes. Accessed through getModule().+ this.modules = [];+ // Indicates function modules that are not subjected to masking. Discarded when constructor finishes.+ this.isFunction = [];+ // Check scalar arguments+ if (version < QrCode.MIN_VERSION || version > QrCode.MAX_VERSION)+ throw new RangeError("Version value out of range");+ if (msk < -1 || msk > 7)+ throw new RangeError("Mask value out of range");+ this.size = version * 4 + 17;+ // Initialize both grids to be size*size arrays of Boolean false+ let row = [];+ for (let i = 0; i < this.size; i++)+ row.push(false);+ for (let i = 0; i < this.size; i++) {+ this.modules.push(row.slice()); // Initially all light+ this.isFunction.push(row.slice());+ }+ // Compute ECC, draw modules+ this.drawFunctionPatterns();+ const allCodewords = this.addEccAndInterleave(dataCodewords);+ this.drawCodewords(allCodewords);+ // Do masking+ if (msk == -1) { // Automatically choose best mask+ let minPenalty = 1000000000;+ for (let i = 0; i < 8; i++) {+ this.applyMask(i);+ this.drawFormatBits(i);+ const penalty = this.getPenaltyScore();+ if (penalty < minPenalty) {+ msk = i;+ minPenalty = penalty;+ }+ this.applyMask(i); // Undoes the mask due to XOR+ }+ }+ assert(0 <= msk && msk <= 7);+ this.mask = msk;+ this.applyMask(msk); // Apply the final choice of mask+ this.drawFormatBits(msk); // Overwrite old format bits+ this.isFunction = [];+ }+ /*-- Static factory functions (high level) --*/+ // Returns a QR Code representing the given Unicode text string at the given error correction level.+ // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer+ // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible+ // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the+ // ecl argument if it can be done without increasing the version.+ static encodeText(text, ecl) {+ const segs = qrcodegen.QrSegment.makeSegments(text);+ return QrCode.encodeSegments(segs, ecl);+ }+ // Returns a QR Code representing the given binary data at the given error correction level.+ // This function always encodes using the binary segment mode, not any text mode. The maximum number of+ // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output.+ // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version.+ static encodeBinary(data, ecl) {+ const seg = qrcodegen.QrSegment.makeBytes(data);+ return QrCode.encodeSegments([seg], ecl);+ }+ /*-- Static factory functions (mid level) --*/+ // Returns a QR Code representing the given segments with the given encoding parameters.+ // The smallest possible QR Code version within the given range is automatically+ // chosen for the output. Iff boostEcl is true, then the ECC level of the result+ // may be higher than the ecl argument if it can be done without increasing the+ // version. The mask number is either between 0 to 7 (inclusive) to force that+ // mask, or -1 to automatically choose an appropriate mask (which may be slow).+ // This function allows the user to create a custom sequence of segments that switches+ // between modes (such as alphanumeric and byte) to encode text in less space.+ // This is a mid-level API; the high-level API is encodeText() and encodeBinary().+ static encodeSegments(segs, ecl, minVersion = 1, maxVersion = 40, mask = -1, boostEcl = true) {+ if (!(QrCode.MIN_VERSION <= minVersion && minVersion <= maxVersion && maxVersion <= QrCode.MAX_VERSION)+ || mask < -1 || mask > 7)+ throw new RangeError("Invalid value");+ // Find the minimal version number to use+ let version;+ let dataUsedBits;+ for (version = minVersion;; version++) {+ const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8; // Number of data bits available+ const usedBits = QrSegment.getTotalBits(segs, version);+ if (usedBits <= dataCapacityBits) {+ dataUsedBits = usedBits;+ break; // This version number is found to be suitable+ }+ if (version >= maxVersion) // All versions in the range could not fit the given data+ throw new RangeError("Data too long");+ }+ // Increase the error correction level while the data still fits in the current version number+ for (const newEcl of [QrCode.Ecc.MEDIUM, QrCode.Ecc.QUARTILE, QrCode.Ecc.HIGH]) { // From low to high+ if (boostEcl && dataUsedBits <= QrCode.getNumDataCodewords(version, newEcl) * 8)+ ecl = newEcl;+ }+ // Concatenate all segments to create the data bit string+ let bb = [];+ for (const seg of segs) {+ appendBits(seg.mode.modeBits, 4, bb);+ appendBits(seg.numChars, seg.mode.numCharCountBits(version), bb);+ for (const b of seg.getData())+ bb.push(b);+ }+ assert(bb.length == dataUsedBits);+ // Add terminator and pad up to a byte if applicable+ const dataCapacityBits = QrCode.getNumDataCodewords(version, ecl) * 8;+ assert(bb.length <= dataCapacityBits);+ appendBits(0, Math.min(4, dataCapacityBits - bb.length), bb);+ appendBits(0, (8 - bb.length % 8) % 8, bb);+ assert(bb.length % 8 == 0);+ // Pad with alternating bytes until data capacity is reached+ for (let padByte = 0xEC; bb.length < dataCapacityBits; padByte ^= 0xEC ^ 0x11)+ appendBits(padByte, 8, bb);+ // Pack bits into bytes in big endian+ let dataCodewords = [];+ while (dataCodewords.length * 8 < bb.length)+ dataCodewords.push(0);+ bb.forEach((b, i) => dataCodewords[i >>> 3] |= b << (7 - (i & 7)));+ // Create the QR Code object+ return new QrCode(version, ecl, dataCodewords, mask);+ }+ /*-- Accessor methods --*/+ // Returns the color of the module (pixel) at the given coordinates, which is false+ // for light or true for dark. The top left corner has the coordinates (x=0, y=0).+ // If the given coordinates are out of bounds, then false (light) is returned.+ getModule(x, y) {+ return 0 <= x && x < this.size && 0 <= y && y < this.size && this.modules[y][x];+ }+ /*-- Private helper methods for constructor: Drawing function modules --*/+ // Reads this object's version field, and draws and marks all function modules.+ drawFunctionPatterns() {+ // Draw horizontal and vertical timing patterns+ for (let i = 0; i < this.size; i++) {+ this.setFunctionModule(6, i, i % 2 == 0);+ this.setFunctionModule(i, 6, i % 2 == 0);+ }+ // Draw 3 finder patterns (all corners except bottom right; overwrites some timing modules)+ this.drawFinderPattern(3, 3);+ this.drawFinderPattern(this.size - 4, 3);+ this.drawFinderPattern(3, this.size - 4);+ // Draw numerous alignment patterns+ const alignPatPos = this.getAlignmentPatternPositions();+ const numAlign = alignPatPos.length;+ for (let i = 0; i < numAlign; i++) {+ for (let j = 0; j < numAlign; j++) {+ // Don't draw on the three finder corners+ if (!(i == 0 && j == 0 || i == 0 && j == numAlign - 1 || i == numAlign - 1 && j == 0))+ this.drawAlignmentPattern(alignPatPos[i], alignPatPos[j]);+ }+ }+ // Draw configuration data+ this.drawFormatBits(0); // Dummy mask value; overwritten later in the constructor+ this.drawVersion();+ }+ // Draws two copies of the format bits (with its own error correction code)+ // based on the given mask and this object's error correction level field.+ drawFormatBits(mask) {+ // Calculate error correction code and pack bits+ const data = this.errorCorrectionLevel.formatBits << 3 | mask; // errCorrLvl is uint2, mask is uint3+ let rem = data;+ for (let i = 0; i < 10; i++)+ rem = (rem << 1) ^ ((rem >>> 9) * 0x537);+ const bits = (data << 10 | rem) ^ 0x5412; // uint15+ assert(bits >>> 15 == 0);+ // Draw first copy+ for (let i = 0; i <= 5; i++)+ this.setFunctionModule(8, i, getBit(bits, i));+ this.setFunctionModule(8, 7, getBit(bits, 6));+ this.setFunctionModule(8, 8, getBit(bits, 7));+ this.setFunctionModule(7, 8, getBit(bits, 8));+ for (let i = 9; i < 15; i++)+ this.setFunctionModule(14 - i, 8, getBit(bits, i));+ // Draw second copy+ for (let i = 0; i < 8; i++)+ this.setFunctionModule(this.size - 1 - i, 8, getBit(bits, i));+ for (let i = 8; i < 15; i++)+ this.setFunctionModule(8, this.size - 15 + i, getBit(bits, i));+ this.setFunctionModule(8, this.size - 8, true); // Always dark+ }+ // Draws two copies of the version bits (with its own error correction code),+ // based on this object's version field, iff 7 <= version <= 40.+ drawVersion() {+ if (this.version < 7)+ return;+ // Calculate error correction code and pack bits+ let rem = this.version; // version is uint6, in the range [7, 40]+ for (let i = 0; i < 12; i++)+ rem = (rem << 1) ^ ((rem >>> 11) * 0x1F25);+ const bits = this.version << 12 | rem; // uint18+ assert(bits >>> 18 == 0);+ // Draw two copies+ for (let i = 0; i < 18; i++) {+ const color = getBit(bits, i);+ const a = this.size - 11 + i % 3;+ const b = Math.floor(i / 3);+ this.setFunctionModule(a, b, color);+ this.setFunctionModule(b, a, color);+ }+ }+ // Draws a 9*9 finder pattern including the border separator,+ // with the center module at (x, y). Modules can be out of bounds.+ drawFinderPattern(x, y) {+ for (let dy = -4; dy <= 4; dy++) {+ for (let dx = -4; dx <= 4; dx++) {+ const dist = Math.max(Math.abs(dx), Math.abs(dy)); // Chebyshev/infinity norm+ const xx = x + dx;+ const yy = y + dy;+ if (0 <= xx && xx < this.size && 0 <= yy && yy < this.size)+ this.setFunctionModule(xx, yy, dist != 2 && dist != 4);+ }+ }+ }+ // Draws a 5*5 alignment pattern, with the center module+ // at (x, y). All modules must be in bounds.+ drawAlignmentPattern(x, y) {+ for (let dy = -2; dy <= 2; dy++) {+ for (let dx = -2; dx <= 2; dx++)+ this.setFunctionModule(x + dx, y + dy, Math.max(Math.abs(dx), Math.abs(dy)) != 1);+ }+ }+ // Sets the color of a module and marks it as a function module.+ // Only used by the constructor. Coordinates must be in bounds.+ setFunctionModule(x, y, isDark) {+ this.modules[y][x] = isDark;+ this.isFunction[y][x] = true;+ }+ /*-- Private helper methods for constructor: Codewords and masking --*/+ // Returns a new byte string representing the given data with the appropriate error correction+ // codewords appended to it, based on this object's version and error correction level.+ addEccAndInterleave(data) {+ const ver = this.version;+ const ecl = this.errorCorrectionLevel;+ if (data.length != QrCode.getNumDataCodewords(ver, ecl))+ throw new RangeError("Invalid argument");+ // Calculate parameter numbers+ const numBlocks = QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];+ const blockEccLen = QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver];+ const rawCodewords = Math.floor(QrCode.getNumRawDataModules(ver) / 8);+ const numShortBlocks = numBlocks - rawCodewords % numBlocks;+ const shortBlockLen = Math.floor(rawCodewords / numBlocks);+ // Split data into blocks and append ECC to each block+ let blocks = [];+ const rsDiv = QrCode.reedSolomonComputeDivisor(blockEccLen);+ for (let i = 0, k = 0; i < numBlocks; i++) {+ let dat = data.slice(k, k + shortBlockLen - blockEccLen + (i < numShortBlocks ? 0 : 1));+ k += dat.length;+ const ecc = QrCode.reedSolomonComputeRemainder(dat, rsDiv);+ if (i < numShortBlocks)+ dat.push(0);+ blocks.push(dat.concat(ecc));+ }+ // Interleave (not concatenate) the bytes from every block into a single sequence+ let result = [];+ for (let i = 0; i < blocks[0].length; i++) {+ blocks.forEach((block, j) => {+ // Skip the padding byte in short blocks+ if (i != shortBlockLen - blockEccLen || j >= numShortBlocks)+ result.push(block[i]);+ });+ }+ assert(result.length == rawCodewords);+ return result;+ }+ // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire+ // data area of this QR Code. Function modules need to be marked off before this is called.+ drawCodewords(data) {+ if (data.length != Math.floor(QrCode.getNumRawDataModules(this.version) / 8))+ throw new RangeError("Invalid argument");+ let i = 0; // Bit index into the data+ // Do the funny zigzag scan+ for (let right = this.size - 1; right >= 1; right -= 2) { // Index of right column in each column pair+ if (right == 6)+ right = 5;+ for (let vert = 0; vert < this.size; vert++) { // Vertical counter+ for (let j = 0; j < 2; j++) {+ const x = right - j; // Actual x coordinate+ const upward = ((right + 1) & 2) == 0;+ const y = upward ? this.size - 1 - vert : vert; // Actual y coordinate+ if (!this.isFunction[y][x] && i < data.length * 8) {+ this.modules[y][x] = getBit(data[i >>> 3], 7 - (i & 7));+ i++;+ }+ // If this QR Code has any remainder bits (0 to 7), they were assigned as+ // 0/false/light by the constructor and are left unchanged by this method+ }+ }+ }+ assert(i == data.length * 8);+ }+ // XORs the codeword modules in this QR Code with the given mask pattern.+ // The function modules must be marked and the codeword bits must be drawn+ // before masking. Due to the arithmetic of XOR, calling applyMask() with+ // the same mask value a second time will undo the mask. A final well-formed+ // QR Code needs exactly one (not zero, two, etc.) mask applied.+ applyMask(mask) {+ if (mask < 0 || mask > 7)+ throw new RangeError("Mask value out of range");+ for (let y = 0; y < this.size; y++) {+ for (let x = 0; x < this.size; x++) {+ let invert;+ switch (mask) {+ case 0:+ invert = (x + y) % 2 == 0;+ break;+ case 1:+ invert = y % 2 == 0;+ break;+ case 2:+ invert = x % 3 == 0;+ break;+ case 3:+ invert = (x + y) % 3 == 0;+ break;+ case 4:+ invert = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 == 0;+ break;+ case 5:+ invert = x * y % 2 + x * y % 3 == 0;+ break;+ case 6:+ invert = (x * y % 2 + x * y % 3) % 2 == 0;+ break;+ case 7:+ invert = ((x + y) % 2 + x * y % 3) % 2 == 0;+ break;+ default: throw new Error("Unreachable");+ }+ if (!this.isFunction[y][x] && invert)+ this.modules[y][x] = !this.modules[y][x];+ }+ }+ }+ // Calculates and returns the penalty score based on state of this QR Code's current modules.+ // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score.+ getPenaltyScore() {+ let result = 0;+ // Adjacent modules in row having same color, and finder-like patterns+ for (let y = 0; y < this.size; y++) {+ let runColor = false;+ let runX = 0;+ let runHistory = [0, 0, 0, 0, 0, 0, 0];+ for (let x = 0; x < this.size; x++) {+ if (this.modules[y][x] == runColor) {+ runX++;+ if (runX == 5)+ result += QrCode.PENALTY_N1;+ else if (runX > 5)+ result++;+ }+ else {+ this.finderPenaltyAddHistory(runX, runHistory);+ if (!runColor)+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;+ runColor = this.modules[y][x];+ runX = 1;+ }+ }+ result += this.finderPenaltyTerminateAndCount(runColor, runX, runHistory) * QrCode.PENALTY_N3;+ }+ // Adjacent modules in column having same color, and finder-like patterns+ for (let x = 0; x < this.size; x++) {+ let runColor = false;+ let runY = 0;+ let runHistory = [0, 0, 0, 0, 0, 0, 0];+ for (let y = 0; y < this.size; y++) {+ if (this.modules[y][x] == runColor) {+ runY++;+ if (runY == 5)+ result += QrCode.PENALTY_N1;+ else if (runY > 5)+ result++;+ }+ else {+ this.finderPenaltyAddHistory(runY, runHistory);+ if (!runColor)+ result += this.finderPenaltyCountPatterns(runHistory) * QrCode.PENALTY_N3;+ runColor = this.modules[y][x];+ runY = 1;+ }+ }+ result += this.finderPenaltyTerminateAndCount(runColor, runY, runHistory) * QrCode.PENALTY_N3;+ }+ // 2*2 blocks of modules having same color+ for (let y = 0; y < this.size - 1; y++) {+ for (let x = 0; x < this.size - 1; x++) {+ const color = this.modules[y][x];+ if (color == this.modules[y][x + 1] &&+ color == this.modules[y + 1][x] &&+ color == this.modules[y + 1][x + 1])+ result += QrCode.PENALTY_N2;+ }+ }+ // Balance of dark and light modules+ let dark = 0;+ for (const row of this.modules)+ dark = row.reduce((sum, color) => sum + (color ? 1 : 0), dark);+ const total = this.size * this.size; // Note that size is odd, so dark/total != 1/2+ // Compute the smallest integer k >= 0 such that (45-5k)% <= dark/total <= (55+5k)%+ const k = Math.ceil(Math.abs(dark * 20 - total * 10) / total) - 1;+ assert(0 <= k && k <= 9);+ result += k * QrCode.PENALTY_N4;+ assert(0 <= result && result <= 2568888); // Non-tight upper bound based on default values of PENALTY_N1, ..., N4+ return result;+ }+ /*-- Private helper functions --*/+ // Returns an ascending list of positions of alignment patterns for this version number.+ // Each position is in the range [0,177), and are used on both the x and y axes.+ // This could be implemented as lookup table of 40 variable-length lists of integers.+ getAlignmentPatternPositions() {+ if (this.version == 1)+ return [];+ else {+ const numAlign = Math.floor(this.version / 7) + 2;+ const step = (this.version == 32) ? 26 :+ Math.ceil((this.version * 4 + 4) / (numAlign * 2 - 2)) * 2;+ let result = [6];+ for (let pos = this.size - 7; result.length < numAlign; pos -= step)+ result.splice(1, 0, pos);+ return result;+ }+ }+ // Returns the number of data bits that can be stored in a QR Code of the given version number, after+ // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8.+ // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table.+ static getNumRawDataModules(ver) {+ if (ver < QrCode.MIN_VERSION || ver > QrCode.MAX_VERSION)+ throw new RangeError("Version number out of range");+ let result = (16 * ver + 128) * ver + 64;+ if (ver >= 2) {+ const numAlign = Math.floor(ver / 7) + 2;+ result -= (25 * numAlign - 10) * numAlign - 55;+ if (ver >= 7)+ result -= 36;+ }+ assert(208 <= result && result <= 29648);+ return result;+ }+ // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any+ // QR Code of the given version number and error correction level, with remainder bits discarded.+ // This stateless pure function could be implemented as a (40*4)-cell lookup table.+ static getNumDataCodewords(ver, ecl) {+ return Math.floor(QrCode.getNumRawDataModules(ver) / 8) -+ QrCode.ECC_CODEWORDS_PER_BLOCK[ecl.ordinal][ver] *+ QrCode.NUM_ERROR_CORRECTION_BLOCKS[ecl.ordinal][ver];+ }+ // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be+ // implemented as a lookup table over all possible parameter values, instead of as an algorithm.+ static reedSolomonComputeDivisor(degree) {+ if (degree < 1 || degree > 255)+ throw new RangeError("Degree out of range");+ // Polynomial coefficients are stored from highest to lowest power, excluding the leading term which is always 1.+ // For example the polynomial x^3 + 255x^2 + 8x + 93 is stored as the uint8 array [255, 8, 93].+ let result = [];+ for (let i = 0; i < degree - 1; i++)+ result.push(0);+ result.push(1); // Start off with the monomial x^0+ // Compute the product polynomial (x - r^0) * (x - r^1) * (x - r^2) * ... * (x - r^{degree-1}),+ // and drop the highest monomial term which is always 1x^degree.+ // Note that r = 0x02, which is a generator element of this field GF(2^8/0x11D).+ let root = 1;+ for (let i = 0; i < degree; i++) {+ // Multiply the current product by (x - r^i)+ for (let j = 0; j < result.length; j++) {+ result[j] = QrCode.reedSolomonMultiply(result[j], root);+ if (j + 1 < result.length)+ result[j] ^= result[j + 1];+ }+ root = QrCode.reedSolomonMultiply(root, 0x02);+ }+ return result;+ }+ // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials.+ static reedSolomonComputeRemainder(data, divisor) {+ let result = divisor.map(_ => 0);+ for (const b of data) { // Polynomial division+ const factor = b ^ result.shift();+ result.push(0);+ divisor.forEach((coef, i) => result[i] ^= QrCode.reedSolomonMultiply(coef, factor));+ }+ return result;+ }+ // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result+ // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8.+ static reedSolomonMultiply(x, y) {+ if (x >>> 8 != 0 || y >>> 8 != 0)+ throw new RangeError("Byte out of range");+ // Russian peasant multiplication+ let z = 0;+ for (let i = 7; i >= 0; i--) {+ z = (z << 1) ^ ((z >>> 7) * 0x11D);+ z ^= ((y >>> i) & 1) * x;+ }+ assert(z >>> 8 == 0);+ return z;+ }+ // Can only be called immediately after a light run is added, and+ // returns either 0, 1, or 2. A helper function for getPenaltyScore().+ finderPenaltyCountPatterns(runHistory) {+ const n = runHistory[1];+ assert(n <= this.size * 3);+ const core = n > 0 && runHistory[2] == n && runHistory[3] == n * 3 && runHistory[4] == n && runHistory[5] == n;+ return (core && runHistory[0] >= n * 4 && runHistory[6] >= n ? 1 : 0)+ + (core && runHistory[6] >= n * 4 && runHistory[0] >= n ? 1 : 0);+ }+ // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore().+ finderPenaltyTerminateAndCount(currentRunColor, currentRunLength, runHistory) {+ if (currentRunColor) { // Terminate dark run+ this.finderPenaltyAddHistory(currentRunLength, runHistory);+ currentRunLength = 0;+ }+ currentRunLength += this.size; // Add light border to final run+ this.finderPenaltyAddHistory(currentRunLength, runHistory);+ return this.finderPenaltyCountPatterns(runHistory);+ }+ // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore().+ finderPenaltyAddHistory(currentRunLength, runHistory) {+ if (runHistory[0] == 0)+ currentRunLength += this.size; // Add light border to initial run+ runHistory.pop();+ runHistory.unshift(currentRunLength);+ }+ }+ /*-- Constants and tables --*/+ // The minimum version number supported in the QR Code Model 2 standard.+ QrCode.MIN_VERSION = 1;+ // The maximum version number supported in the QR Code Model 2 standard.+ QrCode.MAX_VERSION = 40;+ // For use in getPenaltyScore(), when evaluating which mask is best.+ QrCode.PENALTY_N1 = 3;+ QrCode.PENALTY_N2 = 3;+ QrCode.PENALTY_N3 = 40;+ QrCode.PENALTY_N4 = 10;+ QrCode.ECC_CODEWORDS_PER_BLOCK = [+ // Version: (note that index 0 is for padding, and is set to an illegal value)+ //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level+ [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],+ [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28],+ [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30],+ [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], // High+ ];+ QrCode.NUM_ERROR_CORRECTION_BLOCKS = [+ // Version: (note that index 0 is for padding, and is set to an illegal value)+ //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level+ [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25],+ [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49],+ [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68],+ [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81], // High+ ];+ qrcodegen.QrCode = QrCode;+ // Appends the given number of low-order bits of the given value+ // to the given buffer. Requires 0 <= len <= 31 and 0 <= val < 2^len.+ function appendBits(val, len, bb) {+ if (len < 0 || len > 31 || val >>> len != 0)+ throw new RangeError("Value out of range");+ for (let i = len - 1; i >= 0; i--) // Append bit by bit+ bb.push((val >>> i) & 1);+ }+ // Returns true iff the i'th bit of x is set to 1.+ function getBit(x, i) {+ return ((x >>> i) & 1) != 0;+ }+ // Throws an exception if the given condition is false.+ function assert(cond) {+ if (!cond)+ throw new Error("Assertion error");+ }+ /*---- Data segment class ----*/+ /*+ * A segment of character/binary/control data in a QR Code symbol.+ * Instances of this class are immutable.+ * The mid-level way to create a segment is to take the payload data+ * and call a static factory function such as QrSegment.makeNumeric().+ * The low-level way to create a segment is to custom-make the bit buffer+ * and call the QrSegment() constructor with appropriate values.+ * This segment class imposes no length restrictions, but QR Codes have restrictions.+ * Even in the most favorable conditions, a QR Code can only hold 7089 characters of data.+ * Any segment longer than this is meaningless for the purpose of generating QR Codes.+ */+ class QrSegment {+ /*-- Constructor (low level) and fields --*/+ // Creates a new QR Code segment with the given attributes and data.+ // The character count (numChars) must agree with the mode and the bit buffer length,+ // but the constraint isn't checked. The given bit buffer is cloned and stored.+ constructor(+ // The mode indicator of this segment.+ mode,+ // The length of this segment's unencoded data. Measured in characters for+ // numeric/alphanumeric/kanji mode, bytes for byte mode, and 0 for ECI mode.+ // Always zero or positive. Not the same as the data's bit length.+ numChars,+ // The data bits of this segment. Accessed through getData().+ bitData) {+ this.mode = mode;+ this.numChars = numChars;+ this.bitData = bitData;+ if (numChars < 0)+ throw new RangeError("Invalid argument");+ this.bitData = bitData.slice(); // Make defensive copy+ }+ /*-- Static factory functions (mid level) --*/+ // Returns a segment representing the given binary data encoded in+ // byte mode. All input byte arrays are acceptable. Any text string+ // can be converted to UTF-8 bytes and encoded as a byte mode segment.+ static makeBytes(data) {+ let bb = [];+ for (const b of data)+ appendBits(b, 8, bb);+ return new QrSegment(QrSegment.Mode.BYTE, data.length, bb);+ }+ // Returns a segment representing the given string of decimal digits encoded in numeric mode.+ static makeNumeric(digits) {+ if (!QrSegment.isNumeric(digits))+ throw new RangeError("String contains non-numeric characters");+ let bb = [];+ for (let i = 0; i < digits.length;) { // Consume up to 3 digits per iteration+ const n = Math.min(digits.length - i, 3);+ appendBits(parseInt(digits.substring(i, i + n), 10), n * 3 + 1, bb);+ i += n;+ }+ return new QrSegment(QrSegment.Mode.NUMERIC, digits.length, bb);+ }+ // Returns a segment representing the given text string encoded in alphanumeric mode.+ // The characters allowed are: 0 to 9, A to Z (uppercase only), space,+ // dollar, percent, asterisk, plus, hyphen, period, slash, colon.+ static makeAlphanumeric(text) {+ if (!QrSegment.isAlphanumeric(text))+ throw new RangeError("String contains unencodable characters in alphanumeric mode");+ let bb = [];+ let i;+ for (i = 0; i + 2 <= text.length; i += 2) { // Process groups of 2+ let temp = QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)) * 45;+ temp += QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i + 1));+ appendBits(temp, 11, bb);+ }+ if (i < text.length) // 1 character remaining+ appendBits(QrSegment.ALPHANUMERIC_CHARSET.indexOf(text.charAt(i)), 6, bb);+ return new QrSegment(QrSegment.Mode.ALPHANUMERIC, text.length, bb);+ }+ // Returns a new mutable list of zero or more segments to represent the given Unicode text string.+ // The result may use various segment modes and switch modes to optimize the length of the bit stream.+ static makeSegments(text) {+ // Select the most efficient segment encoding automatically+ if (text == "")+ return [];+ else if (QrSegment.isNumeric(text))+ return [QrSegment.makeNumeric(text)];+ else if (QrSegment.isAlphanumeric(text))+ return [QrSegment.makeAlphanumeric(text)];+ else+ return [QrSegment.makeBytes(QrSegment.toUtf8ByteArray(text))];+ }+ // Returns a segment representing an Extended Channel Interpretation+ // (ECI) designator with the given assignment value.+ static makeEci(assignVal) {+ let bb = [];+ if (assignVal < 0)+ throw new RangeError("ECI assignment value out of range");+ else if (assignVal < (1 << 7))+ appendBits(assignVal, 8, bb);+ else if (assignVal < (1 << 14)) {+ appendBits(0b10, 2, bb);+ appendBits(assignVal, 14, bb);+ }+ else if (assignVal < 1000000) {+ appendBits(0b110, 3, bb);+ appendBits(assignVal, 21, bb);+ }+ else+ throw new RangeError("ECI assignment value out of range");+ return new QrSegment(QrSegment.Mode.ECI, 0, bb);+ }+ // Tests whether the given string can be encoded as a segment in numeric mode.+ // A string is encodable iff each character is in the range 0 to 9.+ static isNumeric(text) {+ return QrSegment.NUMERIC_REGEX.test(text);+ }+ // Tests whether the given string can be encoded as a segment in alphanumeric mode.+ // A string is encodable iff each character is in the following set: 0 to 9, A to Z+ // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon.+ static isAlphanumeric(text) {+ return QrSegment.ALPHANUMERIC_REGEX.test(text);+ }+ /*-- Methods --*/+ // Returns a new copy of the data bits of this segment.+ getData() {+ return this.bitData.slice(); // Make defensive copy+ }+ // (Package-private) Calculates and returns the number of bits needed to encode the given segments at+ // the given version. The result is infinity if a segment has too many characters to fit its length field.+ static getTotalBits(segs, version) {+ let result = 0;+ for (const seg of segs) {+ const ccbits = seg.mode.numCharCountBits(version);+ if (seg.numChars >= (1 << ccbits))+ return Infinity; // The segment's length doesn't fit the field's bit width+ result += 4 + ccbits + seg.bitData.length;+ }+ return result;+ }+ // Returns a new array of bytes representing the given string encoded in UTF-8.+ static toUtf8ByteArray(str) {+ str = encodeURI(str);+ let result = [];+ for (let i = 0; i < str.length; i++) {+ if (str.charAt(i) != "%")+ result.push(str.charCodeAt(i));+ else {+ result.push(parseInt(str.substring(i + 1, i + 3), 16));+ i += 2;+ }+ }+ return result;+ }+ }+ /*-- Constants --*/+ // Describes precisely all strings that are encodable in numeric mode.+ QrSegment.NUMERIC_REGEX = /^[0-9]*$/;+ // Describes precisely all strings that are encodable in alphanumeric mode.+ QrSegment.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/;+ // The set of all legal characters in alphanumeric mode,+ // where each character value maps to the index in the string.+ QrSegment.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";+ qrcodegen.QrSegment = QrSegment;+})(qrcodegen || (qrcodegen = {}));+/*---- Public helper enumeration ----*/+(function (qrcodegen) {+ var QrCode;+ (function (QrCode) {+ /*+ * The error correction level in a QR Code symbol. Immutable.+ */+ class Ecc {+ /*-- Constructor and fields --*/+ constructor(+ // In the range 0 to 3 (unsigned 2-bit integer).+ ordinal,+ // (Package-private) In the range 0 to 3 (unsigned 2-bit integer).+ formatBits) {+ this.ordinal = ordinal;+ this.formatBits = formatBits;+ }+ }+ /*-- Constants --*/+ Ecc.LOW = new Ecc(0, 1); // The QR Code can tolerate about 7% erroneous codewords+ Ecc.MEDIUM = new Ecc(1, 0); // The QR Code can tolerate about 15% erroneous codewords+ Ecc.QUARTILE = new Ecc(2, 3); // The QR Code can tolerate about 25% erroneous codewords+ Ecc.HIGH = new Ecc(3, 2); // The QR Code can tolerate about 30% erroneous codewords+ QrCode.Ecc = Ecc;+ })(QrCode = qrcodegen.QrCode || (qrcodegen.QrCode = {}));+})(qrcodegen || (qrcodegen = {}));+/*---- Public helper enumeration ----*/+(function (qrcodegen) {+ var QrSegment;+ (function (QrSegment) {+ /*+ * Describes how a segment's data bits are interpreted. Immutable.+ */+ class Mode {+ /*-- Constructor and fields --*/+ constructor(+ // The mode indicator bits, which is a uint4 value (range 0 to 15).+ modeBits,+ // Number of character count bits for three different version ranges.+ numBitsCharCount) {+ this.modeBits = modeBits;+ this.numBitsCharCount = numBitsCharCount;+ }+ /*-- Method --*/+ // (Package-private) Returns the bit width of the character count field for a segment in+ // this mode in a QR Code at the given version number. The result is in the range [0, 16].+ numCharCountBits(ver) {+ return this.numBitsCharCount[Math.floor((ver + 7) / 17)];+ }+ }+ /*-- Constants --*/+ Mode.NUMERIC = new Mode(0x1, [10, 12, 14]);+ Mode.ALPHANUMERIC = new Mode(0x2, [9, 11, 13]);+ Mode.BYTE = new Mode(0x4, [8, 16, 16]);+ Mode.KANJI = new Mode(0x8, [8, 10, 12]);+ Mode.ECI = new Mode(0x7, [0, 0, 0]);+ QrSegment.Mode = Mode;+ })(QrSegment = qrcodegen.QrSegment || (qrcodegen.QrSegment = {}));+})(qrcodegen || (qrcodegen = {}));++// FreeVideo ES module adapter.+export {qrcodegen};diff --git a/web/studio.js b/web/studio.jsindex 996f0dc..a41b8a6 100644--- a/web/studio.js+++ b/web/studio.js@@ -1,3 +1,4 @@+import {createLanAccess} from './lan_access.js';import { createErrorPanel, errorText, createErrorReport } from './error_panel.js';import {topDialog} from './dialog_keys.js';import {createExpandButton} from './editor_expand.js';@@ -649,6 +650,7 @@ export function openStudio(node, {extendFrom = null} = {}) {brand.append(wordmark());const tools = el('div', null, 'fv-header-actions');const agents = createAgentActivity(t, api, dialog); tools.append(agents.element); cleanup.push(agents.dispose);+ const phoneAccess = createLanAccess(t, api); tools.append(phoneAccess.element); cleanup.push(phoneAccess.dispose);const versionInfo = createVersionInfo(cn); tools.append(versionInfo.element); cleanup.push(versionInfo.dispose);tools.append(feedbackButton(t), button(t('Settings', '设置'), openSetup, 'fv-quiet'));// The Agent's page is the fourth tab, shown where the Agent interface is on; the guide's last step circles it.@@ -1224,6 +1226,7 @@ export function openStudio(node, {extendFrom = null} = {}) {const previewObserver = new ResizeObserver(fitPreview);previewObserver.observe(previewSpace); cleanup.push(() => previewObserver.disconnect());function showProgress(message) {+ phoneAccess.observe(message);watchedRun = true; reportTipFor = null; clearTimeout(reportTipTimer);reuseRow.hidden = true;stats.hidden = true;diff --git a/web/theme.css b/web/theme.cssindex 17ec71a..6301ba9 100644--- a/web/theme.css+++ b/web/theme.css@@ -1,7 +1,7 @@/* One token table for the web views, mirroring freevideo_engine/branding.py soa control looks the same in the launcher and in ComfyUI. Scope the tokens toour own views; never change ComfyUI's theme. */-:where(.fv-studio,.fv-setup,.fv-panel,.fv-generation-progress,.fv-view-navigation,.fv-prompt-guide,.fv-failure-dialog,.fv-reference-picker,.fv-release-notes,.fv-image-editor,.fv-cast-dialog,.fv-tutorial-book){+:where(.fv-phone,.fv-lan,.fv-studio,.fv-setup,.fv-panel,.fv-generation-progress,.fv-view-navigation,.fv-prompt-guide,.fv-failure-dialog,.fv-reference-picker,.fv-release-notes,.fv-image-editor,.fv-cast-dialog,.fv-tutorial-book){/* Surfaces, from the backdrop up to a hovered control; mirrors branding.py. */--fv-bg:#111720;--fv-canvas:#161e29;--fv-card:#1a222e;--fv-raised:#212a37;--fv-hover:#2a3341;--fv-border:#2a3443;--fv-sheen:#35404e;diff --git a/web/view_navigation.js b/web/view_navigation.jsindex 3f102c9..2be364d 100644--- a/web/view_navigation.js+++ b/web/view_navigation.js@@ -1,3 +1,5 @@+import {createLanAccess} from './lan_access.js';+import {api} from '../../scripts/api.js';import { app } from '../../scripts/app.js';import { openSetup } from './setup.js';import { feedbackButton } from './feedback.js';@@ -139,7 +141,7 @@ export function installNavigation(openStudio, agent = false, {openWorkflow = nulconst handle = await openEditorView(node);if (created) handle?.notify(t('Created an editing project for you.', '已为你新建一个剪辑工程'));return handle;- }, true), () => choose(node => openAutopilot(node), true)), createVersionInfo(cn).element, feedbackButton(t, 'fv-view-settings'), settings); toolbar.append(row);+ }, true), () => choose(node => openAutopilot(node), true)), createLanAccess(t, api).element, createVersionInfo(cn).element, feedbackButton(t, 'fv-view-settings'), settings); toolbar.append(row);toolbar.append(createUpdateNotice(cn).element);document.body.append(toolbar); refreshNavigation();makeMovable(toolbar);