A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Add macOS release update prompts
Fei24118dbabfe9713b
diff --git a/app/scripts/check-update.mjs b/app/scripts/check-update.mjsindex 7dbfce2c..2db07771 100644--- a/app/scripts/check-update.mjs+++ b/app/scripts/check-update.mjs@@ -1,8 +1,7 @@-// Check the update of a packaged app on Windows: serve a folder with a latest.yml and its-// installer, start the app on throwaway folders with that feed, and wait until the app has-// downloaded the update and checked its sha512. Then close the app as a user does, so that it-// installs the update as it quits, or with --kill end it at once, so that nothing is installed.-// Usage: node scripts/check-update.mjs <app executable> <feed folder> [--kill]+// Check a packaged app's update on throwaway folders. Windows downloads and installs a feed;+// macOS reads the latest release and opens no browser.+// Usage: node scripts/check-update.mjs <app executable> <feed folder> [--kill] (Windows)+// node scripts/check-update.mjs <app executable> <version> (macOS)import { spawn, spawnSync } from 'node:child_process'import { createReadStream, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync } from 'node:fs'import { createServer } from 'node:http'@@ -10,19 +9,33 @@ import { tmpdir } from 'node:os'import { basename, join, resolve } from 'node:path'import { setTimeout as sleep } from 'node:timers/promises'-const [executable, feedDir, mode] = process.argv.slice(2)-if (!executable || !feedDir || !existsSync(executable) || !existsSync(join(feedDir, 'latest.yml'))) {- console.error('check-update: usage: node scripts/check-update.mjs <app executable> <feed folder with latest.yml> [--kill]')+const [executable, source, mode] = process.argv.slice(2)+const mac = process.platform === 'darwin'+if (!executable || !source || !existsSync(executable)+ || (mac ? mode !== undefined : !existsSync(join(source, 'latest.yml')))) {+ console.error(`check-update: usage: ${mac+ ? 'node scripts/check-update.mjs <app executable> <version>'+ : 'node scripts/check-update.mjs <app executable> <feed folder with latest.yml> [--kill]'}`)process.exit(2)}-const version = /^version:\s*(\S+)/mu.exec(readFileSync(join(feedDir, 'latest.yml'), 'utf8'))?.[1]+const version = mac ? source : /^version:\s*(\S+)/mu.exec(readFileSync(join(source, 'latest.yml'), 'utf8'))?.[1]const work = mkdtempSync(join(tmpdir(), 'ds-bot-update-'))mkdirSync(join(work, 'home'))const served = []const server = createServer((request, response) => {+ if (mac) {+ const pathname = new URL(request.url, 'http://feed/').pathname+ if (request.method !== 'GET' || pathname !== '/') { response.writeHead(404).end(); return }+ served.push(pathname)+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({+ tag_name: `v${version}`,+ html_url: `https://github.com/Fei2411/DeepSeek-Bot/releases/tag/v${version}`,+ }))+ return+ }const name = basename(decodeURIComponent(new URL(request.url, 'http://feed/').pathname))- const file = join(feedDir, name)+ const file = join(source, name)served.push(name)if (!existsSync(file) || !statSync(file).isFile()) { response.writeHead(404).end(); return }response.writeHead(200, { 'content-length': statSync(file).size })@@ -33,7 +46,7 @@ const feed = `http://127.0.0.1:${String(server.address().port)}/`// Closes the window from inside the page, as check-packed does; the app then quits as it does// when a user closes it. The page goes away with the window, so the call gets no answer.-async function closeWindow(port) {+async function closeWindow(port, waitForReady = false) {const targets = await (await fetch(`http://127.0.0.1:${String(port)}/json/list`)).json()const page = targets.find(target => target.type === 'page' && target.url.startsWith('dsh-app://app'))if (!page) throw new Error('the app window is not there')@@ -42,6 +55,28 @@ async function closeWindow(port) {socket.addEventListener('open', done, { once: true })socket.addEventListener('error', reject, { once: true })})+ if (waitForReady) {+ const ready = await new Promise((done, reject) => {+ const timer = setTimeout(() => { reject(new Error('the app window did not finish booting')) }, 120_000)+ socket.addEventListener('message', (event) => {+ const message = JSON.parse(String(event.data))+ if (message.id !== 1) return+ clearTimeout(timer)+ if (message.error) reject(new Error(message.error.message))+ else done(message.result?.result?.value === true)+ })+ socket.send(JSON.stringify({+ id: 1,+ method: 'Runtime.evaluate',+ params: {+ expression: "new Promise(resolve => { const end = Date.now() + 120000; const check = () => { if (document.querySelector('.bt-tile, .bt-row')) resolve(true); else if (Date.now() >= end) resolve(false); else setTimeout(check, 250) }; check() })",+ returnByValue: true,+ awaitPromise: true,+ },+ }))+ })+ if (!ready) throw new Error('the app window did not finish booting')+ }socket.send(JSON.stringify({ id: 1, method: 'Runtime.evaluate', params: { expression: 'window.close()' } }))}@@ -59,16 +94,28 @@ try {stream.setEncoding('utf8')stream.on('data', (chunk) => { output += chunk; process.stdout.write(chunk) })}- const downloaded = `DeepSeek Bot: update ${String(version)} downloaded`- const end = Date.now() + 5 * 60_000- while (!output.includes(downloaded)) {- if (/DeepSeek Bot: update failed/u.test(output)) throw new Error('the app reported a failed update')- if (app.exitCode !== null) throw new Error(`the app exited (code ${String(app.exitCode)}) before the update was downloaded`)- if (Date.now() > end) throw new Error('the update was not downloaded within 5 minutes')+ const updateLine = `DeepSeek Bot: update ${String(version)} ${mac ? 'available' : 'downloaded'}`+ const end = Date.now() + (mac ? 3 : 5) * 60_000+ while (!output.includes(updateLine)) {+ if (mac ? /DeepSeek Bot: update check failed/u.test(output) : /DeepSeek Bot: update failed/u.test(output)) {+ throw new Error('the app reported a failed update')+ }+ if (app.exitCode !== null) {+ const status = mac ? 'the update was found' : 'the update was downloaded'+ throw new Error(`the app exited (code ${String(app.exitCode)}) before ${status}`)+ }+ if (Date.now() > end) throw new Error(mac ? 'the update was not found within 3 minutes' : 'the update was not downloaded within 5 minutes')await sleep(500)}- console.log(`check-update: ${downloaded}; the feed served ${served.join(', ')}`)- if (mode === '--kill') {+ if (mac && !served.includes('/')) throw new Error('the release feed was not requested')+ console.log(`check-update: ${updateLine}; the feed served ${served.join(', ')}`)+ if (mac) {+ await closeWindow(port, true)+ const code = await Promise.race([exited, sleep(60_000).then(() => 'timeout')])+ if (code === 'timeout') throw new Error('the app did not exit after its window closed')+ if (code !== 0) throw new Error(`the app exited with code ${String(code)}`)+ console.log('check-update: the app closed without installing')+ } else if (mode === '--kill') {spawnSync('taskkill', ['/pid', String(app.pid), '/T', '/F'], { stdio: 'ignore' })await exitedconsole.log('check-update: ended the app, so nothing was installed')@@ -83,7 +130,10 @@ try {} catch (error) {failed = trueconsole.error(`check-update: FAILED: ${error instanceof Error ? error.message : String(error)}`)- if (app?.exitCode === null) spawnSync('taskkill', ['/pid', String(app.pid), '/T', '/F'], { stdio: 'ignore' })+ if (app?.exitCode === null) {+ if (mac) app.kill()+ else spawnSync('taskkill', ['/pid', String(app.pid), '/T', '/F'], { stdio: 'ignore' })+ }}server.close()await sleep(500)diff --git a/app/src/main.mjs b/app/src/main.mjsindex 4cc5f637..d4d77087 100644--- a/app/src/main.mjs+++ b/app/src/main.mjs@@ -12,7 +12,7 @@ import electronUpdater from 'electron-updater'import { chooseLocations, localeText, text } from './first-run.mjs'import { HostProcess } from './host-process.mjs'import { importTeam } from './import.mjs'-import { UPDATE_TEXT, watchUpdates } from './updates.mjs'+import { UPDATE_TEXT, watchReleases, watchUpdates } from './updates.mjs'import { APP_ORIGIN, authenticateWebHost, forwardWebRequest, serveWebDocument } from './web.mjs'// DSH writes dsh-app://app/ into workspace file URLs and Markdown file links, so the window keeps that scheme.@@ -139,13 +139,21 @@ async function copyTeam(where, newHost) {}}-// The installed app on Windows updates itself. A run on throwaway folders (DS_BOT_HOME) checks-// only the feed it is given (DS_BOT_UPDATE_URL) and never asks, so the update waits for the quit.+// Windows updates itself; macOS asks to download the new version. Throwaway runs check only a+// given feed and never ask.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 undefined- return watchUpdates({ updater: electronUpdater.autoUpdater, feed, ask: throwaway ? undefined : askRestart, beforeInstall: stopHost })+ if (!app.isPackaged || (throwaway && feed === undefined)) return undefined+ if (process.platform === 'darwin') {+ return watchReleases({+ current: app.getVersion(), feed, ask: throwaway ? undefined : askDownload, open: url => shell.openExternal(url),+ })+ }+ if (process.platform === 'win32') {+ return watchUpdates({ updater: electronUpdater.autoUpdater, feed, ask: throwaway ? undefined : askRestart, beforeInstall: stopHost })+ }+ return undefined}async function askRestart(version) {@@ -157,6 +165,14 @@ async function askRestart(version) {return response === 0}+async function askDownload(version) {+ if (failed) return false+ const t = localeText(UPDATE_TEXT)+ const options = { type: 'info', title: 'DeepSeek Bot', message: t.available(version), detail: t.availableDetail, buttons: [t.download, t.later], defaultId: 0, cancelId: 1, noLink: true }+ const { response } = await (mainWindow ? dialog.showMessageBox(mainWindow, options) : dialog.showMessageBox(options))+ return response === 0+}+function createWindow() {mainWindow = new BrowserWindow({width: 1320, height: 860, minWidth: 720, minHeight: 480,@@ -204,16 +220,21 @@ function openOutside(url) {if (/^https?:\/\//iu.test(url)) void shell.openExternal(url)}-// 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.+// A new version may fix what keeps this one from starting.async function fail(error) {console.error(error)if (failed || stopping) returnfailed = trueconst 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)}` : ''+ const throwaway = Boolean(process.env.DS_BOT_HOME)+ const t = localeText(UPDATE_TEXT)+ const next = found ? `\n\n${found.page ? t.onFailurePage(found.version) : t.onFailure(found.version)}` : ''dialog.showErrorBox('DeepSeek Bot', `${text().notStarted}\n\n${error instanceof Error ? error.message : String(error)}${next}`)+ if (found?.page) {+ if (!throwaway) await shell.openExternal(found.page)+ app.quit()+ return+ }if (found) {mainWindow?.hide()if (await Promise.race([found.downloaded, sleep(UPDATE_DOWNLOAD_WAIT_MS).then(() => false)])) {diff --git a/app/src/updates.mjs b/app/src/updates.mjsindex d8e80d5e..c57875f6 100644--- a/app/src/updates.mjs+++ b/app/src/updates.mjs@@ -1,7 +1,4 @@-// Updates of the installed app on Windows. electron-updater reads latest.yml of the newest-// GitHub release, downloads the installer in the background and checks its sha512. When the-// download is done, the window asks whether to restart now; otherwise the installer runs at-// the next quit.+// Windows downloads and installs updates; macOS asks before opening the release page.export const UPDATE_TEXT = {en: {@@ -9,16 +6,100 @@ export const UPDATE_TEXT = {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.`,+ available: version => `DeepSeek Bot ${version} is available.`,+ availableDetail: 'This version cannot update itself. Download the new version from its release page, then replace DeepSeek Bot in Applications.',+ download: 'Download',+ onFailurePage: version => `DeepSeek Bot ${version} is available. After this box, its download page opens.`,},zh: {ready: version => `DeepSeek Bot ${version} 已经下载好。`,readyDetail: '现在重启就能更新;不重启的话,下次退出时安装。',restart: '立即重启', later: '稍后',onFailure: version => `DeepSeek Bot ${version} 下载完会自动安装,然后重新打开。`,+ available: version => `DeepSeek Bot ${version} 已经发布。`,+ availableDetail: '这个版本不能自己更新。请到发布页下载新版,再用它替换「应用程序」里的 DeepSeek Bot。',+ download: '下载',+ onFailurePage: version => `DeepSeek Bot ${version} 已经发布。关掉这个对话框后,会打开它的下载页面。`,},}const CHECK_EVERY_MS = 4 * 60 * 60_000+export const RELEASES_URL = 'https://api.github.com/repos/Fei2411/DeepSeek-Bot/releases/latest'++function parseVersion(version) {+ if (typeof version !== 'string') return null+ const value = version.replace(/^v/u, '')+ const separator = value.indexOf('-')+ const core = separator < 0 ? value : value.slice(0, separator)+ const pre = separator < 0 ? null : value.slice(separator + 1).split('.')+ const parts = core.split('.')+ if (parts.length > 3 || parts.some(part => !/^\d+$/u.test(part)) || pre?.some(part => part === '')) return null+ return {+ core: [0, 1, 2].map(index => (index < parts.length ? BigInt(parts[index]) : 0n)),+ pre,+ }+}++export function isNewer(candidate, current) {+ const newer = parseVersion(candidate)+ const older = parseVersion(current)+ if (newer === null || older === null) return false+ for (let index = 0; index < 3; index += 1) {+ if (newer.core[index] !== older.core[index]) return newer.core[index] > older.core[index]+ }+ if (newer.pre === null) return older.pre !== null+ if (older.pre === null) return false+ for (let index = 0; index < Math.max(newer.pre.length, older.pre.length); index += 1) {+ const left = newer.pre[index]+ const right = older.pre[index]+ if (left === undefined) return false+ if (right === undefined) return true+ if (left === right) continue+ const leftNumeric = /^\d+$/u.test(left)+ const rightNumeric = /^\d+$/u.test(right)+ if (leftNumeric && rightNumeric) return BigInt(left) > BigInt(right)+ if (leftNumeric !== rightNumeric) return !leftNumeric+ return left > right+ }+ return false+}++export function watchReleases({ current, fetch = globalThis.fetch, ask, open, feed = RELEASES_URL, log = console }) {+ let asked+ let latest = Promise.resolve(null)+ const check = () => {+ latest = (async () => {+ try {+ const response = await fetch(feed, {+ headers: { accept: 'application/vnd.github+json', 'user-agent': `DeepSeek-Bot/${current}` },+ })+ if (!response.ok) {+ log.error(`DeepSeek Bot: update check failed: HTTP ${String(response.status)}`)+ return null+ }+ const { tag_name, html_url: page } = await response.json()+ const version = typeof tag_name === 'string' ? tag_name.replace(/^v/u, '') : ''+ if (!isNewer(version, current)) return null+ if (typeof page !== 'string' || new URL(page).protocol !== 'https:') throw new Error('release page URL is not HTTPS')+ const found = { version, page }+ log.info(`DeepSeek Bot: update ${version} available`)+ if (ask !== undefined && asked !== version) {+ asked = version+ void Promise.resolve().then(() => ask(version))+ .then(yes => (yes ? open(page) : undefined))+ .catch((error) => { log.error(`DeepSeek Bot: update ${version} not opened: ${error instanceof Error ? error.message : String(error)}`) })+ }+ return found+ } catch (error) {+ log.error(`DeepSeek Bot: update check failed: ${error instanceof Error ? error.message : String(error)}`)+ return null+ }+ })()+ }+ check()+ const timer = setInterval(check, CHECK_EVERY_MS)+ return { stop: () => { clearInterval(timer) }, latest: () => latest }+}/*** @param {{diff --git a/app/test/updates.test.mjs b/app/test/updates.test.mjsindex da3a73d1..6b0de65c 100644--- a/app/test/updates.test.mjs+++ b/app/test/updates.test.mjs@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'import { EventEmitter } from 'node:events'import { describe, test } from 'node:test'import { setTimeout as sleep } from 'node:timers/promises'-import { watchUpdates } from '../src/updates.mjs'+import { isNewer, RELEASES_URL, watchReleases, watchUpdates } from '../src/updates.mjs'// 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.@@ -32,6 +32,172 @@ const quietLog = () => {return { lines, info: (line) => { lines.push(line) }, error: (line) => { lines.push(line) } }}+const release = (version, page = 'https://github.com/Fei2411/DeepSeek-Bot/releases/tag/v0.1.9') => ({+ tag_name: `v${version}`, html_url: page,+})++const releaseResponse = (body, status = 200) => ({+ ok: status >= 200 && status < 300,+ status,+ json: async () => body,+})++describe('isNewer', () => {+ for (const [candidate, current, expected] of [+ ['0.1.8', '0.1.7', true],+ ['v0.2.0', '0.1.9', true],+ ['0.1.7', '0.1.7', false],+ ['0.1.6', '0.1.7', false],+ ['0.2.0', '0.2.0-rc.2', true],+ ['0.2.0-rc.2', '0.2.0', false],+ ['0.2.0-rc.10', '0.2.0-rc.2', true],+ ['0.1.10', '0.1.9', true],+ ['nightly', '0.1.7', false],+ ]) {+ test(`${candidate} compared with ${current}`, () => {+ assert.equal(isNewer(candidate, current), expected)+ })+ }+})++describe('watchReleases', () => {+ test('checks the latest release at once with the GitHub headers, or uses a given feed', async (t) => {+ const calls = []+ const fetch = async (url, options) => {+ calls.push({ url, options })+ return releaseResponse(release('0.1.7'))+ }+ const updates = watchReleases({ current: '0.1.7', fetch, log: quietLog() })+ t.after(updates.stop)+ assert.equal(await updates.latest(), null)+ assert.deepEqual(calls[0], {+ url: RELEASES_URL,+ options: { headers: { accept: 'application/vnd.github+json', 'user-agent': 'DeepSeek-Bot/0.1.7' } },+ })++ const feed = 'http://127.0.0.1:8080/'+ const custom = watchReleases({ current: '0.1.7', fetch, feed, log: quietLog() })+ t.after(custom.stop)+ await custom.latest()+ assert.equal(calls[1].url, feed)+ })++ test('reports a newer release and opens its page only when accepted', async (t) => {+ const page = 'https://github.com/Fei2411/DeepSeek-Bot/releases/tag/v0.1.9'+ for (const accepted of [true, false]) {+ const asked = []+ const opened = []+ const updates = watchReleases({+ current: '0.1.7', fetch: async () => releaseResponse(release('0.1.9', page)), log: quietLog(),+ ask: async version => { asked.push(version); return accepted },+ open: url => { opened.push(url) },+ })+ t.after(updates.stop)+ assert.deepEqual(await updates.latest(), { version: '0.1.9', page })+ await sleep(0)+ assert.deepEqual(asked, ['0.1.9'])+ assert.deepEqual(opened, accepted ? [page] : [])+ }+ })++ test('ignores the same or an older release', async (t) => {+ for (const version of ['0.1.7', '0.1.6']) {+ const asked = []+ const updates = watchReleases({+ current: '0.1.7', fetch: async () => releaseResponse(release(version)), log: quietLog(),+ ask: async value => { asked.push(value); return true }, open: () => {},+ })+ t.after(updates.stop)+ assert.equal(await updates.latest(), null)+ assert.deepEqual(asked, [])+ }+ })++ test('asks once per version and asks again for a later version', async (t) => {+ t.mock.timers.enable({ apis: ['setInterval'] })+ let version = '0.1.9'+ let checks = 0+ const asked = []+ const updates = watchReleases({+ current: '0.1.7',+ fetch: async () => { checks += 1; return releaseResponse(release(version)) },+ ask: async value => { asked.push(value); return false },+ open: () => {},+ log: quietLog(),+ })+ t.after(updates.stop)++ await updates.latest()+ await sleep(0)+ t.mock.timers.tick(4 * 60 * 60_000)+ await updates.latest()+ await sleep(0)+ version = '0.1.10'+ t.mock.timers.tick(4 * 60 * 60_000)+ await updates.latest()+ await sleep(0)++ assert.equal(checks, 3)+ assert.deepEqual(asked, ['0.1.9', '0.1.10'])+ })++ test('reports releases without asking in throwaway runs', async (t) => {+ let opens = 0+ const updates = watchReleases({+ current: '0.1.7', fetch: async () => releaseResponse(release('0.1.9')),+ ask: undefined, open: () => { opens += 1 }, log: quietLog(),+ })+ t.after(updates.stop)+ assert.equal((await updates.latest()).version, '0.1.9')+ assert.equal(opens, 0)+ })++ test('logs failed requests, invalid JSON, and non-HTTPS release pages without throwing', async (t) => {+ const cases = [+ [async () => releaseResponse({}, 403), 'DeepSeek Bot: update check failed: HTTP 403'],+ [async () => { throw new Error('offline') }, 'DeepSeek Bot: update check failed: offline'],+ [async () => ({ ok: true, status: 200, json: async () => { throw new Error('bad JSON') } }), 'DeepSeek Bot: update check failed: bad JSON'],+ [async () => releaseResponse(release('0.1.9', 'http://github.com/Fei2411/DeepSeek-Bot')), 'DeepSeek Bot: update check failed: release page URL is not HTTPS'],+ ]+ for (const [fetch, message] of cases) {+ const log = quietLog()+ const updates = watchReleases({ current: '0.1.7', fetch, log })+ t.after(updates.stop)+ assert.equal(await updates.latest(), null)+ assert.deepEqual(log.lines, [message])+ }+ })++ test('logs a rejected prompt without an unhandled rejection', async (t) => {+ const unhandled = []+ const note = error => { unhandled.push(error) }+ process.on('unhandledRejection', note)+ t.after(() => { process.off('unhandledRejection', note) })+ const log = quietLog()+ const updates = watchReleases({+ current: '0.1.7', fetch: async () => releaseResponse(release('0.1.9')),+ ask: async () => { throw new Error('dialog failed') }, open: () => {}, log,+ })+ t.after(updates.stop)+ await updates.latest()+ await sleep(20)+ assert.deepEqual(log.lines, ['DeepSeek Bot: update 0.1.9 available', 'DeepSeek Bot: update 0.1.9 not opened: dialog failed'])+ assert.deepEqual(unhandled, [])+ })++ test('stop clears the interval', async (t) => {+ t.mock.timers.enable({ apis: ['setInterval'] })+ let checks = 0+ const updates = watchReleases({+ current: '0.1.7', fetch: async () => { checks += 1; return releaseResponse(release('0.1.7')) }, log: quietLog(),+ })+ await updates.latest()+ updates.stop()+ t.mock.timers.tick(4 * 60 * 60_000)+ assert.equal(checks, 1)+ })+})+describe('watchUpdates', () => {test('downloads in the background, installs at the quit, and checks at once', (t) => {const updater = new FakeUpdater()