diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml index eb2404b..0337010 100644 --- a/.github/workflows/windows.yml +++ b/.github/workflows/windows.yml @@ -15,7 +15,7 @@ jobs: - run: node node_modules/electron/install.js - run: npm run check - run: npm run check:public - - run: npm test + - run: node --test --test-concurrency=2 tests/*.test.js - run: npm run build:release - run: node scripts/verify-artifact.js dist/portable-marketplace/plugins/codex-continuer - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 diff --git a/AGENTS.md b/AGENTS.md index 075c01e..d800dbd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,7 @@ # 本对话的版本约定 +- 用户于 2026-11-05 更新约定:当前及后续更改统一记录为 `0.7.0`,在独立目录及本地分支 `codex/0.7.0` 开发;不要递增版本号或添加 preview 序号。保留 `0.6.0` 源码、构建和安装,不覆盖、不安装、不推送、不发布,除非收到新的明确指令。 + - 用户于 2026-10-31 更新约定:当前及后续版本固定为 `0.6.0`,本地开发分支为 `codex/0.6.0`;不要自动递增或添加 preview 序号。下方旧版本约定仅作历史记录。 - 用户于 2026-10-31 明确授权本轮将最新源码及用户 README 同步到本地脱敏发布仓库后推送并合入公开 `main`。通过独立公开仓库和正常 PR 检查完成,不推送私有开发历史;此次不安装或发布 Release,之后默认仍只保存本地。 - assessment 和临时 `.review` 审查材料统一保存在被忽略的 `.cache/assessments/`;不要加入 Git 暂存区、提交或公开源码包。用户明确仅移走现有 `.review` 审查目录,`docs` 中的项目评估等正式文档保留。使用明确文件列表暂存,提交前检查列表。 diff --git a/CHANGELOG.md b/CHANGELOG.md index 670b460..3179eea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,30 @@ # 更新记录 +## 0.7.0 — 本地开发 + +- 自动启动期间手动打开或点击托盘,窗口就绪后会显示到前台;启动期间退出会取消迟到的窗口创建和显示,并等待后台清理完成。 +- 修复启动与恢复:中文及 Windows 短路径下正确停止监听器;自启动改用支持长参数的用户启动快捷方式,显式重新启用会清除退出标记;启动失败允许重试,手动打开恢复可见,旧监听器 PID 不再阻止恢复。 +- 修复交互状态:旧保存响应不关闭新草稿,语言切换保留提交锁,详情刷新保留阅读位置与选择,设置连接状态和错误提示及时更新;服务重启后重新读取详情,延迟响应不覆盖较新的状态。 +- 修复任务和显示:首次排队的一次性工作在额度恢复后执行一次;新建/导入保存失败可安全重试;详情未加载时明确提示,较早聊天可继续分页访问,重置位置立即生效,小挂件按实际额度周期显示。 + +- 回答续作可选择是否重复和本轮最多发送次数(1–100,包含首次);新记录默认只发一次,达到次数仅关闭回答监测。暂停、重启和编辑保留计数,明确重新开启回答监测开始新一轮且不重发旧回复。 +- 回答监测与额度监测改为独立开关,卡片与监测设置均可操作;监测总开关保留用于总暂停。关闭一种不会停止另一种,全部发送仍受原聊天累计发送总上限约束。 +- 独立开关与次数设置验证:独立副本 411 项完整回归通过,0 失败、0 跳过;包含两种界面真实 DOM、HTTP 保存、单次/重复、独立取消、重启、去重、次数耗尽和旧数据迁移。语法及公开源码检查通过。 + +- 第三轮自审修复:连续缩放中后续 IPC 请求失败时保留最新原生状态,避免旧结果使视图或尺寸回退;无新事件时保留最近确认结果,失败后可继续调整。新增失败复现与恢复回归,独立副本 401 项完整回归全部通过,语法及公开源码检查通过。 + +- 第二轮自审修复:小屏幕下调整卡片大小时保持窗口为正方形;展开/收起时取消上一视图排队中的拖动缩放,保留独立滑块设置。新增失败复现后完成修复,独立副本 400 项完整回归全部通过,语法及公开源码检查通过。 + +- 卡片和面板新增右下角拖动调整手柄及键盘微调;面板增加独立宽高滑块,尺寸分别保存,跟随、收起/展开和重启后保留,并按屏幕可用范围限制实际尺寸。 +- 自审修复:分页读取历史后复查运行状态,避免读取期间开始的新回答被忽略;完整回答续作发送结果不明、重启恢复及保存重试时清除过时等待原因和重试时间。 +- 尺寸调整与自审修复验证:独立源码副本 398 项完整回归全部通过,0 失败、0 跳过,包含真实隐藏 Electron 窗口尺寸、界面加载、跟随与切换;语法及公开源码检查通过。 + +- 监测新增「完整回答后继续」开关,默认关闭。根据最新轮次正常结束且形成完整最终回复判断本次指令结束,发送单独保存、可编辑的继续消息,留空使用当前语言的“继续”。 +- 完整回答续作与额度恢复续作使用独立消息,同一完整回答只触发一次;两者共用累计发送上限,暂停、重新启用及重启均保留计数和去重记录。 +- 发送前再次核对最新回答;暂停、调度关闭、断线、额度过期或新指令到来时取消尚未发送的消息。发送结果不明时停止自动重试。 +- 新版本固定记录为 0.7.0,在独立本地分支与目录开发,保留 0.6.0 源码、构建及安装;本轮不安装、不推送、不发布。 +- 验证:388 项完整回归全部通过(0 失败、0 跳过),包含真实隐藏 Electron 表单、独立数据持久化与重启、模拟发送竞态;语法与公开源码检查通过。 + ## 0.6.0 — 2026-10-31 - 汇总 0.5.1 发布后的数据目录、首次额度监测、演示窗口隔离、备份恢复及表单修复。 diff --git a/Enable-Autostart.ps1 b/Enable-Autostart.ps1 index 06e993e..d8eacc5 100644 --- a/Enable-Autostart.ps1 +++ b/Enable-Autostart.ps1 @@ -14,19 +14,25 @@ New-Item -ItemType Directory -Path $continuerData -Force | Out-Null $continuerRegistryKey = Get-Item -LiteralPath $continuerRegistry -ErrorAction SilentlyContinue $continuerExisting = if ($continuerRegistryKey) { $continuerRegistryKey.GetValue($continuerName, $null) } else { $null } if ($continuerExisting -and $continuerExisting -notmatch 'desktop[\\/]watch-codex\.ps1') { throw 'An unrelated startup item already uses the CodexContinuer name.' } +$continuerShell = New-Object -ComObject WScript.Shell +$continuerStartup = $continuerShell.SpecialFolders.Item('Startup') +$continuerShortcutPath = Join-Path $continuerStartup 'CodexContinuer.lnk' +$continuerShortcut = $continuerShell.CreateShortcut($continuerShortcutPath) +if ((Test-Path -LiteralPath $continuerShortcutPath) -and $continuerShortcut.Description -ne 'Codex Continuer startup') { throw 'An unrelated startup shortcut already uses the CodexContinuer name.' } # Stop only the previous watcher identified by its saved PID and executable/script. $continuerStatusPath = Join-Path $continuerData 'autostart-status.json' if (Test-Path -LiteralPath $continuerStatusPath) { try { - $continuerSaved = Get-Content -LiteralPath $continuerStatusPath -Raw | ConvertFrom-Json + $continuerSaved = Get-Content -LiteralPath $continuerStatusPath -Raw -Encoding UTF8 | ConvertFrom-Json $continuerProcess = Get-CimInstance Win32_Process -Filter "ProcessId=$([int]$continuerSaved.pid)" $continuerLegacy = $continuerProcess -and $continuerProcess.Name -eq 'powershell.exe' -and $continuerProcess.CommandLine.Contains((Join-Path $continuerSaved.pluginRoot 'desktop/watch-codex.ps1')) - $continuerNative = $continuerProcess -and $continuerProcess.Name -eq 'continuer-monitor.exe' -and $continuerProcess.ExecutablePath -eq (Join-Path $continuerSaved.pluginRoot 'desktop/continuer-monitor.exe') -and $continuerProcess.CommandLine -match '(?:^|\s)"?--watch"?(?:\s|$)' + $continuerNative = $continuerProcess -and $continuerProcess.Name -eq 'continuer-monitor.exe' -and $continuerProcess.ExecutablePath -and [IO.Path]::GetFullPath($continuerProcess.ExecutablePath) -eq (Join-Path ([IO.Path]::GetFullPath($continuerSaved.pluginRoot)) 'desktop/continuer-monitor.exe') -and $continuerProcess.CommandLine -match '(?:^|\s)"?--watch"?(?:\s|$)' if ($continuerLegacy -or $continuerNative) { Stop-Process -Id $continuerProcess.ProcessId } } catch { Write-Warning 'Could not stop the previous watcher. Its single-instance lock prevents duplicate watchers.' } } if ($Disable) { if ($continuerExisting) { Remove-ItemProperty -Path $continuerRegistry -Name $continuerName } + if (Test-Path -LiteralPath $continuerShortcutPath) { Remove-Item -LiteralPath $continuerShortcutPath -Force } @{ enabled = $false; updatedAt = (Get-Date).ToString('o') } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $continuerData 'autostart-preferences.json') -Encoding UTF8 Write-Host 'Continuer startup disabled. Existing project work is unchanged.' exit 0 @@ -34,8 +40,21 @@ if ($Disable) { if (-not (Test-Path -LiteralPath $continuerWatcher)) { throw 'Build/install the plugin before enabling startup.' } $continuerPowerShell = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe' $continuerArguments = '-NoProfile -WindowStyle Hidden -ExecutionPolicy Bypass -File "{0}" -NodePath "{1}" -PluginRoot "{2}" -DataDir "{3}"' -f $continuerWatcher,$continuerNode,$continuerRoot,$continuerData -if (-not (Test-Path -LiteralPath $continuerRegistry)) { New-Item -Path $continuerRegistry -Force | Out-Null } -New-ItemProperty -Path $continuerRegistry -Name $continuerName -Value ('"' + $continuerPowerShell + '" ' + $continuerArguments) -PropertyType String -Force | Out-Null +# Startup shortcuts support the full argument list; Run values have a short +# command-line limit that long plugin/data paths exceed. +New-Item -ItemType Directory -Path $continuerStartup -Force | Out-Null +$continuerShortcut.TargetPath = $continuerPowerShell +$continuerShortcut.Arguments = $continuerArguments +$continuerShortcut.WorkingDirectory = $continuerRoot +$continuerShortcut.Description = 'Codex Continuer startup' +$continuerShortcut.WindowStyle = 7 +$continuerShortcut.Save() +if (-not (Test-Path -LiteralPath $continuerShortcutPath)) { throw 'Could not save the startup shortcut.' } +if ($continuerExisting) { Remove-ItemProperty -Path $continuerRegistry -Name $continuerName } +# Explicit enable is a new user request; passive Codex launches still leave the +# exit latch intact until the user enables startup or opens Continuer manually. +$continuerQuit = Join-Path $continuerData 'quit.request' +if (Test-Path -LiteralPath $continuerQuit) { Remove-Item -LiteralPath $continuerQuit -Force } @{ enabled = $true; updatedAt = (Get-Date).ToString('o') } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $continuerData 'autostart-preferences.json') -Encoding UTF8 Start-Process -FilePath $continuerPowerShell -ArgumentList $continuerArguments -WindowStyle Hidden | Out-Null -Write-Host 'Enabled for the current user: Continuer opens whenever Codex desktop starts.' +Write-Host 'Startup registered for the current user. Watcher launch requested; open Continuer to check its status.' diff --git a/desktop/geometry.cjs b/desktop/geometry.cjs index d308d62..5fb8142 100644 --- a/desktop/geometry.cjs +++ b/desktop/geometry.cjs @@ -30,8 +30,15 @@ function expandFromCard(card, workArea, size) { return { x: align(card.x, card.width, workArea.x, workArea.width, width), y: align(card.y, card.height, workArea.y, workArea.height, height), width, height }; } function compactSize(value) { return Number.isFinite(value) ? Math.min(420,Math.max(160,Math.round(value))) : 256; } +function expandedSize(value) { + return { + width: Number.isFinite(value?.width) ? Math.min(960,Math.max(360,Math.round(value.width))) : 432, + height: Number.isFinite(value?.height) ? Math.min(1200,Math.max(400,Math.round(value.height))) : 720, + }; +} function samePlacementContext(a,b) { return !!a && a.mode===b.mode && a.follow===b.follow && a.compactSize===b.compactSize && + a.panelWidth===b.panelWidth && a.panelHeight===b.panelHeight && (!a.follow || ['x','y','width','height'].every(key=>a.anchor?.[key]===b.anchor?.[key])); } function restoreModePosition(fallback,saved,workArea) { @@ -43,4 +50,4 @@ function restoreModePosition(fallback,saved,workArea) { ? {...fallback,x,y} : fallback; } const sizes = { compact: { width: 256, height: 256 }, expanded: { width: 432, height: 720 } }; -module.exports = { place, placeIndependent, expandFromCard, offsetFrom, sizes, compactSize, samePlacementContext, restoreModePosition }; +module.exports = { place, placeIndependent, expandFromCard, offsetFrom, sizes, compactSize, expandedSize, samePlacementContext, restoreModePosition }; diff --git a/desktop/runtime.cjs b/desktop/runtime.cjs index b40ee1e..503ee60 100644 --- a/desktop/runtime.cjs +++ b/desktop/runtime.cjs @@ -6,7 +6,7 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = const { createInterface } = load('node:readline'); const { join } = load('node:path'); const { readFileSync, writeFileSync, mkdirSync, existsSync } = load('node:fs'); - const { place, placeIndependent, expandFromCard, offsetFrom, sizes, compactSize, samePlacementContext, restoreModePosition } = load('./geometry.cjs'); + const { place, placeIndependent, expandFromCard, offsetFrom, sizes, compactSize, expandedSize, samePlacementContext, restoreModePosition } = load('./geometry.cjs'); const { createPointerDrag } = load('./pointer-drag.cjs'); const runtimeConfig = load('../server/config.cjs'); const logging = load('../server/logging.cjs'); @@ -24,6 +24,7 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = const preferenceFile = widget.preferences; let prefs = { follow: true, expanded: false, hidden: false, compactSize: 256, offsets: {}, positions: {} }; try { prefs = { ...prefs, ...JSON.parse(readFileSync(preferenceFile, 'utf8')) }; } catch {} + prefs.panelSize = expandedSize(prefs.panelSize); let preferenceError = null; let nativeText = () => 'Codex Continuer', refreshMenu = () => {}; const save = () => { try { writeFileSync(preferenceFile, JSON.stringify(prefs)); preferenceError = null; } catch (error) { preferenceError = error.message; console.error(`挂件设置未保存:${error.message}`); } }; @@ -34,8 +35,9 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = let settledPlacement, restoringMode=false, expansionOrigin=null; let pendingTransition, transitionSequence=0, renderedExpanded=prefs.expanded; const mode = () => prefs.expanded ? 'expanded' : 'compact'; - const placementContext = () => ({ mode:mode(),follow:prefs.follow,compactSize:compactSize(prefs.compactSize),anchor:anchor ? {...anchor} : null }); - if (processInfo.argv.includes('--auto')) prefs.hidden = false; + const placementContext = () => ({ mode:mode(),follow:prefs.follow,compactSize:compactSize(prefs.compactSize),panelWidth:prefs.panelSize.width,panelHeight:prefs.panelSize.height,anchor:anchor ? {...anchor} : null }); + if (!processInfo.argv.includes('--quit')) prefs.hidden = false; + let revealOnReady = !processInfo.argv.includes('--auto'), exitReason = 'user-quit'; function diagnostics() { if (!win || win.isDestroyed() || dragging || pointerDrag?.active) return; const next = JSON.stringify({ ...widgetInfo(), pid: processInfo.pid, ready: isReady, visible: win.isVisible(), ...state(), bounds: win.getBounds() }); @@ -47,7 +49,13 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = else if (processInfo.argv.includes('--quit')) { app.whenReady().then(quitAll); } else { app.on('second-instance', (_event, argv, _directory, identity) => { if (!matchesWidgetIdentity(identity, widget.identity, processInfo.platform)) return; if (argv.includes('--quit')) { void quitAll(); return; } if (closing) return; prefs.hidden = false; if (!argv.includes('--auto')) changeExpanded(true); save(); show(!argv.includes('--auto')); }); - app.whenReady().then(start).catch(error => { dialog.showErrorBox(nativeText("native.continuer_could_not_start"), error.message); app.quit(); }); + app.whenReady().then(start).catch(error => { + if (closing) return; + // Startup failure is retryable; only an explicit quit stops the service + // and writes the persistent user-exit latch. + exitReason = 'startup-failed'; shutdownComplete = true; + dialog.showErrorBox(nativeText("native.continuer_could_not_start"), error.message); app.quit(); + }); } function quitAll() { if (quitting) return quitting; @@ -63,7 +71,7 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = })(); return quitting; } - function state() { return { follow: prefs.follow, expanded: prefs.expanded, hidden: prefs.hidden, preferenceError, tracking: !!anchor, visible: !!win?.isVisible(), compactSize: compactSize(prefs.compactSize), transitioning: !!boundsTimer, transition: pendingTransition ? {id:pendingTransition.id,fromExpanded:pendingTransition.fromExpanded} : null, panelSize, platform: processInfo.platform }; } + function state() { return { follow: prefs.follow, expanded: prefs.expanded, hidden: prefs.hidden, preferenceError, tracking: !!anchor, visible: !!win?.isVisible(), compactSize: compactSize(prefs.compactSize), preferredPanelSize: {...prefs.panelSize}, transitioning: !!boundsTimer, transition: pendingTransition ? {id:pendingTransition.id,fromExpanded:pendingTransition.fromExpanded} : null, panelSize, platform: processInfo.platform }; } function cancelTransition() { clearTimeout(boundsTimer); boundsTimer=null; pendingTransition=null; } @@ -102,11 +110,11 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = const saved = prefs.positions[mode()]; const following = prefs.follow && anchor; const target = following ? anchor : { ...(saved || current), width: (saved || current).width + 16, height: (saved || current).height + 16 }; - const size = prefs.expanded ? sizes.expanded : { width: compactSize(prefs.compactSize), height: compactSize(prefs.compactSize) }; + const size = prefs.expanded ? {...prefs.panelSize} : { width: compactSize(prefs.compactSize), height: compactSize(prefs.compactSize) }; const offset = prefs.follow && anchor ? (prefs.offsets[mode()] || prefs.offsets[prefs.expanded ? 'compact' : 'expanded']) : undefined; const desired = { x: target.x + target.width - size.width - (offset?.right ?? 16), y: target.y + target.height - size.height - (offset?.bottom ?? 16), ...size }; const display = screen.getDisplayMatching(fromCard || desired); - panelSize = { width: Math.min(sizes.expanded.width,display.workArea.width)-18, height: Math.min(sizes.expanded.height,display.workArea.height)-18 }; + panelSize = { width: Math.min(prefs.panelSize.width,display.workArea.width)-18, height: Math.min(prefs.panelSize.height,display.workArea.height)-18 }; if (!prefs.expanded) size.width=size.height=Math.min(size.width,display.workArea.width,display.workArea.height); let next = fromCard ? expandFromCard(fromCard,display.workArea,size) : following ? place(target, display.workArea, size, offset) : placeIndependent(saved,current,display.workArea,size); if (restoringMode && !fromCard) { @@ -127,7 +135,13 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = } else { cancelTransition(); renderedExpanded=prefs.expanded; settle(); } } function show(force = false, animate = false) { - if (!win || !isReady) return; + if (closing) return; + if (!win || !isReady) { + // Second-instance, tray and shortcut requests can precede renderer-ready. + // Preserve their foreground intent until there is a window to reveal. + if (force) revealOnReady = true; + return; + } // Tracking still records the latest anchor, but must not query/mutate the // window, send renderer state, or write diagnostics during a user drag. if (!force && !prefs.hidden && (dragging || pointerDrag?.active)) return; @@ -180,7 +194,40 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = prefs.expanded=expanded; } function setFollow(value) { prefs.follow = value; syncTracker(); } + function resetPosition() { + pointerDrag?.finish(); cancelTransition(); + settledPlacement = null; restoringMode = false; expansionOrigin = null; + prefs.offsets = {}; prefs.positions = {}; + if (win && !win.isDestroyed() && !(prefs.follow && anchor)) { + const area = screen.getDisplayMatching(win.getBounds()).workArea; + const size = prefs.expanded ? prefs.panelSize : {width:compactSize(prefs.compactSize),height:compactSize(prefs.compactSize)}; + win.setBounds(place(area, area, size), false); + } + save(); show(true); + } + function resize(view, value) { + if (!['compact','expanded'].includes(view)) throw new Error('Unsupported size mode'); + if (view === 'compact' ? !Number.isFinite(value) : !Number.isFinite(value?.width) || !Number.isFinite(value?.height)) throw new Error('Invalid widget size'); + pointerDrag?.finish(); finishTransition(); dragging=false; + if (view === 'compact') prefs.compactSize=compactSize(value); + else prefs.panelSize=expandedSize(value); + if ((view === 'expanded') === prefs.expanded && win && !win.isDestroyed()) { + // Resize from the current top-left, independently of remembered follow offsets. + const current=win.getBounds(), workArea=screen.getDisplayMatching(current).workArea; + const edge=Math.min(prefs.compactSize,workArea.width,workArea.height); + const size=prefs.expanded ? prefs.panelSize : {width:edge,height:edge}; + const next=placeIndependent(current,current,workArea,size); + win.setBounds(next,false); renderedExpanded=prefs.expanded; + prefs.positions[mode()]=next; + if (prefs.follow && anchor) prefs.offsets[mode()]=offsetFrom(anchor,next); + panelSize={width:Math.min(prefs.panelSize.width,workArea.width)-18,height:Math.min(prefs.panelSize.height,workArea.height)-18}; + restoringMode=false; expansionOrigin=null; + } + settledPlacement=placementContext(); + save(); show(); return state(); + } function syncTracker() { + if (closing) return; if (processInfo.platform !== 'win32') { prefs.follow = false; return; } if (!prefs.follow) { const previous = tracker; tracker = null; @@ -214,10 +261,13 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = child.on('exit', ended); } async function start() { + if (closing) return; const { interfaceText } = await import('../public/i18n.js'); nativeText = text => interfaceText(text, prefs.language || 'zh'); const runtime = await import('../plugin/runtime.js'); + if (closing) return; await runtime.ensureService(); + if (closing) return; const display = screen.getPrimaryDisplay().workArea; win = new BrowserWindow({ x: display.x + display.width - sizes.compact.width - 16, y: display.y + display.height - sizes.compact.height - 16, ...sizes.compact, show: false, alwaysOnTop: false, frame: false, thickFrame: false, roundedCorners: false, transparent: true, backgroundColor: '#00000000', resizable: false, skipTaskbar: true, hasShadow: false, autoHideMenuBar: true, title: 'Codex Continuer Widget', webPreferences: { preload: join(__dirname, 'preload.cjs'), contextIsolation: true, nodeIntegration: false, sandbox: true, devTools: false } }); win.webContents.setWindowOpenHandler(() => ({ action: 'deny' })); @@ -262,9 +312,15 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = ipcMain.handle('continuer:control', (event, action, value) => { if (!allowed(event)) throw new Error('Untrusted widget request'); if (action === 'language' && ['zh', 'en'].includes(value)) { if (prefs.language !== value) { prefs.language = value; save(); refreshMenu(); } return state(); } - if (action === 'renderer-ready') { isReady = true; show(); return state(); } + if (action === 'renderer-ready') { if (closing) return state(); isReady = true; show(revealOnReady); revealOnReady = false; return state(); } if (action === 'quit') { setImmediate(() => { void quitAll(); }); return { quitting: true }; } if (action === 'transition-ready') { finishTransition(value); return state(); } + if (action === 'compact-size') return resize('compact',value); + if (action === 'panel-size') return resize('expanded',value); + if (action === 'resize') { + if (value?.expanded !== prefs.expanded || boundsTimer) return state(); + return resize(mode(),prefs.expanded ? value : value.width); + } if (action === 'drag-start') { if (!Number.isInteger(value) || prefs.expanded || boundsTimer || dragging) return { ok:false }; return pointerDrag.start(value); @@ -274,11 +330,10 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = if (action === 'expand' && typeof value === 'boolean') changeExpanded(value); else if (action === 'follow' && typeof value === 'boolean') setFollow(value) else if (action === 'hide') prefs.hidden = true; - else if (action === 'reset-position') { settledPlacement=null; prefs.offsets = {}; prefs.positions = {}; } - else if (action === 'compact-size' && Number.isFinite(value) && value >= 160 && value <= 420) prefs.compactSize=compactSize(value); + else if (action === 'reset-position') { resetPosition(); return state(); } else if (action === 'state') return state(); else throw new Error('Unsupported action'); - save(); show(action === 'expand',action === 'expand' || action === 'compact-size'); return state(); + save(); show(action === 'expand',action === 'expand'); return state(); }); ipcMain.handle('continuer:pick-directory', async event => { if (!allowed(event)) throw new Error('Untrusted widget request'); @@ -293,7 +348,7 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = { label: nativeText("native.open_quota_and_work_panel"), click: reveal }, { label: nativeText("native.follow_codex_window"), click: () => { prefs.hidden = false; setFollow(true); save(); show(); } }, { label: nativeText("native.show_independently"), click: () => { setFollow(false); reveal(); } }, - { label: nativeText("ui.reset_widget_position"), click: () => { settledPlacement=null; prefs.offsets = {}; prefs.positions = {}; save(); show(true); } }, + { label: nativeText("ui.reset_widget_position"), click: resetPosition }, { type: 'separator' }, { label: nativeText("native.hide_to_tray"), click: () => { prefs.hidden = true; save(); show(); } }, { label: nativeText("ui.quit_continuer"), click: () => { void quitAll(); } }, @@ -321,10 +376,10 @@ function createDesktopRuntime({ load = require, processInfo = process, timing = if (!ownsInstance) return; if (!shutdownComplete) { event.preventDefault(); void quitAll(); return; } closing = true; pointerDrag?.finish(); cancelTransition(); tracker?.kill(); globalShortcut.unregisterAll(); tray?.destroy(); - try { writeFileSync(widget.status, JSON.stringify({ ...widgetInfo(), pid: processInfo.pid, ready: false, exitReason: 'user-quit', updatedAt: Date.now() })); } catch {} + try { writeFileSync(widget.status, JSON.stringify({ ...widgetInfo(), pid: processInfo.pid, ready: false, exitReason, updatedAt: Date.now() })); } catch {} }); app.on('window-all-closed', () => app.quit()); - return { changeExpanded, finishTransition, show, savePosition, state, setFollow, get preferences() { return prefs; } }; + return { changeExpanded, finishTransition, show, savePosition, state, setFollow, resize, get preferences() { return prefs; } }; } module.exports = { createDesktopRuntime }; diff --git a/docs/task-models.md b/docs/task-models.md index 40afa1c..9d21408 100644 --- a/docs/task-models.md +++ b/docs/task-models.md @@ -1,6 +1,6 @@ # 两种任务的状态模型 -版本:0.5.1。日期:2026-10-29。 +版本:0.7.0。更新日期:2026-11-06。 任务列表继续通过原有 HTTP、MCP 和快照接口读取。后台以 `mode` 区分两种记录,各自定义创建、状态、操作、校验和恢复规则;Manager 只分发操作并协调保存、授权取消及中断。 @@ -18,7 +18,15 @@ 两种模式仍使用现有的 `continuous` 字段以兼容界面和持久化格式,含义分别是“允许继续下一轮”和“开启额度监测”。状态及计数的规则由各自模块维护,调用方不再通过同一段分支处理两类任务的暂停、继续和完成。 -通过挂件或完整页面加入原聊天时,可勾选「加入后开始监测」,与新记录一并保存;未勾选和 MCP 导入都保持暂停。开启监测不会改变后台调度开关,也不会因当前额度正常而立即发送消息,仍需确认后续耗尽与恢复。 +通过挂件或完整页面加入原聊天时,可勾选「加入后开始监测」,与新记录一并保存;未勾选和 MCP 导入都保持暂停。开启监测不会改变后台调度开关。额度恢复消息仍需确认耗尽与恢复;另行开启完整回答监测后,最新完整回答可独立触发专用消息。 + +## 完整回答续作 + +`completionMonitoring` 为独立功能开关,旧记录缺省视为关闭;`completionMessage` 独立于额度消息 `continuationMessage`。`continuous` 仍是整条记录的监测总开关。`server/completion-wake.js` 按轮询周期读取最新轮次,只保留轮次 ID 与协议状态,不保存聊天正文;正常结束且存在非空最终回答时准备发送。 + +`completion` 保存 `delivery`(idle/sending/sent/uncertain)、目标 `turnId` 与已处理 `lastTurnId`。入队前持久化 sending,再由队列能力探测后的复查确认同一轮次仍完整。确认发送才增加 `sentCount`,与额度恢复共用 `maxWakeSends`;发送成功同时清除旧额度恢复记录。重复轮询、重启、暂停或编辑消息不会重发同一回答。 + +未实际发送的取消可稍后重试。发送结果不明或重启发现 sending 时阻塞;人工重新开启后记下该轮次并跳过,不把不确定结果算作确认发送。恢复备份和存储重试继续关闭调度。MCP 不能开启或修改完整回答续作设置,用户通过挂件或完整页面操作。 ## 旧数据与恢复 @@ -32,6 +40,10 @@ ## 验证 +0.7.0 完整回归:**388 项通过,0 失败、0 跳过**;语法与公开源码检查通过。测试使用独立数据目录和模拟队列,未发送真实聊天消息或切换安装。新增覆盖完整回答触发、两种消息独立编辑、分页历史、轮询间隔、额度新鲜度、发送前复查、暂停与断线竞态、共享上限、发送不确定、保存失败及去重重启;真实隐藏 Electron 页面同时验证两种界面在切换语言后保留并提交新表单。 + +以下为此前 0.5.1 状态模型重构的历史验证记录: + 固定源码副本 `.cache/task-model-refactor-0.5.1/` 的完整回归:**311 项通过,0 失败、0 跳过**,包括真实隐藏 Electron 检查。语法检查与公开源码检查通过。 新增 `tests/task-models.test.js` 的 7 项回归覆盖模式字段、跨模式非法状态、计数与执行隔离、外部通知和授权隔离、混合旧数据的一次性迁移、在途发送重启,以及备份恢复。既有暂停竞态、发送上限、回复检查、保存失败、HTTP/MCP 和界面回归继续通过。 diff --git a/docs/usage.md b/docs/usage.md index ce2d1c8..dd94d59 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -8,10 +8,12 @@ 收起后显示动态仪表:默认先显示**五小时额度及其重置倒计时**,每 12 秒切换一次,使用 1 秒的淡出、换值、淡入过渡;额度文字不再随装饰动画长时间隐藏,原版 SVG 的 60 秒动画时间线保持连续。倒计时每秒更新,数据未知或过期时显示「待同步」,重置时间已到则显示「待刷新」。这仅切换显示,续作调度仍需所有窗口的真实新额度样本达标。系统开启「减少动态效果」时关闭装饰动画与转场,但保留额度轮播。 -桌面卡片默认 256 px,可在「工作策略与显示」中用滑块调为 160–420 px,也可按住 Ctrl 在卡片上滚动鼠标滚轮调整;大小会保存。**点击整张卡片展开,拖动任意位置移动**;桌面光标移动超过 6 个逻辑像素视为拖动,不触发展开。静止按住或轻微抖动不会移动卡片或保存新位置;失焦、取消或丢失指针捕获时结束拖动。展开/收起先淡出,在不可见时一次切换窗口尺寸和位置,再淡入;收起会恢复卡片原位,从卡片展开时以当前卡片为锚,屏幕边缘空间不足时换向展开,不跳回旧面板位置。 +桌面卡片默认 256 px,可在「工作策略与显示」中用滑块调为 160–420 px,也可按住 Ctrl 在卡片上滚动鼠标滚轮调整。0.7.0 新增右下角调整手柄:卡片和展开面板都可拖动调整大小,聚焦手柄后可用方向键微调;面板另有独立的宽度(360–960 px)和高度(400–1200 px)滑块。卡片和面板尺寸分别保存,重启与收起/展开后保留;屏幕较小时限制实际窗口大小,保留偏好供大屏恢复。**点击卡片主体展开,拖动主体移动**;调整手柄不触发展开或移动。桌面光标移动超过 6 个逻辑像素视为拖动,不触发展开。静止按住或轻微抖动不会移动卡片或保存新位置;失焦、取消或丢失指针捕获时结束拖动。展开/收起先淡出,在不可见时一次切换窗口尺寸和位置,再淡入;收起会恢复卡片原位,从卡片展开时以当前卡片为锚,屏幕边缘空间不足时换向展开,不跳回旧面板位置。 **右键卡片**可打开与系统托盘相同的菜单:打开面板、跟随 Codex、独立显示、重置位置、隐藏挂件或退出挂件。隐藏到托盘只隐藏界面;关闭按钮和“退出 Continuer”会保存状态、停止本工具的执行轮次与服务、结束跟随和自启动监听进程。已进入原聊天队列的消息仍不能撤回。 +0.7.0 手动重新打开会恢复窗口显示;启动失败不会被记录成用户主动退出。重置位置立即将独立窗口移回当前屏幕的默认位置。自启动使用当前用户的启动快捷方式保存完整路径,重新启用时会恢复监听;禁用时移除本工具的快捷方式及旧登录启动项。普通状态查询或被动打开 Codex 仍不会撤销主动退出,需手动打开 Continuer 或重新启用自启动。 + 卡片采用普通窗口层级,其他应用可以正常覆盖它。独立模式不运行窗口跟随监测;切换到跟随模式时才启动监测,切回独立模式后结束。隐藏窗口使用 Chromium 默认的后台节流。窗口枚举和内存排查记录见 [桌面内存排查](desktop-memory-audit.md)。 源码构建使用 Visual Studio Build Tools 的 Roslyn 编译器确定性生成 `desktop/continuer-monitor.exe`,可通过 `CONTINUER_CSC` 指定编译器。自启动与跟随监测优先使用此隐藏程序,PowerShell 启动入口在交接后退出。便携包已经包含监听器,无需安装编译工具。源码环境仍保留 PowerShell 监测回退。 @@ -24,6 +26,20 @@ 原版 SVG 与像素数字相关内容按 GPL-3.0-only 使用,来源与完整许可证见 `THIRD_PARTY_NOTICES.md` 和 `LICENSE`;分发包包含对应源文件。 +### 完整回答后继续(0.7.0) + +回答监测和额度监测现在有独立开关,卡片上可分别调整;详情的「监测与续作设置」也可同时配置。两种监测分别控制触发类型,「监测总开关」和后台调度负责总暂停/开启。只关闭一种监测不会停止另一种;关闭两种会暂停该记录。修改独立选项不会自动启动已暂停的记录,仍需开启总开关。 + +回答续作新增「重复续作」和「本轮最多发送次数」。新记录默认不重复,即只发送一次;勾选重复后,按每个新的完整回复逐次触发,最多发送 1–100 次(包含首次),同一条回复仍只触发一次。达到本轮次数后只关闭回答监测,额度监测按自己的开关继续。页面显示本轮已发送/最多发送次数;暂停、重启、编辑消息和修改上限不会清零。明确重新开启已关闭的回答监测会开始新一轮,但不会重发上一次已处理的回复,原聊天的累计发送总次数也不清零。所有发送仍受「原聊天发送上限」约束,若该总上限较小会提前暂停整条记录。 + +旧记录升级时保留原先额度监测和连续回答续作的行为,不自动启动新的工作;可在新设置中改为单次或指定次数。 + +加入原聊天时,或在记录详情的「编辑完整回答续作」中,开启「完整回答后继续」并编辑专用消息。这条消息与额度恢复时的续作消息分开保存;留空发送当前语言的“继续”。此选项默认关闭,保存设置不会自动启动暂停中的监测;还需开启该记录监测与后台调度。 + +开启后按轮询周期检查最新指令:轮次正常结束、最终回复非空,且原聊天没有正在生成的回答时,视为本次指令结束。在有充足的新额度样本时,通过原聊天队列发送一次专用消息,无需经历额度耗尽。同一回答在暂停、重新开启、修改消息和服务重启后均不会再次触发;下一条指令形成完整回答后可以再次触发。启用时已有的最新完整回答也会触发一次。 + +两种触发共用「原聊天发送次数上限」。完整回答发送成功也会消耗该指令的待恢复记录,避免重复接续。发送前会再次读取最新轮次,新指令到来、仍在回答、状态未知、暂停、断线或额度过期时取消尚未发出的消息。结果不明则阻塞自动发送;检查原聊天后手动重新开启,将跳过该不确定回答并继续监测后续回答,不会自动补发它。完整回答仅表示当前指令的回答结束,不代表项目验收通过。 + ## 安装 Codex 插件(Windows) 源码安装需要 Windows x64、Node.js 22.12+(推荐 24)、Visual Studio Build Tools(MSBuild/Roslyn)、已安装并登录且支持插件的 Codex CLI。安装器先运行只读能力检查;`npm run doctor` 可单独检查。其他系统和架构尚未完成验收。 diff --git a/package-lock.json b/package-lock.json index aac648f..59f10b9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "codex-continuer", - "version": "0.6.0", + "version": "0.7.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "codex-continuer", - "version": "0.6.0", + "version": "0.7.0", "devDependencies": { "electron": "45.0.0" }, diff --git a/package.json b/package.json index 2c0c106..c9cc47e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "codex-continuer", - "version": "0.6.0", + "version": "0.7.0", "private": true, "type": "module", "description": "Local Codex quota monitor and resumable task manager", diff --git a/plugin.json b/plugin.json index 1bb96b6..8a7a8bf 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "codex-continuer", - "version": "0.6.0", + "version": "0.7.0", "description": "Windows 预览版:Codex 额度监测、原聊天接续与任务管理", "extensions": { "com.openai": { diff --git a/plugin/lifecycle.js b/plugin/lifecycle.js index b24da6e..d30bdc8 100644 --- a/plugin/lifecycle.js +++ b/plugin/lifecycle.js @@ -1,6 +1,6 @@ import { join } from 'node:path'; import { setTimeout as delay } from 'node:timers/promises'; -import { assertServiceIdentity, runtimeError, samePath, serviceUnavailable } from './local-client.js'; +import { assertServiceIdentity, runtimeError, serviceUnavailable } from './local-client.js'; import { message, messageFields } from '../public/message.js'; import widgetStateModule from '../server/widget-state.cjs'; const { widgetState, matchesWidgetIdentity } = widgetStateModule; @@ -71,17 +71,20 @@ export function createLifecycle({ root, dataDir, port, demo = false, platform = function ensureWatcher() { if (demo || !diagnostic(join(dataDir, 'autostart-preferences.json'))?.enabled) return; - const watcher = diagnostic(join(dataDir, 'autostart-status.json')); - if (samePath(watcher?.pluginRoot, root, platform) && alive(watcher?.pid)) return; + // Saved PIDs can be recycled. Let the watcher's OS mutex arbitrate an + // explicit reopen instead of trusting a previous process's diagnostic file. const native = join(root, 'desktop/continuer-monitor.exe'); if (exists(native)) launch(native, ['--watch', widgetNode, root, dataDir], 'watcher'); else launch('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', join(root, 'desktop/watch-codex.ps1'), '-NodePath', widgetNode, '-PluginRoot', root, '-DataDir', dataDir], 'watcher'); } - async function open(automatic, expected) { + async function open(job) { + const expected = job.generation; assertOpen(expected); await ensureService(); assertOpen(expected); const executable = join(root, 'node_modules/electron/dist', platform === 'win32' ? 'electron.exe' : 'electron'); if (!exists(executable)) throw runtimeError('DESKTOP_MISSING', 'runtime.desktop_missing'); + const automatic = !job.manual; + job.launchedAutomatic = automatic; const child = launch(executable, [join(root, 'desktop/main.cjs'), ...(automatic ? ['--auto'] : [])], 'widget', { ELECTRON_RUN_AS_NODE: undefined, CONTINUER_NODE: widgetNode, CONTINUER_PORT: String(port) }); let spawnError; const failed = error => { spawnError = error; }; @@ -110,7 +113,12 @@ export function createLifecycle({ root, dataDir, port, demo = false, platform = const job = opening || { manual: !automatic, generation }; if (!opening) { opening = job; - job.promise = open(automatic, job.generation).then(result => { + job.promise = open(job).then(async result => { + assertOpen(job.generation); + // A manual request can arrive after the automatic process was spawned. + // Forward it through Electron's single-instance lock so the owner is + // revealed, without opening a second window or starting another service. + if (job.manual && job.launchedAutomatic) result = await open({ manual: true, generation: job.generation }); assertOpen(job.generation); // Manual callers joining automatic startup restore one watcher. if (job.manual) ensureWatcher(); diff --git a/plugin/stop-owned.ps1 b/plugin/stop-owned.ps1 index 31c386c..fc4c285 100644 --- a/plugin/stop-owned.ps1 +++ b/plugin/stop-owned.ps1 @@ -9,10 +9,12 @@ function Test-ContinuerCommand($process, [string]$file) { if ($Phase -eq 'watcher') { $continuerStatusFile = Join-Path $DataDir 'autostart-status.json' if (-not (Test-Path -LiteralPath $continuerStatusFile)) { exit 0 } - $continuerSaved = Get-Content -LiteralPath $continuerStatusFile -Raw | ConvertFrom-Json + $continuerSaved = Get-Content -LiteralPath $continuerStatusFile -Raw -Encoding UTF8 | ConvertFrom-Json if (-not $continuerSaved.pid -or -not $continuerSaved.pluginRoot -or [IO.Path]::GetFullPath($continuerSaved.pluginRoot).TrimEnd('\') -ne $continuerRoot) { exit 0 } $continuerProcess = Get-CimInstance Win32_Process -Filter "ProcessId=$([int]$continuerSaved.pid)" - $continuerNative = $continuerProcess -and $continuerProcess.ExecutablePath -eq (Join-Path $continuerRoot 'desktop/continuer-monitor.exe') -and $continuerProcess.CommandLine -match '(?:^|\s)"?--watch"?(?:\s|$)' + # CIM may report an 8.3 alias for the same executable. Normalize both paths + # before checking ownership, just as the saved plugin root is normalized. + $continuerNative = $continuerProcess -and $continuerProcess.ExecutablePath -and [IO.Path]::GetFullPath($continuerProcess.ExecutablePath) -eq (Join-Path $continuerRoot 'desktop/continuer-monitor.exe') -and $continuerProcess.CommandLine -match '(?:^|\s)"?--watch"?(?:\s|$)' $continuerLegacy = $continuerProcess -and $continuerProcess.Name -eq 'powershell.exe' -and (Test-ContinuerCommand $continuerProcess (Join-Path $continuerRoot 'desktop/watch-codex.ps1')) if ($continuerNative -or $continuerLegacy) { $continuerLaunchers = @(Get-CimInstance Win32_Process -Filter "ParentProcessId=$($continuerProcess.ProcessId)" | Where-Object { $_.Name -eq 'node.exe' -and (Test-ContinuerCommand $_ (Join-Path $continuerRoot 'plugin/open.js')) }) diff --git a/plugin/tools.js b/plugin/tools.js index cd4bcb0..356d59d 100644 --- a/plugin/tools.js +++ b/plugin/tools.js @@ -30,7 +30,7 @@ export async function dispatch(name, args, runtime) { const current = await runtime.ensureService(); if (name === 'continuer_status') { const state = current?.tasks ? current : await runtime.request('/api/state'); - return { app: state.app, version: state.version, buildId: state.buildId, protocolVersion: state.protocolVersion, observationOnly: state.observationOnly, persistence: state.persistence, diagnostics: state.diagnostics, connection: state.connection, quota: state.quota, sampledAt: state.sampledAt, settings: state.settings, tasks: state.tasks.map(({ id, mode, name, cwd, threadId, status, progress, activity, continuous, rounds, sentCount, wake }) => ({ id, mode, name, cwd, threadId, status, progress, activity, continuous, rounds, sentCount, wake })), pendingApprovals: state.approvals.length }; + return { app: state.app, version: state.version, buildId: state.buildId, protocolVersion: state.protocolVersion, observationOnly: state.observationOnly, persistence: state.persistence, diagnostics: state.diagnostics, connection: state.connection, quota: state.quota, sampledAt: state.sampledAt, settings: state.settings, tasks: state.tasks.map(({ id, mode, name, cwd, threadId, status, progress, activity, continuous, rounds, sentCount, wake, quotaMonitoring, completionMonitoring, completionRepeat, completionMaxSends, completionSends }) => ({ id, mode, name, cwd, threadId, status, progress, activity, continuous, rounds, sentCount, wake, quotaMonitoring, completionMonitoring, completionRepeat, completionMaxSends, completionSends })), pendingApprovals: state.approvals.length }; } if (name === 'continuer_list_sessions') return runtime.request('/api/threads' + (args.cursor ? '?cursor=' + encodeURIComponent(args.cursor) : '')); const routes = { continuer_import_session: '/api/import', continuer_update_settings: '/api/settings' }; diff --git a/public/api-client.js b/public/api-client.js index 1d213d5..a09832b 100644 --- a/public/api-client.js +++ b/public/api-client.js @@ -3,7 +3,7 @@ import { t as tr } from './i18n.js'; import { isMessage, message, MessageError } from './message.js'; // Both interfaces use the same transport policy and bounded request lifetime. -export function createApiClient({ request = (...args) => fetch(...args), timeoutMs = 35000 } = {}) { +export function createApiClient({ request = (...args) => fetch(...args), timeoutMs = 35000, acceptSnapshot = data => data } = {}) { return async function api(path, body) { const write = body !== undefined; const response = await request(path, { @@ -18,6 +18,6 @@ export function createApiClient({ request = (...args) => fetch(...args), timeout }); const data = await response.json(); if (!response.ok) throw new MessageError(isMessage(data.errorInfo) ? data.errorInfo : data.error ? null : message('ui.request_failed'), data.error || tr("ui.request_failed")); - return data; + return Array.isArray(data.tasks) && data.settings ? acceptSnapshot(data) : data; }; } diff --git a/public/app.js b/public/app.js index 2900e40..933348d 100644 --- a/public/app.js +++ b/public/app.js @@ -5,15 +5,17 @@ import { createApiClient } from './api-client.js'; import { escapeHtml as esc } from './html.js'; import { icon } from './icons.js'; import { taskCardHtml, taskDetailHtml, isTaskActive, toggle } from './task-view.js'; -import { VisibleFeed, setHtml } from './view-lifecycle.js'; +import { VisibleFeed, setHtml, setDetailHtml } from './view-lifecycle.js'; +import { StateSnapshots, FormSessions, chatPage } from './interaction-state.js'; import { ApprovalDetails } from './approval-details.js'; import { storageNotice } from './storage-status.js'; -import { wakeExplanation, continuationEditor } from './task-mode.js'; +import { wakeExplanation, continuationEditor, completionEditor, completionFormSettings, monitorImportSettings } from './task-mode.js'; import { SettingsForm } from './settings-form.js'; export function mountPage(environment = globalThis) { const { document, window, localStorage, Date, FormData, AbortSignal, DOMParser, getComputedStyle, setTimeout, clearTimeout, setInterval, clearInterval, fetch, Blob, URL } = environment; - const api = createApiClient({ request: (...args) => fetch(...args) }); + const snapshots = new StateSnapshots(), forms = new FormSessions(); + const api = createApiClient({ request: (...args) => fetch(...args), acceptSnapshot: data => snapshots.accept(data) }); const applyStaticLanguage = staticInterface(document); const $ = selector => document.querySelector(selector); const settingsForm = new SettingsForm(() => $('#settings-form')); @@ -75,7 +77,7 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ const s = state.settings; const intervals = [...new Set([10, 15, 30, 60, 90, s.pollSeconds])].sort((a, b) => a - b); const intervalOptions = intervals.map(n => ``).join(''); - const connected = state.connection.status === 'connected'; + const connected = streamAlive && state.connection.status === 'connected'; const autostart = state.diagnostics?.autostart; const watcher = autostart?.watcherRunning ? tr("ui.watcher_running") : autostart?.enabled === false ? tr("ui.off") : tr("ui.watcher_stopped_or_status_unknown"); return `${heading(tr("ui.settings"), tr("ui.set_when_and_how_your_work_resumes"))} @@ -103,17 +105,18 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_

${tr("ui.local_connection")}

${tr("ui.uses_local_codex_sign_in_and_the")}
${tr("ui.work_runs_in_the_project_directory_sandbox")}

- ${connected ? tr("ui.connected") : tr("ui.disconnected")} + ${connected ? tr("ui.connected") : tr("ui.disconnected")}
-

${tr("ui.the_local_service_must_stay_running_work")}${watcher}。
${tr("ui.build")}${esc(state.buildId || '')}${tr("ui.protocol")}${state.protocolVersion} ·

`; +

${tr("ui.the_local_service_must_stay_running_work")}${watcher}。
${tr("ui.build")}${esc(state.buildId || '')}${tr("ui.protocol")}${state.protocolVersion} ·

`; } function render() { if (!state || document.hidden) return; const languageChanged = setLanguage(state.settings.language || 'zh'); applyStaticLanguage(); if (languageChanged && modalRenderer && modal.open) refreshLocalizedContent($('#modal-body'), modalRenderer, true); + forms.sync(modal, $('#settings-form')); const draft = languageChanged && page === 'settings' && $('#settings-form') ? new FormData($('#settings-form')) : null; $('#app-version').textContent = `v${state.version} · ${state.buildId.slice(0, 8)}`; $('#nav-count').textContent = state.tasks.filter(t => t.status !== 'completed').length; @@ -130,6 +133,12 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ const control = $('#settings-form .switch'); control.classList.toggle('on', state.settings.enabled); control.setAttribute('aria-checked', String(state.settings.enabled)); + const badge = $('#settings-connection'); + badge.textContent = tr(connected ? 'ui.connected' : 'ui.disconnected'); + badge.classList.toggle('completed', connected); badge.classList.toggle('waiting', !connected); + const autostart = state.diagnostics?.autostart; + $('#settings-watcher').textContent = tr(autostart?.watcherRunning ? 'ui.watcher_running' : autostart?.enabled === false ? 'ui.off' : 'ui.watcher_stopped_or_status_unknown'); + if (modal.open && selectedTask) renderDetail(selectedTask); return; } let html; @@ -141,9 +150,10 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ setHtml(main, html); if (draft) settingsForm.restore(draft); if (page === 'settings') settingsForm.sync(state.settings); + forms.sync(modal, $('#settings-form')); if (modal.open && selectedTask) renderDetail(selectedTask); } - function openModal(html) { modalRenderer = null; importList = null; selectedTask = null; $('#modal-body').innerHTML = html; if (!modal.open) modal.showModal(); } + function openModal(html) { forms.open(); modalRenderer = null; importList = null; selectedTask = null; $('#modal-body').innerHTML = html; if (!modal.open) modal.showModal(); } function openLocalized(render) { openModal(''); modalRenderer = render; refreshLocalizedContent($('#modal-body'), render); } function modalHead(title) { return `

`; } function newTask() { @@ -153,14 +163,14 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ const summary = state.tasks.find(task => task.id === id); if (!summary) { modal.close(); selectedTask = null; return; } const task = taskDetails.read(summary); - $('#modal-body').innerHTML = modalHead(esc(task.name)) + taskDetailHtml(task, state.settings, { + setDetailHtml($('#modal-body'), modalHead(esc(task.name)) + taskDetailHtml(task, state.settings, { canEdit: taskDetails.ready(summary), - }); + })); } async function importModal(cursor = null, append = false) { if (!append) { const list = { data: [], nextCursor: null, loading: true, error: null }; - const render = () => `${modalHead(tr("ui.import_codex_chat"))}

${tr("ui.choose_a_local_chat_to_manage_monitoring")}

${list.loading && !list.data.length ? `
${tr("ui.loading_chats")}
` : list.data.map(t => `
${esc(t.name || t.preview || tr("ui.untitled_chat"))}${esc(t.cwd || t.id)}
`).join('') || `

${tr("ui.no_chats_available_to_import")}

`}
${list.nextCursor ? `` : ''}
`; + const render = () => `${modalHead(tr("ui.import_codex_chat"))}

${tr("ui.choose_a_local_chat_to_manage_monitoring")} ${tr("ui.chat_page_hint")}

${list.loading && !list.data.length ? `
${tr("ui.loading_chats")}
` : list.data.map(t => `
${esc(t.name || t.preview || tr("ui.untitled_chat"))}${esc(t.cwd || t.id)}
`).join('') || `

${tr("ui.no_chats_available_to_import")}

`}
${list.nextCursor ? `` : ''}
`; openLocalized(render); importList = { list, render }; } const current = importList; @@ -170,9 +180,7 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ try { const result = await api(`/api/threads${cursor ? `?cursor=${encodeURIComponent(cursor)}` : ''}`); if (modalRenderer !== current.render || !modal.open) return; - const remaining = 300 - (append ? current.list.data.length : 0); - current.list.data = [...(append ? current.list.data : []), ...result.data.slice(0, remaining)]; - current.list.nextCursor = result.nextCursor && remaining > result.data.length ? result.nextCursor : null; + Object.assign(current.list, chatPage(current.list.data, result, append)); } catch (error) { current.list.error = error; } finally { current.list.loading = false; @@ -189,11 +197,11 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ if (action === 'new') { newTask(); return; } if (action === 'health') { const health = await api('/api/health'); openLocalized(() => `${modalHead(tr("ui.diagnostics"))}

${esc(JSON.stringify(health, null, 2))}
`); return; } if (action === 'detail') { openModal(''); selectedTask = id; renderDetail(id); return; } - if (action === 'edit-message') { + if (action === 'edit-message' || action === 'edit-completion') { const summary = state.tasks.find(task => task.id === id), task = summary && taskDetails.read(summary); if (!task || task.mode !== 'quota-wake') throw Error(tr("ui.only_monitored_chats_support_editing_continuation_messages")); if (!taskDetails.ready(summary)) throw Error(tr("ui.wait_for_the_full_work_details_to")); - openLocalized(() => `${modalHead(tr("ui.edit_continuation_message"))}${continuationEditor(task, esc)}`); return; + openLocalized(() => `${modalHead(tr(action === 'edit-completion' ? 'ui.edit_completion' : 'ui.edit_continuation_message'))}${action === 'edit-completion' ? completionEditor(task, esc) : continuationEditor(task, esc)}`); return; } if (action === 'import') { await importModal(); return; } if (action === 'more-threads') { await importModal(button.dataset.cursor, true); return; } @@ -207,6 +215,7 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ else if (action === 'refresh') { state = await api('/api/refresh', {}); toast(state.connection.status === 'connected' ? tr("ui.quota_synced") : tr("ui.connection_failed_check_the_notice")); } else if (action === 'scheduler') { state = await api('/api/settings', { enabled: !state.settings.enabled }); toast(state.settings.enabled ? tr("ui.scheduling_enabled") : tr("ui.scheduling_paused")); } else if (action === 'continuous') { state = await api(`/api/tasks/${id}`, { action, value: !state.tasks.find(t => t.id === id).continuous }); } + else if (action === 'quota-monitoring' || action === 'completion-monitoring') { const task=state.tasks.find(t=>t.id===id); const enabled=action==='quota-monitoring' ? task.quotaMonitoring!==false : !!task.completionMonitoring; state=await api(`/api/tasks/${encodeURIComponent(id)}`,{action,value:!enabled});taskDetails.clear(); } else if (['pause', 'resume', 'complete'].includes(action)) { const wake = state.tasks.find(t => t.id === id)?.mode === 'quota-wake'; state = await api(`/api/tasks/${id}`, { action }); toast(wake ? (action === 'resume' ? tr("ui.monitoring_enabled") : action === 'complete' ? tr("ui.monitoring_ended_and_removed") : tr("ui.monitoring_paused")) : (action === 'resume' ? tr("ui.work_queued") : action === 'complete' ? tr("ui.marked_complete") : tr("ui.pause_requested"))); } else if (action === 'approve' || action === 'decline') { if (action === 'approve' && !approvalDetails.ready(state.approvals.find(item => String(item.id) === id && item.detailToken === token))) throw Error(tr("ui.wait_for_the_full_approval_details_to")); state = await api('/api/approval', { id, token, decision: action === 'approve' ? 'accept' : 'decline' }); } else if (action === 'exhaust' || action === 'recover') { state = await api('/api/demo/quota', { exhausted: action === 'exhaust' }); toast(action === 'exhaust' ? tr("ui.simulated_quota_exhausted") : tr("ui.simulated_quota_recovered")); } @@ -215,22 +224,28 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ }); document.addEventListener('submit', async event => { const form = event.target; event.preventDefault(); + const job = forms.begin(form); if (!job) return; const values = Object.fromEntries(new FormData(form)); const submit = form.querySelector('[type="submit"],button.primary'); submit.disabled = true; + const current = () => forms.current(job) && (!job.modal || modal.open); + const close = () => { if (current()) modal.close(); }; + const errorElement = () => job.modal ? $('#modal-body').querySelector('.form-error') : $('#settings-error'); + if (errorElement()) setFormError(errorElement(), ''); try { - if (form.id === 'task-form') { state = await api('/api/tasks', { ...values, continuous: values.continuous === 'on' }); modal.close(); toast(tr("ui.work_created")); } - else if (form.id === 'import-form') { const startMonitoring = values.startMonitoring === 'on'; state = await api('/api/import', { ...values, startMonitoring, threadId: form.dataset.id }); modal.close(); toast(tr(startMonitoring ? "ui.chat_added_monitoring_enabled" : "ui.chat_imported_monitoring_stays_paused")); } - else if (form.id === 'message-form') { state = await api(`/api/tasks/${encodeURIComponent(form.dataset.id)}`, { action: 'message', value: values.continuationMessage }); taskDetails.clear(); modal.close(); toast(tr("ui.continuation_message_saved")); } + if (form.id === 'task-form') { state = await api('/api/tasks', { ...values, continuous: values.continuous === 'on' }); close(); toast(tr("ui.work_created")); } + else if (form.id === 'import-form') { const startMonitoring = values.startMonitoring === 'on'; state = await api('/api/import', { ...values, ...monitorImportSettings(values), completionMonitoring: values.completionMonitoring === 'on', startMonitoring, threadId: form.dataset.id }); close(); toast(tr(startMonitoring ? "ui.chat_added_monitoring_enabled" : "ui.chat_imported_monitoring_stays_paused")); } + else if (form.id === 'message-form') { state = await api(`/api/tasks/${encodeURIComponent(form.dataset.id)}`, { action: 'message', value: values.continuationMessage }); taskDetails.clear(); close(); toast(tr("ui.continuation_message_saved")); } + else if (form.id === 'completion-form') { state = await api(`/api/tasks/${encodeURIComponent(form.dataset.id)}`, { action: 'completion', value: completionFormSettings(values) }); taskDetails.clear(); close(); toast(tr('ui.continuation_message_saved')); } else if (form.id === 'settings-form') { state = await api('/api/settings', settingsForm.changes(values)); document.activeElement?.blur(); toast(tr("ui.settings_saved")); } render(); - } catch (error) { const errorEl = form.querySelector('.form-error'); if (errorEl) setFormError(errorEl, error); else toast(systemText(error)); } - finally { submit.disabled = false; } + } catch (error) { const errorEl = current() && errorElement(); if (errorEl) setFormError(errorEl, error); else toast(systemText(error)); } + finally { forms.end(job); submit.disabled = false; forms.sync(modal, $('#settings-form')); } }); $('#language').addEventListener('change', async event => { const input = event.target; input.disabled = true; try { state = await api('/api/settings', { language: input.value }); render(); } catch (error) { toast(systemText(error)); applyStaticLanguage(); } finally { input.disabled = false; } }); $('#theme').addEventListener('click', () => { document.body.classList.toggle('dark'); localStorage.setItem('continuer-theme', document.body.classList.contains('dark') ? 'dark' : 'light'); }); if (localStorage.getItem('continuer-theme') === 'dark') document.body.classList.add('dark'); - modal.addEventListener('close', () => { if (modal.open) return; modalRenderer = null; importList = null; selectedTask = null; taskDetails.clear(); }); - const stream = new VisibleFeed({ ...(environment.createSource ? { create: environment.createSource } : {}), visible: () => !document.hidden, receive: data => { streamAlive = true; state = data; render(); }, error: () => { streamAlive = false; if (state) render(); else setHtml(main, `

${tr("ui.could_not_connect_to_the_local_service")}
`); } }); + modal.addEventListener('close', () => { if (modal.open) return; forms.open(); modalRenderer = null; importList = null; selectedTask = null; taskDetails.clear(); }); + const stream = new VisibleFeed({ ...(environment.createSource ? { create: environment.createSource } : {}), visible: () => !document.hidden, receive: data => { streamAlive = true; state = snapshots.accept(data); render(); }, error: () => { streamAlive = false; if (state) render(); else setHtml(main, `
${tr("ui.could_not_connect_to_the_local_service")}
`); } }); document.addEventListener('visibilitychange', () => { stream.sync(); if (!document.hidden) render(); }); window.addEventListener('pagehide', () => stream.close()); window.addEventListener('pageshow', () => stream.sync()); diff --git a/public/interaction-state.js b/public/interaction-state.js new file mode 100644 index 0000000..0fd7aca --- /dev/null +++ b/public/interaction-state.js @@ -0,0 +1,38 @@ +// HTTP responses and the live stream share one order across service restarts. +export class StateSnapshots { + constructor() { this.current = null; this.retired = new Set(); } + accept(next) { + if (!next?.instanceId || !Number.isSafeInteger(next.snapshotRevision)) return next; + const old = this.current; + if (this.retired.has(next.instanceId)) return old; + if (old?.instanceId === next.instanceId && old.snapshotRevision > next.snapshotRevision) return old; + if (old && old.instanceId !== next.instanceId) this.retired.add(old.instanceId); + return this.current = next; + } +} + +// Submission ownership survives DOM replacement during localization. +export class FormSessions { + constructor() { this.modal = {}; this.settings = {}; } + open() { this.modal = {}; } + begin(form) { + const session = form.id === 'settings-form' ? this.settings : this.modal; + if (session.pending) return null; + session.pending = true; + return { session, modal: form.id !== 'settings-form' }; + } + current(job) { return !job.modal || job.session === this.modal; } + end(job) { job.session.pending = false; } + sync(modal, settings) { + for (const [root, session] of [[modal, this.modal], [settings, this.settings]]) { + for (const button of root?.querySelectorAll('[type="submit"]') || []) button.disabled = !!session.pending; + } + } +} + +// Keep pagination bounded without making older chats unreachable. +export function chatPage(previous, result, append) { + const data = result.data || []; + const items = [...new Map([...(append && previous.length + data.length <= 300 ? previous : []), ...data].map(item => [item.id, item])).values()]; + return { data: items, nextCursor: result.nextCursor || null }; +} diff --git a/public/messages.js b/public/messages.js index b245e9a..0fb6d52 100644 --- a/public/messages.js +++ b/public/messages.js @@ -1,5 +1,25 @@ // Stable IDs own both translations; literal source text is never a lookup key. export const messages = Object.freeze({ + "ui.monitor_master": { "zh": "监测总开关", "en": "Master monitor" }, + "ui.reply_monitor": { "zh": "回答监测", "en": "Reply monitor" }, + "ui.completion_repeat": { "zh": "重复续作(每个新的完整回复触发一次)", "en": "Repeat for each new complete reply" }, + "ui.completion_max_sends": { "zh": "本轮最多发送次数(含首次,重复时生效)", "en": "Maximum sends this run (includes first; used when repeating)" }, + "ui.completion_run_count": { "zh": "本轮回答续作:{count}/{limit} 次", "en": "Completion follow-ups this run: {count}/{limit}" }, + "ui.completion_controls_hint": { "zh": "回答监测和额度监测独立选择,监测总开关与后台调度需开启。不重复时只发送一次;重复时每个新完整回复触发一次,达到本轮次数后只关闭回答监测。暂停、重启和编辑不清零;明确重新开启回答监测开始新一轮,但不重发旧回复。所有发送仍受原聊天累计发送总上限约束。", "en": "Choose reply and quota monitoring independently; the master monitor and scheduler must be on. Without repeat, send once. With repeat, each new complete reply triggers once until this run reaches its limit, then only reply monitoring turns off. Pause, restart and edits retain the count. Explicitly re-enabling reply monitoring starts a new run without replaying old replies. All sends still share the chat's cumulative send cap." }, + "ui.details_pending": { "zh": "完整详情尚未加载,请稍后重试。", "en": "Full details are not loaded yet. Please retry shortly." }, + "ui.chat_page_hint": { "zh": "每批最多显示 300 个聊天,继续加载可查看更早的聊天。", "en": "Up to 300 chats are shown per batch. Load more to reach older chats." }, + "ui.quota_period_unknown": { "zh": "当前窗口", "en": "Current window" }, + "ui.period_hours": { "zh": "{p0}小时", "en": "{p0}h" }, + "ui.period_days": { "zh": "{p0}天", "en": "{p0}d" }, + "ui.panel_width": { "zh": "面板宽度", "en": "Panel width" }, + "ui.panel_height": { "zh": "面板高度", "en": "Panel height" }, + "ui.resize_widget": { "zh": "拖动调整大小;方向键微调", "en": "Drag to resize; use arrow keys to adjust" }, + "ui.completion_monitoring": { "zh": "完整回答后继续", "en": "Continue after a complete reply" }, + "ui.reply_and_quota_monitor": { "zh": "回答与额度监测", "en": "Reply and quota monitoring" }, + "ui.completion_message": { "zh": "完整回答后的继续消息(独立保存)", "en": "Follow-up after a complete reply (saved separately)" }, + "ui.edit_completion": { "zh": "监测与续作设置", "en": "Monitoring and follow-up settings" }, + "ui.completion_hint": { "zh": "默认关闭。开启后,在监测运行且额度充足时,将最新轮次的完整最终回答视为本次指令结束,发送此独立消息;留空发送“继续”。同一回答只发送一次,与额度恢复消息共用发送次数上限。此判断不代表项目验收通过。", "en": "Off by default. While monitoring is running and quota is available, a complete final reply ends the latest instruction and triggers this separate message. Blank sends Continue. Each answer triggers once; both message types share the send limit. This does not verify project acceptance." }, + "ui.disabled": { "zh": "已关闭", "en": "Disabled" }, "ui.start_monitoring_after_adding": { "zh": "加入后开始监测", "en": "Start monitoring after adding" diff --git a/public/quota-display.js b/public/quota-display.js index 6431968..b8f34cf 100644 --- a/public/quota-display.js +++ b/public/quota-display.js @@ -22,6 +22,11 @@ export function quotaWindow(state, slot = 'primary', connected = true, now = Dat const all = Object.values(state.quota?.rateLimitsByLimitId || {}).filter(Boolean); const bucket = all.find(b => b.limitId === 'codex') || all[0] || state.quota?.rateLimits; const targetDuration = slot === 'primary' ? 300 : 10080; - const window = [bucket?.primary,bucket?.secondary].find(w => w?.windowDurationMins === targetDuration) || bucket?.[slot]; + const candidates = [bucket?.primary,bucket?.secondary].filter(Boolean); + const matched = candidates.find(w => w.windowDurationMins === targetDuration); + const fallback = bucket?.[slot]; + // A standard window belongs only to its matching slot, even if the server + // returned it under primary (for example an account with just weekly quota). + const window = matched || (fallback && ![300,10080].includes(fallback.windowDurationMins) ? fallback : null); return { remaining: Number.isFinite(window?.usedPercent) ? Math.max(0,Math.min(100,100-window.usedPercent)) : null, resetsAt: Number.isFinite(window?.resetsAt) && window.resetsAt > 0 ? window.resetsAt : null, windowMinutes: window?.windowDurationMins ?? targetDuration }; } diff --git a/public/style.css b/public/style.css index f306c36..ab9bdee 100644 --- a/public/style.css +++ b/public/style.css @@ -22,3 +22,4 @@ nav>button.active,body.dark nav>button.active{background:var(--tint);color:var(- .detail-summary{white-space:pre-wrap} #language{padding:6px 8px;font-size:12px} .setting-row>div:last-child{flex-shrink:0;white-space:nowrap} +.monitor-switches{display:flex;gap:8px;flex-wrap:wrap;font-size:11px;margin:10px 0}.monitor-switches button{padding:5px 8px;font-size:11px} diff --git a/public/system-messages.js b/public/system-messages.js index 3d196c7..c487631 100644 --- a/public/system-messages.js +++ b/public/system-messages.js @@ -1,5 +1,14 @@ // Service-owned messages use stable IDs and explicit parameters. export const systemMessages = Object.freeze({ + "error.completion_send_limit": { "zh": "回答续作发送次数须为 1–100 的整数,计数须为非负整数", "en": "Completion send limit must be an integer from 1 to 100; counts must be nonnegative integers." }, + "error.choose_monitor": { "zh": "请先开启回答监测或额度监测,再开启监测总开关", "en": "Enable reply or quota monitoring before starting the master monitor." }, + "task.completion_limit": { "zh": "本轮回答续作已发送 {count}/{limit} 次,回答监测已关闭;额度监测仍按其独立开关运行", "en": "Completion follow-ups sent: {count}/{limit}. Reply monitoring is off; quota monitoring follows its separate switch." }, + "log.completion_settings_updated": { "zh": "完整回答续作设置已更新", "en": "Completion follow-up settings updated" }, + "task.monitoring_replies_and_quota": { "zh": "正在监测完整回答与额度恢复,满足条件后发送对应的独立续作消息", "en": "Monitoring complete replies and quota recovery. The corresponding follow-up will be sent when its conditions are met." }, + "task.completion_sending": { "zh": "已检测到完整回答,正在发送独立的继续消息", "en": "Complete reply detected. Sending the separate follow-up message." }, + "task.completion_queued": { "zh": "完整回答后的继续消息已入队;继续监测,请在原聊天确认结果", "en": "Completion follow-up queued. Monitoring continues; check results in the original chat." }, + "task.completion_queued_paused": { "zh": "完整回答后的继续消息已入队,监测已暂停;已入队消息无法撤回", "en": "Completion follow-up queued; monitoring is paused. Queued messages cannot be recalled." }, + "task.completion_changed": { "zh": "原聊天最新轮次已改变或尚未形成完整回答,本次未发送继续消息,稍后重试", "en": "The latest turn changed or no longer has a complete reply. Follow-up was not sent; retrying later." }, "runtime.widget_ready": { "zh": "挂件已就绪。可使用 Ctrl+Alt+C 展开。", "en": "The widget is ready. Press Ctrl+Alt+C to expand it." }, "runtime.port_in_use": { "zh": "端口属于其他应用", "en": "Port belongs to another application" }, "runtime.build_mismatch": { "zh": "运行服务与当前插件构建不一致,请先停止并重新启动 Continuer", "en": "The service and plugin builds differ. Stop and restart Continuer." }, diff --git a/public/task-details.js b/public/task-details.js index 1d9b40a..fdba269 100644 --- a/public/task-details.js +++ b/public/task-details.js @@ -1,9 +1,10 @@ // Only one open detail is cached; stale responses cannot replace a newer selection. +const version = summary => JSON.stringify([summary.detailInstanceId ?? null, summary.detailRevision ?? 0]); export class TaskDetails { constructor(request, changed, error = () => {}) { this.request = request; this.changed = changed; this.error = error; this.slot = null; } read(summary) { if (!this.slot || this.slot.id !== summary.id) this.slot = { id: summary.id }; - const slot = this.slot, revision = summary.detailRevision ?? 0; + const slot = this.slot, revision = version(summary); if (!slot.pending && slot.revision !== revision && (!slot.retryAt || Date.now() >= slot.retryAt)) { slot.pending = true; slot.revision = revision; this.request(`/api/tasks/${encodeURIComponent(summary.id)}`).then(result => { @@ -15,6 +16,6 @@ export class TaskDetails { if (slot.task && slot.taskRevision === revision) for (const key of ['cwd', 'activity', 'activityMessage', 'name']) if (key in slot.task) result[key] = slot.task[key]; return result; } - ready(summary) { return !!this.slot?.task && this.slot.id === summary.id && !this.slot.pending && this.slot.taskRevision === (summary.detailRevision ?? 0); } + ready(summary) { return !!this.slot?.task && this.slot.id === summary.id && !this.slot.pending && this.slot.taskRevision === version(summary); } clear() { this.slot = null; } } diff --git a/public/task-forms.js b/public/task-forms.js index 3ee0090..9aa4538 100644 --- a/public/task-forms.js +++ b/public/task-forms.js @@ -1,5 +1,5 @@ import { t as tr } from './i18n.js'; -import { wakeExplanation } from './task-mode.js'; +import { wakeExplanation, completionFields } from './task-mode.js'; import { escapeHtml as esc } from './html.js'; import { icon } from './icons.js'; @@ -47,6 +47,7 @@ export function monitorImportForm(threadId, { layout = 'page', thread = null } = placeholder="${tr("ui.leave_blank_to_send_continue_example_run")}"> ${tr("ui.sent_to_the_original_chat_after_each")} + ${completionFields({}, esc, fieldClass, page ? 'check-label' : 'check')} diff --git a/public/task-mode.js b/public/task-mode.js index 9805b2e..89022a8 100644 --- a/public/task-mode.js +++ b/public/task-mode.js @@ -9,7 +9,7 @@ export function taskMode(task, settings) { description: wake ? tr("ui.monitoring_note_local_only", { p0: task.note || tr("ui.not_provided") }) : task.prompt, counter: wake ? tr("ui.queued_messages", { p0: task.sentCount || 0, p1: settings.maxWakeSends }) : tr("ui.executed_turns", { p0: task.rounds, p1: settings.maxRounds }), progress: wake ? tr("ui.check_progress_in_the_original_chat") : null, - continuous: wake ? tr("ui.quota_monitor") : tr("ui.continuous_work"), + continuous: wake ? tr('ui.monitor_master') : tr("ui.continuous_work"), pause: wake ? tr("ui.pause_monitoring") : tr("ui.pause"), resume: wake ? tr("ui.enable_monitoring") : tr("ui.continue"), complete: wake ? tr("ui.end_monitoring_and_remove") : tr("ui.mark_complete"), @@ -18,3 +18,31 @@ export function taskMode(task, settings) { export function continuationEditor(task, esc) { return `

${tr("ui.leave_blank_to_use_the_default_message")}

${tr("ui.the_saved_message_is_used_for_future")}

`; } + +export function completionFields(task, esc, fieldClass = 'form-field', checkClass = 'check check-label') { + return ` + + + + +

${tr('ui.completion_controls_hint')}

`; +} + +export function completionFormSettings(values) { + return {enabled:values.completionMonitoring==='on',message:values.completionMessage || '',quotaMonitoring:values.quotaMonitoring==='on',repeat:values.completionRepeat==='on',maxSends:Number(values.completionMaxSends || 20)}; +} +export function monitorImportSettings(values) { + const settings=completionFormSettings(values); + return {quotaMonitoring:settings.quotaMonitoring,completionRepeat:settings.repeat,completionMaxSends:settings.maxSends}; +} + +export function monitorSwitches(task, esc, layout='page') { + if (task.mode!=='quota-wake') return ''; + return `
${[['quota-monitoring',task.quotaMonitoring!==false,'ui.quota_monitor'],['completion-monitoring',!!task.completionMonitoring,'ui.reply_monitor']].map(([action,enabled,label])=>layout==='widget' + ? `` + : ``).join('')}
`; +} + +export function completionEditor(task, esc) { + return `
${completionFields(task, esc)}
`; +} diff --git a/public/task-view.js b/public/task-view.js index 80771fd..62828d6 100644 --- a/public/task-view.js +++ b/public/task-view.js @@ -1,5 +1,5 @@ import { t as tr, systemText, defaultContinuation } from './i18n.js'; -import { taskMode, wakeExplanation } from './task-mode.js'; +import { taskMode, wakeExplanation, monitorSwitches } from './task-mode.js'; import { escapeHtml as esc } from './html.js'; import { icon } from './icons.js'; @@ -81,6 +81,7 @@ function pageTaskCard(view) { ${badge(view)} ${monitorNote(view)} + ${monitorSwitches(task,esc,'page')}
${esc(mode.progress || view.progressText)} @@ -106,6 +107,7 @@ function widgetTaskCard(view) {
${esc(task.cwd)}
${monitorNote(view)} + ${monitorSwitches(task,esc,'widget')}
${mode.wake ? tr("ui.view_in_original_chat") : esc(view.progressText)} @@ -129,8 +131,14 @@ export function taskCardHtml(task, settings, layout = 'page') { function monitorDetails(view, settings, canEdit, hint) { const task = view.task; + const completionCap=task.completionRepeat===false?1:(task.completionMaxSends??100); + if (!canEdit) return `

${tr('ui.details_pending')}

`; return `

${tr("ui.continuation_message")}
${esc(task.continuationMessage?.trim() || defaultContinuation(settings.language))}

+

${tr('ui.completion_message')} · ${tr(task.completionMonitoring ? 'ui.enabled' : 'ui.disabled')}
${esc(task.completionMessage?.trim() || defaultContinuation(settings.language))}

+ +

${tr('ui.completion_run_count',{count:task.completionSends||0,limit:completionCap})}

+

${tr('ui.completion_controls_hint')}

${esc(wakeExplanation)}

`; } @@ -170,7 +178,7 @@ export function taskDetailHtml(task, settings, { layout = 'page', canEdit = fals const thread = page && task.threadId ? `

${tr("ui.chat")}${esc(task.threadId)}

` : ''; const actions = page ? `` : complete; - const description = `

${esc(view.mode.description)}

`; + const description = `

${esc(view.mode.wake && !canEdit ? (task.notePreview || tr('ui.details_pending')) : view.mode.description)}

`; const details = view.mode.wake ? monitorDetails(view, settings, canEdit, hint) : planDetails(view, layout); return `${page ? context + description : description + context}${details}${activity}${thread}${outputDetails(view, layout, hint)}${actions}`; } diff --git a/public/view-lifecycle.js b/public/view-lifecycle.js index bda62b1..5266018 100644 --- a/public/view-lifecycle.js +++ b/public/view-lifecycle.js @@ -32,6 +32,40 @@ export class LazyResource { // Preserve focus, selection and DOM nodes if only unrelated state changed. const rendered = new WeakMap(); export function setHtml(element, html) { - if (rendered.get(element) === html) return false; - element.innerHTML = html; rendered.set(element, html); return true; + const previous = rendered.get(element); + if (previous?.html === html && previous.first === element.firstChild) return false; + element.innerHTML = html; rendered.set(element, { html, first: element.firstChild }); return true; +} + +export function setDetailHtml(element, html) { + const container = element.closest?.('dialog') || element; + const scroll = container.scrollTop; + const outputs = [...(element.querySelectorAll('pre') || [])].map(node => ({ top: node.scrollTop, bottom: node.scrollHeight > node.clientHeight && node.scrollHeight - node.clientHeight - node.scrollTop < 2 })); + const document = element.ownerDocument, selection = document?.getSelection?.(); + let selected; + if (selection?.rangeCount && element.contains(selection.anchorNode) && element.contains(selection.focusNode)) { + const range = selection.getRangeAt(0), prefix = range.cloneRange(); + prefix.selectNodeContents(element); prefix.setEnd(range.startContainer, range.startOffset); + selected = { text: range.toString(), offset: prefix.toString().length }; + } + if (!setHtml(element, html)) return; + container.scrollTop = scroll; + [...element.querySelectorAll('pre')].forEach((node, index) => { const old = outputs[index]; if (old) node.scrollTop = old.bottom ? node.scrollHeight : old.top; }); + if (selected?.text) { + const text = element.textContent; + let start = text.indexOf(selected.text); + for (let at = start; at >= 0; at = text.indexOf(selected.text, at + 1)) { + if (Math.abs(at - selected.offset) < Math.abs(start - selected.offset)) start = at; + if (at >= selected.offset) break; + } + if (start < 0) return; + const range = document.createRange(), walker = document.createTreeWalker(element, 4); + let node, offset = 0, began = false; + while ((node = walker.nextNode())) { + const end = offset + node.length; + if (!began && end > start) { range.setStart(node, start - offset); began = true; } + if (began && end >= start + selected.text.length) { range.setEnd(node, start + selected.text.length - offset); selection.removeAllRanges(); selection.addRange(range); break; } + offset = end; + } + } } diff --git a/public/widget-size.js b/public/widget-size.js new file mode 100644 index 0000000..81f0cf9 --- /dev/null +++ b/public/widget-size.js @@ -0,0 +1,124 @@ +const clamp = (value, min, max, fallback) => Number.isFinite(Number(value)) ? Math.max(min,Math.min(max,Math.round(Number(value)))) : fallback; + +// Keep rapid slider/pointer input ordered; older IPC replies cannot replace a +// newer draft. The main process owns native bounds and durable preferences. +export function mountSizeControls({ document, window, localStorage, bridge, onState, onError, isDragging = () => false }) { + const $ = selector => document.querySelector(selector); + let compact = 256, panel = {width:432,height:720}, busy = false, lastState, lastExpanded, drag; + const pending=new Map(); + const handle = $('#resize-widget'); + function render() { + document.documentElement.style.setProperty('--compact-size',`${compact}px`); + $('#compact-size').value=compact; $('#compact-size-value').textContent=`${compact} px`; + for (const [key,value] of Object.entries(panel)) { + $(`#panel-${key}`).value=value; $(`#panel-${key}-value`).textContent=`${value} px`; + if (!bridge) document.documentElement.style.setProperty(`--panel-${key}`,`${value-18}px`); + } + } + function apply(state) { + if (typeof state.expanded==='boolean') { + if (typeof lastExpanded==='boolean' && state.expanded!==lastExpanded) { + end(); + for (const [key,update] of pending) if (update.action==='resize') pending.delete(key); + } + lastExpanded=state.expanded; + } + lastState=state; + if (busy) return; + compact=clamp(state.compactSize,160,420,256); + panel={width:clamp(state.preferredPanelSize?.width,360,960,432),height:clamp(state.preferredPanelSize?.height,400,1200,720)}; + render(); + } + async function send(action,value) { + if (!bridge) { + try { + localStorage.setItem('continuer-compact-size',String(compact)); + localStorage.setItem('continuer-panel-size',JSON.stringify(panel)); + } catch (error) { onError(error); } + return; + } + const key=action==='compact-size' || (action==='resize' && !value.expanded) ? 'compact' : 'panel'; + pending.set(key,{action,value}); + if (busy) return; + busy=true; + let result; + try { + while (pending.size) { + const [key,next]=pending.entries().next().value; pending.delete(key); + const observed=lastState; + try { + const reply=await bridge.control(next.action,next.value); + result=lastState!==observed ? lastState : reply; + } + catch (error) { + if (lastState!==observed) result=lastState; + onError(error); + } + } + } finally { + busy=false; + if (result || lastState) onState(result || lastState); + } + } + function changeCompact(value) { compact=clamp(value,160,420,256); render(); return send('compact-size',compact); } + function changePanel(value) { + panel={width:clamp(value.width,360,960,432),height:clamp(value.height,400,1200,720)}; + render(); return send('panel-size',{...panel}); + } + $('#compact-size').addEventListener('input',event => { void changeCompact(event.target.value); }); + for (const key of ['width','height']) $(`#panel-${key}`).addEventListener('input',event => { void changePanel({...panel,[key]:event.target.value}); }); + $('#mini').addEventListener('wheel',event => { + if (!event.ctrlKey) return; + event.preventDefault(); + if (!isDragging() && !drag) void changeCompact(compact+(event.deltaY<0?16:-16)); + },{passive:false}); + function resize(expanded,width,height) { + if (expanded) panel={width:clamp(width,360,960,432),height:clamp(height,400,1200,720)}; + else compact=clamp(width,160,420,256); + render(); + return send('resize',{expanded,width:expanded?panel.width:compact,height:expanded?panel.height:compact}); + } + handle.addEventListener('pointerdown',event => { + if (event.button!==0 || event.isPrimary===false || drag || isDragging() || document.body.classList.contains('is-switching')) return; + event.preventDefault(); + const expanded=!document.body.classList.contains('collapsed'); + const rect=$('.shell').getBoundingClientRect?.(); + drag={id:event.pointerId,x:event.screenX,y:event.screenY,expanded, + width:bridge ? window.innerWidth || (expanded?panel.width:compact) : rect?.width+16 || (expanded?panel.width:compact), + height:bridge ? window.innerHeight || (expanded?panel.height:compact) : rect?.height+16 || (expanded?panel.height:compact)}; + handle.setPointerCapture(event.pointerId); + }); + function move(event) { + if (!drag || drag.id!==event.pointerId) return; + if (drag.expanded===document.body.classList.contains('collapsed')) { end(); return; } + const dx=event.screenX-drag.x,dy=event.screenY-drag.y; + if ((!dx && !dy && !drag.lastMove) || drag.lastMove===`${dx},${dy}`) return; + drag.lastMove=`${dx},${dy}`; + void resize(drag.expanded,drag.width+(drag.expanded?dx:Math.abs(dx)>=Math.abs(dy)?dx:dy),drag.height+dy); + } + function end() { + if (!drag) return; + const id=drag.id; drag=null; + if (handle.hasPointerCapture(id)) handle.releasePointerCapture(id); + } + handle.addEventListener('pointermove',move); + handle.addEventListener('pointerup',event => { if (drag?.id===event.pointerId) { move(event); end(); } }); + handle.addEventListener('pointercancel',end); handle.addEventListener('lostpointercapture',end); + handle.addEventListener('click',event => event.preventDefault()); + handle.addEventListener('keydown',event => { + if (!['ArrowLeft','ArrowRight','ArrowUp','ArrowDown'].includes(event.key) || document.body.classList.contains('is-switching')) return; + event.preventDefault(); + const expanded=!document.body.classList.contains('collapsed'),dx=event.key==='ArrowLeft'?-8:event.key==='ArrowRight'?8:0,dy=event.key==='ArrowUp'?-8:event.key==='ArrowDown'?8:0; + void resize(expanded,expanded?panel.width+dx:compact+(dx||-dy),panel.height+dy); + }); + window.addEventListener('blur',end); window.addEventListener('pagehide',end); + if (!bridge) { + try { + compact=clamp(Number(localStorage.getItem('continuer-compact-size'))||256,160,420,256); + const saved=JSON.parse(localStorage.getItem('continuer-panel-size')||'null'); + panel={width:clamp(saved?.width,360,960,432),height:clamp(saved?.height,400,1200,720)}; + } catch { /* Invalid browser preferences use defaults. */ } + } + render(); + return {apply}; +} diff --git a/public/widget.css b/public/widget.css index b3f923a..c1f4f44 100644 --- a/public/widget.css +++ b/public/widget.css @@ -50,3 +50,12 @@ body:not(.browser).is-switching header{-webkit-app-region:no-drag} #language{background:var(--card);color:var(--text);border:1px solid var(--line);border-radius:4px;padding:3px 1px;font-size:10px;max-width:69px;-webkit-app-region:no-drag} html[lang=en-US] .brand small{font-size:8px;letter-spacing:0}html[lang=en-US] .brand strong{font-size:12px}html[lang=en-US] .scheduler strong>span{display:none} html[lang=en-US] #mini-window{font-size:7px;letter-spacing:0}html[lang=en-US] .task-bottom{gap:6px;flex-wrap:wrap}html[lang=en-US] .task-bottom>div{margin-left:auto} + +/* Both views resize explicitly while preserving the frameless transparent window. */ +#panel-width,#panel-height{width:130px;padding:0;accent-color:var(--accent);border:0;background:transparent} +#resize-widget{position:absolute;right:0;bottom:0;width:22px;height:22px;padding:0;border:0;background:transparent;color:var(--accent);opacity:.65;cursor:nwse-resize;touch-action:none;user-select:none;-webkit-app-region:no-drag;z-index:5;font-size:16px;line-height:1} +#resize-widget:hover,#resize-widget:focus-visible{opacity:1;background:var(--tint)} +.is-switching #resize-widget{pointer-events:none;visibility:hidden} +.browser:not(.collapsed) .shell{width:min(calc(var(--panel-width,414px) + 2px),100%);height:min(calc(var(--panel-height,702px) + 2px),calc(100dvh - 16px))} +.browser #panel{width:min(var(--panel-width,414px),calc(100vw - 18px));height:min(var(--panel-height,702px),calc(100dvh - 18px))} +.monitor-switches{display:flex;gap:12px;flex-wrap:wrap;font-size:10px;margin:10px 0}.monitor-switches label{display:inline-flex;gap:5px;align-items:center} diff --git a/public/widget.html b/public/widget.html index 3726e57..ff889ea 100644 --- a/public/widget.html +++ b/public/widget.html @@ -35,6 +35,8 @@ + +

同步周期为 10–90 秒。直接执行受轮次上限约束;原聊天按每条监测记录累计发送次数,到限停止。暂停、重新开启不会清零;提高上限后需手动开启。原聊天工作是否完成需自行确认。

@@ -42,6 +44,7 @@
+
diff --git a/public/widget.js b/public/widget.js index 0cc57c5..1d5b5b3 100644 --- a/public/widget.js +++ b/public/widget.js @@ -4,17 +4,20 @@ import { TaskDetails } from './task-details.js'; import { createApiClient } from './api-client.js'; import { escapeHtml as esc } from './html.js'; import { taskCardHtml, taskDetailHtml } from './task-view.js'; -import { VisibleFeed, LazyResource, setHtml } from './view-lifecycle.js'; +import { VisibleFeed, LazyResource, setHtml, setDetailHtml } from './view-lifecycle.js'; +import { StateSnapshots, FormSessions, chatPage } from './interaction-state.js'; import { ApprovalDetails } from './approval-details.js'; import { storageNotice } from './storage-status.js'; -import { wakeExplanation, continuationEditor } from './task-mode.js'; +import { wakeExplanation, continuationEditor, completionEditor, completionFormSettings, monitorImportSettings } from './task-mode.js'; import { quotaWindow, resetCountdown } from './quota-display.js'; import { pixelText } from './rhine-readout.js'; import { SettingsForm } from './settings-form.js'; +import { mountSizeControls } from './widget-size.js'; export function mountWidget(environment = globalThis) { const { document, window, localStorage, Date, FormData, AbortSignal, DOMParser, getComputedStyle, setTimeout, clearTimeout, setInterval, clearInterval, fetch, Blob, URL } = environment; - const api = createApiClient({ request: (...args) => fetch(...args) }); + const snapshots = new StateSnapshots(), forms = new FormSessions(); + const api = createApiClient({ request: (...args) => fetch(...args), acceptSnapshot: data => snapshots.accept(data) }); const applyStaticLanguage = staticInterface(document); const $ = s => document.querySelector(s); const settingsForm = new SettingsForm(() => $('#settings-form')); @@ -26,7 +29,7 @@ export function mountWidget(environment = globalThis) { let modalRenderer = null, sessionModal = null; let state, connected = true, lastPixelCountdown, timer, detailId; let sessionItems = [], sessionCursor = null, sessionLoading = false, sessionError = null, lastSessionRead = 0, lastSessionAttempt = 0; - let windowSlot='primary', carouselTimer, swapTimer, refreshTimer, gaugeTimer, panelTimer, nativeVisible=!bridge, compactPixels=256; + let windowSlot='primary', carouselTimer, swapTimer, refreshTimer, gaugeTimer, panelTimer, nativeVisible=!bridge; const reducedMotion=window.matchMedia('(prefers-reduced-motion: reduce)'); const animation = new LazyResource(loadRhineAnimation); function viewVisible() { return !document.hidden && nativeVisible; } @@ -106,8 +109,10 @@ export function mountWidget(environment = globalThis) { try { const result = await api('/api/threads' + (more && sessionCursor ? `?cursor=${encodeURIComponent(sessionCursor)}` : '')); const retained = sessionItems.find(t => t.id === ($('#session-select').value || chosen)); - sessionItems = [...new Map([...(more ? sessionItems : []), ...(result.data || []), ...(!more && retained && !(result.data || []).some(t => t.id === retained.id) ? [retained] : [])].map(t => [t.id, t])).values()].slice(0, 300); - sessionCursor = sessionItems.length < 300 ? result.nextCursor : null; + const page = chatPage(sessionItems, result, more); + sessionItems = page.data; + if (retained && !sessionItems.some(t => t.id === retained.id)) sessionItems = [...sessionItems.slice(-299), retained]; + sessionCursor = page.nextCursor; lastSessionRead = Date.now(); } catch (error) { sessionError = error; } finally { sessionLoading = false; renderSessionOptions(); } @@ -135,7 +140,8 @@ export function mountWidget(environment = globalThis) { $('#mini-reset-pixels').setAttribute('transform',`translate(${128-pixels.width*scale/2} 176) scale(${scale})`); } else if(!numeric && countdown!==lastPixelCountdown) $('#mini-reset-pixels').setAttribute('d',''); lastPixelCountdown=countdown; - const windowLabel=windowSlot==='primary'?tr("ui.hour"):tr("ui.day"); + const minutes = reading.windowMinutes; + const windowLabel = minutes === 300 ? tr('ui.hour') : minutes === 10080 ? tr('ui.day') : minutes > 0 ? tr(minutes >= 1440 ? 'ui.period_days' : 'ui.period_hours', {p0: minutes >= 1440 ? minutes/1440 : minutes/60}) : tr('ui.quota_period_unknown'); setText('#mini-window',tr("ui.available_quota", { p0: windowLabel })); setText('#mini-reset-label',tr("ui.until_reset_2")); $('#mini').dataset.window=windowSlot; @@ -150,6 +156,7 @@ export function mountWidget(environment = globalThis) { const languageChanged = setLanguage(state.settings.language || 'zh'); applyStaticLanguage(); if ($('#error').dataset.sourceMessage) setFormError($('#error'), $('#error').errorSource || $('#error').dataset.sourceMessage); if (languageChanged && modalRenderer && $('#modal').open) refreshLocalizedContent($('#modal-body'), modalRenderer, true); + forms.sync($('#modal'), $('#settings-form')); if (bridge && !rendererAnnounced) { rendererAnnounced = true; bridge.control('renderer-ready').then(result => { rendererReady = true; applyDesktop(result); stream.sync(); }).catch(error => { rendererAnnounced = false; toast(systemText(error)); }); @@ -185,7 +192,7 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ else { $('#modal').close(); detailId = null; } } } - function open(title, html) { modalRenderer = null; sessionModal = null; detailId = null; $('#modal-title').textContent = title; $('#modal-body').innerHTML = html; setFormError($('#error'), ''); if (!$('#modal').open) $('#modal').showModal(); } + function open(title, html) { forms.open(); modalRenderer = null; sessionModal = null; detailId = null; $('#modal-title').textContent = title; $('#modal-body').innerHTML = html; setFormError($('#error'), ''); if (!$('#modal').open) $('#modal').showModal(); } function openLocalized(render) { open('', ''); modalRenderer = () => { const view = render(); $('#modal-title').textContent = view.title; return view.html; }; @@ -197,9 +204,9 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ if (!summary) return; const task = taskDetails.read(summary); $('#modal-title').textContent = task.name; - $('#modal-body').innerHTML = taskDetailHtml(task, state.settings, { + setDetailHtml($('#modal-body'), taskDetailHtml(task, state.settings, { layout: 'widget', canEdit: taskDetails.ready(summary), - }); + })); } async function sessions(cursor, append = false) { if (!append) { @@ -209,7 +216,7 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ const empty = list.loading ? `

${tr("ui.loading_local_chats")}

` : list.error ? `

${tr("ui.chats_unavailable")}

` : `

${tr("ui.no_chats_available_to_import")}

`; const more = list.nextCursor ? `` : ''; const retry = list.error ? `` : ''; - return { title: tr("ui.import_an_existing_chat"), html: (options || empty) + more + retry }; + return { title: tr("ui.import_an_existing_chat"), html: `

${tr("ui.chat_page_hint")}

` + (options || empty) + more + retry }; }); sessionModal = { list, render: modalRenderer }; } @@ -220,9 +227,7 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ try { const result = await api('/api/threads' + (cursor ? `?cursor=${encodeURIComponent(cursor)}` : '')); if (modalRenderer !== current.render || !$('#modal').open) return; - const remaining = 300 - (append ? current.list.data.length : 0); - current.list.data = [...(append ? current.list.data : []), ...(result.data || []).slice(0, remaining)]; - current.list.nextCursor = remaining > (result.data || []).length ? result.nextCursor : null; + Object.assign(current.list, chatPage(current.list.data, result, append)); } catch (error) { current.list.error = error; if (modalRenderer === current.render && $('#modal').open) setFormError($('#error'), error); @@ -249,11 +254,11 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ return; } if (action === 'detail') { open(tr("ui.work_details"), ''); detailId = id; detail(id); return; } - if (action === 'edit-message') { + if (action === 'edit-message' || action === 'edit-completion') { const summary = state.tasks.find(task => task.id === id), task = summary && taskDetails.read(summary); if (!task || task.mode !== 'quota-wake') throw Error(tr("ui.only_monitored_chats_support_editing_continuation_messages")); if (!taskDetails.ready(summary)) throw Error(tr("ui.wait_for_the_full_work_details_to")); - openLocalized(() => ({ title: tr("ui.edit_continuation_message"), html: continuationEditor(task, esc) })); return; + openLocalized(() => ({ title: tr(action === 'edit-completion' ? 'ui.edit_completion' : 'ui.edit_continuation_message'), html: action === 'edit-completion' ? completionEditor(task, esc) : continuationEditor(task, esc) })); return; } if (action === 'pick') { const path = await bridge.pickDirectory(); if (path) $('#new-form [name=cwd]').value = path; return; } if (action === 'import' || action === 'more') { await sessions(b.dataset.cursor, action === 'more'); return; } @@ -268,13 +273,26 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ else if (action === 'approve' || action === 'decline') { if (action === 'approve' && !approvalDetails.ready(state.approvals.find(item => String(item.id) === id && item.detailToken === token))) throw Error(tr("ui.wait_for_the_full_approval_details_to")); state = await api('/api/approval', { id, token, decision: action === 'approve' ? 'accept' : 'decline' }); } render(); } catch (error) { if ($('#modal').open) setFormError($('#error'), error); else toast(systemText(error)); } finally { b.disabled = false; } }); - document.addEventListener('change', async e => { const input = e.target; try { if (input.id === 'language') { input.disabled = true; try { state = await api('/api/settings', { language: input.value }); } finally { input.disabled = false; } } else if (input.id === 'scheduler') state = await api('/api/settings', { enabled: input.checked }); else if (input.dataset.continuous) state = await api(`/api/tasks/${encodeURIComponent(input.dataset.continuous)}`, { action: 'continuous', value: input.checked }); else if (input.id === 'follow') { applyDesktop(await bridge.control('follow', input.checked)); return; } else return; render(); } catch (error) { toast(systemText(error)); render(); } }); - document.addEventListener('submit', async e => { e.preventDefault(); const form = e.target, values = Object.fromEntries(new FormData(form)), button = form.querySelector('[type=submit]'); button.disabled = true; setFormError($('#error'), ''); try { if (form.id === 'new-form') state = await api('/api/tasks', { ...values, continuous: values.continuous === 'on' }); else if (form.id === 'import-form') state = await api('/api/import', { threadId: form.dataset.id, note: values.note, continuationMessage: values.continuationMessage, startMonitoring: values.startMonitoring === 'on' }); else if (form.id === 'message-form') { state = await api(`/api/tasks/${encodeURIComponent(form.dataset.id)}`, { action: 'message', value: values.continuationMessage }); taskDetails.clear(); } else if (form.id === 'settings-form') state = await api('/api/settings', settingsForm.changes(values)); if (form.id !== 'settings-form') $('#modal').close(); render(); toast(form.id === 'message-form' ? tr("ui.continuation_message_saved") : tr("ui.saved")); } catch (error) { if ($('#modal').open) setFormError($('#error'), error); else toast(systemText(error)); } finally { button.disabled = false; } }); - function setSize(value) { - compactPixels=Math.max(160,Math.min(420,Math.round(Number(value)||256))); - document.documentElement.style.setProperty('--compact-size',`${compactPixels}px`); - $('#compact-size').value=compactPixels; $('#compact-size-value').textContent=`${compactPixels} px`; - } + document.addEventListener('change', async e => { const input = e.target; try { if (input.id === 'language') { input.disabled = true; try { state = await api('/api/settings', { language: input.value }); } finally { input.disabled = false; } } else if (input.id === 'scheduler') state = await api('/api/settings', { enabled: input.checked }); else if (input.dataset.monitor) { state=await api(`/api/tasks/${encodeURIComponent(input.dataset.id)}`,{action:input.dataset.monitor,value:input.checked});taskDetails.clear(); } else if (input.dataset.continuous) state = await api(`/api/tasks/${encodeURIComponent(input.dataset.continuous)}`, { action: 'continuous', value: input.checked }); else if (input.id === 'follow') { applyDesktop(await bridge.control('follow', input.checked)); return; } else return; render(); } catch (error) { toast(systemText(error)); render(); } }); + document.addEventListener('submit', async e => { + e.preventDefault(); + const form = e.target, job = forms.begin(form); if (!job) return; + const values = Object.fromEntries(new FormData(form)), button = form.querySelector('[type=submit]'); + const current = () => forms.current(job) && (!job.modal || $('#modal').open); + button.disabled = true; setFormError($('#error'), ''); + try { + if (form.id === 'new-form') state = await api('/api/tasks', { ...values, continuous: values.continuous === 'on' }); + else if (form.id === 'import-form') state = await api('/api/import', { threadId: form.dataset.id, note: values.note, continuationMessage: values.continuationMessage, startMonitoring: values.startMonitoring === 'on', completionMonitoring: values.completionMonitoring === 'on', completionMessage: values.completionMessage, ...monitorImportSettings(values) }); + else if (form.id === 'message-form' || form.id === 'completion-form') { + const completion = form.id === 'completion-form'; + state = await api(`/api/tasks/${encodeURIComponent(form.dataset.id)}`, { action: completion ? 'completion' : 'message', value: completion ? completionFormSettings(values) : values.continuationMessage }); + taskDetails.clear(); + } else if (form.id === 'settings-form') state = await api('/api/settings', settingsForm.changes(values)); + if (job.modal && current()) $('#modal').close(); + render(); toast(['message-form', 'completion-form'].includes(form.id) ? tr('ui.continuation_message_saved') : tr('ui.saved')); + } catch (error) { if (job.modal && current()) setFormError($('#error'), error); else toast(systemText(error)); } + finally { forms.end(job); button.disabled = false; forms.sync($('#modal'), $('#settings-form')); } + }); let nativeTransition,transitionAcknowledged; function acknowledgeTransition() { if(!bridge || !nativeTransition || transitionAcknowledged===nativeTransition.id) return; @@ -294,7 +312,7 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ document.body.classList.toggle('collapsed',!expanded); $('#mini').setAttribute('aria-expanded',String(expanded)); document.body.classList.toggle('is-switching',!!s.transitioning); - $('#follow').checked=s.follow; nativeVisible=!!s.visible; setSize(s.compactSize); + $('#follow').checked=s.follow; nativeVisible=!!s.visible; sizeControls.apply(s); syncView(); if(nativeTransition && (reducedMotion.matches || Number(getComputedStyle($('.shell')).opacity)<=.001)) acknowledgeTransition(); } @@ -334,25 +352,19 @@ ${esc(a.cwd)}${a.requiresDetails ? `

${tr("ui.full_approval_details_are_ window.addEventListener('blur',() => endPointer(null,true)); $('#mini').onclick=async e => { e.preventDefault(); const result=await pointerResult; pointerResult=Promise.resolve({moved:false}); if(!result.moved) void setExpanded(true); }; $('#mini').addEventListener('keydown',e => { if(e.key==='Enter'||e.key===' ') { e.preventDefault(); void setExpanded(true); } }); - $('#mini').addEventListener('wheel',e => { if(!e.ctrlKey) return; e.preventDefault(); if(!pointerDrag) void changeSize(compactPixels+(e.deltaY<0?16:-16)); },{passive:false}); - async function changeSize(value) { - setSize(value); - if(bridge) { try { applyDesktop(await bridge.control('compact-size',compactPixels)); } catch(error) { toast(systemText(error)); } } - else localStorage.setItem('continuer-compact-size',String(compactPixels)); - } - $('#compact-size').addEventListener('input',e => { void changeSize(e.target.value); }); + const sizeControls=mountSizeControls({document,window,localStorage,bridge,onState:applyDesktop,onError:error=>toast(systemText(error)),isDragging:()=>!!pointerDrag}); $('#collapse').onclick=() => { void setExpanded(false); }; if(bridge) { bridge.onState(applyDesktop); bridge.control('state').then(applyDesktop).catch(e=>toast(e.message)); $('#quit').onclick=()=>bridge.control('quit'); $('#reset-position').onclick=()=>bridge.control('reset-position').then(()=>toast(tr("ui.widget_position_reset"))); - } else { document.body.classList.add('browser'); setSize(Number(localStorage.getItem('continuer-compact-size'))||256); } + } else { document.body.classList.add('browser'); } document.addEventListener('visibilitychange',syncView); $('#session-select').onchange = () => { localStorage.setItem('continuer-selected-session', $('#session-select').value); updateSessionSelection(); }; - $('#close').onclick = () => $('#modal').close(); $('#modal').addEventListener('close', () => { if ($('#modal').open) return; modalRenderer = null; sessionModal = null; detailId = null; taskDetails.clear(); }); + $('#close').onclick = () => $('#modal').close(); $('#modal').addEventListener('close', () => { if ($('#modal').open) return; forms.open(); modalRenderer = null; sessionModal = null; detailId = null; taskDetails.clear(); }); if (localStorage.getItem('continuer-rhine-theme') === 'light') document.body.classList.add('light'); $('#theme').onclick = () => { document.body.classList.toggle('light'); localStorage.setItem('continuer-rhine-theme', document.body.classList.contains('light') ? 'light' : 'dark'); }; - const stream = new VisibleFeed({ ...(environment.createSource ? { create: environment.createSource } : {}), visible: viewVisible, bootstrap: () => !!bridge && !rendererReady, receive: data => { connected = true; state = data; render(); }, error: () => { connected = false; if (state) render(); else $('#health').textContent = tr("ui.could_not_connect_to_the_local_service_2"); } }); + const stream = new VisibleFeed({ ...(environment.createSource ? { create: environment.createSource } : {}), visible: viewVisible, bootstrap: () => !!bridge && !rendererReady, receive: data => { connected = true; state = snapshots.accept(data); render(); }, error: () => { connected = false; if (state) render(); else $('#health').textContent = tr("ui.could_not_connect_to_the_local_service_2"); } }); window.addEventListener('pagehide', () => { stream.close(); nativeVisible = false; syncActivity(); }); window.addEventListener('pageshow', () => { if (!bridge) nativeVisible = true; syncView(); }); stream.sync(); diff --git a/server/completion-wake.js b/server/completion-wake.js new file mode 100644 index 0000000..c4895d4 --- /dev/null +++ b/server/completion-wake.js @@ -0,0 +1,75 @@ +import { MessageError, setActivity, taskActivityMessage, message as textMessage } from '../public/message.js'; +import { quotaAvailable } from './policy.js'; +import { defaultContinuation } from '../public/i18n.js'; +import { readThreadReplySnapshot } from './thread-reply.js'; +import { enforceWakeLimit, enforceCompletionLimit, completionLimit, isEnabledMonitorTask } from './monitor-task.js'; + +// A completed final answer ends an instruction, not necessarily the project. +// Each final turn can queue one independently configured follow-up message. +export async function tickCompletionWake(manager, epoch = manager.scheduleEpoch) { + for (const task of manager.state.tasks) { + if (!manager.canSchedule(epoch)) break; + if (!isEnabledMonitorTask(task) || task.completionMonitoring !== true) continue; + if (enforceCompletionLimit(task)) { manager.changed(); continue; } + if (enforceWakeLimit(task, manager.state.settings.maxWakeSends)) { manager.changed(); continue; } + if ((manager.completionChecks.get(task.id) || 0) > Date.now() + || !quotaAvailable(manager.wakeQuota, manager.wakeSampledAt, manager.state.settings.minimumRemaining)) continue; + manager.completionChecks.set(task.id, Date.now() + manager.state.settings.pollSeconds * 1000); + const completion = task.completion ||= { delivery: 'idle' }; + if (['sending', 'uncertain'].includes(completion.delivery)) continue; + const permitted = () => manager.canSchedule(epoch) && isEnabledMonitorTask(task) && task.completionMonitoring === true + && task.completion === completion && manager.state.tasks.includes(task) + && (task.sentCount || 0) < manager.state.settings.maxWakeSends + && (task.completionSends || 0) < completionLimit(task) + && quotaAvailable(manager.wakeQuota, manager.wakeSampledAt, manager.state.settings.minimumRemaining); + manager.wakeExecutions.set(task.id, completion); + try { + let reply; + try { reply = await readThreadReplySnapshot(manager.rpc, task.threadId); } + catch { reply = { state: 'unknown' }; } + if (!permitted() || reply.state !== 'complete' || !reply.turnId || reply.turnId === completion.lastTurnId) continue; + if (!manager.wakeSender) continue; + const turnId = reply.turnId; + const inspectReply = async () => { + if (!permitted()) throw Object.assign(new MessageError(textMessage('error.paused_no_continuation_message_sent')), { cancelled: true }); + let current; + try { current = await readThreadReplySnapshot(manager.rpc, task.threadId); } + catch { current = { state: 'unknown' }; } + if (!permitted()) throw Object.assign(new MessageError(textMessage('error.paused_no_continuation_message_sent')), { cancelled: true }); + if (current.state !== 'complete' || current.turnId !== turnId) { + throw Object.assign(new MessageError(textMessage('task.completion_changed')), { waitForReply: true }); + } + }; + try { + // Persist the claim before the queue side effect. A crash cannot replay it. + Object.assign(completion, { delivery: 'sending', turnId }); + setActivity(task, textMessage('task.completion_sending')); manager.changed(); + const result = await manager.wakeSender.send(task.threadId, { + message: task.completionMessage?.trim() || defaultContinuation(manager.state.settings.language), + shouldSend: permitted, beforeSend: inspectReply, + }); + Object.assign(completion, { delivery: 'sent', lastTurnId: turnId, sentAt: Date.now(), queueId: result?.queueId || null }); + task.sentCount = (task.sentCount || 0) + 1; + task.completionSends = (task.completionSends || 0) + 1; + // Consume any quota recovery for the answered instruction as well. + task.wake = { armed: false, delivery: 'idle' }; task.retryAt = 0; task.waitReason = null; + if (task.continuous && task.status !== 'paused') task.status = 'monitoring'; + setActivity(task, textMessage(task.continuous ? 'task.completion_queued' : 'task.completion_queued_paused')); + enforceCompletionLimit(task); + enforceWakeLimit(task, manager.state.settings.maxWakeSends); + manager.log(taskActivityMessage(task), 'success', task.id); + } catch (error) { + if (manager.persistence.status !== 'ok') throw error; + if (error.cancelled || error.waitForReply || error.safeToRetry) { + completion.delivery = 'idle'; + } else { + completion.delivery = 'uncertain'; + task.waitReason = null; task.retryAt = 0; + if (task.status !== 'paused') task.status = 'blocked'; + } + setActivity(task, error); manager.log(taskActivityMessage(task), 'warning', task.id); + } + manager.changed(); + } finally { manager.wakeExecutions.delete(task.id); } + } +} diff --git a/server/direct-task.js b/server/direct-task.js index 74734f0..68ac380 100644 --- a/server/direct-task.js +++ b/server/direct-task.js @@ -19,7 +19,7 @@ const inFlight = ['starting', ...ACTIVE_TURN_STATUSES]; export const isDirectTask = task => task?.mode === 'direct' || (task != null && task.mode === undefined); export const isActiveDirectTask = task => isDirectTask(task) && inFlight.includes(task.status); export const isRunnableDirectTask = (task, now = Date.now()) => isDirectTask(task) - && (task.status === 'queued' || (task.status === 'waiting' && task.continuous)) && (!task.retryAt || now >= task.retryAt); + && (task.status === 'queued' || (task.status === 'waiting' && (task.continuous || task.waitReason === 'quota' && task.rounds === 0))) && (!task.retryAt || now >= task.retryAt); export function createDirectTask(input, { demo = false } = {}) { for (const key of ['name', 'cwd', 'prompt']) if (typeof input[key] !== 'string' || !input[key].trim()) throw new ClientError(textMessage("error.enter_a_name_project_directory_and_work_goal")); @@ -58,7 +58,7 @@ function prepare(task) { function validate(task) { if (!DIRECT_TASK_STATUSES.includes(task.status)) throw new MessageError(textMessage("error.direct_state")); if (task.rounds !== undefined && (!Number.isSafeInteger(task.rounds) || task.rounds < 0)) throw new MessageError(textMessage("error.direct_rounds")); - if (task.wake !== undefined || task.sentCount !== undefined || task.continuationMessage !== undefined) throw new MessageError(textMessage("error.direct_monitor_fields")); + if (task.wake !== undefined || task.sentCount !== undefined || task.continuationMessage !== undefined || task.completionMonitoring !== undefined || task.completionMessage !== undefined || task.completion !== undefined || task.quotaMonitoring !== undefined || task.completionRepeat !== undefined || task.completionMaxSends !== undefined || task.completionSends !== undefined) throw new MessageError(textMessage("error.direct_monitor_fields")); } function action(task, action, value) { diff --git a/server/health.js b/server/health.js index 0ff9230..91b3b85 100644 --- a/server/health.js +++ b/server/health.js @@ -28,7 +28,7 @@ export class Health { previousExit: this.previous ? { status: this.previous.status, reason: this.previous.reason, unexpected: this.previous.status === 'running' || this.previous.status === 'crashed' } : null, resources: { sseClients: this.stream.clients.size, sseLimit: this.stream.limit, slowClientsDropped: this.stream.dropped, taskLimit: 100 }, widget: { running: alive(widget?.pid), ready: !!widget?.ready && alive(widget?.pid), exitReason: widget?.exitReason || null, buildId: widget?.buildId || null }, - autostart: { enabled: preferences?.enabled ?? null, watcherRunning: alive(watcher?.pid), status: watcher?.state || watcher?.status || null }, + autostart: { enabled: preferences?.enabled ?? null, watcherRunning: ['watching', 'launched', 'retrying'].includes(watcher?.state || watcher?.status) && alive(watcher?.pid), status: watcher?.state || watcher?.status || null }, projectRoot: config.root, dataDir: this.dataDir }; } } diff --git a/server/http-routes.js b/server/http-routes.js index e0bae73..8b17e1a 100644 --- a/server/http-routes.js +++ b/server/http-routes.js @@ -16,7 +16,7 @@ export function createApiRouter({ manager, health, stream, rpc, demo, summary, s ['/api/tasks', input => manager.create(input)], ['/api/import', input => { if (input.note !== undefined && input.prompt !== undefined) throw new ClientError(textMessage("error.note_alias_conflict")); - return manager.importThread(input.threadId, input.note ?? input.prompt, input.continuationMessage, { startMonitoring: input.startMonitoring }); + return manager.importThread(input.threadId, input.note ?? input.prompt, input.continuationMessage, { startMonitoring: input.startMonitoring, completionMonitoring: input.completionMonitoring, completionMessage: input.completionMessage, quotaMonitoring: input.quotaMonitoring, completionRepeat: input.completionRepeat, completionMaxSends: input.completionMaxSends }); }], ['/api/approval', input => manager.approve(input.id, input.decision, input.token)], ]); diff --git a/server/manager.js b/server/manager.js index aade90a..b7bb2c5 100644 --- a/server/manager.js +++ b/server/manager.js @@ -4,9 +4,10 @@ import { randomUUID } from 'node:crypto'; import { ClientError } from './http-policy.js'; import { quotaAvailable, progress, buckets, MAX_POLL_SECONDS } from './policy.js'; import { tickQuotaWake } from './quota-wake.js'; +import { tickCompletionWake } from './completion-wake.js'; import { removeCompletedTasks } from './state-lifecycle.js'; import { createDirectTask, isActiveDirectTask, isRunnableDirectTask } from './direct-task.js'; -import { createMonitorTask, validateMonitorInput, isMonitorTask, enforceWakeLimit } from './monitor-task.js'; +import { createMonitorTask, validateMonitorInput, validateCompletionInput, isMonitorTask, enforceWakeLimit } from './monitor-task.js'; import { taskModel } from './task-model.js'; import { StatePersistence } from './state-persistence.js'; import { TurnController } from './turn-controller.js'; @@ -23,7 +24,9 @@ export class Manager extends EventEmitter { this.wakeQuota = null; this.wakeSampledAt = null; this.observationOnly = observeOnly; this.scheduleEpoch = 0; this.stopped = false; - this.wakeExecutions = new Map(); this.detailVersions = new WeakMap(); + this.instanceId = randomUUID(); this.snapshotRevision = 0; + this.on('change', () => { this.snapshotRevision++; }); + this.wakeExecutions = new Map(); this.completionChecks = new Map(); this.detailVersions = new WeakMap(); this.connection = { status: 'disconnected', ...messageFields(textMessage("connection.connecting_to_local_codex")) }; this.quota = null; this.sampledAt = null; @@ -64,7 +67,7 @@ export class Manager extends EventEmitter { get approvals() { return this.turns.approvals; } get executions() { return this.turns.executions; } snapshot({ details = true } = {}) { - const snapshot = { ...this.state, ...config.appInfo(), settings: { ...this.state.settings, enabled: this.state.settings.enabled && !this.observationOnly }, observationOnly: this.observationOnly, + const snapshot = { ...this.state, ...config.appInfo(), instanceId: this.instanceId, snapshotRevision: this.snapshotRevision, settings: { ...this.state.settings, enabled: this.state.settings.enabled && !this.observationOnly }, observationOnly: this.observationOnly, persistence: { ...this.persistence, ...this.store.status?.(), pending: this.pendingSave }, tasks: this.state.tasks.map(task => this.taskSnapshot(task)), connection: this.connection, quota: this.quota, sampledAt: this.sampledAt, demo: this.demo, approvals: [...this.approvals.values()] }; return details ? snapshot : compactSummary(snapshot); @@ -72,11 +75,11 @@ export class Manager extends EventEmitter { taskSnapshot(id) { const task = typeof id === 'object' ? id : this.state.tasks.find(t => t.id === id); if (!task) return null; - const fields = ['name', 'prompt', 'note', 'continuationMessage', 'output', 'outputTruncated', 'plan', 'outcome', 'cwd', 'activity', 'activityMessage', 'toolCount', 'lastError', 'turnId']; + const fields = ['name', 'prompt', 'note', 'continuationMessage', 'quotaMonitoring', 'completionMonitoring', 'completionRepeat', 'completionMaxSends', 'completionSends', 'completionMessage', 'output', 'outputTruncated', 'plan', 'outcome', 'cwd', 'activity', 'activityMessage', 'toolCount', 'lastError', 'turnId']; const values = fields.map(key => task[key]); const previous = this.detailVersions.get(task); if (!previous || values.some((value, index) => value !== previous.values[index])) this.detailVersions.set(task, { values, revision: (previous?.revision || 0) + 1 }); - return { ...task, progress: isMonitorTask(task) ? null : progress(task.plan), detailRevision: this.detailVersions.get(task).revision }; + return { ...task, progress: isMonitorTask(task) ? null : progress(task.plan), detailInstanceId: this.instanceId, detailRevision: this.detailVersions.get(task).revision }; } canSchedule(epoch = this.scheduleEpoch) { return epoch === this.scheduleEpoch && !this.stopped && !this.observationOnly && this.persistence.status === 'ok' && this.state.settings.enabled && this.rpc.ready && this.connection.status === 'connected'; @@ -112,6 +115,7 @@ export class Manager extends EventEmitter { } clearCompletedTasks() { const completedIds = removeCompletedTasks(this.state); + for (const id of completedIds) this.completionChecks.delete(id); for (const [id, request] of this.approvals) if (completedIds.has(request.taskId)) this.approvals.delete(id); return completedIds.size > 0; } @@ -179,6 +183,7 @@ export class Manager extends EventEmitter { const epoch = this.scheduleEpoch; this.scheduling = true; try { + await tickCompletionWake(this, epoch); await tickQuotaWake(this, epoch); if (!this.canSchedule(epoch)) return; if (this.state.tasks.some(isActiveDirectTask)) return; @@ -210,7 +215,18 @@ export class Manager extends EventEmitter { create(input) { if (this.state.tasks.length >= 100) throw new ClientError(textMessage("error.up_to_records_are_supported_end_unused_work")); const task = createDirectTask(input, { demo: this.demo }); - this.state.tasks.unshift(task); this.log(textMessage("log.work_added", { name: task.name })); this.changed(); this.activate(); return task; + this.addTask(task, textMessage("log.work_added", { name: task.name })); this.activate(); return task; + } + addTask(task, logMessage) { + const tasks = this.state.tasks, logs = this.state.logs.slice(); + this.state.tasks = [task, ...tasks]; this.log(logMessage); + try { this.changed(); } + catch (error) { + // Failed additions must be safe to retry; retain the storage error and + // paused scheduling without retaining an unacknowledged new record. + this.state.tasks = tasks; this.state.logs = logs; this.emit('change'); + throw error; + } } async action(id, action, value) { const task = this.state.tasks.find(t => t.id === id); @@ -218,6 +234,7 @@ export class Manager extends EventEmitter { const transition = taskModel(task).action(task, action, value, { sending: this.wakeExecutions.has(task.id), maxWakeSends: this.state.settings.maxWakeSends, }); + if (['completion','completion-monitoring','resume'].includes(action) || (action === 'continuous' && value === true)) this.completionChecks.delete(task.id); if (transition.logMessage) this.log(transition.logMessage, 'info', task.id); if (transition.kind === 'pause-turn') { this.turns.cancelApprovals(task); @@ -244,12 +261,13 @@ export class Manager extends EventEmitter { if (input.enabled === true) this.activate(); } async listThreads(cursor = null) { await this.rpc.connect?.(); return this.rpc.call('thread/list', { limit: 30, sortKey: 'updated_at', cursor }); } - async importThread(id, note = '', continuationMessage = '', { startMonitoring = false } = {}) { + async importThread(id, note = '', continuationMessage = '', { startMonitoring = false, completionMonitoring = false, completionMessage = '', quotaMonitoring = true, completionRepeat = false, completionMaxSends = 20 } = {}) { if (typeof startMonitoring !== 'boolean') throw new ClientError(textMessage("error.invalid_switch_value")); if (this.state.tasks.some(t => t.threadId === id)) throw new ClientError(textMessage("error.this_chat_has_already_been_added")); if (this.importingThreads.has(id)) throw new ClientError(textMessage("error.this_chat_is_being_added_do_not_import")); if (this.state.tasks.length >= 100) throw new ClientError(textMessage("error.up_to_records_are_supported_end_unused_work")); validateMonitorInput(note, continuationMessage); + validateCompletionInput(completionMonitoring, completionMessage, {quotaMonitoring,repeat:completionRepeat,maxSends:completionMaxSends}); // Reserve before yielding: HTTP and MCP imports share this manager. this.importingThreads.add(id); try { @@ -257,9 +275,9 @@ export class Manager extends EventEmitter { // Another task path may have claimed the thread while the read was pending. if (this.state.tasks.some(t => t.threadId === id)) throw new ClientError(textMessage("error.this_chat_has_already_been_added")); if (this.state.tasks.length >= 100) throw new ClientError(textMessage("error.up_to_records_are_supported_end_unused_work")); - const task = createMonitorTask(id, thread, note, continuationMessage); + const task = createMonitorTask(id, thread, note, continuationMessage, { completionMonitoring, completionMessage, quotaMonitoring, completionRepeat, completionMaxSends }); if (startMonitoring) taskModel(task).action(task, 'resume', undefined, { sending: false, maxWakeSends: this.state.settings.maxWakeSends }); - this.state.tasks.unshift(task); this.log(textMessage("log.chat_added", { name: task.name })); this.changed(); + this.addTask(task, textMessage("log.chat_added", { name: task.name })); if (startMonitoring) this.activate(); return task; } finally { this.importingThreads.delete(id); } diff --git a/server/monitor-task.js b/server/monitor-task.js index 5fd64e0..dc49bb0 100644 --- a/server/monitor-task.js +++ b/server/monitor-task.js @@ -8,27 +8,51 @@ import { isWriterConflict } from './policy.js'; * @property {'quota-wake'} mode * @property {string} note Local note; never an execution goal. * @property {string} continuationMessage Message for future recovery deliveries. + * @property {boolean} completionMonitoring Whether complete replies trigger follow-ups. + * @property {string} completionMessage Independent follow-up after a final reply. + * @property {object} completion Durable final-turn claim and deduplication evidence. * @property {number} sentCount Confirmed queue deliveries; resume never resets it. - * @property {boolean} continuous Whether quota monitoring is enabled. + * @property {boolean} continuous Master monitoring switch. + * @property {boolean} quotaMonitoring Whether quota recovery is monitored. + * @property {boolean} completionRepeat Whether new complete replies keep triggering. + * @property {number} completionMaxSends Maximum completion sends per run, including the first. + * @property {number} completionSends Confirmed completion sends in the current run. * @property {object} wake The recovery episode and delivery claim. * @property {string} status A member of MONITOR_TASK_STATUSES. */ export const MONITOR_TASK_STATUSES = Object.freeze(['monitoring', 'waiting', 'paused', 'blocked', 'completed']); export const isMonitorTask = task => task?.mode === 'quota-wake'; export const isEnabledMonitorTask = task => isMonitorTask(task) && task.continuous === true && ['monitoring', 'waiting'].includes(task.status); +export const isEnabledQuotaMonitorTask = task => isEnabledMonitorTask(task) && task.quotaMonitoring !== false; +export const completionLimit = task => task.completionRepeat === false ? 1 : (task.completionMaxSends ?? 100); +function pauseUnusedMonitor(task) { + if (task.quotaMonitoring === false && !task.completionMonitoring && task.continuous) { + task.continuous=false; task.status='paused'; task.waitReason=null; task.retryAt=0; + } +} +export function enforceCompletionLimit(task) { + if (!task.completionMonitoring || (task.completionSends || 0) < completionLimit(task)) return false; + task.completionMonitoring=false; pauseUnusedMonitor(task); + setActivity(task,textMessage('task.completion_limit',{count:task.completionSends,limit:completionLimit(task)})); + return true; +} const executionFields = ['prompt', 'rounds', 'plan', 'output', 'outputTruncated', 'outcome', 'toolCount', 'turnId', 'lastError']; export function resetWake(task) { + // Explicit resume acknowledges ambiguity without resending the same answer. + if (task.completion?.delivery === 'uncertain') { + task.completion.lastTurnId = task.completion.turnId; task.completion.delivery = 'idle'; + } task.wake = { armed: false, delivery: 'idle' }; task.status = task.continuous ? 'monitoring' : 'paused'; task.waitReason = null; task.retryAt = 0; - setActivity(task, task.continuous ? textMessage("task.monitoring_quota_a_continuation_message_will_be_sent") : textMessage("task.quota_recovery_monitoring_paused")); + setActivity(task, task.continuous ? textMessage(task.completionMonitoring ? 'task.monitoring_replies_and_quota' : 'task.monitoring_quota_a_continuation_message_will_be_sent') : textMessage("task.quota_recovery_monitoring_paused")); } export function enforceWakeLimit(task, limit) { if ((task.sentCount || 0) < limit) return false; task.continuous = false; - if (task.wake?.delivery !== 'uncertain') { + if (task.wake?.delivery !== 'uncertain' && task.completion?.delivery !== 'uncertain') { task.status = 'paused'; task.waitReason = 'send-limit'; task.retryAt = 0; if (task.wake && task.wake.delivery !== 'sending') { task.wake.armed = false; @@ -44,10 +68,18 @@ export function validateMonitorInput(note, continuationMessage) { if (typeof continuationMessage !== 'string' || continuationMessage.length > 12000) throw new ClientError(textMessage("error.continuation_messages_must_be_text_of_up_to")); } -export function createMonitorTask(threadId, thread, note = '', continuationMessage = '') { +export function validateCompletionInput(enabled, message, {quotaMonitoring, repeat, maxSends} = {}) { + if (typeof enabled !== 'boolean') throw new ClientError(textMessage('error.invalid_switch_value')); + if ((quotaMonitoring !== undefined && typeof quotaMonitoring !== 'boolean') || (repeat !== undefined && typeof repeat !== 'boolean')) throw new ClientError(textMessage('error.invalid_switch_value')); + if (maxSends !== undefined && (!Number.isSafeInteger(maxSends) || maxSends < 1 || maxSends > 100)) throw new ClientError(textMessage('error.completion_send_limit')); + validateMonitorInput('', message); +} + +export function createMonitorTask(threadId, thread, note = '', continuationMessage = '', { completionMonitoring = false, completionMessage = '', quotaMonitoring = true, completionRepeat = false, completionMaxSends = 20 } = {}) { validateMonitorInput(note, continuationMessage); + validateCompletionInput(completionMonitoring, completionMessage, {quotaMonitoring,repeat:completionRepeat,maxSends:completionMaxSends}); const now = Date.now(); - return { id: randomUUID(), mode: 'quota-wake', threadId, name: (thread.name || thread.preview || 'Codex 会话').slice(0, 80), cwd: thread.cwd, note: note.trim(), continuationMessage: continuationMessage.trim(), continuous: false, status: 'paused', ...activityFields(textMessage("task.chat_added_enable_monitoring_to_send_a_message")), sentCount: 0, wake: { armed: false, delivery: 'idle' }, createdAt: now, updatedAt: now }; + return { id: randomUUID(), mode: 'quota-wake', threadId, name: (thread.name || thread.preview || 'Codex 会话').slice(0, 80), cwd: thread.cwd, note: note.trim(), continuationMessage: continuationMessage.trim(), quotaMonitoring, completionMonitoring, completionRepeat, completionMaxSends, completionSends: 0, completionMessage: completionMessage.trim(), completion: { delivery: 'idle' }, continuous: false, status: 'paused', ...activityFields(textMessage("task.chat_added_enable_monitoring_to_send_a_message")), sentCount: 0, wake: { armed: false, delivery: 'idle' }, createdAt: now, updatedAt: now }; } export function migrateLegacyWriter(task) { @@ -61,6 +93,9 @@ export function migrateLegacyWriter(task) { function prepare(task, settings) { let changed = false; + for (const [key,value] of Object.entries({quotaMonitoring:true,completionRepeat:true,completionMaxSends:100,completionSends:0})) { + if (task[key] === undefined) { task[key]=value; changed=true; } + } if (!task.wake) { task.wake = { armed: false, delivery: 'idle' }; changed = true; } if (task.wake.delivery === 'pending' && (!task.wake.episodeId || !Number.isFinite(task.wake.exhaustedAt))) { task.wake.delivery = 'uncertain'; task.continuous = false; task.status = 'blocked'; @@ -69,17 +104,35 @@ function prepare(task, settings) { if (typeof task.note !== 'string') { task.note = task.prompt || ''; changed = true; } if (!Number.isInteger(task.sentCount) || task.sentCount < 0) { task.sentCount = Math.max(0, Number.isInteger(task.rounds) ? task.rounds : 0); changed = true; } for (const key of executionFields) if (key in task) { delete task[key]; changed = true; } + if (task.completion?.delivery === 'sending') { + task.completion.delivery = 'uncertain'; task.status = 'blocked'; task.continuous = false; + task.waitReason = null; task.retryAt = 0; + setActivity(task, textMessage('task.the_previous_delivery_is_unconfirmed_check_the_original')); changed = true; + } if (task.wake.delivery === 'sending') { task.wake.delivery = 'uncertain'; task.status = 'blocked'; setActivity(task, textMessage("task.the_previous_delivery_is_unconfirmed_check_the_original")); changed = true; } if (enforceWakeLimit(task, settings.maxWakeSends)) changed = true; + if (enforceCompletionLimit(task)) changed=true; return changed; } function validate(task) { + if ((task.quotaMonitoring !== undefined && typeof task.quotaMonitoring !== 'boolean') + || (task.completionRepeat !== undefined && typeof task.completionRepeat !== 'boolean') + || (task.completionMaxSends !== undefined && (!Number.isSafeInteger(task.completionMaxSends) || task.completionMaxSends < 1 || task.completionMaxSends > 100)) + || (task.completionSends !== undefined && (!Number.isSafeInteger(task.completionSends) || task.completionSends < 0))) throw new MessageError(textMessage('error.completion_send_limit')); if (!MONITOR_TASK_STATUSES.includes(task.status)) throw new MessageError(textMessage("error.monitor_state")); if ((task.sentCount !== undefined && (!Number.isSafeInteger(task.sentCount) || task.sentCount < 0)) || (task.rounds !== undefined && (!Number.isSafeInteger(task.rounds) || task.rounds < 0))) throw new MessageError(textMessage("error.monitor_count")); + if ((task.completionMonitoring !== undefined && typeof task.completionMonitoring !== 'boolean') + || (task.completionMessage !== undefined && (typeof task.completionMessage !== 'string' || task.completionMessage.length > 12000))) throw new MessageError(textMessage('error.task_fields')); + const completion = task.completion; + if (completion !== undefined && (!completion || typeof completion !== 'object' || Array.isArray(completion) + || !['idle', 'sending', 'sent', 'uncertain'].includes(completion.delivery) + || (completion.turnId !== undefined && (typeof completion.turnId !== 'string' || !completion.turnId)) + || (completion.lastTurnId !== undefined && (typeof completion.lastTurnId !== 'string' || !completion.lastTurnId)) + || (completion.delivery !== 'idle' && !completion.turnId))) throw new MessageError(textMessage('error.monitor_delivery')); // Old records may contain direct fields; prepare migrates their note/count // before removing them. Delivery evidence is checked without inventing it. if (task.wake === undefined) return; @@ -93,17 +146,49 @@ function validate(task) { } function action(task, action, value, { sending, maxWakeSends }) { + if (action === 'quota-monitoring' || action === 'completion-monitoring') { + if (typeof value !== 'boolean') throw new ClientError(textMessage('error.invalid_switch_value')); + if (value && sending) throw new ClientError(textMessage('error.delivery_is_still_being_confirmed_wait_before_enabling')); + if (action === 'quota-monitoring') { + task.quotaMonitoring=value; + if (!value && task.wake?.delivery === 'pending') { + task.wake={armed:false,delivery:'idle'};task.waitReason=null;task.retryAt=0; + if (task.continuous && task.status==='waiting') task.status='monitoring'; + } + } else { + if (value && !task.completionMonitoring) task.completionSends=0; + task.completionMonitoring=value; + } + pauseUnusedMonitor(task);task.updatedAt=Date.now();return {kind:'changed'}; + } + if (action === 'completion') { + if (!value || typeof value !== 'object' || Array.isArray(value)) throw new ClientError(textMessage('error.invalid_switch_value')); + validateCompletionInput(value.enabled, value.message, value); + if (sending) throw new ClientError(textMessage('error.delivery_is_still_being_confirmed_wait_before_enabling')); + if (value.enabled && !task.completionMonitoring) task.completionSends=0; + task.completionMonitoring = value.enabled; task.completionMessage = value.message.trim(); task.updatedAt = Date.now(); + if (value.repeat !== undefined) task.completionRepeat=value.repeat; + if (value.maxSends !== undefined) task.completionMaxSends=value.maxSends; + if (value.quotaMonitoring !== undefined) task.quotaMonitoring=value.quotaMonitoring; + if (task.quotaMonitoring === false && task.wake?.delivery === 'pending') { + task.wake={armed:false,delivery:'idle'};task.waitReason=null;task.retryAt=0; + if (task.continuous && task.status==='waiting') task.status='monitoring'; + } + enforceCompletionLimit(task);pauseUnusedMonitor(task); + return { kind: 'changed', logMessage: textMessage('log.completion_settings_updated') }; + } if (action === 'message') { if (typeof value !== 'string' || value.length > 12000) throw new ClientError(textMessage("error.continuation_messages_must_be_text_of_up_to")); task.continuationMessage = value.trim(); task.updatedAt = Date.now(); return { kind: 'changed', logMessage: textMessage("log.continuation_message_updated") }; } - if ((sending || task.wake?.delivery === 'uncertain') && (action === 'pause' || (action === 'continuous' && value === false))) { + if ((sending || task.wake?.delivery === 'uncertain' || task.completion?.delivery === 'uncertain') && (action === 'pause' || (action === 'continuous' && value === false))) { task.continuous = false; task.status = 'paused'; task.waitReason = null; task.retryAt = 0; setActivity(task, textMessage("task.monitoring_paused_delivery_is_still_unconfirmed_check_the")); return { kind: 'changed' }; } if (sending) throw new ClientError(textMessage("error.delivery_is_still_being_confirmed_wait_before_enabling")); + if ((action === 'resume' || (action === 'continuous' && value === true)) && task.quotaMonitoring === false && !task.completionMonitoring) throw new ClientError(textMessage('error.choose_monitor')); if ((action === 'resume' || (action === 'continuous' && value === true)) && (task.sentCount || 0) >= maxWakeSends) throw new ClientError(textMessage("error.message_limit_reached_raise_the_limit_then_enable")); if (action === 'continuous') { if (typeof value !== 'boolean') throw new ClientError(textMessage("error.invalid_switch_value")); @@ -120,12 +205,15 @@ function action(task, action, value, { sending, maxWakeSends }) { function restoreBackup(task) { task.continuous = false; task.status = 'blocked'; setActivity(task, textMessage("task.backup_restored_check_the_original_chats_and_projects")); + if (task.completion?.delivery === 'sending') task.completion.delivery = 'uncertain'; if (task.wake?.armed || task.wake?.delivery === 'sending') task.wake.delivery = 'uncertain'; } function retryStorage(task) { - if (task.wake?.delivery !== 'sending') return; - task.wake.delivery = 'uncertain'; task.status = 'blocked'; setActivity(task, textMessage("task.the_delivery_record_could_not_be_saved_check")); + if (task.completion?.delivery === 'sending') task.completion.delivery = 'uncertain'; + else if (task.wake?.delivery === 'sending') task.wake.delivery = 'uncertain'; + else return; + task.status = 'blocked'; task.waitReason = null; task.retryAt = 0; setActivity(task, textMessage("task.the_delivery_record_could_not_be_saved_check")); } export const monitorTaskModel = Object.freeze({ prepare, validate, action, restoreBackup, retryStorage }); diff --git a/server/quota-wake.js b/server/quota-wake.js index 31429da..d9b4e52 100644 --- a/server/quota-wake.js +++ b/server/quota-wake.js @@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto'; import { buckets, quotaAvailable, QUOTA_TTL_MS } from './policy.js'; import { defaultContinuation } from '../public/i18n.js'; import { readThreadReply } from './thread-reply.js'; -import { enforceWakeLimit, isEnabledMonitorTask } from './monitor-task.js'; +import { enforceWakeLimit, isEnabledQuotaMonitorTask } from './monitor-task.js'; export { resetWake, enforceWakeLimit } from './monitor-task.js'; @@ -16,7 +16,7 @@ export async function tickQuotaWake(manager, epoch = manager.scheduleEpoch) { if (!manager.wakeSampledAt || now - manager.wakeSampledAt > QUOTA_TTL_MS) return; for (const task of manager.state.tasks) { if (!manager.canSchedule(epoch)) break; - if (!isEnabledMonitorTask(task)) continue; + if (!isEnabledQuotaMonitorTask(task)) continue; if (enforceWakeLimit(task, manager.state.settings.maxWakeSends)) { manager.changed(); continue; } const wake = task.wake ||= { armed: false, delivery: 'idle' }; if (quotaExhausted(manager.wakeQuota)) { @@ -35,7 +35,7 @@ export async function tickQuotaWake(manager, epoch = manager.scheduleEpoch) { } manager.wakeExecutions.set(task.id, wake); try { - const permitted = () => manager.canSchedule(epoch) && isEnabledMonitorTask(task) + const permitted = () => manager.canSchedule(epoch) && isEnabledQuotaMonitorTask(task) && task.wake === wake && manager.state.tasks.includes(task) && (task.sentCount || 0) < manager.state.settings.maxWakeSends && quotaAvailable(manager.wakeQuota, manager.wakeSampledAt, manager.state.settings.minimumRemaining); const inspectReply = async () => { @@ -66,7 +66,10 @@ export async function tickQuotaWake(manager, epoch = manager.scheduleEpoch) { task.status = task.continuous ? 'monitoring' : 'paused'; } else if (error.waitForReply) { wake.delivery = 'pending'; task.waitReason = 'thread'; task.retryAt = Date.now() + manager.state.settings.pollSeconds * 1000; - } else if (error.cancelled) { if (wake.delivery === 'sending') wake.delivery = 'pending'; } + } else if (error.cancelled) { + if (task.quotaMonitoring === false) task.wake={armed:false,delivery:'idle'}; + else if (wake.delivery === 'sending') wake.delivery = 'pending'; + } else if (error.safeToRetry && task.continuous && task.status !== 'paused') { wake.delivery = 'pending'; task.waitReason = 'desktop'; task.retryAt = Date.now() + 60000; } else { wake.delivery = 'uncertain'; task.waitReason = null; task.retryAt = 0; if (task.status !== 'paused') task.status = 'blocked'; } diff --git a/server/static-assets.js b/server/static-assets.js index bcc0924..a6e2f3d 100644 --- a/server/static-assets.js +++ b/server/static-assets.js @@ -6,7 +6,7 @@ const files = new Map([ ['/', 'index.html'], ['/widget', 'widget.html'], ...[ 'app.js', 'widget.js', 'i18n.js', 'messages.js', 'message.js', 'system-messages.js', 'access.js', 'api-client.js', - 'html.js', 'icons.js', 'task-view.js', 'task-forms.js', 'view-lifecycle.js', 'settings-form.js', + 'html.js', 'icons.js', 'task-view.js', 'task-forms.js', 'view-lifecycle.js', 'settings-form.js', 'interaction-state.js', 'widget-size.js', 'task-mode.js', 'task-details.js', 'approval-details.js', 'storage-status.js', 'quota-display.js', 'rhine-readout.js', 'style.css', 'widget.css', 'favicon.svg', 'rhine-signal-loop.svg', diff --git a/server/summary.js b/server/summary.js index 6f1af10..0c8d777 100644 --- a/server/summary.js +++ b/server/summary.js @@ -10,12 +10,12 @@ const windowSummary = value => value && pick(value, ['usedPercent', 'windowDurat // Budgets apply to the combined UTF-8 frame, not to individual character counts. export function compactSummary(snapshot) { const result = { - ...pick(snapshot, ['app', 'version', 'buildId', 'protocolVersion', 'schemaVersion', 'sampledAt', 'demo', 'observationOnly']), + ...pick(snapshot, ['app', 'version', 'buildId', 'protocolVersion', 'schemaVersion', 'instanceId', 'snapshotRevision', 'sampledAt', 'demo', 'observationOnly']), settings: pick(snapshot.settings, ['enabled', 'language', 'pollSeconds', 'minimumRemaining', 'maxRounds', 'maxWakeSends']), persistence: { ...pick(snapshot.persistence, ['status', 'needsRestore', 'pending', 'failedAt', 'backupAvailable']), message: text(snapshot.persistence?.message, 2000), messageInfo: boundedMessage(snapshot.persistence?.messageInfo, 2000), loadError: text(snapshot.persistence?.loadError, 2000) }, connection: { status: snapshot.connection?.status, message: text(snapshot.connection?.message, 2000), messageInfo: boundedMessage(snapshot.connection?.messageInfo, 2000) }, tasks: snapshot.tasks.map(task => ({ - ...pick(task, ['id', 'mode', 'name', 'threadId', 'status', 'continuous', 'rounds', 'sentCount', 'waitReason', 'retryAt', 'createdAt', 'updatedAt', 'progress', 'detailRevision']), + ...pick(task, ['id', 'mode', 'name', 'threadId', 'status', 'continuous', 'rounds', 'sentCount', 'quotaMonitoring', 'completionMonitoring', 'completionRepeat', 'completionMaxSends', 'completionSends', 'waitReason', 'retryAt', 'createdAt', 'updatedAt', 'progress', 'detailInstanceId', 'detailRevision']), cwd: text(task.cwd, 256), activity: text(task.activity, 240), activityMessage: boundedMessage(task.activityMessage, 240), ...(task.mode === 'quota-wake' ? { notePreview: text(task.note || '', 500), noteTruncated: (task.note?.length || 0) > 500 } : {}), ...(task.wake ? { wake: pick(task.wake, ['armed', 'delivery', 'episodeId', 'exhaustedAt', 'sentAt', 'queueId']) } : {}), diff --git a/server/thread-reply.js b/server/thread-reply.js index 8b1af92..10f357c 100644 --- a/server/thread-reply.js +++ b/server/thread-reply.js @@ -19,17 +19,31 @@ export function turnReplyState(turn) { const runtimeState = thread => thread?.status?.type === 'active' ? 'active' : ['idle', 'notLoaded'].includes(thread?.status?.type) ? null : 'unknown'; -export async function readThreadReply(rpc, threadId) { +const replySnapshot = turn => ({ state: turnReplyState(turn), turnId: typeof turn?.id === 'string' ? turn.id : null }); + +// Return only protocol evidence, never inspected chat text. +export async function readThreadReplySnapshot(rpc, threadId) { const { thread } = await rpc.call('thread/read', { threadId, includeTurns: false }); - if (thread?.id !== threadId) return 'unknown'; + if (thread?.id !== threadId) return { state: 'unknown', turnId: null }; const runtime = runtimeState(thread); - if (runtime) return runtime; + if (runtime) return { state: runtime, turnId: null }; if (thread.historyMode === 'paginated') { const page = await rpc.call('thread/turns/list', { threadId, limit: 1, sortDirection: 'desc', itemsView: 'full' }); - return Array.isArray(page?.data) && page.data.length === 1 ? turnReplyState(page.data[0]) : 'unknown'; + // Listing history and reading runtime status are separate RPCs. A new + // answer may start while the page is in flight; never trust the older idle. + const { thread: current } = await rpc.call('thread/read', { threadId, includeTurns: false }); + if (current?.id !== threadId) return { state: 'unknown', turnId: null }; + const state = runtimeState(current); + if (state) return { state, turnId: null }; + return replySnapshot(Array.isArray(page?.data) && page.data.length === 1 ? page.data[0] : null); } // Legacy app-servers expose full chronological history through thread/read. const { thread: history } = await rpc.call('thread/read', { threadId, includeTurns: true }); - if (history?.id !== threadId) return 'unknown'; - return runtimeState(history) || (Array.isArray(history.turns) ? turnReplyState(history.turns.at(-1)) : 'unknown'); + if (history?.id !== threadId) return { state: 'unknown', turnId: null }; + const state = runtimeState(history); + return state ? { state, turnId: null } : replySnapshot(Array.isArray(history.turns) ? history.turns.at(-1) : null); +} + +export async function readThreadReply(rpc, threadId) { + return (await readThreadReplySnapshot(rpc, threadId)).state; } diff --git a/tests/autostart-data.test.js b/tests/autostart-data.test.js index d1fa8bb..673ca76 100644 --- a/tests/autostart-data.test.js +++ b/tests/autostart-data.test.js @@ -9,7 +9,7 @@ import { promisify } from 'node:util'; const execute = promisify(execFile), root = fileURLToPath(new URL('..', import.meta.url)); test('autostart enable and disable share runtime data selection without changing its default', { skip: process.platform !== 'win32' }, async () => { - const parent = realpathSync(tmpdir()), directory = mkdtempSync(join(parent, 'continuer-autostart-')); + const parent = realpathSync.native(tmpdir()), directory = mkdtempSync(join(parent, 'continuer-autostart-')); try { for (const variant of ['source', 'existing-data', 'portable', 'configured', 'environment']) { for (const disable of [false, true]) { @@ -24,15 +24,50 @@ test('autostart enable and disable share runtime data selection without changing const env = { ...process.env, CONTINUER_DATA_DIR: variant === 'environment' ? join(source, 'override-数据') : '', LOCALAPPDATA: local, CONTINUER_PORT: '4317' }; const selected = async () => Buffer.from((await execute(process.execPath, ['-e', 'process.stdout.write(Buffer.from(require(process.argv[1]).dataDir, "utf16le").toString("base64"))', join(source, 'server/config.cjs')], { env })).stdout, 'base64').toString('utf16le'); const before = await selected(), trace = join(source, 'host-calls.txt'); + mkdirSync(before, { recursive: true }); + writeFileSync(join(before, 'quit.request'), 'Previous explicit exit'); + writeFileSync(join(before, 'autostart-status.json'), JSON.stringify({pid:424242,pluginRoot:source,state:'launched'})); await execute('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', join(root, 'tests/fixtures/autostart-host.ps1'), - '-Script', join(root, 'Enable-Autostart.ps1'), '-PluginRoot', source, '-Trace', trace, ...(disable ? ['-Disable'] : [])], { env, windowsHide: true }); + '-Script', join(root, 'Enable-Autostart.ps1'), '-PluginRoot', source, '-Trace', trace, '-WatcherPid', '424242', ...(disable ? ['-Disable'] : [])], { env, windowsHide: true }); assert.equal(await selected(), before, `${variant}/${disable} must not change runtime default`); const preferences = JSON.parse(readFileSync(join(before, 'autostart-preferences.json'), 'utf8').replace(/^\uFEFF/, '')); assert.equal(preferences.enabled, !disable); if (variant === 'source') assert.equal(existsSync(join(source, 'data')), false); - if (disable) assert.equal(existsSync(trace), false); - else assert.match(readFileSync(trace, 'utf8'), /registry:.*watch-codex\.ps1/); + assert.match(readFileSync(trace, 'utf8'), /stop/,'UTF-8 without BOM must preserve the Chinese watcher path'); + assert.equal(existsSync(join(before,'quit.request')), disable, 'only explicit enable clears the user-exit latch'); + if (disable) assert.doesNotMatch(readFileSync(trace, 'utf8'), /launch:/); + else { + assert.match(readFileSync(trace, 'utf8'), /shortcut:.*watch-codex\.ps1/); + assert.doesNotMatch(readFileSync(trace, 'utf8'), /registry:/); + const shortcut = JSON.parse(readFileSync(join(source, 'fixture-startup/CodexContinuer.lnk'), 'utf8').replace(/^\uFEFF/, '')); + const dataArgument = /(?:^|\s)-DataDir "([^"]+)"(?:\s|$)/.exec(shortcut.Arguments)?.[1]; + assert.ok(dataArgument, `${variant}/${disable}: preserve the complete data argument`); + assert.equal(realpathSync.native(dataArgument), realpathSync.native(before), `${variant}/${disable}: shortcut selects the same physical data directory`); + assert.equal(shortcut.WindowStyle, 7); + if (variant === 'environment') { + await execute('powershell.exe', ['-NoProfile','-ExecutionPolicy','Bypass','-File',join(root,'tests/fixtures/autostart-host.ps1'),'-Script',join(root,'Enable-Autostart.ps1'),'-PluginRoot',source,'-Trace',trace,'-WatcherPid','424242','-ExistingRegistry','-Disable'], {env,windowsHide:true}); + assert.equal(existsSync(join(source,'fixture-startup/CodexContinuer.lnk')),false); + assert.match(readFileSync(trace,'utf8'),/registry-removed/); + } + } + const stopTrace=join(source,'stop-calls.txt'); + await execute('powershell.exe',['-NoProfile','-ExecutionPolicy','Bypass','-File',join(root,'tests/fixtures/autostart-host.ps1'),'-Script',join(root,'plugin/stop-owned.ps1'),'-PluginRoot',source,'-DataDir',before,'-Trace',stopTrace,'-WatcherPid','424242','-StopOnly'],{env,windowsHide:true}); + assert.match(readFileSync(stopTrace,'utf8'),/stop/, `${variant}/${disable}: stop the selected watcher`); } } - } finally { assert.equal(dirname(realpathSync(directory)), parent); rmSync(directory, { recursive: true, force: true }); } + } finally { assert.equal(dirname(realpathSync.native(directory)), parent); rmSync(directory, { recursive: true, force: true }); } +}); + +test('watcher cleanup recognizes a verified executable reported through its Windows short path', { skip: process.platform !== 'win32' }, async () => { + const parent = realpathSync.native(tmpdir()), directory = mkdtempSync(join(parent, 'continuer-short-path-')); + try { + // No files are created in Program Files; these paths only identify a mocked process. + const pluginRoot = join(process.env.ProgramFiles, 'continuer-fixture'), processRoot = join(process.env.SystemDrive + '/', 'PROGRA~1', 'continuer-fixture'); + writeFileSync(join(directory, 'autostart-status.json'), JSON.stringify({ pid: 424242, pluginRoot })); + const trace = join(directory, 'stop.txt'); + await execute('powershell.exe', ['-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', join(root, 'tests/fixtures/autostart-host.ps1'), + '-Script', join(root, 'plugin/stop-owned.ps1'), '-PluginRoot', pluginRoot, '-ProcessRoot', processRoot, '-DataDir', directory, + '-Trace', trace, '-WatcherPid', '424242', '-StopOnly'], { windowsHide: true }); + assert.match(readFileSync(trace, 'utf8'), /stop/); + } finally { assert.equal(dirname(realpathSync.native(directory)), parent); rmSync(directory, { recursive: true, force: true }); } }); diff --git a/tests/completion-wake.test.js b/tests/completion-wake.test.js new file mode 100644 index 0000000..69e9e99 --- /dev/null +++ b/tests/completion-wake.test.js @@ -0,0 +1,207 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { mkdtempSync, realpathSync, rmSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { Manager } from '../server/manager.js'; +import { QueueSender } from '../server/queue-sender.js'; +import { Store, validateState } from '../server/store.js'; +import { validate } from '../plugin/tools.js'; +import { interruptedThread } from './fixtures/thread-history.js'; + +const threadId = '11111111-1111-4111-8111-111111111111'; +const quota = usedPercent => ({ rateLimits: { primary: { usedPercent } } }); +const finished = (id = 'final-turn', phase = 'final_answer') => ({ id, status: 'completed', itemsView: 'full', items: [ + { type: 'userMessage', id: 'instruction' }, { type: 'agentMessage', phase, text: 'PRIVATE ANSWER BODY' }, +] }); +const deferred = () => { let resolve; const promise = new Promise(yes => { resolve = yes; }); return { promise, resolve }; }; + +async function fixture(t, { saved, store, enabled = true } = {}) { + const rpc = new EventEmitter(), commands = [], saves = [], reads = []; + let thread = interruptedThread(threadId, { turns: [finished()] }); + rpc.ready = true; rpc.close = () => {}; + rpc.call = async (method, params) => { + reads.push({ method, params }); + if (method === 'thread/turns/list') return { data: structuredClone(thread.turns.slice(-1)) }; + return { thread: structuredClone(params.includeTurns ? thread : { ...thread, turns: [] }) }; + }; + const sender = new QueueSender({ binary: 'mock-codex', run: async (_binary, args) => { commands.push(args); return `Queued message ${threadId}`; } }); + const m = new Manager(rpc, store || { load: () => saved && structuredClone(saved), save: state => { validateState(state); saves.push(structuredClone(state)); } }, { demo: true, wakeSender: sender }); + m.connection.status = 'connected'; t.after(() => m.stop()); + const task = m.state.tasks[0] || await m.importThread(threadId, 'Local note', 'QUOTA MESSAGE', { completionMonitoring: enabled, completionMessage: 'FINAL MESSAGE', completionRepeat: true, completionMaxSends: 100 }); + const tick = async () => { m.completionChecks.clear(); m.setQuota(quota(0)); await m.tick(); }; + return { m, task, rpc, sender, commands, saves, reads, tick, setThread: value => { thread = value; }, sent: () => commands.filter(args => args.includes('--message')) }; +} + +test('completion follow-up needs explicit opt-in and monitoring; sends its own editable message once per final turn', async t => { + const f = await fixture(t, { enabled: false }); + await f.tick(); await f.m.action(f.task.id, 'resume'); await f.tick(); assert.equal(f.sent().length, 0); + await f.m.action(f.task.id, 'completion', { enabled: true, message: ' 下一项工作\n先运行测试 ' }); + await f.tick(); await f.tick(); + assert.equal(f.sent().length, 1); assert.equal(f.sent()[0].at(-1), '下一项工作\n先运行测试'); + assert.equal(f.task.continuationMessage, 'QUOTA MESSAGE'); assert.equal(f.task.sentCount, 1); + await f.m.action(f.task.id, 'pause'); await f.m.action(f.task.id, 'resume'); await f.tick(); assert.equal(f.sent().length, 1); + f.setThread(interruptedThread(threadId, { turns: [finished('second-final')] })); await f.tick(); + assert.equal(f.sent().length, 2); assert.equal(f.task.completion.lastTurnId, 'second-final'); + assert.ok(!JSON.stringify(f.saves).includes('PRIVATE ANSWER BODY')); + assert.equal(f.m.snapshot({ details: false }).tasks[0].completionMessage, undefined); +}); + +test('complete-reply claim and both messages survive isolated disk restart without replaying the same final answer', async t => { + const parent = realpathSync(tmpdir()), directory = mkdtempSync(join(parent, 'continuer-completion-')); + t.after(() => { assert.equal(dirname(realpathSync(directory)), parent); rmSync(directory, { recursive: true, force: true }); }); + const store = new Store(join(directory, 'state.json')); + const first = await fixture(t, { store }); await first.m.action(first.task.id, 'resume'); await first.tick(); first.m.stop(); + const restored = await fixture(t, { store }); await restored.tick(); + assert.equal(restored.sent().length, 0); assert.equal(restored.task.sentCount, 1); + assert.equal(restored.task.completionMessage, 'FINAL MESSAGE'); assert.equal(restored.task.continuationMessage, 'QUOTA MESSAGE'); + restored.m.stop(); +}); + +test('only complete replies on the newest instruction trigger, including paginated history', async t => { + const f = await fixture(t); await f.m.action(f.task.id, 'resume'); + const bad = [ + { status: { type: 'active' }, turns: [finished()] }, + { turns: [finished('old'), { ...finished('new'), status: 'interrupted' }] }, + { turns: [{ ...finished(), status: 'failed' }] }, + { turns: [finished('comment', 'commentary')] }, + { turns: [{ ...finished(), itemsView: 'summary' }] }, + { turns: [{ ...finished(), items: [...finished().items, { type: 'userMessage' }] }] }, + { turns: [] }, { status: { type: 'future-state' } }, + ]; + for (const overrides of bad) { f.setThread(interruptedThread(threadId, overrides)); await f.tick(); } + assert.equal(f.sent().length, 0); assert.equal(f.task.sentCount, 0); + f.setThread(interruptedThread(threadId, { historyMode: 'paginated', turns: [finished()] })); await f.tick(); + assert.equal(f.sent().length, 1); + assert.ok(f.reads.some(read => read.method === 'thread/turns/list' && read.params.itemsView === 'full')); +}); + +test('final reply monitoring honors poll cadence and current quota rather than requiring exhaustion', async t => { + const f = await fixture(t); await f.m.action(f.task.id, 'resume'); + f.m.setQuota(quota(100)); await f.m.tick(); assert.equal(f.sent().length, 0); + f.m.setQuota(quota(0)); f.m.wakeSampledAt -= 90001; await f.m.tick(); assert.equal(f.sent().length, 0); + await f.tick(); const count = f.reads.length; await f.m.tick(); + assert.equal(f.reads.length, count); assert.equal(f.sent().length, 1); + assert.equal(f.task.wake.armed, false); assert.equal(f.task.wake.delivery, 'idle'); +}); + +test('new instructions arriving during capability probe cancel a stale final follow-up', async t => { + for (const active of [true, false]) { + const f = await fixture(t); await f.m.action(f.task.id, 'resume'); + f.sender.run = async (_binary, args) => { + f.commands.push(args); + if (args.includes('--help')) f.setThread(interruptedThread(threadId, active ? { status: { type: 'active' } } : { turns: [finished('newer-final')] })); + return ''; + }; + await f.tick(); assert.equal(f.sent().length, 0); assert.equal(f.task.sentCount, 0); assert.equal(f.task.completion.delivery, 'idle'); + } +}); + +test('a new reply starting during the final paginated read cancels the completion follow-up', async t => { + const f=await fixture(t);await f.m.action(f.task.id,'resume'); + f.setThread(interruptedThread(threadId,{historyMode:'paginated',turns:[finished()]})); + const call=f.rpc.call;let pages=0; + f.rpc.call=async(method,params)=>{ + const result=await call(method,params); + if(method==='thread/turns/list' && ++pages===2) f.setThread(interruptedThread(threadId,{historyMode:'paginated',status:{type:'active'},turns:[finished()]})); + return result; + }; + await f.tick();assert.equal(pages,2);assert.equal(f.sent().length,0);assert.equal(f.task.sentCount,0); + assert.equal(f.task.completion.delivery,'idle'); +}); + +test('pause, epoch invalidation, stale quota, disconnect and lowered limits all cancel before queue side effect', async t => { + for (const change of ['pause', 'toggle', 'stale', 'disconnect', 'limit']) { + const f = await fixture(t); await f.m.action(f.task.id, 'resume'); + const entered = deferred(), release = deferred(); + f.sender.run = async (_binary, args) => { f.commands.push(args); if (args.includes('--help')) { entered.resolve(); await release.promise; } return ''; }; + const pending = f.tick(); await entered.promise; + assert.equal(f.saves.at(-1).tasks[0].completion.delivery, 'sending'); + if (change === 'pause') await f.m.action(f.task.id, 'pause'); + if (change === 'toggle') { f.m.updateSettings({ enabled: false }); f.m.updateSettings({ enabled: true }); } + if (change === 'stale') f.m.wakeSampledAt -= 90001; + if (change === 'disconnect') f.rpc.emit('disconnect', 'Fixture disconnect'); + if (change === 'limit') { f.task.sentCount = 1; f.m.updateSettings({ maxWakeSends: 1 }); } + release.resolve(); await pending; + assert.equal(f.sent().length, 0, change); assert.equal(f.m.wakeExecutions.size, 0); + } +}); + +test('uncertain delivery blocks automatic retries and restart; manual resume skips that answer', async t => { + const f = await fixture(t); await f.m.action(f.task.id, 'resume'); + f.task.status='waiting'; f.task.waitReason='thread'; f.task.retryAt=Date.now()+60000; + f.sender.run = async (_binary, args) => { if (args.includes('--message')) throw Error('queue result unknown'); return ''; }; + await f.tick(); assert.equal(f.task.completion.delivery, 'uncertain'); assert.equal(f.task.status, 'blocked'); assert.equal(f.task.sentCount, 0); + assert.equal(f.task.waitReason,null); assert.equal(f.task.retryAt,0); + const restored = await fixture(t, { saved: f.saves.at(-1) }); await restored.tick(); assert.equal(restored.sent().length, 0); + await restored.m.action(restored.task.id, 'resume'); await restored.tick(); assert.equal(restored.sent().length, 0); + restored.setThread(interruptedThread(threadId, { turns: [finished('next-final')] })); await restored.tick(); assert.equal(restored.sent().length, 1); +}); + +test('restart during in-flight delivery becomes uncertain and never silently replays', async t => { + const f = await fixture(t); await f.m.action(f.task.id, 'resume'); + Object.assign(f.task.completion, { delivery: 'sending', turnId: 'final-turn' }); f.m.changed(); + f.task.waitReason='quota';f.task.retryAt=Date.now()+60000;f.m.changed(); + const restored = await fixture(t, { saved: f.saves.at(-1) }); await restored.tick(); + assert.equal(restored.task.completion.delivery, 'uncertain'); assert.equal(restored.task.continuous, false); assert.equal(restored.task.status, 'blocked'); + assert.equal(restored.task.waitReason,null);assert.equal(restored.task.retryAt,0); + assert.equal(restored.sent().length, 0); +}); + +test('storage failure before or after queue effect stops scheduling without replaying the claimed answer', async t => { + for (const stage of ['claim', 'confirm']) { + let fail = false, durable; + const store = { load: () => null, save: state => { + const delivery = state.tasks[0]?.completion?.delivery; + if (fail && delivery === (stage === 'claim' ? 'sending' : 'sent')) throw Error('fixture disk failure'); + validateState(state); durable = structuredClone(state); + } }; + const f = await fixture(t, { store }); await f.m.action(f.task.id, 'resume'); fail = true; + await assert.rejects(f.tick(), /disk failure/); + assert.equal(f.m.persistence.status, 'error'); assert.equal(f.m.state.settings.enabled, false); + assert.equal(f.sent().length, stage === 'claim' ? 0 : 1); assert.equal(f.task.sentCount, stage === 'claim' ? 0 : 1); + fail = false; f.m.recoverStorage('retry'); + const restored = await fixture(t, { saved: durable }); + restored.m.updateSettings({ enabled: true }); await restored.m.action(restored.task.id, 'resume'); await restored.tick(); + assert.equal(restored.sent().length, 0, stage); + } +}); + +test('pausing while queue confirmation is in flight keeps the pause and the confirmed deduplication record', async t => { + const f = await fixture(t); await f.m.action(f.task.id, 'resume'); + const entered = deferred(), release = deferred(); + f.sender.run = async (_binary, args) => { + f.commands.push(args); + if (args.includes('--message')) { entered.resolve(); await release.promise; } + return ''; + }; + const pending = f.tick(); await entered.promise; await f.m.action(f.task.id, 'pause'); + release.resolve(); await pending; + assert.equal(f.sent().length, 1); assert.equal(f.task.sentCount, 1); assert.equal(f.task.continuous, false); assert.equal(f.task.status, 'paused'); + await f.m.action(f.task.id, 'resume'); await f.tick(); assert.equal(f.sent().length, 1); +}); + +test('send cap is shared across quota and final-answer deliveries and never resets on resume', async t => { + const f = await fixture(t); f.m.updateSettings({ maxWakeSends: 2 }); await f.m.action(f.task.id, 'resume'); + f.setThread(interruptedThread(threadId)); f.m.setQuota(quota(100)); await f.m.tick(); await f.tick(); + assert.equal(f.sent()[0].at(-1), 'QUOTA MESSAGE'); + f.setThread(interruptedThread(threadId, { turns: [finished()] })); await f.tick(); + assert.equal(f.sent()[1].at(-1), 'FINAL MESSAGE'); assert.equal(f.task.sentCount, 2); assert.equal(f.task.continuous, false); + await assert.rejects(f.m.action(f.task.id, 'resume'), /上限/); + f.m.updateSettings({ maxWakeSends: 3 }); await f.m.action(f.task.id, 'resume'); await f.tick(); assert.equal(f.sent().length, 2); +}); + +test('blank completion message follows saved language and validation never changes a valid configuration', async t => { + const f = await fixture(t); await f.m.action(f.task.id, 'completion', { enabled: true, message: ' \n ' }); + f.m.updateSettings({ language: 'en' }); await f.m.action(f.task.id, 'resume'); await f.tick(); assert.equal(f.sent()[0].at(-1), 'Continue'); + const before = structuredClone(f.task); + for (const value of [null, [], { enabled: 'on', message: '' }, { enabled: true, message: null }, { enabled: true, message: 'x'.repeat(12001) }]) { + await assert.rejects(f.m.action(f.task.id, 'completion', value)); assert.deepEqual(f.task, before); + } + for (const patch of [{ completionMonitoring: 'on' }, { completionMessage: null }, { completion: { delivery: 'sending' } }]) { + Object.assign(f.task, patch); assert.throws(() => validateState(f.m.state)); Object.assign(f.task, structuredClone(before)); + } + for (const args of [{ completionMonitoring: true }, { completionMessage: 'Continue' }]) assert.throws(() => validate('continuer_import_session', { threadId, ...args })); + assert.throws(() => validate('continuer_task_action', { id: f.task.id, action: 'completion', value: true })); +}); diff --git a/tests/desktop-layout.test.js b/tests/desktop-layout.test.js index 34d18d0..edd7e75 100644 --- a/tests/desktop-layout.test.js +++ b/tests/desktop-layout.test.js @@ -6,10 +6,11 @@ import { EventEmitter } from 'node:events'; const require=createRequire(import.meta.url); const { createDesktopRuntime } = require('../desktop/runtime.cjs'); -function fixture(x=700,y=300,nativeMonitor=true,rounding=0) { +function fixture(x=700,y=300,nativeMonitor=true,rounding=0,options={}) { let now=0,serial=0,bounds={x,y,width:160+rounding,height:160+rounding},top=false; const timers=new Map(),updates=[],children=[]; - const prefs={follow:false,expanded:false,hidden:false,compactSize:160,offsets:{},positions:{}}; + const prefs={follow:false,expanded:false,hidden:false,compactSize:160,offsets:{},positions:{},...options.prefs}; + let saved; const window={getBounds:()=>({...bounds}),setBounds:next=>{bounds={...next,width:next.width+rounding,height:next.height+rounding};updates.push({...next});}, isDestroyed:()=>false,isVisible:()=>true,isFocused:()=>true,isAlwaysOnTop:()=>top, setAlwaysOnTop:value=>{top=value;},focus:()=>{},hide:()=>{},webContents:{send:()=>{}}}; @@ -17,10 +18,10 @@ function fixture(x=700,y=300,nativeMonitor=true,rounding=0) { whenReady:()=>({then:()=>({catch:()=>{}})})}; const layout=createDesktopRuntime({ window, - load:name=>name==='electron'?{app,screen:{getDisplayMatching:()=>({workArea:{x:0,y:0,width:1920,height:1080}}),screenToDipRect:(_window,rect)=>rect}}: + load:name=>name==='electron'?{app,screen:{getDisplayMatching:()=>({workArea:options.workArea || {x:0,y:0,width:1920,height:1080}}),screenToDipRect:(_window,rect)=>rect}}: name==='../server/config.cjs'?{dataDir:'fixture-data',port:4317,appInfo:()=>({})}: name==='../server/logging.cjs'?{installLogs(){}}: - name==='node:fs'?{mkdirSync:()=>{},readFileSync:()=>JSON.stringify(prefs),writeFileSync:()=>{},existsSync:()=>nativeMonitor}: + name==='node:fs'?{mkdirSync:()=>{},readFileSync:()=>JSON.stringify(prefs),writeFileSync:(file,text)=>{if(file.includes('preferences'))saved=JSON.parse(text);},existsSync:()=>nativeMonitor}: name==='node:child_process'?{spawn:(command,args,options)=>{const child=new EventEmitter();Object.assign(child,{command,args,options});child.stdout={};child.stderr={resume:()=>{}};child.kill=()=>{child.killed=true;};children.push(child);return child;}}: name==='node:readline'?{createInterface:({input})=>{const lines=new EventEmitter();lines.close=()=>{lines.closed=true;};input.lines=lines;return lines;}}: name.startsWith('./')?require('../desktop/'+name.slice(2)):require(name), @@ -29,7 +30,7 @@ function fixture(x=700,y=300,nativeMonitor=true,rounding=0) { }); function advance(ms=450){for(let elapsed=0;elapsed=timer.at){timers.delete(id);timer.callback();}}} function toggle(expanded){layout.changeExpanded(expanded);layout.show(true,true);} - return {layout,toggle,advance,updates,children,get top(){return top;},get bounds(){return {...bounds};},move:next=>{bounds={...bounds,...next};},get timers(){return timers.size;}}; + return {layout,toggle,advance,updates,children,get top(){return top;},get saved(){return saved;},get bounds(){return {...bounds};},move:next=>{bounds={...bounds,...next};},get timers(){return timers.size;}}; } test('show and mode switches leave the card in the normal window layer',()=>{ @@ -156,3 +157,63 @@ test('repeated expansion does not accumulate fractional-DPI rounding or overwrit } } }); + +test('compact and panel sizes resize live, persist independently and survive a restart',()=>{ + const f=fixture(); f.layout.resize('compact',304); + assert.deepEqual(f.bounds,{x:700,y:300,width:304,height:304}); + f.toggle(true); f.advance(); const origin={x:f.bounds.x,y:f.bounds.y}; + f.layout.resize('expanded',{width:600,height:820}); + assert.deepEqual(f.bounds,{...origin,y:Math.min(origin.y,260),width:600,height:820}); + assert.deepEqual(f.layout.state().panelSize,{width:582,height:802}); + assert.deepEqual(f.saved.panelSize,{width:600,height:820}); assert.equal(f.saved.compactSize,304); + for(let cycle=0;cycle<6;cycle++) { + f.toggle(false);f.advance();assert.deepEqual(f.bounds,{x:700,y:300,width:304,height:304}); + f.toggle(true);f.advance();assert.equal(f.bounds.width,600);assert.equal(f.bounds.height,820); + } + const restored=fixture(700,300,true,0,{prefs:f.saved}); restored.layout.show(); + assert.equal(restored.bounds.width,600); assert.equal(restored.bounds.height,820); + restored.toggle(false);restored.advance();assert.equal(restored.bounds.width,304); +}); + +test('size settings for the other view leave the current window untouched',()=>{ + const f=fixture();f.layout.show();const original=f.bounds; + f.layout.resize('expanded',{width:560,height:800});assert.deepEqual(f.bounds,original); + f.toggle(true);f.advance();const expanded=f.bounds; + f.layout.resize('compact',320);assert.deepEqual(f.bounds,expanded); + f.toggle(false);f.advance();assert.equal(f.bounds.width,320); +}); + +test('resizing a followed panel updates its offset without tracker snapback or fractional DPI creep',()=>{ + const f=fixture(700,300,true,1);f.layout.setFollow(true); + const tracker=f.children[0],anchor={found:true,visible:true,x:0,y:0,width:1600,height:1000}; + tracker.stdout.lines.emit('line',JSON.stringify(anchor));f.toggle(true);f.advance(); + f.layout.resize('expanded',{width:556,height:780});const resized=f.bounds; + for(let i=0;i<20;i++)tracker.stdout.lines.emit('line',JSON.stringify(anchor)); + assert.deepEqual(f.bounds,resized); + tracker.stdout.lines.emit('line',JSON.stringify({...anchor,x:15,y:10})); + assert.equal(f.bounds.x,resized.x+15);assert.equal(f.bounds.y,resized.y+10); +}); + +test('preferred panel size is validated and screen clamping never overwrites the saved preference',()=>{ + const workArea={x:0,y:0,width:480,height:600}; + const f=fixture(20,20,true,0,{workArea,prefs:{panelSize:{width:'bad',height:-5}}}); + assert.deepEqual(f.layout.state().preferredPanelSize,{width:432,height:400}); + f.toggle(true);f.advance();f.layout.resize('expanded',{width:2000,height:2000}); + assert.deepEqual(f.bounds,{x:0,y:0,width:480,height:600}); + assert.deepEqual(f.saved.panelSize,{width:960,height:1200}); + assert.deepEqual(f.layout.state().panelSize,{width:462,height:582}); + for(const value of [{width:NaN,height:600},{width:500,height:Infinity},null])assert.throws(()=>f.layout.resize('expanded',value)); + assert.throws(()=>f.layout.resize('compact','320')); + assert.deepEqual(f.saved.panelSize,{width:960,height:1200}); +}); + +test('compact resizing stays square when either screen dimension is smaller than the preferred card',()=>{ + for(const workArea of [{x:0,y:0,width:1000,height:300},{x:0,y:0,width:300,height:1000}]) { + const f=fixture(20,20,true,0,{workArea}); + f.layout.resize('compact',420); + assert.equal(f.bounds.width,300);assert.equal(f.bounds.height,300); + assert.equal(f.saved.compactSize,420,'Screen clamping must not replace the preferred size'); + for(let i=0;i<3;i++)f.layout.show(); + assert.equal(f.bounds.width,f.bounds.height); + } +}); diff --git a/tests/desktop-startup.test.js b/tests/desktop-startup.test.js new file mode 100644 index 0000000..09295e6 --- /dev/null +++ b/tests/desktop-startup.test.js @@ -0,0 +1,16 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { fileURLToPath } from 'node:url'; + +test('desktop startup preserves foreground requests, respects exit during startup, and resets position immediately', async () => { + const { stdout } = await promisify(execFile)(process.execPath, ['--experimental-vm-modules', fileURLToPath(new URL('./fixtures/desktop-startup.mjs', import.meta.url))], { + cwd: fileURLToPath(new URL('..', import.meta.url)), windowsHide: true, timeout: 10000, + }); + const results = JSON.parse(stdout); + assert.equal(results.length, 11); + assert.ok(results.filter(item => item.failure).every(item => item.stopCalls === 0 && item.exitReason === 'startup-failed')); + assert.ok(results.filter(item => item.afterStartup).every(item => item.afterStartup.visible && item.stopCalls === 1)); + assert.ok(results.filter(item => item.exitDuring).every(item => item.stopCalls === 1 && item.quitCalls === 1 && item.exitReason === 'user-quit')); +}); diff --git a/tests/fixtures/autostart-host.ps1 b/tests/fixtures/autostart-host.ps1 index 24381eb..60f07c7 100644 --- a/tests/fixtures/autostart-host.ps1 +++ b/tests/fixtures/autostart-host.ps1 @@ -1,8 +1,15 @@ -param([string]$Script, [string]$PluginRoot, [string]$Trace, [switch]$Disable) +param([string]$Script, [string]$PluginRoot, [string]$Trace, [switch]$Disable, [int]$WatcherPid = 0, [switch]$ExistingRegistry, [switch]$StopOnly, [string]$DataDir, [string]$ProcessRoot) $ErrorActionPreference = 'Stop' # Execute the complete installer with OS boundaries mocked. File writes stay in # the isolated fixture; registry and background launch operations are recorded. -function Get-Item { param($LiteralPath, $ErrorAction) if ($LiteralPath -notlike 'HKCU:*') { throw 'Unexpected Get-Item' }; return $null } +function Get-Item { + param($LiteralPath, $ErrorAction) + if ($LiteralPath -notlike 'HKCU:*') { throw 'Unexpected Get-Item' } + if (-not $ExistingRegistry) { return $null } + $item = [pscustomobject]@{} + $item | Add-Member ScriptMethod GetValue { param($name,$fallback) return 'powershell.exe desktop\watch-codex.ps1' } + return $item +} function Test-Path { param($LiteralPath, $Path) $candidate = if ($LiteralPath) { $LiteralPath } else { $Path } @@ -10,8 +17,38 @@ function Test-Path { return Microsoft.PowerShell.Management\Test-Path -LiteralPath $candidate } function New-ItemProperty { param($Path, $Name, $Value, $PropertyType, [switch]$Force) Add-Content -LiteralPath $Trace -Value ('registry:' + $Value) } -function Remove-ItemProperty { throw 'No existing registry item should be removed in this fixture' } +function Remove-ItemProperty { param($Path,$Name) if (-not $ExistingRegistry) { throw 'Unexpected registry removal' }; Add-Content -LiteralPath $Trace -Value 'registry-removed' } function Start-Process { param($FilePath, $ArgumentList, $WindowStyle) Add-Content -LiteralPath $Trace -Value ('launch:' + $ArgumentList) } -function Get-CimInstance { throw 'No process inspection should occur in this fixture' } -function Stop-Process { throw 'No process should be stopped in this fixture' } -& $Script -PluginRoot $PluginRoot -Disable:$Disable +function Get-CimInstance { + param($ClassName,$Filter) + if (-not $WatcherPid) { throw 'Unexpected process inspection' } + if ($Filter -like 'ParentProcessId=*') { return @() } + if ($Filter -ne "ProcessId=$WatcherPid") { throw 'Unexpected PID' } + Add-Content -LiteralPath $Trace -Value 'query' + $processPluginRoot = if ($ProcessRoot) { $ProcessRoot } else { $PluginRoot } + return [pscustomobject]@{ ProcessId=$WatcherPid; Name='continuer-monitor.exe'; ExecutablePath=(Join-Path $processPluginRoot 'desktop/continuer-monitor.exe'); CommandLine='fixture --watch' } +} +function Stop-Process { param($Id,$ErrorAction) if ($Id -ne $WatcherPid) { throw 'Unexpected stop' }; Add-Content -LiteralPath $Trace -Value 'stop' } +function New-Object { + param($ComObject) + if ($ComObject -ne 'WScript.Shell') { throw 'Unexpected COM object' } + $folders = [pscustomobject]@{ Root = (Join-Path $PluginRoot 'fixture-startup') } + $folders | Add-Member ScriptMethod Item { param($name) if ($name -ne 'Startup') { throw 'Unexpected folder' }; return $this.Root } + $shell = [pscustomobject]@{ SpecialFolders = $folders } + $shell | Add-Member ScriptMethod CreateShortcut { + param($path) + $shortcut = [pscustomobject]@{ Path=$path; TargetPath=''; Arguments=''; WorkingDirectory=''; Description=''; WindowStyle=0 } + if (Test-Path -LiteralPath $path) { + $saved = Get-Content -LiteralPath $path -Raw -Encoding UTF8 | ConvertFrom-Json + foreach ($name in @('TargetPath','Arguments','WorkingDirectory','Description','WindowStyle')) { $shortcut.$name = $saved.$name } + } + $shortcut | Add-Member ScriptMethod Save { + $this | ConvertTo-Json | Set-Content -LiteralPath $this.Path -Encoding UTF8 + Add-Content -LiteralPath $Trace -Value ('shortcut:' + $this.Arguments) + } + return $shortcut + } + return $shell +} +if ($StopOnly) { & $Script -PluginRoot $PluginRoot -DataDir $DataDir -Phase watcher } +else { & $Script -PluginRoot $PluginRoot -Disable:$Disable } diff --git a/tests/fixtures/desktop-startup.mjs b/tests/fixtures/desktop-startup.mjs new file mode 100644 index 0000000..2266d70 --- /dev/null +++ b/tests/fixtures/desktop-startup.mjs @@ -0,0 +1,74 @@ +import assert from 'node:assert/strict'; +import vm from 'node:vm'; +import { EventEmitter } from 'node:events'; +import { createRequire } from 'node:module'; +import { join, resolve } from 'node:path'; +import * as fs from 'node:fs'; +const require=createRequire(import.meta.url), repo=process.cwd(), out=resolve('.cache/isolated-desktop-fixture'); +const deferred=()=>{let resolve,reject;const promise=new Promise((yes,no)=>{resolve=yes;reject=no;});return {promise,resolve,reject};}; +async function scenario(hidden,automatic=false,failure=false,reopen=null,exitDuring=null){ +const handlers=new Map(),workArea={x:0,y:0,width:1920,height:1080},trace=[]; +const startGate=deferred(),stopGate=deferred();let ensureCalls=0; +let win,menu,lastStatus,identity,stopCalls=0,quitCalls=0;let saved={follow:false,expanded:false,hidden,compactSize:256,positions:{},offsets:{}}; +const app=new EventEmitter();Object.assign(app,{setName(){},setPath(){},requestSingleInstanceLock:value=>{identity=value;return true;},whenReady:()=>Promise.resolve(),quit(){quitCalls++;app.emit('before-quit',{preventDefault(){}});}}); +class Window extends EventEmitter { + constructor(options){super();win=this;this.bounds={x:options.x,y:options.y,width:options.width,height:options.height};this.visible=false;this.webContents=new EventEmitter();Object.assign(this.webContents,{id:1,setWindowOpenHandler(){},send(){},session:{setPermissionRequestHandler(){},setCertificateVerifyProc(){},webRequest:{onBeforeSendHeaders(){}}}});} + getBounds(){return {...this.bounds};} setBounds(b){this.bounds={...b};trace.push({setBounds:b});} + isDestroyed(){return false;}isVisible(){return this.visible;}isFocused(){return !!this.focused;}showInactive(){this.visible=true;}hide(){this.visible=false;}focus(){this.focused=true;} + async loadURL(){this.loaded=true;if(failure)throw Error('Mock page load failure');} +} +class Tray extends EventEmitter {setToolTip(){}setContextMenu(){}destroy(){}} +const mocks={ + electron:{app,BrowserWindow:Window,screen:{on(){},getPrimaryDisplay:()=>({workArea}),getDisplayMatching:()=>({workArea})},ipcMain:{handle:(name,fn)=>handlers.set(name,fn)},Tray,Menu:{buildFromTemplate:items=>{menu=items;return {popup(){}};}},nativeImage:{createFromPath:()=>({})},dialog:{showErrorBox:()=>{}},globalShortcut:{register(){},unregisterAll(){}}}, + '../server/config.cjs':{dataDir:join(out,'mock-window-data'),port:4317,appInfo:()=>({version:'0.7.0'})}, + '../server/logging.cjs':{installLogs(){}},'../server/local-tls.cjs':{readIdentity:()=>({certificate:'mock'}),matchesCertificate:()=>false}, + 'node:fs':{mkdirSync(){},readFileSync:()=>JSON.stringify(saved),writeFileSync:(file,text)=>{if(String(file).endsWith('widget-preferences.json'))saved=JSON.parse(text);else if(String(file).endsWith('widget-status.json'))lastStatus=JSON.parse(text);},existsSync:()=>false}, + 'node:child_process':{spawn(){throw Error('Unexpected process launch');}}, +}; +const context=vm.createContext({console,setImmediate,setTimeout,clearTimeout,__dirname:join(repo,'desktop')}); +const script=new vm.Script('(function(module){'+fs.readFileSync(join(repo,'desktop/runtime.cjs'),'utf8')+'\n})',{filename:join(repo,'desktop/runtime.cjs'),importModuleDynamically:async name=>{ + const values=name==='../public/i18n.js'?{interfaceText:id=>id}:name==='../plugin/runtime.js'?{ensureService:async()=>{ensureCalls++;if(exitDuring?.startsWith('service'))await startGate.promise;},stopBackground:async()=>{stopCalls++;if(exitDuring)await stopGate.promise;}}:null;if(!values)throw Error('Unexpected import '+name); + const m=new vm.SyntheticModule(Object.keys(values),function(){for(const[k,v]of Object.entries(values))this.setExport(k,v);},{context});await m.link(()=>{});await m.evaluate();return m; +}}); +const mod={exports:{}};script.runInContext(context)(mod); +const runtime=mod.exports.createDesktopRuntime({load:name=>mocks[name]??(name.startsWith('.')?require(join(repo,'desktop',name)):require(name)),processInfo:{env:{},argv:automatic?['--auto']:[],pid:1,platform:'win32'}}); +if(reopen==='before-window')app.emit('second-instance',{},[],repo,identity); +if(exitDuring?.startsWith('service')){ + for(let i=0;i<100&&!ensureCalls;i++)await new Promise(r=>setTimeout(r,5));assert.equal(ensureCalls,1); + app.emit('second-instance',{},['--quit'],repo,identity); + for(let i=0;i<100&&!stopCalls;i++)await new Promise(r=>setTimeout(r,5));assert.equal(stopCalls,1); + if(exitDuring==='service-error')startGate.reject(Error('Startup cancelled'));else startGate.resolve(); + await new Promise(r=>setTimeout(r,20));assert.equal(win,undefined,'quit cancels the pending window creation');assert.equal(quitCalls,0,'startup callbacks must not interrupt background shutdown'); + stopGate.resolve();await new Promise(r=>setTimeout(r,20));assert.equal(lastStatus.exitReason,'user-quit'); + return {exitDuring,stopCalls,quitCalls,exitReason:lastStatus.exitReason}; +} +for(let i=0;i<100&&!win?.loaded;i++)await new Promise(r=>setTimeout(r,10)); +assert.ok(win.loaded); +const event={sender:win.webContents,senderFrame:{url:'https://127.0.0.1:4317/widget'}},control=(action,value)=>handlers.get('continuer:control')(event,action,value); +await new Promise(r=>setTimeout(r,20)); +if(failure){assert.equal(stopCalls,0);assert.equal(quitCalls,1);assert.equal(lastStatus.exitReason,'startup-failed');return {failure,stopCalls,quitCalls,exitReason:lastStatus.exitReason};} +if(exitDuring==='renderer'){ + app.emit('second-instance',{},['--quit'],repo,identity); + for(let i=0;i<100&&!stopCalls;i++)await new Promise(r=>setTimeout(r,5));assert.equal(stopCalls,1); + control('renderer-ready');menu.find(item=>item.label==='native.open_quota_and_work_panel').click(); + assert.equal(win.visible,false,'late readiness and tray clicks must not reveal an exiting window');assert.equal(lastStatus.ready,false); + stopGate.resolve();await new Promise(r=>setTimeout(r,20));assert.equal(lastStatus.exitReason,'user-quit'); + return {exitDuring,stopCalls,quitCalls,exitReason:lastStatus.exitReason}; +} +if(reopen==='before-renderer')app.emit('second-instance',{},[],repo,identity); +if(reopen==='tray-before-renderer')menu.find(item=>item.label==='native.open_quota_and_work_panel').click(); +control('renderer-ready');const afterStartup=runtime.state(); +assert.equal(afterStartup.hidden,false);assert.equal(afterStartup.visible,true); +if(reopen){assert.equal(win.focused,true,'manual reveal must survive renderer startup');assert.equal(afterStartup.expanded,true);control('expand',false);runtime.finishTransition();} +win.bounds={x:650,y:240,width:256,height:256};runtime.savePosition();control('reset-position'); +assert.deepEqual(win.getBounds(),{x:1648,y:808,width:256,height:256}); +const reset=win.getBounds(); +win.bounds={x:700,y:300,width:256,height:256};runtime.savePosition();menu.find(item=>item.label==='ui.reset_widget_position').click();assert.deepEqual(win.getBounds(),reset); +control('quit');await new Promise(r=>setTimeout(r,20));assert.equal(stopCalls,1);assert.equal(lastStatus.exitReason,'user-quit'); +return {savedHidden:hidden,automatic,reopen,afterStartup,reset,stopCalls,exitReason:lastStatus.exitReason}; +} +const results=[]; +for(const [hidden,automatic,failure] of [[true,false,false],[true,true,false],[false,false,false],[false,true,true],[false,false,true]])results.push(await scenario(hidden,automatic,failure)); +for(const reopen of ['before-window','before-renderer','tray-before-renderer'])results.push(await scenario(true,true,false,reopen)); +for(const exitDuring of ['service','service-error','renderer'])results.push(await scenario(false,false,false,null,exitDuring)); +console.log(JSON.stringify(results)); diff --git a/tests/fixtures/hidden-widget.cjs b/tests/fixtures/hidden-widget.cjs new file mode 100644 index 0000000..5502b82 --- /dev/null +++ b/tests/fixtures/hidden-widget.cjs @@ -0,0 +1,15 @@ +const electron = require('electron'); +const { createRequire } = require('node:module'); +const path = require('node:path'); +if (process.env.CONTINUER_DEMO !== '1' || !process.env.CONTINUER_DATA_DIR) throw Error('Isolated demo configuration required'); +const load = createRequire(path.resolve(__dirname, '../../desktop/main.cjs')); +const { createDesktopRuntime } = load('./runtime.cjs'); +// Exercise a deliberate hide through the production handler before readiness. +// A saved hidden preference alone no longer hides a manual cold start. +const ipcMain = { handle(name, handler) { + electron.ipcMain.handle(name, (event, action, value) => { + if (name === 'continuer:control' && action === 'renderer-ready') handler(event, 'hide'); + return handler(event, action, value); + }); +} }; +createDesktopRuntime({ load: name => name === 'electron' ? { ...electron, ipcMain } : load(name) }); diff --git a/tests/fixtures/interaction-recovery-ui.cjs b/tests/fixtures/interaction-recovery-ui.cjs new file mode 100644 index 0000000..05e4327 --- /dev/null +++ b/tests/fixtures/interaction-recovery-ui.cjs @@ -0,0 +1,157 @@ +const { app, BrowserWindow } = require('electron'); +const { createServer } = require('node:http'); +const fs = require('node:fs'); +const path = require('node:path'); +const assert = require('node:assert/strict'); +const root = path.resolve(__dirname, '../..'), out = process.env.CONTINUER_INTERACTION_TEST_DIR; +if(!out) throw Error('Isolated test directory required'); +app.setPath('userData', path.join(out, 'isolated-profile')); +app.on('window-all-closed', () => {}); +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const result = { version: '0.7.0', scenarios: [], errors: [] }; +let win, server, state, fullTask, failSettings=false, failDetail=false, pending = [], apiCalls = []; +function initial() { + return { instanceId:'first-service',snapshotRevision:1,app:'codex-continuer',version:'0.7.0',buildId:'round1-isolated',protocolVersion:4, + settings:{enabled:false,language:'zh',pollSeconds:30,minimumRemaining:5,maxRounds:20,maxWakeSends:20}, + connection:{status:'connected'},sampledAt:Date.now(),quota:{rateLimits:{primary:{usedPercent:20,windowDurationMins:300},secondary:{usedPercent:30,windowDurationMins:10080}}}, + tasks:[{id:'work',mode:'direct',name:'审查示例工作',cwd:'E:\\fixture',prompt:'仅模拟,不执行真实工作',status:'paused',continuous:false,rounds:1,detailRevision:1, + plan:[],output:Array.from({length:100},(_,i)=>`第 ${i+1} 行:用于检查阅读位置与文本选择。`).join('\n')}], + approvals:[],logs:[],history:[],diagnostics:{autostart:{enabled:false}},persistence:{status:'ok'} }; +} +const response = (res,value) => { res.writeHead(200,{'Content-Type':'application/json'});res.end(JSON.stringify(value)); }; +async function record(name,details) { result.scenarios.push({name,...details});fs.writeFileSync(path.join(out,'ui-results.json'),JSON.stringify(result,null,2)); } +app.whenReady().then(async()=>{ + try { + const {createStaticAssets}=await import('../../server/static-assets.js'); + const serve=createStaticAssets(root); + server=createServer(async(req,res)=>{ + const url=new URL(req.url,'http://127.0.0.1'); + if(url.pathname.startsWith('/fixture/')) {res.writeHead(200,{'Content-Type':'text/html'});res.end('');return;} + if(url.pathname.startsWith('/api/')) { + let body='';for await(const part of req) body+=part; + apiCalls.push({path:url.pathname,body}); + if(url.pathname==='/api/tasks' && req.method==='POST') {pending.push({res,value:structuredClone(state)});return;} + if(url.pathname==='/api/settings'){ if(failSettings){res.writeHead(500,{'Content-Type':'application/json'});res.end(JSON.stringify({error:'Simulated save failure'}));return;} Object.assign(state.settings,JSON.parse(body));state.snapshotRevision++; } + if(url.pathname==='/api/threads'){const start=Number(url.searchParams.get('cursor')||0),end=Math.min(start+30,301);return response(res,{data:Array.from({length:end-start},(_,i)=>({id:'chat-'+(start+i+1),name:'Chat '+(start+i+1)})),nextCursor:end<301?String(end):null});} + if(url.pathname==='/api/tasks/work'){if(failDetail){res.writeHead(500,{'Content-Type':'application/json'});res.end(JSON.stringify({error:'Simulated detail failure'}));return;}return response(res,{task:fullTask||state.tasks[0]});} + return response(res,state); + } + if(await serve(req,res,url)) return; + res.writeHead(404);res.end(); + }); + await new Promise(resolve=>server.listen(0,'127.0.0.1',resolve)); + for(const surface of ['page','widget']) { + state=initial();fullTask=null;failSettings=false;failDetail=false;pending=[];apiCalls=[]; + win=new BrowserWindow({show:false,width:surface==='page'?1180:432,height:surface==='page'?880:720, + webPreferences:{sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false,offscreen:true}}); + win.webContents.on('console-message',d=>{if(d.level==='error') result.errors.push(d.message);}); + await win.loadURL(`http://127.0.0.1:${server.address().port}/fixture/${surface}`); + win.webContents.debugger.attach(); + const send=(method,params)=>win.webContents.debugger.sendCommand(method,params); + const {result:object}=await send('Runtime.evaluate',{expression:'globalThis'}); + const parsed=await send('Runtime.callFunctionOn',{objectId:object.objectId, + functionDeclaration:`function(html){const d=new DOMParser().parseFromString(html,'text/html');d.querySelectorAll('script').forEach(s=>s.remove());document.documentElement.replaceWith(document.importNode(d.documentElement,true));}`, + arguments:[{value:fs.readFileSync(path.join(root,'public',surface==='page'?'index.html':'widget.html'),'utf8')}]}); + assert.equal(parsed.exceptionDetails,undefined);win.webContents.debugger.detach(); + const ev=code=>win.webContents.executeJavaScript(code); + const until=async code=>{for(let i=0;i<100;i++){if(await ev(code))return;await sleep(30);}throw Error('Timeout: '+code);}; + const feed=()=>{state.snapshotRevision++;return ev(`window.testFeed.onmessage({data:${JSON.stringify(JSON.stringify(state))}})`);}; + await ev(`(async()=>{Object.defineProperty(document,'hidden',{value:false,configurable:true}); + window.createSource=()=>{const s={close(){}};window.testFeed=s;setTimeout(()=>s.onmessage({data:${JSON.stringify(JSON.stringify(state))}}),0);return s;}; + ${surface==='widget'?`const desktop={expanded:true,visible:true,follow:false,compactSize:256,panelSize:{width:414,height:702}};window.continuerDesktop={onState(c){window.desktopListener=c;},async control(){return {...desktop};}};`:''} + await import('/${surface==='page'?'app':'widget'}.js');})()`); + await until("!!document.querySelector('[data-action=detail]')");await sleep(250); + fs.writeFileSync(path.join(out,`${surface}-overview.png`),(await win.webContents.capturePage()).toPNG()); + await ev("document.querySelector('[data-action=detail]').click()"); + await until("!!document.querySelector('#modal pre') && document.querySelector('#modal pre').textContent.includes('第 100 行')"); + const before=await ev(`(()=>{const p=document.querySelector('#modal pre');window.oldOutput=p;p.scrollTop=300;const r=document.createRange();r.setStart(p.firstChild,0);r.setEnd(p.firstChild,20);const s=getSelection();s.removeAllRanges();s.addRange(r);return {scroll:p.scrollTop,selection:s.toString()};})()`); + state.logs=[{id:'update',time:Date.now(),message:'Unrelated refresh',type:'info'}];await feed(); + const after=await ev("({scroll:document.querySelector('#modal pre').scrollTop,selection:getSelection().toString(),sameNode:window.oldOutput===document.querySelector('#modal pre')})"); + assert.equal(after.sameNode,true);assert.equal(after.scroll,before.scroll);assert.equal(after.selection,before.selection); + state.tasks[0].output+='\nNew output after the reading position';state.tasks[0].detailRevision++;await feed(); + await until("document.querySelector('#modal pre').textContent.includes('New output after the reading position')"); + assert.equal(await ev("document.querySelector('#modal pre').scrollTop"),before.scroll); + assert.equal(await ev("getSelection().toString()"),before.selection); + await record('detail-reading-preserved',{surface,before,after}); + const close=async()=>{await ev("document.querySelector('#modal').close()");await sleep(40);}; + await close(); + await ev("document.querySelector('[data-action=new]').click();document.querySelector('[name=name]').value='first';document.querySelector('[name=cwd]').value='E:\\fixture';document.querySelector('[name=prompt]').value='mock';document.querySelector('#modal form').requestSubmit()"); + for(let i=0;i<100&&!pending.length;i++)await sleep(20);assert.equal(pending.length,1); + await close();await ev("document.querySelector('[data-action=new]').click();document.querySelector('[name=name]').value='second draft'"); + state.settings.enabled=true;state.tasks.push({id:'newer',name:'New live record',mode:'direct',status:'paused',rounds:0});await feed(); + const old=pending.shift();response(old.res,old.value);await sleep(150); + assert.equal(await ev("document.querySelector('#modal').open"),true); + assert.equal(await ev("document.querySelector('[name=name]').value"),'second draft'); + assert.equal(await ev("!!document.querySelector('[data-action=detail][data-id=newer]')"),true); + await record('old-save-keeps-new-draft-and-live-state',{surface});await close(); + await ev("document.querySelector('[data-action=new]').click();document.querySelector('[name=name]').value='slow';document.querySelector('[name=cwd]').value='E:\\fixture';document.querySelector('[name=prompt]').value='mock';document.querySelector('#modal form').requestSubmit()"); + for(let i=0;i<100&&!pending.length;i++)await sleep(20);assert.equal(pending.length,1); + state.settings.language='en';await feed(); + assert.equal(await ev("document.querySelector('#modal [type=submit]').disabled"),true); + // requestSubmit also exercises the handler guard, independently of disabled UI. + await ev("document.querySelector('#modal form').requestSubmit()");await sleep(100);assert.equal(pending.length,1); + const saved=pending.shift();response(saved.res,state);await sleep(100); + assert.equal(await ev("document.querySelector('#modal').open"),false); + await record('language-retains-submission-lock',{surface}); + state.settings.language='zh';await feed(); + if(surface==='page') { + await ev("document.querySelector('[data-page=settings]').click()"); + await ev("document.querySelector('[name=minimumRemaining]').value='17'"); + state.connection={status:'disconnected',message:'Mock disconnect'};await feed(); + assert.equal(await ev("document.querySelector('#settings-connection').textContent"),'未连接'); + assert.equal(await ev("document.querySelector('[name=minimumRemaining]').value"),'17'); + failSettings=true;await ev("document.querySelector('#settings-form').requestSubmit()"); + await until("document.querySelector('#settings-error').textContent.includes('Simulated save failure')"); + failSettings=false;await ev("document.querySelector('#settings-form').requestSubmit()"); + await until("!document.querySelector('#settings-form [type=submit]').disabled"); + assert.equal(await ev("document.querySelector('#settings-error').textContent"),''); + await record('settings-live-status-and-error-recovery',{surface}); + await ev("document.querySelector('[data-page=overview]').click()"); + } + // The final server page remains reachable after the 300-chat window fills. + if(surface==='page') { + await ev("document.querySelector('[data-action=import]').click()"); + await until("document.querySelectorAll('.thread-option').length===30"); + for(let i=0;i<12;i++){ + if(!await ev("!!document.querySelector('[data-action=more-threads]')"))break; + await ev("document.querySelector('[data-action=more-threads]').click()"); + await until("!document.querySelector('[data-action=more-threads]') || !document.querySelector('[data-action=more-threads]').disabled"); + } + assert.equal(await ev("!!document.querySelector('[data-id=chat-301]')"),true);await close(); + } else { + for(let i=0;i<12;i++){ + if(await ev("document.querySelector('#session-more').hidden"))break; + await ev("document.querySelector('#session-more').click()"); + await until("document.querySelector('#session-more').hidden || !document.querySelector('#session-more').disabled"); + } + assert.equal(await ev("!!document.querySelector('option[value=chat-301]')"),true); + } + await record('older-chat-reachable',{surface}); + fullTask={id:'work',mode:'quota-wake',name:'Monitor',status:'paused',note:'Local note',continuationMessage:'Old saved message',completionMessage:'Separate completion',detailInstanceId:'first-service',detailRevision:1}; + state.tasks=[{id:'work',mode:'quota-wake',name:'Monitor',status:'paused',notePreview:'Local note',detailInstanceId:'first-service',detailRevision:1}]; + failDetail=true;await feed();await ev("document.querySelector('[data-action=detail]').click()");await sleep(150); + assert.equal(await ev("document.querySelector('[data-action=edit-message]').disabled"),true); + assert.equal(await ev("document.querySelector('#modal-body').textContent.includes('完整详情尚未加载')"),true); + assert.equal(await ev("document.querySelector('#modal-body').textContent.includes('备注未填写')"),false); + await close();failDetail=false;await ev("document.querySelector('[data-action=detail]').click()"); + await until("!document.querySelector('[data-action=edit-message]').disabled"); + await ev("window.testFeed.onerror(new Error('Mock disconnect'))"); + state.instanceId='restarted-service';state.snapshotRevision=0;state.tasks[0].detailInstanceId=state.instanceId; + fullTask={...fullTask,detailInstanceId:state.instanceId,continuationMessage:'New persisted message'}; + await feed();await until("document.querySelector('#modal-body').textContent.includes('New persisted message')"); + await ev("document.querySelector('[data-action=edit-message]').click()"); + assert.equal(await ev("document.querySelector('[name=continuationMessage]').value"),'New persisted message'); + await record('missing-and-restarted-details',{surface});await close(); + if(surface==='widget'){ + state.connection={status:'connected'};state.sampledAt=Date.now();state.quota={rateLimits:{primary:{usedPercent:20,windowDurationMins:60}}}; + await ev("window.desktopListener({expanded:false,visible:true,follow:false,compactSize:256,panelSize:{width:414,height:702}})");await feed(); + assert.equal(await ev("document.querySelector('#mini-window').textContent"),'1小时可用额度'); + await record('actual-quota-period',{surface}); + } + win.destroy();win=null; + } + result.completed=true; + }catch(error){result.error=error.stack;process.exitCode=1;} + finally{win?.destroy();for(const item of pending)item.res.destroy();if(server)await new Promise(resolve=>server.close(resolve));fs.writeFileSync(path.join(out,'ui-results.json'),JSON.stringify(result,null,2));app.exit(process.exitCode||0);} +}); +setTimeout(()=>{fs.writeFileSync(path.join(out,'ui-timeout.json'),JSON.stringify(result,null,2));app.exit(2);},45000); diff --git a/tests/fixtures/review4-ui.cjs b/tests/fixtures/review4-ui.cjs index 6b1f6c4..ac14065 100644 --- a/tests/fixtures/review4-ui.cjs +++ b/tests/fixtures/review4-ui.cjs @@ -9,7 +9,7 @@ app.setPath('userData', path.join(directory, 'profile')); app.on('window-all-closed', () => {}); const root = path.resolve(__dirname, '../..'), threadId = '77777777-7777-4777-8777-777777777777'; const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); -const initial = () => ({ app: 'codex-continuer', version: '0.5.1', buildId: 'fixture', protocolVersion: 4, +const initial = () => ({ app: 'codex-continuer', version: '0.7.0', buildId: 'fixture', protocolVersion: 4, settings: { enabled: false, language: 'zh', pollSeconds: 30, minimumRemaining: 5, maxRounds: 20, maxWakeSends: 8 }, connection: { status: 'connected' }, tasks: [], approvals: [], history: [], logs: [] }); let win, server, state = initial(); @@ -29,9 +29,19 @@ app.whenReady().then(async () => { if (url.pathname === '/api/import') { const input = JSON.parse(body); imports.push(input); state.tasks.push({ id: 'fixture-monitor', threadId, name: 'Fixture chat', mode: 'quota-wake', + continuationMessage: input.continuationMessage, completionMonitoring: input.completionMonitoring, completionMessage: input.completionMessage, + quotaMonitoring:input.quotaMonitoring,completionRepeat:input.completionRepeat,completionMaxSends:input.completionMaxSends,completionSends:0, continuous: input.startMonitoring, status: input.startMonitoring ? 'monitoring' : 'paused', sentCount: 0, detailRevision: 1 }); } - const result = url.pathname === '/api/threads' ? { data: [{ id: threadId, name: 'Fixture chat', cwd: 'E:\\fixture' }], nextCursor: null } : state; + if (url.pathname === '/api/tasks/fixture-monitor' && req.method === 'POST') { + const input = JSON.parse(body); + if(input.action==='quota-monitoring')state.tasks[0].quotaMonitoring=input.value; + else if(input.action==='completion-monitoring')state.tasks[0].completionMonitoring=input.value; + else {assert.equal(input.action,'completion');Object.assign(state.tasks[0], { completionMonitoring: input.value.enabled, completionMessage: input.value.message, quotaMonitoring:input.value.quotaMonitoring,completionRepeat:input.value.repeat,completionMaxSends:input.value.maxSends });} + state.tasks[0].detailRevision++; + } + const result = url.pathname === '/api/tasks/fixture-monitor' && req.method === 'GET' ? { task: state.tasks[0] } + : url.pathname === '/api/threads' ? { data: [{ id: threadId, name: 'Fixture chat', cwd: 'E:\\fixture' }], nextCursor: null } : state; res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(result)); return; } try { if (await serve(req, res, url)) return; } catch {} @@ -96,16 +106,51 @@ app.whenReady().then(async () => { } await until("!!document.querySelector('#import-form [name=startMonitoring]')"); assert.equal(await evaluate("document.querySelector('[name=startMonitoring]').checked"), false); + assert.equal(await evaluate("document.querySelector('[name=completionMonitoring]').checked"), false); + assert.equal(await evaluate("document.querySelector('[name=quotaMonitoring]').checked"), true); + assert.equal(await evaluate("document.querySelector('[name=completionRepeat]').checked"), false); assert.equal(await evaluate("document.querySelector('[name=startMonitoring]').parentElement.textContent.includes('加入后开始监测')"), true); await evaluate("document.querySelector('[name=startMonitoring]').checked=true; document.querySelector('[name=note]').value='Local note'; document.querySelector('[name=continuationMessage]').value='Continue this'"); + await evaluate("document.querySelector('[name=completionMonitoring]').checked=true; document.querySelector('[name=completionMessage]').value='下一项工作'"); + await evaluate("document.querySelector('[name=quotaMonitoring]').checked=false;document.querySelector('[name=completionRepeat]').checked=true;document.querySelector('[name=completionMaxSends]').value='3'"); assert.equal(await evaluate("document.querySelector('[name=startMonitoring]').getClientRects().length > 0"), true); state.settings.language = 'en'; await feed(); assert.equal(await evaluate("document.querySelector('[name=startMonitoring]').checked"), true); + assert.equal(await evaluate("document.querySelector('[name=completionMonitoring]').checked"), true); + assert.equal(await evaluate("document.querySelector('[name=completionMessage]').value"), '下一项工作'); + assert.equal(await evaluate("document.querySelector('[name=quotaMonitoring]').checked"), false); + assert.equal(await evaluate("document.querySelector('[name=completionRepeat]').checked"), true); + assert.equal(await evaluate("document.querySelector('[name=completionMaxSends]').value"), '3'); assert.equal(await evaluate("document.querySelector('[name=startMonitoring]').parentElement.textContent.includes('Start monitoring after adding')"), true); await evaluate("document.querySelector('#import-form').requestSubmit()"); await until("!document.querySelector('#modal').open"); assert.equal(imports.length, 1); - assert.deepEqual(imports[0], { threadId, note: 'Local note', continuationMessage: 'Continue this', startMonitoring: true }); + assert.deepEqual(imports[0], { threadId, note: 'Local note', continuationMessage: 'Continue this', startMonitoring: true, completionMonitoring: true, completionMessage: '下一项工作',quotaMonitoring:false,completionRepeat:true,completionMaxSends:3 }); + await evaluate("document.querySelector('[data-action=detail][data-id=fixture-monitor]').click()"); + await until("!!document.querySelector('[data-action=edit-completion]:not(:disabled)')"); + await evaluate("document.querySelector('[data-action=edit-completion]').click()"); + await until("!!document.querySelector('#completion-form')"); + assert.equal(await evaluate("document.querySelector('[name=completionMessage]').value"), '下一项工作'); + await evaluate("document.querySelector('[name=completionMonitoring]').checked=false; document.querySelector('[name=completionMessage]').value='Edited final follow-up'"); + await evaluate("document.querySelector('[name=completionRepeat]').checked=false;document.querySelector('[name=completionMaxSends]').value='2'"); + state.settings.language = 'zh'; await feed(); + assert.equal(await evaluate("document.querySelector('[name=completionMonitoring]').checked"), false); + assert.equal(await evaluate("document.querySelector('[name=completionMessage]').value"), 'Edited final follow-up'); + assert.equal(await evaluate("document.querySelector('[name=completionRepeat]').checked"), false); + assert.equal(await evaluate("document.querySelector('[name=completionMaxSends]').value"), '2'); + await evaluate("document.querySelector('#completion-form').requestSubmit()"); + await until("!document.querySelector('#modal').open"); + assert.equal(state.tasks[0].completionMessage, 'Edited final follow-up'); + assert.equal(state.tasks[0].completionMonitoring, false); assert.equal(state.tasks[0].continuationMessage, 'Continue this'); + assert.equal(state.tasks[0].completionRepeat,false);assert.equal(state.tasks[0].completionMaxSends,2);assert.equal(state.tasks[0].quotaMonitoring,false); + for(const [action,field,value] of [['quota-monitoring','quotaMonitoring',true],['completion-monitoring','completionMonitoring',true],['quota-monitoring','quotaMonitoring',false]]){ + const selector=surface==='page'?`[data-action="${action}"]`:`[data-monitor="${action}"]`; + await evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`); + for(let i=0;i<100 && state.tasks[0][field]!==value;i++)await delay(20); + assert.equal(state.tasks[0][field],value); + await until(surface==='page'?`document.querySelector(${JSON.stringify(selector)}).getAttribute('aria-checked')==='${value}'`:`document.querySelector(${JSON.stringify(selector)}).checked===${value}`); + } + assert.equal(state.tasks[0].completionMonitoring,true,'Turning quota off must retain the reply monitor'); results.push({ surface, import: imports[0], defaultPaused: true, checkboxPreservedAcrossLanguage: true }); win.destroy(); win = null; } diff --git a/tests/fixtures/widget-instance.cjs b/tests/fixtures/widget-instance.cjs index a8273e0..95a66f9 100644 --- a/tests/fixtures/widget-instance.cjs +++ b/tests/fixtures/widget-instance.cjs @@ -32,6 +32,9 @@ const layout = createDesktopRuntime({ name === '../server/logging.cjs' ? { installLogs() {} } : name === 'node:fs' ? { mkdirSync() {}, readFileSync: () => JSON.stringify(preferences), writeFileSync() {}, existsSync: () => false } : load(name), }); +// Manual startup now reveals the widget. Simulate hiding the already opened +// owner before checking whether a mismatched second instance can reveal it. +layout.preferences.hidden = true; electron.app.whenReady().then(() => { record.ready = true; persist(); }); const stop = path.join(directory, mode + '.stop'); setInterval(() => { if (fs.existsSync(stop)) electron.app.exit(0); }, 50); diff --git a/tests/fixtures/window-expansion.cjs b/tests/fixtures/window-expansion.cjs index c536adc..82977c0 100644 --- a/tests/fixtures/window-expansion.cjs +++ b/tests/fixtures/window-expansion.cjs @@ -42,7 +42,16 @@ app.whenReady().then(async () => { layout.changeExpanded(false); layout.show(true, true); await delay(); const compact = native.getBounds(); closeTo(compact.x, origin.x); closeTo(compact.y, origin.y); } - cases.push({ compact: origin, expanded: firstExpanded, cycles: 12 }); + layout.resize('compact',288);await delay(); + const resizedCompact=native.getBounds();closeTo(resizedCompact.width,288);closeTo(resizedCompact.height,288); + layout.changeExpanded(true);layout.show(true,true);await delay(); + layout.resize('expanded',{width:560,height:760});await delay(); + const resizedPanel=native.getBounds();closeTo(resizedPanel.width,Math.min(560,work.width));closeTo(resizedPanel.height,Math.min(760,work.height)); + layout.changeExpanded(false);layout.show(true,true);await delay(); + closeTo(native.getBounds().width,288);closeTo(native.getBounds().x,resizedCompact.x);closeTo(native.getBounds().y,resizedCompact.y); + layout.changeExpanded(true);layout.show(true,true);await delay(); + closeTo(native.getBounds().width,resizedPanel.width);closeTo(native.getBounds().height,resizedPanel.height); + cases.push({ compact: origin, expanded: firstExpanded, resizedCompact, resizedPanel, cycles: 12 }); native.destroy(); } fs.writeFileSync(path.join(directory, 'result.json'), JSON.stringify({ passed: true, cases })); diff --git a/tests/import-http.test.js b/tests/import-http.test.js index e47cc15..305ca6d 100644 --- a/tests/import-http.test.js +++ b/tests/import-http.test.js @@ -116,6 +116,25 @@ test('HTTP and MCP imports share one reservation and persist one recovery delive await assert.rejects(request('/api/import', { threadId: 'not-read', startMonitoring: 'on' }), /开关/); await assert.rejects(request('/api/import', { threadId: 'not-read', startMonitoring: null }), /开关/); await assert.rejects(dispatch('continuer_import_session', { threadId: 'not-read', startMonitoring: true }, runtime), /startMonitoring/); + const completionImport = await request('/api/import', { threadId: '55555555-5555-4555-8555-555555555555', continuationMessage: '额度消息', completionMonitoring: true, completionMessage: '回答结束后继续', quotaMonitoring:false,completionRepeat:true,completionMaxSends:3 }); + const completionTask = completionImport.tasks.find(task => task.threadId === '55555555-5555-4555-8555-555555555555'); + assert.equal(completionTask.completionMonitoring, true); assert.equal(completionTask.continuous, false); + assert.equal(completionTask.quotaMonitoring,false);assert.equal(completionTask.completionRepeat,true);assert.equal(completionTask.completionMaxSends,3); + assert.equal(completionTask.completionMessage, undefined); + const completionDetail = (await request(`/api/tasks/${completionTask.id}`)).task; + assert.equal(completionDetail.completionMessage, '回答结束后继续'); assert.equal(completionDetail.continuationMessage, '额度消息'); + await request(`/api/tasks/${completionTask.id}`, { action: 'completion', value: { enabled: false, message: '已编辑\n下一项' } }); + const completionStored = JSON.parse(readFileSync(join(dataDir, 'demo-state.json'), 'utf8')).tasks.find(task => task.id === completionTask.id); + assert.equal(completionStored.completionMonitoring, false); assert.equal(completionStored.completionMessage, '已编辑\n下一项'); + assert.equal(completionStored.continuationMessage, '额度消息'); assert.equal(completionStored.continuous, false); + assert.equal(completionStored.quotaMonitoring,false);assert.equal(completionStored.completionRepeat,true);assert.equal(completionStored.completionMaxSends,3); + await request(`/api/tasks/${completionTask.id}`,{action:'quota-monitoring',value:true}); + assert.equal((await request(`/api/tasks/${completionTask.id}`)).task.completionMonitoring,false); + await request(`/api/tasks/${completionTask.id}`,{action:'completion-monitoring',value:true}); + const independent=(await request(`/api/tasks/${completionTask.id}`)).task; + assert.equal(independent.quotaMonitoring,true);assert.equal(independent.completionMonitoring,true);assert.equal(independent.continuous,false); + await assert.rejects(request('/api/import', { threadId: 'not-read', completionMonitoring: 'on' }), /开关/); + await assert.rejects(request(`/api/tasks/${completionTask.id}`, { action: 'completion', value: { enabled: true, message: null } }), /续作消息/); } finally { if (child.exitCode === null) child.kill(); await exited; diff --git a/tests/interaction-recovery.test.js b/tests/interaction-recovery.test.js new file mode 100644 index 0000000..eb821ae --- /dev/null +++ b/tests/interaction-recovery.test.js @@ -0,0 +1,90 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { Manager } from '../server/manager.js'; +import { initialState } from '../server/state-lifecycle.js'; +import { TaskDetails } from '../public/task-details.js'; +import { StateSnapshots } from '../public/interaction-state.js'; +import { quotaWindow } from '../public/quota-display.js'; + +function fixture() { + let saved = initialState(false), fail = false; + const rpc = new EventEmitter(); Object.assign(rpc, { ready: true, used: 0, calls: [], async connect() {}, close() {} }); + rpc.call = async (method, params) => { + rpc.calls.push(method); + if (method === 'thread/read') return { thread: { id: params.threadId, name: 'Fixture', cwd: 'E:/fixture' } }; + if (method === 'account/rateLimits/read') return { rateLimits: { primary: { usedPercent: rpc.used } } }; + if (method === 'thread/start') return { thread: { id: 'fixture' } }; + if (method === 'turn/start') return { turn: { id: 'fixture-turn' } }; + return {}; + }; + const store = { load: () => structuredClone(saved), save(value) { if (fail) throw Error('Disk full'); saved = structuredClone(value); } }; + return { rpc, manager: () => new Manager(rpc, store, { demo: true }), set fail(value) { fail = value; }, get saved() { return saved; } }; +} + +for (const operation of ['create', 'import']) test(`${operation} can be retried after a failed save without a duplicate or phantom record`, async () => { + const f = fixture(), m = f.manager(); + const add = () => operation === 'create' + ? m.create({ name: 'One record', cwd: 'E:/fixture', prompt: 'Isolated', continuous: false }) + : m.importThread('fixture-thread', 'Note', 'Message'); + try { + f.fail = true; await assert.rejects(async () => add(), /Disk full/); + assert.equal(m.state.tasks.length, 0); assert.equal(f.saved.tasks.length, 0); + assert.equal(m.persistence.status, 'error'); assert.equal(m.state.settings.enabled, false); + f.fail = false; await add(); + assert.equal(m.state.tasks.length, 1); assert.equal(f.saved.tasks.length, 1); + assert.equal(m.persistence.status, 'ok'); assert.equal(f.rpc.calls.includes('turn/start'), false); + } finally { f.fail = false; m.stop(); } +}); + +test('a one-shot task waiting for initial quota starts once and never schedules another turn', async () => { + const f = fixture(), m = f.manager(); + try { + m.updateSettings({ enabled: true }); + const task = m.create({ name: 'One shot', cwd: 'E:/fixture', prompt: 'Isolated', continuous: false }); + f.rpc.used = 100; await m.refresh(); assert.equal(task.status, 'waiting'); + f.rpc.used = 0; await m.refresh(); + assert.equal(task.status, 'running'); assert.equal(f.rpc.calls.filter(x => x === 'turn/start').length, 1); + m.event({ method: 'turn/completed', params: { threadId: task.threadId, turn: { id: task.turnId, status: 'completed' } } }); + for (let i = 0; i < 3; i++) await m.tick(); + assert.equal(f.rpc.calls.filter(x => x === 'turn/start').length, 1); + } finally { m.stop(); } +}); + +test('reconnected details read the persisted message even when the numeric revision repeats', async () => { + const f = fixture(); let m = f.manager(), reads = 0; + try { + const task = await m.importThread('fixture-thread', 'Note', 'Old message'); + const cache = new TaskDetails(async () => { reads++; return { task: structuredClone(m.taskSnapshot(task.id)) }; }, () => {}); + const before = m.snapshot({ details: false }).tasks[0]; + cache.read(before); await new Promise(setImmediate); + await m.action(task.id, 'message', 'New message'); m.stop(); m = f.manager(); + const after = m.snapshot({ details: false }).tasks[0]; + assert.equal(after.detailRevision, before.detailRevision); + assert.notEqual(after.detailInstanceId, before.detailInstanceId); + cache.read(after); assert.equal(cache.ready(after), false); await new Promise(setImmediate); + assert.equal(cache.read(after).continuationMessage, 'New message'); + assert.equal(cache.ready(after), true); assert.equal(reads, 2); + } finally { m.stop(); } +}); + +test('late HTTP state cannot replace newer live state or return to a retired service', () => { + const f = fixture(), first = f.manager(), second = f.manager(), snapshots = new StateSnapshots(); + try { + const old = first.snapshot({ details: false }); + first.updateSettings({ enabled: true }); + const live = first.snapshot({ details: false }); + assert.equal(snapshots.accept(old), old); assert.equal(snapshots.accept(live), live); + assert.equal(snapshots.accept(old), live); + const restarted = second.snapshot({ details: false }); + assert.equal(snapshots.accept(restarted), restarted); assert.equal(snapshots.accept(live), restarted); + } finally { first.stop(); second.stop(); } +}); + +test('a weekly-only sample is not borrowed for the five-hour slot; other durations retain their identity', () => { + const now = Date.now(), sample = primary => ({ connection: {status:'connected'}, sampledAt:now, quota:{rateLimits:{primary}} }); + const weekly = sample({usedPercent:40,windowDurationMins:10080}); + assert.equal(quotaWindow(weekly,'primary',true,now).remaining,null); + assert.equal(quotaWindow(weekly,'secondary',true,now).remaining,60); + assert.equal(quotaWindow(sample({usedPercent:20,windowDurationMins:60}),'primary',true,now).windowMinutes,60); +}); diff --git a/tests/interaction-ui.test.js b/tests/interaction-ui.test.js new file mode 100644 index 0000000..e250c8a --- /dev/null +++ b/tests/interaction-ui.test.js @@ -0,0 +1,24 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { mkdtempSync, realpathSync, existsSync, readFileSync, rmSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { fileURLToPath } from 'node:url'; +const executable = fileURLToPath(new URL('../node_modules/electron/dist/electron.exe', import.meta.url)); + +test('real interfaces preserve drafts, reading position, submission ownership and current state', + { skip: process.platform !== 'win32' || !existsSync(executable), timeout: 50000 }, async () => { + const parent = realpathSync(tmpdir()), directory = mkdtempSync(join(parent, 'continuer-interaction-')); + try { + try { + await promisify(execFile)(executable, [fileURLToPath(new URL('./fixtures/interaction-recovery-ui.cjs', import.meta.url))], { + env: { ...process.env, ELECTRON_RUN_AS_NODE: undefined, NODE_OPTIONS: '', CONTINUER_INTERACTION_TEST_DIR: directory }, windowsHide: true, timeout: 47000, + }); + } catch (error) { if (existsSync(join(directory, 'ui-results.json'))) error.message += '\n' + readFileSync(join(directory, 'ui-results.json'), 'utf8'); throw error; } + const result = JSON.parse(readFileSync(join(directory, 'ui-results.json'), 'utf8')); + assert.equal(result.error, undefined); assert.equal(result.completed, true); assert.equal(result.scenarios.length, 12); + assert.deepEqual(result.errors, []); + } finally { assert.equal(dirname(realpathSync(directory)), parent); rmSync(directory, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } + }); diff --git a/tests/monitor-controls.test.js b/tests/monitor-controls.test.js new file mode 100644 index 0000000..986bcf7 --- /dev/null +++ b/tests/monitor-controls.test.js @@ -0,0 +1,108 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { EventEmitter } from 'node:events'; +import { Manager } from '../server/manager.js'; +import { QueueSender } from '../server/queue-sender.js'; +import { validateState } from '../server/store.js'; +import { validate } from '../plugin/tools.js'; +import { interruptedThread } from './fixtures/thread-history.js'; + +const threadId='11111111-1111-4111-8111-111111111111'; +const quota=usedPercent=>({rateLimits:{primary:{usedPercent}}}); +const final=id=>interruptedThread(threadId,{turns:[{id,status:'completed',itemsView:'full',items:[{type:'userMessage'},{type:'agentMessage',phase:'final_answer',text:'Answer'}]}]}); +const deferred=()=>{let resolve;const promise=new Promise(yes=>{resolve=yes;});return {promise,resolve};}; +async function fixture(t,options={},saved) { + const rpc=new EventEmitter(),commands=[],saves=[];let thread=final('first'); + rpc.ready=true;rpc.close=()=>{};rpc.call=async()=>({thread:structuredClone(thread)}); + const sender=new QueueSender({binary:'mock',run:async(_bin,args)=>{commands.push(args);return '';}}); + const m=new Manager(rpc,{load:()=>saved&&structuredClone(saved),save:state=>{validateState(state);saves.push(structuredClone(state));}},{demo:true,wakeSender:sender}); + m.connection.status='connected';t.after(()=>m.stop()); + const task=m.state.tasks[0]||await m.importThread(threadId,'note','QUOTA',{completionMonitoring:true,completionMessage:'ANSWER',...options}); + const tick=async()=>{m.completionChecks.clear();m.setQuota(quota(0));await m.tick();}; + const cycle=async()=>{m.setQuota(quota(100));await m.tick();await tick();}; + return {m,task,rpc,sender,commands,saves,tick,cycle,setThread:value=>{thread=value;},sent:()=>commands.filter(args=>args.includes('--message'))}; +} + +test('answer-only monitoring sends once by default and never arms quota recovery',async t=>{ + const f=await fixture(t,{quotaMonitoring:false});await f.m.action(f.task.id,'resume'); + f.m.setQuota(quota(100));await f.m.tick();assert.equal(f.task.wake.armed,false); + await f.tick();assert.equal(f.sent().length,1);assert.equal(f.sent()[0].at(-1),'ANSWER'); + assert.equal(f.task.completionSends,1);assert.equal(f.task.completionMonitoring,false);assert.equal(f.task.continuous,false); + f.setThread(final('second'));await f.tick();assert.equal(f.sent().length,1); + await f.m.action(f.task.id,'completion-monitoring',true);assert.equal(f.task.completionSends,0);assert.equal(f.task.continuous,false); + await f.m.action(f.task.id,'resume');f.setThread(final('first'));await f.tick();assert.equal(f.sent().length,1,'Re-enabling cannot replay the previous final'); + f.setThread(final('second'));await f.tick();assert.equal(f.sent().length,2);assert.equal(f.task.sentCount,2); +}); + +test('quota-only monitoring uses only quota messages and switches do not activate a paused record',async t=>{ + const f=await fixture(t,{completionMonitoring:false}); + await f.m.action(f.task.id,'quota-monitoring',false);await f.m.action(f.task.id,'quota-monitoring',true); + assert.equal(f.task.continuous,false);await f.m.action(f.task.id,'resume'); + f.setThread(interruptedThread(threadId));await f.cycle();assert.equal(f.sent()[0].at(-1),'QUOTA');assert.equal(f.task.completionSends,0); + f.setThread(final('done'));await f.cycle();assert.equal(f.sent().length,1); +}); + +test('repeat count stops only reply monitoring; quota monitoring keeps working independently',async t=>{ + const f=await fixture(t,{completionRepeat:true,completionMaxSends:3});await f.m.action(f.task.id,'resume'); + for(let i=1;i<=3;i++){f.setThread(final('reply-'+i));await f.tick();await f.tick();assert.equal(f.sent().length,i);} + assert.equal(f.task.completionMonitoring,false);assert.equal(f.task.quotaMonitoring,true);assert.equal(f.task.continuous,true);assert.equal(f.task.completionSends,3); + f.setThread(final('fourth'));await f.tick();assert.equal(f.sent().length,3); + f.setThread(interruptedThread(threadId));await f.cycle();assert.equal(f.sent().at(-1).at(-1),'QUOTA');assert.equal(f.task.sentCount,4);assert.equal(f.task.completionSends,3); +}); + +test('pause, restart and message edits preserve the current repeat count and delivery deduplication',async t=>{ + const f=await fixture(t,{completionRepeat:true,completionMaxSends:2});await f.m.action(f.task.id,'resume');await f.tick(); + await f.m.action(f.task.id,'pause');await f.m.action(f.task.id,'resume'); + await f.m.action(f.task.id,'completion',{enabled:true,message:'Edited',repeat:true,maxSends:2,quotaMonitoring:true}); + assert.equal(f.task.completionSends,1);const restored=await fixture(t,{},f.m.state); + await restored.tick();assert.equal(restored.sent().length,0); + restored.setThread(final('second'));await restored.tick();assert.equal(restored.sent()[0].at(-1),'Edited');assert.equal(restored.task.completionSends,2);assert.equal(restored.task.completionMonitoring,false); +}); + +test('lowering the repeat budget applies immediately without resetting quota or cumulative counts',async t=>{ + const f=await fixture(t,{completionRepeat:true,completionMaxSends:5});await f.m.action(f.task.id,'resume');await f.tick(); + await f.m.action(f.task.id,'completion',{enabled:true,message:'Changed',repeat:false,maxSends:5,quotaMonitoring:true}); + assert.equal(f.task.completionMonitoring,false);assert.equal(f.task.completionSends,1);assert.equal(f.task.sentCount,1);assert.equal(f.task.continuous,true); + await f.m.action(f.task.id,'completion',{enabled:true,message:'Changed',repeat:true,maxSends:2,quotaMonitoring:true});assert.equal(f.task.completionSends,0); + await f.tick();assert.equal(f.sent().length,1,'An explicit new run still cannot replay an old answer'); +}); + +test('disabling quota monitoring cancels a pending queue probe without cancelling reply monitoring',async t=>{ + const f=await fixture(t);f.setThread(interruptedThread(threadId));await f.m.action(f.task.id,'resume'); + f.m.setQuota(quota(100));await f.m.tick();const entered=deferred(),release=deferred(); + f.sender.run=async(_bin,args)=>{f.commands.push(args);if(args.includes('--help')){entered.resolve();await release.promise;}return '';}; + const pending=f.tick();await entered.promise;await f.m.action(f.task.id,'quota-monitoring',false);release.resolve();await pending; + assert.equal(f.sent().length,0);assert.equal(f.task.wake.delivery,'idle');assert.equal(f.task.completionMonitoring,true);assert.equal(f.task.continuous,true); + f.setThread(final('next'));await f.tick();assert.equal(f.sent()[0].at(-1),'ANSWER'); +}); + +test('disabling reply monitoring during its queue probe leaves quota monitoring available',async t=>{ + const f=await fixture(t);await f.m.action(f.task.id,'resume');const entered=deferred(),release=deferred(); + f.sender.run=async(_bin,args)=>{f.commands.push(args);if(args.includes('--help')){entered.resolve();await release.promise;}return '';}; + const pending=f.tick();await entered.promise;await f.m.action(f.task.id,'completion-monitoring',false);release.resolve();await pending; + assert.equal(f.sent().length,0);assert.equal(f.task.completionSends,0);assert.equal(f.task.continuous,true); + f.setThread(interruptedThread(threadId));await f.cycle();assert.equal(f.sent()[0].at(-1),'QUOTA'); +}); + +test('global send cap still overrides larger reply budgets and enabling neither monitor cannot run',async t=>{ + const f=await fixture(t,{completionRepeat:true,completionMaxSends:5});f.m.updateSettings({maxWakeSends:2});await f.m.action(f.task.id,'resume'); + await f.tick();f.setThread(final('second'));await f.tick();assert.equal(f.task.sentCount,2);assert.equal(f.task.continuous,false);assert.equal(f.task.completionSends,2); + const none=await fixture(t,{quotaMonitoring:false,completionMonitoring:false});await assert.rejects(none.m.action(none.task.id,'resume'),/请先开启/); +}); + +test('invalid independent policies are atomic and cannot be enabled through MCP',async t=>{ + const f=await fixture(t);const before=structuredClone(f.task); + for(const patch of [{quotaMonitoring:'on'},{repeat:'on'},{maxSends:0},{maxSends:101},{maxSends:1.5},{maxSends:null}]){ + await assert.rejects(f.m.action(f.task.id,'completion',{enabled:true,message:'new',...patch}));assert.deepEqual(f.task,before); + } + for(const patch of [{completionRepeat:1},{quotaMonitoring:null},{completionMaxSends:0},{completionSends:-1}]){ + Object.assign(f.task,patch);assert.throws(()=>validateState(f.m.state));Object.assign(f.task,structuredClone(before)); + } + for(const action of ['quota-monitoring','completion-monitoring'])assert.throws(()=>validate('continuer_task_action',{id:f.task.id,action,value:true})); +}); + +test('legacy records migrate to their previous repeated-monitor behavior without starting work',async t=>{ + const f=await fixture(t);for(const key of ['quotaMonitoring','completionRepeat','completionMaxSends','completionSends'])delete f.task[key]; + const restored=await fixture(t,{},f.m.state); + assert.equal(restored.task.quotaMonitoring,true);assert.equal(restored.task.completionRepeat,true);assert.equal(restored.task.completionMaxSends,100);assert.equal(restored.task.completionSends,0);assert.equal(restored.sent().length,0); +}); diff --git a/tests/runtime-lifecycle.test.js b/tests/runtime-lifecycle.test.js index f9ff8b9..bcd5bc8 100644 --- a/tests/runtime-lifecycle.test.js +++ b/tests/runtime-lifecycle.test.js @@ -166,10 +166,23 @@ test('manual callers joining automatic opening share one widget and restore one const manual = Array.from({ length: 10 }, () => f.lifecycle.openWidget()); pending.resolve(f.state); assert.equal((await automatic).ready, true); await Promise.all(manual); assert.deepEqual(f.launches.map(item => item.name), ['widget', 'watcher']); - assert.deepEqual(f.launches[0].args, [join(f.host.root, 'desktop/main.cjs'), '--auto']); + assert.deepEqual(f.launches[0].args, [join(f.host.root, 'desktop/main.cjs')]); assert.equal(f.launches[0].env.CONTINUER_NODE, 'fixture-widget-node'); assert.equal(f.launches[0].env.ELECTRON_RUN_AS_NODE, undefined); }); +test('manual opening after the automatic process has launched forwards a foreground request to the single-instance owner', async () => { + const pending = deferred(), f = fixture({ wait: () => pending.promise }); + f.diagnostics.set('autostart-preferences.json', { enabled: true }); + const automatic = f.lifecycle.openWidget({ automatic: true }); + for (let attempt = 0; !f.launches.length && attempt < 10; attempt++) await Promise.resolve(); + assert.ok(f.launches[0].args.includes('--auto')); + const manual = Array.from({ length: 10 }, () => f.lifecycle.openWidget()); + readyWidget(f); pending.resolve(); + assert.equal((await automatic).ready, true); await Promise.all(manual); + assert.deepEqual(f.launches.map(item => item.name), ['widget', 'widget', 'watcher']); + assert.deepEqual(f.launches[1].args, [join(f.host.root, 'desktop/main.cjs')]); +}); + test('automatic and demo openings leave the watcher alone and automatic opening does not clear exit intent', async () => { for (const demo of [false, true]) { const f = fixture({ demo }); readyWidget(f); f.diagnostics.set('autostart-preferences.json', { enabled: true }); @@ -216,7 +229,7 @@ test('watcher startup respects ownership and retains the source-only fallback', f.diagnostics.set('autostart-preferences.json', { enabled: true }); f.diagnostics.set('autostart-status.json', { pid: 123, pluginRoot: watcher === 'owned' ? f.host.root : 'foreign' }); await f.lifecycle.openWidget(); const launched = f.launches.filter(item => item.name === 'watcher'); - assert.equal(launched.length, watcher === 'owned' ? 0 : 1); + assert.equal(launched.length, 1, 'saved PIDs never suppress recovery; the OS mutex prevents duplicate watchers'); if (watcher === 'foreign') assert.deepEqual(launched[0].args, ['--watch', 'fixture-widget-node', f.host.root, f.host.dataDir]); if (watcher === 'fallback') { assert.equal(launched[0].command, 'powershell.exe'); assert.ok(launched[0].args.includes(join(f.host.root, 'desktop/watch-codex.ps1'))); } } diff --git a/tests/shared-ui.test.js b/tests/shared-ui.test.js index 410c84a..326a7f5 100644 --- a/tests/shared-ui.test.js +++ b/tests/shared-ui.test.js @@ -125,18 +125,51 @@ for (const [layout, createView] of [['page', pageView], ['widget', widgetView]]) const create = view.apiCalls.find(call => call.path === '/api/tasks'); assert.deepEqual(JSON.parse(create.options.body), { name: '中文工作', cwd: 'E:\\fixture', prompt: 'Goal', continuous: true }); await view.action(layout === 'page' ? 'choose-thread' : 'select-session', 'chat'); - await view.submit('import-form', { note: 'Local note', continuationMessage: 'Continue this' }, { id: 'chat' }); + await view.submit('import-form', { note: 'Local note', continuationMessage: 'Continue this', quotaMonitoring:'on' }, { id: 'chat' }); const imported = view.apiCalls.find(call => call.path === '/api/import'); - assert.deepEqual(JSON.parse(imported.options.body), { threadId: 'chat', note: 'Local note', continuationMessage: 'Continue this', startMonitoring: false }); + assert.deepEqual(JSON.parse(imported.options.body), { threadId: 'chat', note: 'Local note', continuationMessage: 'Continue this', startMonitoring: false, completionMonitoring: false, quotaMonitoring:true, completionRepeat:false, completionMaxSends:20 }); view.visible(false); if (layout === 'widget') view.desktop({ visible: false }); }); test(`${layout} can enable monitoring while adding a chat`, async () => { const state = snapshot([]), view = createView({ request: async () => state }); await view.flush(); view.message(0, state); await view.action(layout === 'page' ? 'choose-thread' : 'select-session', 'chat'); - await view.submit('import-form', { note: 'Local note', continuationMessage: 'Continue this', startMonitoring: 'on' }, { id: 'chat' }); + await view.submit('import-form', { note: 'Local note', continuationMessage: 'Continue this', startMonitoring: 'on', quotaMonitoring:'on' }, { id: 'chat' }); const imported = view.apiCalls.find(call => call.path === '/api/import'); - assert.deepEqual(JSON.parse(imported.options.body), { threadId: 'chat', note: 'Local note', continuationMessage: 'Continue this', startMonitoring: true }); + assert.deepEqual(JSON.parse(imported.options.body), { threadId: 'chat', note: 'Local note', continuationMessage: 'Continue this', startMonitoring: true, completionMonitoring: false, quotaMonitoring:true, completionRepeat:false, completionMaxSends:20 }); + view.visible(false); if (layout === 'widget') view.desktop({ visible: false }); + }); +} + +for (const [layout, createView] of [['page', pageView], ['widget', widgetView]]) { + test(`${layout} saves a separate completion message and toggle without changing quota message`, async () => { + const task = watched(), state = snapshot([task]); + task.completionMessage = ''; task.completionMonitoring = true; + const view = createView({ task: async (_path, options) => { + if (options.method !== 'POST') return { task }; + const body = JSON.parse(options.body); + assert.deepEqual(body, { action: 'completion', value: { enabled: false, message: '下一项工作\n先验证', quotaMonitoring:true,repeat:true,maxSends:3 } }); + task.completionMessage = body.value.message; task.completionMonitoring = body.value.enabled; return state; + } }); + await view.flush(); view.message(0, state); await view.action('detail', task.id); await view.flush(); + await view.action('edit-completion', task.id); + assert.match(view.element('#modal-body').innerHTML, /name="completionMonitoring"[^>]*checked/); + assert.match(view.element('#modal-body').innerHTML, /<script>/); + assert.match(view.element('#modal-body').innerHTML, /<SCRIPT>/); + assert.doesNotMatch(view.element('#modal-body').innerHTML, / { + const state = snapshot([]), view = createView({ request: async () => state }); + await view.flush(); view.message(0, state); await view.action(layout === 'page' ? 'choose-thread' : 'select-session', 'chat'); + assert.doesNotMatch(view.element('#modal-body').innerHTML, /name="completionMonitoring"[^>]*checked/); + await view.submit('import-form', { continuationMessage: '恢复额度', completionMonitoring: 'on', completionMessage: '继续下一步', startMonitoring: 'on',completionRepeat:'on',completionMaxSends:'3' }, { id: 'chat' }); + const imported = view.apiCalls.find(call => call.path === '/api/import'); + assert.deepEqual(JSON.parse(imported.options.body), { threadId: 'chat', continuationMessage: '恢复额度', startMonitoring: true, completionMonitoring: true, completionMessage: '继续下一步',quotaMonitoring:false,completionRepeat:true,completionMaxSends:3 }); view.visible(false); if (layout === 'widget') view.desktop({ visible: false }); }); } diff --git a/tests/widget-size.test.js b/tests/widget-size.test.js new file mode 100644 index 0000000..d6043d0 --- /dev/null +++ b/tests/widget-size.test.js @@ -0,0 +1,131 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { mountSizeControls } from '../public/widget-size.js'; + +function fixture({native=true,control,storage=new Map()}={}) { + const nodes=new Map(),classes=new Set(['collapsed']),calls=[],errors=[],windowEvents=new Map(); + const state={expanded:false,visible:true,compactSize:256,preferredPanelSize:{width:432,height:720}}; + const element=selector=>{ + if(!nodes.has(selector)) nodes.set(selector,{ + value:'',textContent:'',listeners:new Map(),capture:null, + addEventListener(name,handler){this.listeners.set(name,handler);}, + setPointerCapture(id){this.capture=id;},hasPointerCapture(id){return this.capture===id;},releasePointerCapture(){this.capture=null;}, + emit(name,event={}){return this.listeners.get(name)?.({preventDefault(){},...event});}, + }); + return nodes.get(selector); + }; + const window={innerWidth:256,innerHeight:256,addEventListener:(name,handler)=>windowEvents.set(name,handler)}; + const document={querySelector:element,body:{classList:{contains:name=>classes.has(name)}},documentElement:{style:{setProperty(){}}}}; + const bridge={async control(action,value){ + calls.push({action,value:structuredClone(value)}); + if(control)return control(action,value); + if(action==='compact-size')state.compactSize=value; + else if(action==='panel-size')state.preferredPanelSize={...value}; + else if(action==='resize' && value.expanded===state.expanded) { + if(value.expanded)state.preferredPanelSize={width:value.width,height:value.height};else state.compactSize=value.width; + } + return structuredClone(state); + }}; + const ui=mountSizeControls({document,window,bridge:native?bridge:null,localStorage:{getItem:key=>storage.get(key)||null,setItem:(key,value)=>storage.set(key,value)},onState:result=>{Object.assign(state,result);ui.apply(result);},onError:error=>errors.push(error)}); + if(native)ui.apply(state); + return {state,calls,errors,storage,element,windowEvents,window,native:change=>ui.apply({...state,...change}), + expanded(value){state.expanded=value;if(value)classes.delete('collapsed');else classes.add('collapsed');window.innerWidth=value?state.preferredPanelSize.width:state.compactSize;window.innerHeight=value?state.preferredPanelSize.height:state.compactSize;}, + flush:()=>new Promise(resolve=>setImmediate(resolve))}; +} + +test('native size sliders send independent dimensions and retain the latest draft during slow IPC',async()=>{ + let release; + const f=fixture({control:()=>new Promise(resolve=>{release=resolve;})}); + f.element('#compact-size').emit('input',{target:{value:'280'}}); + f.element('#compact-size').emit('input',{target:{value:'320'}}); + f.element('#panel-width').emit('input',{target:{value:'600'}}); + f.element('#panel-height').emit('input',{target:{value:'840'}}); + assert.equal(f.calls.length,1);assert.equal(f.element('#compact-size').value,320); + f.expanded(true);f.native({expanded:true}); + release({compactSize:280,preferredPanelSize:{width:432,height:720}});await f.flush(); + assert.deepEqual(f.calls[1],{action:'compact-size',value:320}); + assert.equal(f.element('#compact-size').value,320); + release({compactSize:320,preferredPanelSize:{width:432,height:720}});await f.flush(); + assert.deepEqual(f.calls[2],{action:'panel-size',value:{width:600,height:840}}); + release({compactSize:320,preferredPanelSize:{width:600,height:840}});await f.flush(); + assert.equal(f.element('#panel-height').value,840);assert.equal(f.errors.length,0); +}); + +test('corner drag resizes compact and expanded views without expanding or moving the card',async()=>{ + const f=fixture(),handle=f.element('#resize-widget'); + handle.emit('pointerdown',{button:0,pointerId:1,screenX:100,screenY:100}); + handle.emit('pointermove',{pointerId:1,screenX:148,screenY:120});await f.flush(); + handle.emit('pointerup',{pointerId:1,screenX:148,screenY:120});await f.flush(); + assert.deepEqual(f.calls,[{action:'resize',value:{expanded:false,width:304,height:304}}]); + assert.equal(f.state.expanded,false);assert.equal(handle.capture,null); + f.expanded(true); + handle.emit('pointerdown',{button:0,pointerId:2,screenX:50,screenY:50}); + handle.emit('pointerup',{pointerId:2,screenX:150,screenY:90});await f.flush(); + assert.deepEqual(f.calls.at(-1),{action:'resize',value:{expanded:true,width:532,height:760}}); +}); + +test('resize cancellation, a stationary click and a mode change never submit a stale resize',async()=>{ + const f=fixture(),handle=f.element('#resize-widget'); + const down={button:0,pointerId:3,screenX:50,screenY:50}; + handle.emit('pointerdown',down);handle.emit('pointerup',down);assert.equal(f.calls.length,0); + handle.emit('pointerdown',down);f.windowEvents.get('blur')();handle.emit('pointermove',{...down,screenX:90});assert.equal(f.calls.length,0); + handle.emit('pointerdown',down);f.expanded(true);handle.emit('pointermove',{...down,screenX:90});assert.equal(f.calls.length,0); + assert.equal(handle.capture,null); +}); + +test('keyboard and Ctrl-wheel resizing clamp inputs and browser sizes persist without native calls',async()=>{ + const f=fixture({native:false}),handle=f.element('#resize-widget'); + handle.emit('keydown',{key:'ArrowRight'});assert.equal(f.element('#compact-size').value,264); + f.element('#mini').emit('wheel',{ctrlKey:true,deltaY:-1});assert.equal(f.element('#compact-size').value,280); + f.expanded(true);f.element('#panel-width').emit('input',{target:{value:'10000'}}); + f.element('#panel-height').emit('input',{target:{value:'1'}}); + assert.deepEqual(JSON.parse(f.storage.get('continuer-panel-size')),{width:960,height:400}); + const restored=fixture({native:false,storage:f.storage}); + assert.equal(restored.element('#compact-size').value,280);assert.equal(restored.element('#panel-width').value,960); + assert.equal(restored.element('#panel-height').value,400);assert.equal(restored.calls.length,0); +}); + +test('a late size reply cannot restore an older native view or overwrite a newer size event',async()=>{ + let release; + const f=fixture({control:()=>new Promise(resolve=>{release=resolve;})}); + f.element('#compact-size').emit('input',{target:{value:'280'}}); + f.expanded(true);f.native({expanded:true,compactSize:320,preferredPanelSize:{width:600,height:800}}); + release({expanded:false,compactSize:280,preferredPanelSize:{width:432,height:720}});await f.flush(); + assert.equal(f.state.expanded,true);assert.equal(f.element('#compact-size').value,320); + assert.equal(f.element('#panel-width').value,600); +}); + +test('changing view cancels queued drag sizes even after switching back before the old reply arrives',async()=>{ + let release; + const f=fixture({control:()=>new Promise(resolve=>{release=resolve;})}),handle=f.element('#resize-widget'); + handle.emit('pointerdown',{button:0,pointerId:7,screenX:100,screenY:100}); + handle.emit('pointermove',{pointerId:7,screenX:140,screenY:140}); + handle.emit('pointermove',{pointerId:7,screenX:180,screenY:180}); + assert.equal(f.calls.length,1); + f.expanded(true);f.native({expanded:true}); + f.expanded(false);f.native({expanded:false}); + release({expanded:false,compactSize:296,preferredPanelSize:{width:432,height:720}});await f.flush(); + assert.equal(f.calls.length,1,'A queued update from the departed view must never replay'); + assert.equal(handle.capture,null,'Mode changes must release the cancelled drag'); +}); + +test('size request failures preserve newer native events and otherwise retain the last confirmed reply',async()=>{ + for(const newerEvent of [false,true]) { + const pending=[]; + const f=fixture({control:()=>new Promise((resolve,reject)=>pending.push({resolve,reject}))}); + f.element('#compact-size').emit('input',{target:{value:'280'}}); + f.element('#compact-size').emit('input',{target:{value:'320'}}); + pending[0].resolve({expanded:false,compactSize:280,preferredPanelSize:{width:432,height:720}});await f.flush(); + assert.equal(f.calls.length,2); + if(newerEvent){f.expanded(true);f.native({expanded:true,compactSize:320,preferredPanelSize:{width:600,height:800}});} + pending[1].reject(new Error('fixture IPC failure'));await f.flush(); + assert.equal(f.errors.length,1); + assert.equal(f.state.expanded,newerEvent,'Failed IPC must not restore an earlier view'); + assert.equal(f.element('#compact-size').value,newerEvent?320:280); + assert.equal(f.element('#panel-width').value,newerEvent?600:432); + f.element('#compact-size').emit('input',{target:{value:'344'}}); + assert.equal(f.calls.length,3,'An IPC error must not strand the resize queue'); + pending[2].resolve({...f.state,compactSize:344});await f.flush(); + assert.equal(f.element('#compact-size').value,344); + } +}); diff --git a/tests/widget-smoke.test.js b/tests/widget-smoke.test.js index 6f1a08e..dc234db 100644 --- a/tests/widget-smoke.test.js +++ b/tests/widget-smoke.test.js @@ -33,7 +33,7 @@ for (const expanded of [false, true]) test(`hidden isolated widget is ready with } assert.equal(running, true); let nativeErrors = ''; - widget = spawn(executable, ['--disable-gpu', 'desktop/main.cjs'], { env, windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'] }); + widget = spawn(executable, ['--disable-gpu', 'tests/fixtures/hidden-widget.cjs'], { env, windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'] }); widget.stderr.on('data', chunk => { nativeErrors = (nativeErrors + chunk).slice(-2500); }); const exited = once(widget, 'exit'); let status; for (let i = 0; i < 120; i++) {