diff --git a/web/app/runners.js b/web/app/runners.js index 29b73a548..6f29e5eb2 100644 --- a/web/app/runners.js +++ b/web/app/runners.js @@ -2,9 +2,9 @@ function syncRunModalKnowledgeSummary(){ const summary=$('#runKnowledgeRefsSummary'),reset=$('#runKnowledgeRefsResetBtn'); const override=state.runModalKnowledgeRefs; if(summary){ - if(override===null||override===undefined)summary.textContent='默认按节点或角色配置'; - else if(override.length)summary.textContent=`本次覆盖:已选 ${override.length} 个连接器`; - else summary.textContent='本次覆盖:不挂载知识库'; + if(override===null||override===undefined)summary.textContent=lfT('默认按节点或角色配置','Defaults to each step or role'); + else if(override.length)summary.textContent=lfT(`本次覆盖:已选 ${override.length} 个连接器`,`Override for this run: ${override.length} ${override.length===1?'connector':'connectors'} selected`); + else summary.textContent=lfT('本次覆盖:不挂载知识库','Override for this run: no knowledge base'); } if(reset)reset.hidden=override===null||override===undefined; } @@ -15,7 +15,7 @@ function openRunModal(workflowId){ syncRunModalKnowledgeSummary(); const refBtn=$('#runKnowledgeRefsBtn'); if(refBtn)refBtn.onclick=()=>{ - if(typeof window.editKnowledgeRefs!=='function')return toast('知识库选择器尚未加载'); + if(typeof window.editKnowledgeRefs!=='function')return toast(lfT('知识库选择器尚未加载','The knowledge base picker has not loaded yet')); window.editKnowledgeRefs(currentProject()?.id||state.projectFilter||'',state.runModalKnowledgeRefs||[],refs=>{ state.runModalKnowledgeRefs=refs; syncRunModalKnowledgeSummary(); @@ -72,21 +72,23 @@ async function ensureRunnerBindCode(silent){ } function runnerConcurrencyLabel(runner){ const limit=Number(runner?.runLimit)||0; - return limit>0?`最多同时运行 ${limit} 条`:'不限同时运行数'; + return limit>0?lfT(`最多同时运行 ${limit} 条`,`Up to ${limit} concurrent ${limit===1?'run':'runs'}`):lfT('不限同时运行数','No concurrency limit'); } function runnerRunLimitHTML(runner,platform=false){ if(platform?!runner.canEditLimit:!(Number(runner?.ownerUserId)>0))return ''; const limit=Number(runner?.runLimit)||0; - const scope=platform?'默认 10 条,平台所有项目共用此名额。按顶层 LOOP 计数。':'新绑定机器默认 10 条。按顶层 LOOP 计数,共享项目共用机器名额。'; - const tip=scope+'超出名额后排队。失败、暂停、待确认的 LOOP 空闲 1 小时后自动归档并回收工作区,释放名额。继续或重试时自动恢复工作区。输入 0 或留空表示不限。'; + const scope=platform + ?lfT('默认 10 条,平台所有项目共用此名额。按顶层 LOOP 计数。','Defaults to 10, shared by every project on the platform. Counts top-level LOOPs. ') + :lfT('新绑定机器默认 10 条。按顶层 LOOP 计数,共享项目共用机器名额。','Newly bound machines default to 10. Counts top-level LOOPs; shared projects share the machine\'s slots. '); + const tip=scope+lfT('超出名额后排队。失败、暂停、待确认的 LOOP 空闲 1 小时后自动归档并回收工作区,释放名额。继续或重试时自动恢复工作区。输入 0 或留空表示不限。','Runs over the limit queue. Failed, paused and awaiting-confirmation LOOPs idle for 1 hour are archived and their workspaces reclaimed to free slots; continuing or retrying restores the workspace. Enter 0 or leave blank for no limit.'); const id=platform?'runLimit-platform-runner':`runLimit-${escapeHTML(runner.id)}`; const control=platform?'data-platform-run-limit':`data-runner-run-limit="${escapeHTML(runner.id)}"`; - return `
?
`; + return `
?
`; } async function saveRunnerRunLimit(runnerId,raw,platform=false){ const text=String(raw??'').trim(); const value=text===''?0:Number(text); - if(!Number.isSafeInteger(value)||value<0){toast('请输入非负整数,0 或留空表示不限');refreshRunners(true);return} + if(!Number.isSafeInteger(value)||value<0){toast(lfT('请输入非负整数,0 或留空表示不限','Enter a non-negative integer; 0 or blank means no limit'));refreshRunners(true);return} try{ const target=platform?'platform':encodeURIComponent(runnerId); const projectId=platform?currentProject()?.id||'':''; @@ -98,7 +100,7 @@ async function saveRunnerRunLimit(runnerId,raw,platform=false){ const i=(state.runners||[]).findIndex(r=>r.id===runnerId); if(i>=0&&runner?.id)state.runners[i]={...state.runners[i],...runner}; } - toast(value>0?`已设置:最多同时运行 ${value} 条`:'已设为不限','ok');renderRunnersView(); + toast(value>0?lfT(`已设置:最多同时运行 ${value} 条`,`Saved: up to ${value} concurrent ${value===1?'run':'runs'}`):lfT('已设为不限','Set to unlimited'),'ok');renderRunnersView(); void refreshRunners(true); }catch(err){toast(err.message);refreshRunners(true)} } @@ -141,26 +143,30 @@ function runnerLoadHTML(runner){ const parts=[]; const limit=Number(runner.runLimit)||0; if(runner.load){ - parts.push(`运行中 ${Number(runner.load.runningRuns)||0}`); - parts.push(limit>0?`已占 ${Number(runner.load.occupiedRuns)||0} / ${limit}`:'不限'); - if(runner.load.queuedRuns>0)parts.push(`排队 ${Number(runner.load.queuedRuns)}`); + parts.push(`${lfT('运行中','Running')} ${Number(runner.load.runningRuns)||0}`); + parts.push(limit>0?`${lfT('已占','Occupied')} ${Number(runner.load.occupiedRuns)||0} / ${limit}`:lfT('不限','Unlimited')); + if(runner.load.queuedRuns>0)parts.push(`${lfT('排队','Queued')} ${Number(runner.load.queuedRuns)}`); } - if(runner.cloudPool)parts.push(`云端池 ${Number(runner.cloudPoolOnline)||0} 台在线`); + if(runner.cloudPool)parts.push(lfT(`云端池 ${Number(runner.cloudPoolOnline)||0} 台在线`,`Cloud pool: ${Number(runner.cloudPoolOnline)||0} online`)); return parts.length?`${parts.join(' · ')}`:''; } function runnerStatusLabel(status,lastSeen){ - const label=status==='online'?'在线':status==='offline'?'离线':(status||'未知'); + const label=status==='online'?lfT('在线','Online'):status==='offline'?lfT('离线','Offline'):(status||lfT('未知','Unknown')); const style=status==='online'?' online':status==='offline'?' offline':''; const seen=lastSeen?` title="${escapeHTML(runnerLastSeen(lastSeen))}"`:''; return `${escapeHTML(label)}`; } const runnerCLILabels={'claude-code':'Claude Code','codex':'Codex','codebuddy':'CodeBuddy',opencode:'OpenCode',cursor:'Cursor CLI',agy:'Antigravity',kimi:'Kimi Code',pi:'Pi',dsh:'DeepSeek Harness',zcode:'ZCode'}; -const runnerAuthLabel={local:'账号登录',personal:'API Key'}; -const runnerAuthDescription={local:'Claude Code、Codex 和 Antigravity 可以使用运行 Runner 的系统账号在这台机器上的已有登录,对话与 LOOP 的 native、Docker 沙箱均可复用。共享对话中,只有机器所有者发言时会使用此登录。',personal:'读取「个人配置」中保存的 API Key。对话使用当前发言人的 Key,LOOP 使用运行责任人的 Key。Antigravity 的 Gemini API Key 按 API 单独计费。'}; +// Getters: the page language is read when the copy is shown, not when this file loads. +const runnerAuthLabel={get local(){return lfT('账号登录','Account login')},personal:'API Key'}; +const runnerAuthDescription={ + get local(){return lfT('Claude Code、Codex 和 Antigravity 可以使用运行 Runner 的系统账号在这台机器上的已有登录,对话与 LOOP 的 native、Docker 沙箱均可复用。共享对话中,只有机器所有者发言时会使用此登录。','Claude Code, Codex and Antigravity can reuse the login of the system user running the Runner, in both native and Docker sandboxes for chats and LOOPs. In a shared chat, that login applies to messages from the machine owner.')}, + get personal(){return lfT('读取「个人配置」中保存的 API Key。对话使用当前发言人的 Key,LOOP 使用运行责任人的 Key。Antigravity 的 Gemini API Key 按 API 单独计费。','Uses the API Key saved in Personal settings. Chats use the current speaker\'s key; LOOPs use the run owner\'s key. Antigravity\'s Gemini API Key is billed separately per API call.')}, +}; const runnerOSLabels={darwin:'macOS',linux:'Linux',windows:'Windows'}; function runnerKeyDescription(provider){ - if(provider==='zcode')return 'GLM Coding Plan 的 API Key 配合套餐专用地址可使用订阅额度,请在「个人配置」中填写。Start Plan 额度需要登录 ZCode 账号,无法通过 API Key 使用。'; - return '该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。'; + if(provider==='zcode')return lfT('GLM Coding Plan 的 API Key 配合套餐专用地址可使用订阅额度,请在「个人配置」中填写。Start Plan 额度需要登录 ZCode 账号,无法通过 API Key 使用。','Enter the GLM Coding Plan API key and its dedicated endpoint in Personal Settings to use your subscription allowance. Start Plan allowance requires signing in to ZCode.'); + return lfT('该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。','This CLI supports API keys. With a key included in your provider\'s subscription, usage counts toward that plan\'s allowance. Enter the API key in Personal Settings.'); } function runnerPersonalCredentialConfigured(provider){ const user=userById(state.currentUser?.id)||{}; @@ -179,12 +185,12 @@ function runnerAuthHTML(runtime,key,busy,shared){ const supportsLogin=runnerRuntimeSupportsLogin(runtime); const mode=shared?'personal':runnerAuthChanges.get(key)||runnerRuntimeAuthMode(runtime); const missing=mode==='personal'&&!runnerPersonalCredentialConfigured(runtime.provider); - const title=missing?' title="请在个人配置中填写 API Key"':''; - if(!shared&&supportsLogin)return ` `; - const keyHelp=supportsLogin?'':``; + const keyHelp=supportsLogin?'':``; return `${runnerAuthLabel[mode]}${keyHelp}`; } function runnerRuntimeHTML(runner,runtime,shared){ @@ -196,45 +202,50 @@ function runnerRuntimeHTML(runner,runtime,shared){ const icon=window.AgentFlowAssistantModels?.cliIcon(provider); return `
${runnerAuthHTML(runtime,key,busy,shared)} - ${shared?'':``} + ${shared?'':``}
`; } function runnerLastSeen(value){ - if(!value)return '尚无心跳'; + if(!value)return lfT('尚无心跳','No heartbeat yet'); const seconds=Math.max(0,Math.round((Date.now()-new Date(value).getTime())/1000)); - if(seconds<60)return `${seconds} 秒前`; - if(seconds<3600)return `${Math.floor(seconds/60)} 分钟前`; + if(seconds<60)return lfT(`${seconds} 秒前`,`${seconds}s ago`); + if(seconds<3600)return lfT(`${Math.floor(seconds/60)} 分钟前`,`${Math.floor(seconds/60)} min ago`); return new Date(value).toLocaleString(); } function runnerCopyCommand(btn,text,message){ const done=()=>{ toast(message,'ok'); if(!btn.dataset.label)btn.dataset.label=btn.textContent; - btn.textContent='已复制';btn.classList.add('copied'); + btn.textContent=lfT('已复制','Copied');btn.classList.add('copied'); clearTimeout(btn._copiedTimer); btn._copiedTimer=setTimeout(()=>{btn.textContent=btn.dataset.label;btn.classList.remove('copied')},1400); }; - if(!navigator.clipboard){toast('复制失败,请手动选择复制');return} - navigator.clipboard.writeText(text).then(done).catch(()=>toast('复制失败,请手动选择复制')); + const failed=()=>toast(lfT('复制失败,请手动选择复制','Copy failed; select the text and copy it manually')); + if(!navigator.clipboard){failed();return} + navigator.clipboard.writeText(text).then(done).catch(failed); } function runnerProjectWritable(project){ const userId=Number(state.currentUser?.id)||0; return !!(userId>0&&project&&!project.archivedAt&&(Number(project.ownerId)===userId|| project.members?.some(m=>Number(m.userId)===userId&&String(m.role||'').trim().toLowerCase()!=='viewer'))); } +// The server always names the platform runner domain.PlatformRunnerName; show it in the page language. +function platformRunnerLabel(){ + return lfT('平台执行机器(云端)','Platform runner (cloud)'); +} function platformRunnerCardHTML(runner,isDefault,canSetDefault){ - const name=escapeHTML(runner.name||'平台执行机器(云端)'); + const name=escapeHTML(platformRunnerLabel()); const limit=runner.canEditLimit?runnerRunLimitHTML(runner,true):`${runnerConcurrencyLabel(runner)}`; return `
-
${name}平台自带${isDefault?'此项目默认':''}
+
${name}${lfT('平台自带','Built-in')}${isDefault?`${lfT('此项目默认','Project default')}`:''}
${runnerLoadHTML(runner)}
@@ -254,18 +265,18 @@ function renderRunnersView(){ const bindHTTPS=$('#bindHttpsOrigin'),bindHTTP=$('#bindHttpOrigin'),bindHost=$('#bindServerHost'); if(bindHTTPS)bindHTTPS.textContent=httpsOrigin;if(bindHTTP)bindHTTP.textContent=httpOrigin;if(bindHost)bindHost.textContent=host; const tokenSpan=$('#bindToken'); - if(tokenSpan)tokenSpan.textContent=state.runnerBindCode?.code||'生成中…'; + if(tokenSpan)tokenSpan.textContent=state.runnerBindCode?.code||lfT('生成中…','Generating…'); const copyBtn=$('#copyBindCommand'); if(copyBtn)copyBtn.onclick=()=>{ const text=$('#bindCliCommand')?.innerText||''; - runnerCopyCommand(copyBtn,text,'已复制,10 分钟内有效'); + runnerCopyCommand(copyBtn,text,lfT('已复制,10 分钟内有效','Copied; valid for 10 minutes')); }; const uninstallHTTPS=$('#uninstallHttpsOrigin'),uninstallHTTP=$('#uninstallHttpOrigin'); if(uninstallHTTPS)uninstallHTTPS.textContent=httpsOrigin;if(uninstallHTTP)uninstallHTTP.textContent=httpOrigin; const copyUnBtn=$('#copyUninstallCommand'); if(copyUnBtn)copyUnBtn.onclick=(e)=>{ const text=e.currentTarget.parentElement?.querySelector('pre')?.innerText||''; - runnerCopyCommand(copyUnBtn,text,'已复制卸载命令'); + runnerCopyCommand(copyUnBtn,text,lfT('已复制卸载命令','Uninstall command copied')); }; const project=currentProject(); const projectId=project?.id||''; @@ -282,13 +293,13 @@ function renderRunnersView(){ const dispatchBar=$('#runnerDispatchBar'); if(dispatchBar)dispatchBar.classList.toggle('is-auto',projectMode==='auto'); const dispatchLabel=$('#runnerDispatchLabel'); - if(dispatchLabel)dispatchLabel.textContent=projectId?'本项目执行调度':'当前执行调度'; + if(dispatchLabel)dispatchLabel.textContent=projectId?lfT('本项目执行调度','Project dispatch'):lfT('当前执行调度','Execution dispatch'); const dispatchHint=$('#runnerDispatchHint'); if(dispatchHint){ dispatchHint.hidden=!canSetMode; dispatchHint.textContent=!canSetMode?'':projectMode==='auto' - ?'已开启自动分配:新建顶层 LOOP 将在「平台机器」和兼容的「可用机器」间自动调度。' - :'开启「自动分配」后,新建顶层 LOOP 将在「平台机器」和兼容的「可用机器」间自动调度;也可在下方指定单台机器为项目默认。'; + ?lfT('已开启自动分配:新建顶层 LOOP 将在「平台机器」和兼容的「可用机器」间自动调度。','Auto-assign is on: new top-level LOOPs are scheduled across the platform machine and compatible available runners.') + :lfT('开启「自动分配」后,新建顶层 LOOP 将在「平台机器」和兼容的「可用机器」间自动调度;也可在下方指定单台机器为项目默认。','Turn on Auto-assign to schedule new top-level LOOPs across the platform machine and compatible available runners, or set a single runner below as the project default.'); } const autoAssign=$('#runnerAutoAssign'); if(autoAssign){ @@ -297,8 +308,8 @@ function renderRunnersView(){ autoAssign.classList.toggle('hui-btn-soft',active); autoAssign.classList.toggle('ghost',!active); autoAssign.setAttribute('aria-pressed',String(active)); - autoAssign.textContent=active?'已开启自动分配':'自动分配'; - autoAssign.title='自动分配涵盖平台机器与兼容的可用机器'; + autoAssign.textContent=active?lfT('已开启自动分配','Auto-assign on'):lfT('自动分配','Auto-assign'); + autoAssign.title=lfT('自动分配涵盖平台机器与兼容的可用机器','Auto-assign covers the platform machine and compatible available runners'); autoAssign.onclick=()=>setDefaultRunner('',projectId,active?'':'auto'); } const poolStatus=$('#runnerPoolStatus'); @@ -307,23 +318,23 @@ function renderRunnersView(){ let text='',warn=false; if(projectMode==='auto'){ const usable=runners.filter(r=>r.canUseInProject&&!runnerDefaultBlocker(r)).length+(platform?.status==='online'?1:0); - text=`此项目 LOOP 自动分配 · ${usable} 台在线机器可用`; + text=lfT(`此项目 LOOP 自动分配 · ${usable} 台在线机器可用`,`Project LOOPs auto-assigned · ${usable} online ${usable===1?'runner':'runners'} available`); warn=usable===0; }else if(projectMode==='platform'){ - text='此项目默认 · 平台执行机器(云端)'; + text=`${lfT('此项目默认','Project default')} · ${platformRunnerLabel()}`; warn=platform?.status==='offline'; }else if(def){ warn=def.status!=='online'; - const label=projectDefaultId?'此项目默认':'个人默认'; - text=warn?`${label}执行机器已离线,请启动机器或更改默认`:`${label} · ${def.name||def.id}`; + const label=projectDefaultId?lfT('此项目默认','Project default'):lfT('个人默认','Personal default'); + text=warn?lfT(`${label}执行机器已离线,请启动机器或更改默认`,`${label} runner is offline; start it or change the default`):`${label} · ${def.name||def.id}`; }else if(platform){ warn=platform.status!=='online'; - text=warn?'平台执行机器离线':'在平台云端执行'; + text=warn?lfT('平台执行机器离线','Platform runner offline'):lfT('在平台云端执行','Runs in the platform cloud'); }else if(pool?.configured){ warn=!pool.online; - text=pool.online?`云端执行 · ${pool.online} 台在线`:'云端暂无在线机器,新任务最多等待 10 分钟'; + text=pool.online?lfT(`云端执行 · ${pool.online} 台在线`,`Cloud execution · ${pool.online} online`):lfT('云端暂无在线机器,新任务最多等待 10 分钟','No cloud runner online; new tasks wait up to 10 minutes'); }else{ - text='在平台云端执行'; + text=lfT('在平台云端执行','Runs in the platform cloud'); } poolStatus.textContent=text;poolStatus.classList.toggle('warn',warn); } @@ -347,7 +358,7 @@ function renderRunnersView(){ const isProjectDefault=r.id===projectDefaultId; const canSetProjectDefault=projectLoaded&&projectId&&r.canUseInProject&&!isProjectDefault; const cliRows=discoveredCLIs.map(rt=>runnerRuntimeHTML(r,rt,shared)).join(''); - const cliSection=cliRows||'
未发现支持的 Agent CLI
'; + const cliSection=cliRows||`
${lfT('未发现支持的 Agent CLI','No supported Agent CLI found')}
`; const osLabel=runnerOSLabels[r.os]||r.os||'?'; const defaultBlocker=runnerDefaultBlocker(r); const checking=runnerMaintenancePending.has(r.id); @@ -355,21 +366,21 @@ function renderRunnersView(){
-
${escapeHTML(r.name||r.id)}${isProjectDefault?'此项目默认':isPersonalDefault?'个人默认':''}${shared?'项目共享':''}
- ${escapeHTML(osLabel)} · ${escapeHTML(r.arch||'?')} · Runner ${escapeHTML(r.runnerVersion||'未知')} +
${escapeHTML(r.name||r.id)}${isProjectDefault?`${lfT('此项目默认','Project default')}`:isPersonalDefault?`${lfT('个人默认','Personal default')}`:''}${shared?`${lfT('项目共享','Shared with project')}`:''}
+ ${escapeHTML(osLabel)} · ${escapeHTML(r.arch||'?')} · Runner ${escapeHTML(r.runnerVersion||lfT('未知','unknown'))} ${runnerLoadHTML(r)}
-
${runnerStatusLabel(r.status,r.lastSeenAt)}${shared?'':``}
+
${runnerStatusLabel(r.status,r.lastSeenAt)}${shared?'':``}
- ${cliRows?`
CLI
`:''} + ${cliRows?`
CLI
`:''} ${cliSection}
${shared?`${runnerConcurrencyLabel(r)}`:runnerRunLimitHTML(r)} ${runnerPrivilegedSandboxHTML(r,!shared)} - ${shared?'':``} + ${shared?'':``} ${isPersonalDefault?'':''} ${shared||r.status==='online'?'':``} ${!shared&&!isPersonalDefault?``:''} @@ -378,7 +389,7 @@ function renderRunnersView(){
`; }).join(''); - list.innerHTML=runnerCards||'
还没有机器执行上方命令后自动出现
'; + list.innerHTML=runnerCards||`
${lfT('还没有机器','No runners yet')}${lfT('执行上方命令后自动出现','Runners appear here after you run the command above')}
`; const platformDefault=platformHost?.querySelector('[data-runner-platform-default]'); if(platformDefault){ platformDefault.onclick=()=>setDefaultRunner('',projectId,projectMode==='platform'?'':'platform'); @@ -416,13 +427,13 @@ function renderRunnersView(){ setRunnerRuntimeAuth(runnerId,provider,select.value); }); list.querySelectorAll('[data-runner-auth-help]').forEach(btn=>btn.onclick=()=>afAlert({ - title:'模型认证方式', + title:lfT('模型认证方式','Model authentication'), message:`${runnerAuthLabel.local}\n${runnerAuthDescription.local}\n\n${runnerAuthLabel.personal}\n${runnerAuthDescription.personal}` })); list.querySelectorAll('[data-runner-key-help]').forEach(btn=>btn.onclick=()=>{ const provider=btn.dataset.runnerKeyHelp; return afAlert({ - title:`${runnerCLILabels[provider]} API Key 说明`, + title:`${runnerCLILabels[provider]} ${lfT('API Key 说明','API Key help')}`, message:runnerKeyDescription(provider) }); }); @@ -444,10 +455,10 @@ async function editRunnerSharing(runner){ const projects=(state.data.projects||[]).filter(runnerProjectWritable); const shared=new Set(runner.sharedProjectIds||[]); const projectIds=await afOpenDialog(modal=>{ - $('#confirmTitle').textContent=`共享 ${runner.name||runner.id}`; + $('#confirmTitle').innerHTML=`${lfT('共享','Share')} ${escapeHTML(runner.name||runner.id)}`; $('#confirmMessage').textContent=projects.length - ?'所选项目的可写成员可以在这台机器上运行代码,执行时使用各自的凭据。' - :'加入项目并获得写权限后,即可共享这台机器。'; + ?lfT('所选项目的可写成员可以在这台机器上运行代码,执行时使用各自的凭据。','Members with write access to the selected projects can run code on this machine, each with their own credentials.') + :lfT('加入项目并获得写权限后,即可共享这台机器。','Join a project with write access to share this machine with it.'); const ok=$('#confirmOkBtn'); ok.textContent='保存'; ok.className='button primary'; @@ -455,8 +466,8 @@ async function editRunnerSharing(runner){ setConfirmIcon('info','monitor'); const fields=document.createElement('fieldset'); fields.className='runner-share-projects'; - fields.setAttribute('aria-label','共享项目'); - fields.innerHTML=projects.map(p=>``).join(''); + fields.setAttribute('aria-label',lfT('共享项目','Shared projects')); + fields.innerHTML=projects.map(p=>``).join(''); if(projects.length)modal.querySelector('.confirm-modal-footer').before(fields); return {focus:fields.querySelector('input')||ok,value:accepted=>{ fields.remove(); @@ -466,13 +477,13 @@ async function editRunnerSharing(runner){ if(!projectIds)return; try{ await api(`/api/runners/${encodeURIComponent(runner.id)}/shared-projects`,{method:'PUT',body:JSON.stringify({projectIds})}); - toast('已更新共享项目','ok'); + toast(lfT('已更新共享项目','Shared projects updated'),'ok'); await refreshRunners(true); }catch(err){toast(err.message,'err')} } async function removeRunner(runnerId){ const runner=(state.runners||[]).find(r=>r.id===runnerId); - if(!await afConfirm({title:'移除执行机器',message:`确定移除 ${runner?.name||runnerId}?之后如需再用这台机器,重新复制接入命令执行即可。`,confirmText:'移除',isDanger:true}))return; + if(!await afConfirm({title:lfT('移除执行机器','Remove runner'),message:lfT(`确定移除 ${runner?.name||runnerId}?之后如需再用这台机器,重新复制接入命令执行即可。`,`Remove ${runner?.name||runnerId}? To use this machine again later, copy and run the connect command again.`),confirmText:lfT('移除','Remove'),isDanger:true}))return; try{ await api(`/api/runners/${encodeURIComponent(runnerId)}`,{method:'DELETE'}); toast('已移除','ok');refreshRunners(true); @@ -489,9 +500,9 @@ function runnerVersionAtLeast(have,want){ return true; } function runnerDefaultBlocker(r){ - if(r.status!=='online')return '机器离线'; + if(r.status!=='online')return lfT('机器离线','Runner offline'); const min=state.minRunnerVersion||''; - if(min&&!runnerVersionAtLeast(r.runnerVersion,min))return `执行机器版本 ${r.runnerVersion||'未知'} 过低,需升级至 ${min} 及以上`; + if(min&&!runnerVersionAtLeast(r.runnerVersion,min))return lfT(`执行机器版本 ${r.runnerVersion||'未知'} 过低,需升级至 ${min} 及以上`,`Runner version ${r.runnerVersion||'unknown'} is too old; upgrade to ${min} or later`); return ''; } let runnerPreferenceSaving=false; @@ -511,7 +522,7 @@ function toggleRunnerRuntime(runnerId,provider,enabled){ async function runnerRuntimeRequest(runnerId,provider,status){ try{ await api('/api/runners/runtimes',{method:'PUT',body:JSON.stringify({runnerId,provider,status})}); - toast(`${runnerCLILabels[provider]||provider} 已${status==='online'?'启用':'停用'}`,'ok');refreshRunners(true); + toast(status==='online'?lfT(`${runnerCLILabels[provider]||provider} 已启用`,`${runnerCLILabels[provider]||provider} enabled`):lfT(`${runnerCLILabels[provider]||provider} 已停用`,`${runnerCLILabels[provider]||provider} disabled`),'ok');refreshRunners(true); }catch(err){toast(err.message);refreshRunners(true)} } async function setRunnerRuntimeAuth(runnerId,provider,authMode){ @@ -521,7 +532,9 @@ async function setRunnerRuntimeAuth(runnerId,provider,authMode){ try{ await api('/api/runners/runtimes',{method:'PUT',body:JSON.stringify({runnerId,provider,authMode})}); const ready=runnerPersonalCredentialConfigured(provider); - toast(authMode==='personal'?(ready?'将使用「个人配置」中的 API Key':'已切换,请先到「个人配置」补充该 CLI 的 API Key'):'将使用这台机器上已登录的 CLI 账号',ready||authMode!=='personal'?'ok':undefined); + toast(authMode==='personal' + ?(ready?lfT('将使用「个人配置」中的 API Key','Will use the API Key from Personal settings'):lfT('已切换,请先到「个人配置」补充该 CLI 的 API Key','Switched; add an API Key for this CLI in Personal settings')) + :lfT('将使用这台机器上已登录的 CLI 账号','Will use the CLI account signed in on this machine'),ready||authMode!=='personal'?'ok':undefined); }catch(err){toast(err.message,'err')} finally{ await refreshRunners(true); @@ -536,7 +549,7 @@ async function testRunnerRuntime(runnerId,provider){ renderRunnersView(); try{ await api('/api/runners/runtimes/test',{method:'POST',silent:true,body:JSON.stringify({runnerId,provider})}); - toast(`${runnerCLILabels[provider]} 测试通过`,'ok'); + toast(lfT(`${runnerCLILabels[provider]} 测试通过`,`${runnerCLILabels[provider]} test passed`),'ok'); }catch(err){toast(`${runnerCLILabels[provider]}:${err.message}`,'err',5000)} finally{ runnerRuntimeTests.delete(key); @@ -569,12 +582,12 @@ function showRunnerRuntimeMenu(trigger,last=false){ const menu=runnerRuntimeMenu; const testBusy=runnerRuntimeTests.has(key),updateBusy=runnerMaintenancePending.has(key); const actions=[ - {label:testBusy?'测试中…':'测试',icon:'flask',disabled:testBusy||runnerAuthChanges.has(key)||runner.status!=='online'||runtime.status==='disabled',run:()=>testRunnerRuntime(id,provider)}, - {label:updateBusy?'更新中…':'更新',icon:'download',disabled:updateBusy||runner.status!=='online',run:()=>updateRunnerCLI(runner,runtime)}, - {label:'模型列表',icon:'layers',disabled:runnerAuthChanges.has(key),run:()=>showRunnerModels(runner,runtime)} + {label:testBusy?lfT('测试中…','Testing…'):lfT('测试','Test'),icon:'flask',disabled:testBusy||runnerAuthChanges.has(key)||runner.status!=='online'||runtime.status==='disabled',run:()=>testRunnerRuntime(id,provider)}, + {label:updateBusy?lfT('更新中…','Updating…'):lfT('更新','Update'),icon:'download',disabled:updateBusy||runner.status!=='online',run:()=>updateRunnerCLI(runner,runtime)}, + {label:lfT('模型列表','Models'),icon:'layers',disabled:runnerAuthChanges.has(key),run:()=>showRunnerModels(runner,runtime)} ]; menu.innerHTML=actions.map((action,index)=>``).join(''); - menu.setAttribute('aria-label',`${runnerCLILabels[provider]} 更多操作`); + menu.setAttribute('aria-label',`${runnerCLILabels[provider]} ${lfT('更多操作','more actions')}`); menu.hidden=false; runnerRuntimeTrigger=trigger; trigger.setAttribute('aria-expanded','true'); @@ -606,19 +619,19 @@ function showRunnerModels(runner,runtime){ const kind=CREDENTIAL_KINDS.find(item=>item.models?.engine===provider); if(!kind)return; return afOpenDialog(modal=>{ - $('#confirmTitle').textContent=`${runnerCLILabels[provider]} 模型列表`; - const keySource=kind.extra?.url?'API Key 和服务地址':kind.extra?'API Key 和网络环境':'API Key'; + $('#confirmTitle').textContent=`${runnerCLILabels[provider]} ${lfT('模型列表','models')}`; + const keySource=kind.extra?.url?lfT('API Key 和服务地址','API Key and service URL'):kind.extra?lfT('API Key 和网络环境','API Key and network environment'):'API Key'; $('#confirmMessage').textContent=separateCatalog - ?'用于这台机器的账号登录。清空目录后使用 CLI 自带的模型。' + ?lfT('用于这台机器的账号登录。清空目录后使用 CLI 自带的模型。','Used with this machine\'s account login. Clear the list to use the CLI\'s built-in models.') :local - ?'与个人配置共用模型目录。获取时使用这台机器的账号登录。' - :`与个人配置共用模型目录。获取时使用个人配置里的 ${keySource}。`; + ?lfT('与个人配置共用模型目录。获取时使用这台机器的账号登录。','Shares the model list with Personal settings. Fetching uses this machine\'s account login.') + :lfT(`与个人配置共用模型目录。获取时使用个人配置里的 ${keySource}。`,`Shares the model list with Personal settings. Fetching uses the ${keySource} from Personal settings.`); const ok=$('#confirmOkBtn'),cancel=$('#confirmCancelBtn'),card=modal.querySelector('.confirm-modal-card'); const panel=document.createElement('div'); panel.className='credential-panel runner-model-editor'; panel.dataset.credentialRow=kind.key; const savedModels=separateCatalog?runner.loginModels?.[provider]||[]:undefined; - panel.innerHTML=credentialCatalogHTML(kind,credentialUser(),{runnerLogin:local,label:local?'账号登录':'API Key',savedModels}); + panel.innerHTML=credentialCatalogHTML(kind,credentialUser(),{runnerLogin:local,label:local?runnerAuthLabel.local:'API Key',savedModels}); modal.querySelector('.confirm-modal-footer').before(panel); card.classList.add('runner-model-card'); const catalog=panel.querySelector('[data-credential-catalog]'); @@ -676,7 +689,7 @@ function showRunnerModels(runner,runtime){ }else{ await saveCredential(kind.key,{models}); } - toast('模型列表已保存','ok'); + toast(lfT('模型列表已保存','Model list saved'),'ok'); if(panel.isConnected)confirmPromiseResolve?.(true); }catch(err){ if(panel.isConnected){ @@ -710,15 +723,15 @@ async function checkRunnerUpdate(id){ if(result.status==='updating'||result.status==='restarting'){ await followRunnerUpdate(id); }else if(result.status==='available'&&result.canUpdate){ - const confirmed=await afConfirm({title:'Runner 有可用更新',message:`当前版本 ${result.current||'未知'}。更新会重启空闲的 Runner。`,confirmText:'立即更新',info:true}); + const confirmed=await afConfirm({title:lfT('Runner 有可用更新','Runner update available'),message:lfT(`当前版本 ${result.current||'未知'}。更新会重启空闲的 Runner。`,`Current version ${result.current||'unknown'}. Updating restarts the Runner when it is idle.`),confirmText:lfT('立即更新','Update now'),info:true}); if(confirmed){ await api(runnerMaintenancePath(id),{method:'POST',silent:true}); await followRunnerUpdate(id); } }else if(result.status==='current'){ - toast(`Runner ${result.current||''} 已是平台当前版本`.replace(' ',' '),'ok'); + toast(lfT(`Runner ${result.current||''} 已是平台当前版本`,`Runner ${result.current||''} is already the platform version`).replace(' ',' '),'ok'); }else{ - toast(result.message||'暂时无法检查更新','err',5000); + toast(result.message||lfT('暂时无法检查更新','Cannot check for updates right now'),'err',5000); } }catch(err){toast(err.message,'err',5000)} finally{ @@ -729,7 +742,7 @@ async function checkRunnerUpdate(id){ async function updateRunnerCLI(runner,runtime){ const id=runner.id,provider=runtime.provider,label=runnerCLILabels[provider],key=`${id}|${provider}`; if(!runtime.capabilities?.some(capability=>capability==='native_update'||capability==='managed_update')){ - await afAlert({title:`更新 ${label}`,message:'请在这台执行机器上使用原来的安装方式更新。更新后刷新机器列表即可看到版本。'}); + await afAlert({title:lfT(`更新 ${label}`,`Update ${label}`),message:lfT('请在这台执行机器上使用原来的安装方式更新。更新后刷新机器列表即可看到版本。','Update it on this runner the way it was installed, then refresh the runner list to see the new version.')}); return; } if(runnerMaintenancePending.has(key))return; @@ -753,16 +766,16 @@ async function followRunnerUpdate(id,provider){ if(!result||result.status==='updating'||result.status==='restarting')continue; if(result.status==='current'||result.status==='updated'){ const version=result.version||result.current; - toast(`${label}${version?' '+version:''} 已就绪`,'ok'); + toast(lfT(`${label}${version?' '+version:''} 已就绪`,`${label}${version?' '+version:''} is ready`),'ok'); await refreshRunners(true); }else if(provider&&result.status==='manual'){ - await afAlert({title:`更新 ${label}`,message:result.message||'请在执行机器上使用该 CLI 原来的安装方式更新'}); + await afAlert({title:lfT(`更新 ${label}`,`Update ${label}`),message:result.message||lfT('请在执行机器上使用该 CLI 原来的安装方式更新','Update this CLI on the runner the way it was installed')}); }else if(result.status==='ready'){ - toast(`${label} 更新状态已中断,请刷新确认版本`,'err',5000); + toast(lfT(`${label} 更新状态已中断,请刷新确认版本`,`${label} update status was interrupted; refresh to confirm the version`),'err',5000); }else{ - toast(result.message||`${label} 还有可用更新,请再次检查`,result.status==='failed'?'err':'info',5000); + toast(result.message||lfT(`${label} 还有可用更新,请再次检查`,`${label} still has an update available; check again`),result.status==='failed'?'err':'info',5000); } return; } - toast(`等待 ${label} 更新超时,请稍后检查版本`,'err',5000); + toast(lfT(`等待 ${label} 更新超时,请稍后检查版本`,`Timed out waiting for the ${label} update; check the version later`),'err',5000); } diff --git a/web/i18n-en.js b/web/i18n-en.js index bcbb89c8d..1ecec5601 100644 --- a/web/i18n-en.js +++ b/web/i18n-en.js @@ -811,10 +811,6 @@ Object.assign(window.LF_I18N_EN,{ "绑定已登录 Claude Code、Codex 或 Antigravity 的机器,选「账号登录」即可用订阅额度运行对话和 LOOP,无需 API Key。":"Connect a machine where you are signed in to Claude Code, Codex, or Antigravity. Select Account login to use your subscription for chats and LOOPs without an API key.", "配置执行机器":"Configure runners", "Claude Code、Codex 和 Antigravity 可用账号登录":"Account login for Claude Code, Codex and Antigravity", - "Claude Code、Codex 和 Antigravity 可以使用运行 Runner 的系统账号在这台机器上的已有登录,对话与 LOOP 的 native、Docker 沙箱均可复用。共享对话中,只有机器所有者发言时会使用此登录。":"Claude Code, Codex and Antigravity can reuse the login of the system user running the Runner, in both native and Docker sandboxes for chats and LOOPs. In a shared chat, that login applies to messages from the machine owner.", - "API Key 说明":"API Key help", - "GLM Coding Plan 的 API Key 配合套餐专用地址可使用订阅额度,请在「个人配置」中填写。Start Plan 额度需要登录 ZCode 账号,无法通过 API Key 使用。":"Enter the GLM Coding Plan API key and its dedicated endpoint in Personal Settings to use your subscription allowance. Start Plan allowance requires signing in to ZCode.", - "该 CLI 支持 API Key。使用服务商订阅套餐提供的 Key,执行用量会计入对应的套餐额度。请在「个人配置」中填写 API Key。":"This CLI supports API keys. With a key included in your provider's subscription, usage counts toward that plan's allowance. Enter the API key in Personal Settings." }); Object.assign(window.LF_I18N_EN,{"查看其他项目共享的技能;共享技能只读,会自动装入平台上所有对话和定时任务,也可绑定到本项目角色。": "Skills shared by other projects. Shared Skills are read-only, are installed automatically into every conversation and scheduled task on the platform, and can be bound to Roles in this project.", "共享后,这个技能会自动装入平台上所有用户的对话和定时任务(包括其他项目和无项目的对话),模型可以直接调用。继续?": "Once shared, this Skill is installed automatically into every user's conversations and scheduled tasks on the platform (including other projects and conversations without a project), and the model can call it directly. Continue?", "共享这个角色会同时共享它绑定的技能:": "Sharing this Role also shares the Skills bound to it: ", "已共享,所有对话和定时任务会自动装入": "Shared. Every conversation and scheduled task will install it automatically", "其他项目可在「共享角色」里选用;绑定的本项目技能会一起共享,并自动装入所有对话": "Other projects can pick it under Shared roles; the project Skills bound to it are shared too and installed into every conversation automatically", "共享技能": "Share Skill"}); Object.assign(window.LF_I18N_EN, { @@ -1095,3 +1091,24 @@ Object.assign(window.LF_I18N_EN, { "在对话里澄清和改代码": "Clarify and change code in chat", "这条需求不使用 LOOP,在对话里澄清需求、直接改代码;定时任务不会自动认领它。": "This requirement uses no LOOP: clarify and change code in chat; scheduled jobs won't pick it up.", }); +// 执行机器 page: static copy in index.html. runners.js renders its dynamic copy with lfT. +Object.assign(window.LF_I18N_EN, { + "连接电脑或 CVM,可将机器共享给多个项目。": "Connect a computer or CVM and share it with multiple projects.", + "安装 CLI": "Install a CLI", + "claude / codex 等": "claude, codex, etc.", + "绑定码 10 分钟有效": "The bind code is valid for 10 minutes", + "仅主动连接平台,不开放本机端口": "Connects out to the platform only; opens no local ports", + "自动分配": "Auto-assign", + "可用机器": "Available runners", + // PUT /api/runners/default success messages, shown as toasts. + "已设为默认执行机器,你的任务和沙箱将在这台机器上执行": "Set as your default runner; your tasks and sandboxes will run on this machine", + "已切回云端执行": "Switched back to cloud execution", + "已设为你在此项目的默认执行机器": "Set as your default runner for this project", + "已开启此项目 LOOP 自动分配": "Auto-assign is on for this project's LOOPs", + "已设为此项目使用平台执行机器": "This project now uses the platform runner", + "已清除此项目的默认执行机器": "Cleared this project's default runner", + // Run list and run detail labels for the auto-assigned runner (runs.js). + "自动分配 · 等待可用机器": "Auto-assign · waiting for a runner", + "自动分配 · 平台云端": "Auto-assign · platform cloud", + "自动分配失败": "Auto-assign failed", +}); diff --git a/web/index.html b/web/index.html index 1b1ddc193..0cd9535fb 100644 --- a/web/index.html +++ b/web/index.html @@ -830,7 +830,7 @@

我的知识库

当前执行调度 -

+

diff --git a/web/run_queue_test.js b/web/run_queue_test.js index 961691115..e790c239f 100644 --- a/web/run_queue_test.js +++ b/web/run_queue_test.js @@ -16,6 +16,8 @@ function source(name) { return next ? tail.slice(0, next.index) : tail; } function load(context, names) { + // The page copy is Chinese unless i18n.js switched the page to English. + if (!('lfT' in context)) context.lfT = zh => zh; vm.createContext(context); for (const name of names) vm.runInContext(source(name), context); return context; @@ -140,7 +142,7 @@ async function main() { auto.concurrencyExempt=true; assert.match(machine.runExecutionChipHTML(auto),/自动分配 · Team machine/); - const limitUI=load({escapeHTML:s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))},['runnerRunLimitHTML']); + const limitUI=load({escapeHTML:s=>String(s).replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]))},['platformRunnerLabel','runnerRunLimitHTML']); assert.equal(limitUI.runnerRunLimitHTML({id:'cloud',ownerUserId:0}),'','platform machines have no per-machine limit'); const unlimited=limitUI.runnerRunLimitHTML({id:'m',name:'mac',ownerUserId:9}); assert.match(unlimited,/placeholder="不限" value=""/); diff --git a/web/runner_default_rule_test.js b/web/runner_default_rule_test.js index 7290a652a..549fa038f 100644 --- a/web/runner_default_rule_test.js +++ b/web/runner_default_rule_test.js @@ -8,7 +8,7 @@ function extract(name) { return code.slice(start, code.indexOf('\n}', start) + 2); } -const context = {state: {minRunnerVersion: '0.8.0'}}; +const context = {state: {minRunnerVersion: '0.8.0'}, lfT: zh => zh}; vm.createContext(context); vm.runInContext(extract('runnerVersionAtLeast') + extract('runnerDefaultBlocker'), context); const blocker = r => context.runnerDefaultBlocker(r); @@ -24,5 +24,5 @@ context.state.minRunnerVersion = ''; assert.equal(blocker({status: 'online', runnerVersion: '0.1.0'}), ''); assert.ok(code.includes('${defaultBlocker?`disabled title='), 'set-default button must use runnerDefaultBlocker'); -assert.ok(code.includes("Runner ${escapeHTML(r.runnerVersion||'未知')}"), 'card shows the runner version'); +assert.ok(code.includes("Runner ${escapeHTML(r.runnerVersion||lfT('未知','unknown'))}"), 'card shows the runner version'); console.log('runner default rule ok'); diff --git a/webtest/lib/load-app.mjs b/webtest/lib/load-app.mjs index 9c225c0f4..5991759f3 100644 --- a/webtest/lib/load-app.mjs +++ b/webtest/lib/load-app.mjs @@ -194,7 +194,7 @@ class ObserverStub { takeRecords() { return []; } } -export async function loadApp({ routes = [], hash = '', dispatchReady = true, origin = 'http://127.0.0.1' } = {}) { +export async function loadApp({ routes = [], hash = '', dispatchReady = true, origin = 'http://127.0.0.1', lang = '' } = {}) { const html = await readFile(path.join(WEB_ROOT, 'index.html'), 'utf8'); const dom = new JSDOM(html, { runScripts: 'outside-only', @@ -202,6 +202,8 @@ export async function loadApp({ routes = [], hash = '', dispatchReady = true, or url: `${origin}/${hash ? `#${hash.replace(/^#/, '')}` : ''}`, }); const { window } = dom; + // boot.js reads the saved language before the app scripts run. + if (lang) window.localStorage.setItem('loopforge.lang', lang); const router = createFetchRouter(routes); window.fetch = router.fetch; diff --git a/webtest/tests/i18n-runners.test.mjs b/webtest/tests/i18n-runners.test.mjs new file mode 100644 index 000000000..6238a2b23 --- /dev/null +++ b/webtest/tests/i18n-runners.test.mjs @@ -0,0 +1,168 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { loadApp, settle } from '../lib/load-app.mjs'; + +const HAN = /[㐀-鿿]/; +const ATTRS = ['placeholder', 'title', 'aria-label', 'data-tip', 'data-tooltip']; + +const runner = { + id: 'runner-mac', name: 'mac-mini', ownerUserId: 1, status: 'online', os: 'darwin', arch: 'arm64', + runnerVersion: '0.9.0', runLimit: 10, lastSeenAt: new Date().toISOString(), canUseInProject: true, + allowPrivilegedSandbox: false, sharedProjectIds: ['p1'], + load: { runningRuns: 1, occupiedRuns: 2, queuedRuns: 1 }, + runtimes: [ + { provider: 'codex', status: 'online', authMode: 'local', version: '1.0' }, + { provider: 'opencode', status: 'online', authMode: 'personal', version: '0.5' }, + ], +}; +const offline = { ...runner, id: 'runner-old', name: 'old-box', status: 'offline', runnerVersion: '0.1.0', runtimes: [], sharedProjectIds: [] }; +const shared = { ...runner, id: 'runner-team', name: 'team-box', ownerUserId: 2, runtimes: [runner.runtimes[0]] }; +const platformRunner = { name: '平台执行机器(云端)', status: 'online', runLimit: 10, canEditLimit: true, allowPrivilegedSandbox: true, load: { runningRuns: 0, occupiedRuns: 1 } }; + +async function runnersPage(lang, defaults) { + const app = await loadApp({ lang }); + app.router.post('/api/runners/bind-codes', { code: 'BIND123', expiresAt: '2099-01-01T00:00:00Z' }); + app.router.get('/api/runners?projectId=p1', [runner, offline, shared]); + app.router.get('/api/runners/default?projectId=p1', { minRunnerVersion: '0.8.0', platformRunner, ...defaults }); + app.evaluate(` + state.currentUser={id:1,loginName:'owner'}; + state.data.users=[{id:1,loginName:'owner',codexApiKeyConfigured:true}]; + state.data.projects=[{id:'p1',name:'Shop',ownerId:1,members:[]}]; + state.projectFilter='p1'; + document.querySelector('#runnersView').classList.add('active'); + `); + await app.evaluate('refreshRunners(true)'); + await settle(6); + return app; +} + +// What the English page still shows in Chinese once i18n.js has rewritten the +// text the app rendered (its MutationObserver is stubbed out in these tests). +function leftoverChinese(window, root) { + const left = []; + for (const el of [root, ...root.querySelectorAll('*')]) { + if (el.closest('[data-i18n-skip]')) continue; + for (const node of el.childNodes) { + if (node.nodeType === 3 && HAN.test(window.lfTranslate(node.nodeValue))) left.push(node.nodeValue.trim()); + } + for (const name of ATTRS) { + const value = el.getAttribute(name); + if (value && HAN.test(window.lfTranslate(value))) left.push(`${name}="${value}"`); + } + } + return left; +} + +for (const [mode, defaults] of [ + ['personal default', { runnerId: 'runner-mac', personalRunnerId: 'runner-mac' }], + ['project default', { runnerId: 'runner-mac', projectRunnerId: 'runner-mac' }], + ['auto-assign', { projectRunnerMode: 'auto' }], + ['offline project default', { runnerId: 'runner-old', projectRunnerId: 'runner-old' }], +]) { + test(`English 执行机器 page leaves no Chinese (${mode})`, async (t) => { + const app = await runnersPage('en', defaults); + t.after(app.close); + const view = app.document.querySelector('#runnersView'); + assert.match(view.querySelector('#runnersList').textContent, /mac-mini/); + assert.deepEqual(leftoverChinese(app.window, view), []); + }); +} + +test('English 执行机器 page renders whole English phrases, not mixed fragments', async (t) => { + const app = await runnersPage('en', { runnerId: 'runner-mac', personalRunnerId: 'runner-mac' }); + t.after(app.close); + const { document } = app; + const limit = document.querySelector('.runner-platform-card .runner-run-limit label'); + // The label wraps the input; CSS gap spaces the words around it. + assert.deepEqual([...limit.childNodes].filter(n => n.nodeType === 3).map(n => n.nodeValue), ['Max concurrent', 'runs']); + assert.equal(limit.querySelector('input').placeholder, 'Unlimited'); + assert.match(document.querySelector('.runner-platform-card .runner-tip').dataset.tip, /^Defaults to 10, shared by every project on the platform\. .*Enter 0 or leave blank for no limit\.$/); + assert.equal(document.querySelector('.runner-platform-card .runner-load').textContent, 'Running 0 · Occupied 1 / 10'); + assert.equal(document.querySelector('.runner-platform-card .runner-card-name b').textContent, 'Platform runner (cloud)'); + assert.equal(document.querySelector('#runnerPoolStatus').textContent, 'Personal default · mac-mini'); + assert.equal(app.evaluate(`runnerConcurrencyLabel({runLimit:1})`), 'Up to 1 concurrent run'); + assert.equal(app.evaluate(`runnerDefaultBlocker({status:'online',runnerVersion:'0.1.0'})`), 'Runner version 0.1.0 is too old; upgrade to 0.8.0 or later'); + assert.equal(app.evaluate(`runnerLastSeen(new Date(Date.now()-120000).toISOString())`), '2 min ago'); + for (const text of [app.evaluate('runnerKeyDescription("zcode")'), app.evaluate('runnerKeyDescription("pi")'), + app.evaluate('runnerAuthDescription.local'), app.evaluate('runnerAuthDescription.personal')]) { + assert.doesNotMatch(text, HAN, text); + } +}); + +test('English 执行机器 dialogs: share, remove and the auth help are English', async (t) => { + const app = await runnersPage('en', { runnerId: 'runner-mac', personalRunnerId: 'runner-mac' }); + t.after(app.close); + const { document } = app; + document.querySelector('[data-runner-auth-help]').click(); + await settle(2); + assert.equal(document.querySelector('#confirmTitle').textContent, 'Model authentication'); + assert.doesNotMatch(document.querySelector('#confirmMessage').textContent, HAN); + document.querySelector('#confirmOkBtn').click(); + await settle(4); + app.evaluate(`window.__share=editRunnerSharing(state.runners[0])`); + await settle(2); + assert.equal(document.querySelector('#confirmTitle').textContent, 'Share mac-mini'); + assert.doesNotMatch(document.querySelector('#confirmMessage').textContent, HAN); + document.querySelector('#confirmCancelBtn').click(); + await app.evaluate('window.__share'); + await settle(4); + app.evaluate(`window.__remove=removeRunner('runner-old')`); + await settle(2); + assert.equal(document.querySelector('#confirmTitle').textContent, 'Remove runner'); + assert.match(document.querySelector('#confirmMessage').textContent, /^Remove old-box\?/); + document.querySelector('#confirmCancelBtn').click(); + await app.evaluate('window.__remove'); +}); + +test('English 执行机器 page keeps runner and project names as typed', async (t) => { + const app = await loadApp({ lang: 'en' }); + t.after(app.close); + app.router.post('/api/runners/bind-codes', { code: 'BIND123', expiresAt: '2099-01-01T00:00:00Z' }); + app.router.get('/api/runners?projectId=p1', [{ ...runner, name: '测试 机器' }]); + app.router.get('/api/runners/default?projectId=p1', { runnerId: 'runner-mac', personalRunnerId: 'runner-mac', platformRunner }); + app.evaluate(` + state.currentUser={id:1,loginName:'owner'}; + state.data.users=[{id:1,loginName:'owner',codexApiKeyConfigured:true}]; + state.data.projects=[{id:'p1',name:'Shop 项目',ownerId:1,members:[]}]; + state.projectFilter='p1'; + `); + await app.evaluate('refreshRunners(true)'); + await settle(6); + const { document, window } = app; + // Run i18n.js over the rendered page the way its MutationObserver would. + const english = el => el.closest('[data-i18n-data]') ? el.textContent : window.lfTranslate(el.textContent); + const name = document.querySelector('#runnersList .runner-card-name b'); + assert.equal(english(name), '测试 机器'); + assert.equal(english(document.querySelector('#runnerPoolStatus')), 'Personal default · 测试 机器'); + assert.ok(document.querySelector('[data-runner-run-limit]').closest('[data-i18n-data]'), 'the aria-label carries the runner name'); + app.evaluate(`window.__share=editRunnerSharing(state.runners[0])`); + await settle(2); + assert.equal(document.querySelector('#confirmTitle').textContent, 'Share 测试 机器'); + assert.equal(english(document.querySelector('#confirmTitle span')), '测试 机器'); + assert.equal(english(document.querySelector('.runner-share-projects label span')), 'Shop 项目'); + document.querySelector('#confirmCancelBtn').click(); + await app.evaluate('window.__share'); +}); + +test('English mode translates the runner default toasts the server sends', async (t) => { + const app = await loadApp({ lang: 'en', dispatchReady: false }); + t.after(app.close); + for (const message of ['已设为默认执行机器,你的任务和沙箱将在这台机器上执行', '已切回云端执行', '已设为你在此项目的默认执行机器', + '已开启此项目 LOOP 自动分配', '已设为此项目使用平台执行机器', '已清除此项目的默认执行机器', + '自动分配 · 等待可用机器', '自动分配 · 平台云端', '自动分配失败']) { + assert.doesNotMatch(app.window.lfTranslate(message), HAN, message); + } +}); + +test('Chinese 执行机器 page keeps its Chinese copy', async (t) => { + const app = await runnersPage('', { runnerId: 'runner-mac', personalRunnerId: 'runner-mac' }); + t.after(app.close); + const { document } = app; + assert.equal(document.documentElement.dataset.lang, 'zh'); + const limit = document.querySelector('.runner-platform-card .runner-run-limit label'); + assert.deepEqual([...limit.childNodes].filter(n => n.nodeType === 3).map(n => n.nodeValue), ['最多同时运行', '条']); + assert.equal(document.querySelector('.runner-platform-card .runner-load').textContent, '运行中 0 · 已占 1 / 10'); + assert.equal(document.querySelector('#runnerPoolStatus').textContent, '个人默认 · mac-mini'); + assert.match(document.querySelector('#runnersList').textContent, /还没有机器|mac-mini/); + assert.equal(app.evaluate(`runnerConcurrencyLabel({runLimit:3})`), '最多同时运行 3 条'); +});