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.uses_local_codex_sign_in_and_the")}
${tr("ui.work_runs_in_the_project_directory_sandbox")}
${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} ·
${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 `
${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")}
${tr("ui.no_chats_available_to_import")}
`}${tr("ui.choose_a_local_chat_to_manage_monitoring")} ${tr("ui.chat_page_hint")}
${tr("ui.no_chats_available_to_import")}
`}${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.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 `${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 ? `${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 @@${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