A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Let an update come when the app's Host does not start
Fei2411ce8be1db72bc
diff --git a/app/src/first-run.mjs b/app/src/first-run.mjsindex 388f6f40..745efc11 100644--- a/app/src/first-run.mjs+++ b/app/src/first-run.mjs@@ -24,6 +24,7 @@ const TEXT = {quit: 'Quit', startEmpty: 'Start without the team',whichModels: 'Which model settings should DeepSeek Bot use?',failed: message => `The team could not be copied: ${message}\n\nDeepSeek Bot starts with a new team. The team in DeepSeek Harness is unchanged.`,+ notStarted: 'DeepSeek Bot could not start.',},zh: {welcome: '欢迎使用 DeepSeek Bot',@@ -42,6 +43,7 @@ const TEXT = {quit: '退出', startEmpty: '不带团队开始',whichModels: 'DeepSeek Bot 用哪一份模型设置?',failed: message => `团队没有复制成功:${message}\n\nDeepSeek Bot 会用一个新团队开始。DeepSeek Harness 里的团队没有变化。`,+ notStarted: 'DeepSeek Bot 没能启动。',},}export const localeText = table => (app.getLocale().toLowerCase().startsWith('zh') ? table.zh : table.en)diff --git a/app/src/main.mjs b/app/src/main.mjsindex 5dedd8d8..4cc5f637 100644--- a/app/src/main.mjs+++ b/app/src/main.mjs@@ -5,6 +5,7 @@ import { app, BrowserWindow, dialog, ipcMain, Menu, nativeTheme, protocol, sessiimport { mkdirSync } from 'node:fs'import { createRequire } from 'node:module'import { dirname, join } from 'node:path'+import { setTimeout as sleep } from 'node:timers/promises'import { fileURLToPath } from 'node:url'import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot'import electronUpdater from 'electron-updater'@@ -18,6 +19,8 @@ import { APP_ORIGIN, authenticateWebHost, forwardWebRequest, serveWebDocument }const SCHEME = 'dsh-app'const IPC = { boot: 'ds-bot:boot', bootFailed: 'ds-bot:boot-failed' }const STATIC_PATHS = new Set(['/', '/index.html', '/manifest.webmanifest'])+const UPDATE_CHECK_WAIT_MS = 15_000+const UPDATE_DOWNLOAD_WAIT_MS = 15 * 60_000const here = dirname(fileURLToPath(import.meta.url))const webDist = join(dirname(createRequire(import.meta.url).resolve('@deepseek-ai/dsh-web-frontend/package.json')), 'dist')@@ -34,6 +37,7 @@ let mainWindowlet hostlet hostStatelet hostStop+let updateslet stopping = falselet stopped = falselet failed = false@@ -72,13 +76,15 @@ function start() {})const ready = (async () => {if (where.import) await copyTeam(where, newHost)+ // Not during the import, which a restart would cut short; before the Host, so that an+ // update can still come when this version's Host does not start.+ updates = startUpdates()host = newHost()const started = await host.start()hostState = { ...started, cookie: await authenticateWebHost(started.url) }return hostState})()ready.catch(fail)- ready.then(startUpdates, () => {})protocol.handle(SCHEME, (request) => {const url = new URL(request.url)@@ -138,11 +144,13 @@ async function copyTeam(where, newHost) {function startUpdates() {const feed = process.env.DS_BOT_UPDATE_URL || undefinedconst throwaway = Boolean(process.env.DS_BOT_HOME)- if (!app.isPackaged || process.platform !== 'win32' || (throwaway && feed === undefined)) return- watchUpdates({ updater: electronUpdater.autoUpdater, feed, ask: throwaway ? undefined : askRestart, beforeInstall: stopHost })+ if (!app.isPackaged || process.platform !== 'win32' || (throwaway && feed === undefined)) return undefined+ return watchUpdates({ updater: electronUpdater.autoUpdater, feed, ask: throwaway ? undefined : askRestart, beforeInstall: stopHost })}async function askRestart(version) {+ // After a failed start, fail() installs the update itself.+ if (failed) return falseconst t = localeText(UPDATE_TEXT)const options = { type: 'info', title: 'DeepSeek Bot', message: t.ready(version), detail: t.readyDetail, buttons: [t.restart, t.later], defaultId: 0, cancelId: 1, noLink: true }const { response } = await (mainWindow ? dialog.showMessageBox(mainWindow, options) : dialog.showMessageBox(options))@@ -180,7 +188,7 @@ function setMenu() {}function focusWindow() {- if (mainWindow === undefined) return+ if (mainWindow === undefined || failed) returnif (mainWindow.isMinimized()) mainWindow.restore()mainWindow.show()mainWindow.focus()@@ -196,10 +204,22 @@ function openOutside(url) {if (/^https?:\/\//iu.test(url)) void shell.openExternal(url)}-function fail(error) {+// A new version may fix what keeps this one from starting. So a failed start waits for the+// newest update check and, when it found a version, for its download; the installer then+// opens the app again.+async function fail(error) {console.error(error)if (failed || stopping) returnfailed = true- dialog.showErrorBox('DeepSeek Bot', `DeepSeek Bot could not start.\n\n${error instanceof Error ? error.message : String(error)}`)+ const found = await Promise.race([updates?.latest() ?? null, sleep(UPDATE_CHECK_WAIT_MS).then(() => null)])+ const next = found ? `\n\n${localeText(UPDATE_TEXT).onFailure(found.version)}` : ''+ dialog.showErrorBox('DeepSeek Bot', `${text().notStarted}\n\n${error instanceof Error ? error.message : String(error)}${next}`)+ if (found) {+ mainWindow?.hide()+ if (await Promise.race([found.downloaded, sleep(UPDATE_DOWNLOAD_WAIT_MS).then(() => false)])) {+ await updates.install()+ return+ }+ }app.quit()}diff --git a/app/src/updates.mjs b/app/src/updates.mjsindex f9b1d53f..d8e80d5e 100644--- a/app/src/updates.mjs+++ b/app/src/updates.mjs@@ -8,11 +8,13 @@ export const UPDATE_TEXT = {ready: version => `DeepSeek Bot ${version} is ready to install.`,readyDetail: 'Restart now to update, or it is installed the next time you quit.',restart: 'Restart now', later: 'Later',+ onFailure: version => `DeepSeek Bot ${version} is installed when its download is done, and then DeepSeek Bot opens again.`,},zh: {ready: version => `DeepSeek Bot ${version} 已经下载好。`,readyDetail: '现在重启就能更新;不重启的话,下次退出时安装。',restart: '立即重启', later: '稍后',+ onFailure: version => `DeepSeek Bot ${version} 下载完会自动安装,然后重新打开。`,},}@@ -28,27 +30,38 @@ const CHECK_EVERY_MS = 4 * 60 * 60_000* }} options `ask` answers whether to restart now; without it the update waits for the next* quit. `beforeInstall` stops the Host, which runs from the files the installer replaces.* `feed` is a folder URL with a latest.yml, in place of the GitHub releases.- * @returns {() => void} stops the checks+ * @returns {{+ * stop: () => void,+ * latest: () => Promise<{ version: string, downloaded: Promise<boolean> } | null>,+ * install: () => Promise<void>,+ * }} `latest` is what the newest check found: the version and whether its download finished.+ * `install` stops the Host and runs the installer, which opens the app again.*/export function watchUpdates({ updater, beforeInstall, ask, feed, log = console }) {updater.autoDownload = trueupdater.autoInstallOnAppQuit = trueif (feed) updater.setFeedURL({ provider: 'generic', url: feed })+ const install = async () => {+ await beforeInstall()+ updater.quitAndInstall(true, true)+ }let askedupdater.on('update-downloaded', ({ version }) => {log.info(`DeepSeek Bot: update ${version} downloaded`)if (ask === undefined || asked === version) returnasked = version- void ask(version).then(async (now) => {- if (!now) return- await beforeInstall()- updater.quitAndInstall(true, true)- }).catch((error) => { log.error(`DeepSeek Bot: update ${version} not installed: ${error instanceof Error ? error.message : String(error)}`) })+ void ask(version).then(now => (now ? install() : undefined))+ .catch((error) => { log.error(`DeepSeek Bot: update ${version} not installed: ${error instanceof Error ? error.message : String(error)}`) })})updater.on('error', (error) => { log.error(`DeepSeek Bot: update failed: ${error instanceof Error ? error.message : String(error)}`) })+ let latest = Promise.resolve(null)// A failed check or download also comes as an 'error' event.- const check = () => { updater.checkForUpdates().then(result => result?.downloadPromise?.catch(() => {}), () => {}) }+ const check = () => {+ latest = updater.checkForUpdates().then(result => (result?.isUpdateAvailable && result.downloadPromise+ ? { version: result.updateInfo.version, downloaded: result.downloadPromise.then(() => true, () => false) }+ : null), () => null)+ }check()const timer = setInterval(check, CHECK_EVERY_MS)- return () => { clearInterval(timer) }+ return { stop: () => { clearInterval(timer) }, latest: () => latest, install }}diff --git a/app/test/updates.test.mjs b/app/test/updates.test.mjsindex fa2b8a72..da3a73d1 100644--- a/app/test/updates.test.mjs+++ b/app/test/updates.test.mjs@@ -4,23 +4,29 @@ import { describe, test } from 'node:test'import { setTimeout as sleep } from 'node:timers/promises'import { watchUpdates } from '../src/updates.mjs'-// electron-updater's AppUpdater, as far as the app uses it.+// electron-updater's AppUpdater, as far as the app uses it. `found` makes the answer of a+// check that finds a version, with the download that autoDownload starts.class FakeUpdater extends EventEmitter {checks = 0feeds = []installs = []failCheck = false+ found = nullcheckForUpdates() {this.checks += 1- if (!this.failCheck) return Promise.resolve(null)- const error = new Error('offline')- this.emit('error', error)- return Promise.reject(error)+ if (this.failCheck) {+ const error = new Error('offline')+ this.emit('error', error)+ return Promise.reject(error)+ }+ return Promise.resolve(this.found?.() ?? { isUpdateAvailable: false, updateInfo: { version: '0.1.7' } })}setFeedURL(options) { this.feeds.push(options) }quitAndInstall(...args) { this.installs.push(args) }}+const finds = (version, download) => () => ({ isUpdateAvailable: true, updateInfo: { version }, downloadPromise: download() })+const quietLog = () => {const lines = []return { lines, info: (line) => { lines.push(line) }, error: (line) => { lines.push(line) } }@@ -29,7 +35,7 @@ const quietLog = () => {describe('watchUpdates', () => {test('downloads in the background, installs at the quit, and checks at once', (t) => {const updater = new FakeUpdater()- t.after(watchUpdates({ updater, beforeInstall: async () => {}, log: quietLog() }))+ t.after(watchUpdates({ updater, beforeInstall: async () => {}, log: quietLog() }).stop)assert.equal(updater.autoDownload, true)assert.equal(updater.autoInstallOnAppQuit, true)assert.equal(updater.checks, 1)@@ -38,7 +44,7 @@ describe('watchUpdates', () => {test('reads a given feed in place of the GitHub releases', (t) => {const updater = new FakeUpdater()- t.after(watchUpdates({ updater, beforeInstall: async () => {}, feed: 'http://127.0.0.1:8080/', log: quietLog() }))+ t.after(watchUpdates({ updater, beforeInstall: async () => {}, feed: 'http://127.0.0.1:8080/', log: quietLog() }).stop)assert.deepEqual(updater.feeds, [{ provider: 'generic', url: 'http://127.0.0.1:8080/' }])})@@ -50,7 +56,7 @@ describe('watchUpdates', () => {updater, log: quietLog(),ask: async (version) => { asked.push(version); return true },beforeInstall: async () => { await sleep(10); steps.push('host stopped') },- }))+ }).stop)updater.quitAndInstall = (...args) => { steps.push(['install', ...args]) }updater.emit('update-downloaded', { version: '0.1.9' })updater.emit('update-downloaded', { version: '0.1.9' })@@ -64,7 +70,7 @@ describe('watchUpdates', () => {const updater = new FakeUpdater()const log = quietLog()let stopped = false- t.after(watchUpdates({ updater, ask, log, beforeInstall: async () => { stopped = true } }))+ t.after(watchUpdates({ updater, ask, log, beforeInstall: async () => { stopped = true } }).stop)updater.emit('update-downloaded', { version: '0.1.9' })await sleep(20)assert.deepEqual(updater.installs, [])@@ -77,27 +83,58 @@ describe('watchUpdates', () => {const updater = new FakeUpdater()updater.failCheck = trueconst log = quietLog()- t.after(watchUpdates({ updater, beforeInstall: async () => {}, log }))- await sleep(10)+ const updates = watchUpdates({ updater, beforeInstall: async () => {}, log })+ t.after(updates.stop)+ assert.equal(await updates.latest(), null)assert.deepEqual(log.lines, ['DeepSeek Bot: update failed: offline'])})+ test('tells what the newest check found and whether its download finished', async (t) => {+ const cases = [+ [null, null],+ [finds('0.1.9', () => Promise.resolve(['installer.exe'])), true],+ [finds('0.1.9', () => Promise.reject(new Error('sha512 checksum mismatch'))), false],+ ]+ for (const [found, downloaded] of cases) {+ const updater = new FakeUpdater()+ updater.found = found+ const updates = watchUpdates({ updater, beforeInstall: async () => {}, log: quietLog() })+ t.after(updates.stop)+ const latest = await updates.latest()+ if (downloaded === null) assert.equal(latest, null)+ else {+ assert.equal(latest.version, '0.1.9')+ assert.equal(await latest.downloaded, downloaded)+ }+ }+ })+test('a failed download, which electron-updater also reports as an error, is not left unhandled', async (t) => {const unhandled = []const note = (error) => { unhandled.push(error) }process.on('unhandledRejection', note)t.after(() => { process.off('unhandledRejection', note) })const updater = new FakeUpdater()- updater.checkForUpdates = () => Promise.resolve({ downloadPromise: Promise.reject(new Error('sha512 checksum mismatch')) })- t.after(watchUpdates({ updater, beforeInstall: async () => {}, log: quietLog() }))+ updater.found = finds('0.1.9', () => Promise.reject(new Error('sha512 checksum mismatch')))+ t.after(watchUpdates({ updater, beforeInstall: async () => {}, log: quietLog() }).stop)await sleep(20)assert.deepEqual(unhandled, [])})+ test('installs on request: the Host stops first, then the installer runs and opens the app again', async (t) => {+ const updater = new FakeUpdater()+ const steps = []+ const updates = watchUpdates({ updater, beforeInstall: async () => { steps.push('host stopped') }, log: quietLog() })+ t.after(updates.stop)+ updater.quitAndInstall = (...args) => { steps.push(['install', ...args]) }+ await updates.install()+ assert.deepEqual(steps, ['host stopped', ['install', true, true]])+ })+test('checks again every few hours until stopped', (t) => {t.mock.timers.enable({ apis: ['setInterval'] })const updater = new FakeUpdater()- const stop = watchUpdates({ updater, beforeInstall: async () => {}, log: quietLog() })+ const { stop } = watchUpdates({ updater, beforeInstall: async () => {}, log: quietLog() })t.mock.timers.tick(4 * 60 * 60_000)assert.equal(updater.checks, 2)stop()