A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Keep the desktop running behind a system tray
klarkxy9385bf8a7119
diff --git a/NOTICE b/NOTICEindex b5b5631d..944c7d20 100644--- a/NOTICE+++ b/NOTICE@@ -24,6 +24,10 @@ MIT License, Copyright (c) 2026 DeepSeekapps/desktop/src/preload-windows.ts, apps/desktop/src/preload-platform.tsand apps/desktop/src/preload-theme.ts: the caption-band marks, thefullscreen mark, the caption-color measure and the theme sync.+ - app/src/shell.mjs, app/src/tray.mjs and app/src/background-notice.mjs follow+ apps/desktop/src/tray.ts and apps/desktop/src/background-notice.ts: the+ system tray with its menu, the window that hides instead of closing, and+ the one-time confirmation before it hides.- app/src/bot-browser.mjs adapts apps/desktop/src/browser-guests.ts, andthe browser part of app/src/preload.cjs followsapps/desktop/src/preload-browser.ts: the webview leases, the attachmentdiff --git a/app/README.md b/app/README.mdindex 0bc00879..bca72a89 100644--- a/app/README.md+++ b/app/README.md@@ -47,9 +47,9 @@ At every start the Host puts these three bundles at the head of the profile's bu## Check a change-`npm test` checks the composition of the profile, the import on throwaway folders, the first-run check on a chat with a record that the pinned DSH does not know, and that every package the app runs on is a dependency (see [Package](#package)).+`npm test` checks the composition of the profile, the import on throwaway folders, the first-run check on a chat with a record that the pinned DSH does not know, and that every package the app runs on is a dependency (see [Package](#package)). It also checks the window and the tray: the close hides the window, the tray opens it again, a window that is gone is built anew against the Host that runs, the application menu of macOS has no Quit of its own, the launch URL of the Host is used once, and the update waits for a window that is hidden. The main process runs there with the Electron parts as test doubles (`test/helpers/`), so that no display, no DSH and no data of the user are needed.-`scripts/shot.mjs` starts the app on throwaway folders, saves a screenshot of its window, prints the page text, closes the window the way a user does and waits until the app exits. Use the mock model of the plugin, `../ds-bot/dev/mock-llm.mjs` (`MOCK_PORT=<port> node ../ds-bot/dev/mock-llm.mjs`).+`scripts/shot.mjs` starts the app on throwaway folders, saves a screenshot of its window, prints the page text, closes the window the way a user does (it hides, and the app goes on) and ends the app the way the tray's Quit ends it. Use the mock model of the plugin, `../ds-bot/dev/mock-llm.mjs` (`MOCK_PORT=<port> node ../ds-bot/dev/mock-llm.mjs`).```shDS_BOT_HOME=<tmp>/home DS_BOT_SHELL_DATA=<tmp>/shell \@@ -97,7 +97,7 @@ node scripts/check-update.mjs "dist-pack/win-unpacked/DeepSeek Bot.exe" dist-nexnode scripts/check-update.mjs ./deepseek-bot.AppImage dist-next --kill # a Linux AppImage (latest-linux.yml)```-It serves the feed folder, starts the app on throwaway folders and waits until the app has downloaded the update and checked its sha512. Then it closes the app as a user does, so that the app installs the update as it quits; with `--kill` it ends the app, so that nothing is installed. On your own machine use `--kill`: the installer would install into `%LOCALAPPDATA%\Programs\DeepSeek Bot`, and an AppImage replaces itself. The download stays in `%LOCALAPPDATA%\deepseek-bot-updater` (`~/.cache/deepseek-bot-updater` on Linux). CI runs it without `--kill` on its installed app, then checks that the installed version is the new one and that the updated app passes `check-packed`; for an AppImage it checks that the file is the new one.+It serves the feed folder, starts the app on throwaway folders and waits until the app has downloaded the update and checked its sha512. Then it ends the app the way the tray's Quit ends it, so that the app installs the update as it quits; with `--kill` it ends the app, so that nothing is installed. On your own machine use `--kill`: the installer would install into `%LOCALAPPDATA%\Programs\DeepSeek Bot`, and an AppImage replaces itself. The download stays in `%LOCALAPPDATA%\deepseek-bot-updater` (`~/.cache/deepseek-bot-updater` on Linux). CI runs it without `--kill` on its installed app, then checks that the installed version is the new one and that the updated app passes `check-packed`; for an AppImage it checks that the file is the new one.On macOS and for a Linux deb, pass the app executable and a version to mock a newer release:@@ -105,13 +105,31 @@ On macOS and for a Linux deb, pass the app executable and a version to mock a nenode scripts/check-update.mjs "<app executable>" 99.0.0```-The script serves a releases list with one release of that version that has this machine's package (the Mac's zip, or the `linux-amd64` deb), starts the app on throwaway folders with it, waits until the app logs the new version, and closes the window. It does not open a browser.+The script serves a releases list with one release of that version that has this machine's package (the Mac's zip, or the `linux-amd64` deb), starts the app on throwaway folders with it, waits until the app logs the new version, and ends the app the way the tray's Quit ends it. It does not open a browser.++## The tray and quitting++The app builds a system tray icon on Windows, macOS and Linux (`src/shell.mjs`, `src/tray.mjs`); the icon is the app's own whale (`assets/tray.*`, drawn by `npm run icon`). The menu holds "Open DeepSeek Bot" and "Quit DeepSeek Bot". Whether the icon is visible belongs to the desktop: on Linux, GNOME and KDE draw it only with a tray extension.++Closing the window hides it: the Host and the Bots go on working, and the Bot browsers' tabs stay. Starting the app again brings the window back, because the second copy hands itself to the one that runs. When the window is gone for good, the tray's Open builds a new one that talks to the Host that runs: it loads the Host's plain address, and the cookie of the first load still carries the session, so neither the launch token nor a second Host is needed.++No window closed ends the app; the tray's Quit is the one ordinary way out. The first close asks once, because the app stays in the tray; the answer is kept in the app's own data (the `tray-close-acknowledged` file in its user data folder). A close during the first start's import or during a data move cancels that work, as it did before. An update that restarts the app, a data move that restarts it, a failed start and the end of the operating system's session close the window for good.++The application menu of macOS has no Quit and no ⌘Q, for the same reason: the tray's Quit is the one ordinary way out. Only when the tray cannot be built does the menu carry a Quit, so that the app can still be ended.++Without a tray (some Linux desktops have none), closing the window asks whether the app should end, and minimizes it when the answer is no: the window stays reachable, and the app does not vanish. This is the one exceptional path, and it is the only place where the app asks before it ends.++The launch URL of the Host is good for one use only. When the first load never came through (the window died while it loaded), no window carries the token again: the new window loads the Host's plain address, and the Host refuses it when the cookie is not there. Starting the app again then gives a new token.++`scripts/check-lifecycle.mjs` (`npm run check-lifecycle`) checks this in a real Electron with a fake Host: no DSH, no model, no data of the user. It keeps its data in `app/.dsh-test-tray-lifecycle` and removes it afterwards. It needs a desktop; the unit tests cover the same rules without one.## Layout| File | What it does ||---|---|| `src/main.mjs` | Main process: one instance, the window, which loads the Host's loopback address as DSH Web does, and the sign-in page DSH opens, which goes to the system browser |+| `src/shell.mjs`, `src/tray.mjs`, `src/background-notice.mjs` | The window and the tray: the window hides instead of closing, the tray opens it again and quits the app, and the one-time confirmation before the window hides |+| `src/update-prompt.mjs` | An update prompt that waits for the window to be shown again || `src/host-port.mjs` | The Host's port, kept between starts, since the page keeps its storage per address || `src/preload.cjs` | Hands DS Bot's settings the data location and its move, and DS Bot's Bot browsers their webview leases and cookie imports. On Windows it marks the page for the frameless window and sends the caption buttons the colors of the surface under them || `src/bot-browser.mjs` | The Bot browsers' webviews: only a leased one attaches, with fixed preferences; each Bot's logins stay on disk until the Bot is deleted; pages cannot reach the Host |@@ -126,12 +144,13 @@ The script serves a releases list with one release of that version that has this| `src/move-data.mjs` | The move of the data location: which folders can take it, and the copy through a staging folder || `src/updates.mjs` | The self-updates (Windows installer, Linux AppImage) and the release-page checks (macOS, Linux deb) || `engine/` | On hold, not installed: the bundle `deepseek-bot-engine` for the app's own window in `ui/` |-| `test/` | `npm test`: the composition of the profile, and the dependencies that the package needs |+| `test/` | `npm test`: the composition of the profile, the dependencies that the package needs, and the window and the tray (the main process runs there with the Electron parts as test doubles, in `test/helpers/`) || `ui/` | On hold, not built or packaged: the app's own window. React, built with Vite (`vite.config.js`) into `ui/dist`. It draws the plugin's own Bot views from `../ds-bot/src/client/` (sidebar, chat rows, docks, dialogs and their stylesheets) and puts its own Markdown in place of DSH's. It uses ds-bot's `api/bot` channel and its live feed `api/bot/feed` |-| `assets/` | The app icon: `icon.svg`, `icon.png` (1024 px) and `icon.ico` (Windows, 16 to 256 px). `npm run icon` (`scripts/icon.mjs`) draws them again from the Main Bot's whale in `../ds-bot` |+| `assets/` | The app icon: `icon.svg`, `icon.png` (1024 px) and `icon.ico` (Windows, 16 to 256 px), and the tray marks: `tray.ico` (Windows), `tray.png` (Linux) and `trayTemplate.png` with its `@2x` (macOS). `npm run icon` (`scripts/icon.mjs`) draws them again from the Main Bot's whale in `../ds-bot` || `electron-builder.yml`, `build/` | The package and the installers: app identity, files, icons, the Windows installer, the macOS zip and the Linux AppImage and deb || `scripts/check-packed.mjs` | `npm run check-packed`: the check of a packaged app || `scripts/check-update.mjs` | The check of a packaged app's update from a feed folder (Windows, AppImage) or a mocked release (macOS, deb) |+| `scripts/check-lifecycle.mjs` | `npm run check-lifecycle`: the check of the window and the tray in a real Electron, with a fake Host |The Host installs plugins with the app's own pnpm (`node_modules/pnpm`).diff --git a/app/assets/tray.ico b/app/assets/tray.iconew file mode 100644index 00000000..00f1bb77Binary files /dev/null and b/app/assets/tray.ico differdiff --git a/app/assets/tray.png b/app/assets/tray.pngnew file mode 100644index 00000000..e197643dBinary files /dev/null and b/app/assets/tray.png differdiff --git a/app/assets/trayTemplate.png b/app/assets/trayTemplate.pngnew file mode 100644index 00000000..e892085bBinary files /dev/null and b/app/assets/trayTemplate.png differdiff --git a/app/assets/[email protected] b/app/assets/[email protected]new file mode 100644index 00000000..15dc123fBinary files /dev/null and b/app/assets/[email protected] differdiff --git a/app/package.json b/app/package.jsonindex 9f8dca1f..cb1bf41a 100644--- a/app/package.json+++ b/app/package.json@@ -16,6 +16,7 @@"pack": "electron-builder --dir --publish never","dist": "electron-builder --publish never","check-packed": "node scripts/check-packed.mjs",+ "check-lifecycle": "node scripts/check-lifecycle.mjs","shot": "node scripts/shot.mjs","icon": "node scripts/icon.mjs","test": "node --test \"test/*.test.mjs\""diff --git a/app/scripts/check-lifecycle.mjs b/app/scripts/check-lifecycle.mjsnew file mode 100644index 00000000..0839f943--- /dev/null+++ b/app/scripts/check-lifecycle.mjs@@ -0,0 +1,139 @@+// Check the window and the tray of the app in a real Electron, with a fake Host: no DSH, no+// model, no data of the user. The app hides the window instead of closing it, the tray opens+// it again, and a window that is gone for good is built anew and talks to the Host that runs.+// Usage: node scripts/check-lifecycle.mjs+import { spawn, spawnSync } from 'node:child_process'+import { createRequire } from 'node:module'+import { mkdirSync, rmSync } from 'node:fs'+import net from 'node:net'+import { join } from 'node:path'+import { setTimeout as sleep } from 'node:timers/promises'++const require = createRequire(import.meta.url)+const electron = require('electron')+const here = import.meta.dirname+// The data of the run is a folder of its own in the app's own directory: the check never+// writes into the data of the user.+const work = join(here, '..', '.dsh-test-tray-lifecycle')++// The app answers over its standard output and over a plain socket. Both carry one answer+// per line, so that the check needs no dependency.+const answers = []+const waiters = []+let output = ''++const take = (answer) => {+ if (waiters.length > 0) waiters.shift()(answer)+ else answers.push(answer)+}++const nextAnswer = (timeout = 30_000) => {+ if (answers.length > 0) return Promise.resolve(answers.shift())+ return new Promise((done, fail) => {+ const timer = setTimeout(() => { fail(new Error('the app did not answer in time')) }, timeout)+ waiters.push((value) => { clearTimeout(timer); done(value) })+ })+}++// A stream that carries one answer per line: the rest of it is the output of the app.+const reader = (keep = true) => {+ let buffer = ''+ return (chunk) => {+ if (keep) output += chunk+ buffer += chunk+ for (;;) {+ const index = buffer.indexOf('\n')+ if (index < 0) break+ const line = buffer.slice(0, index).trim()+ buffer = buffer.slice(index + 1)+ if (line.startsWith('{')) take(JSON.parse(line))+ }+ }+}++const fail = (message) => { throw new Error(message) }++let child+let connection++try {+ rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 500 })+ mkdirSync(work, { recursive: true })+ child = spawn(electron, [join(here, '..', 'test', 'electron', 'lifecycle-main.mjs')], {+ cwd: join(here, '..'),+ env: { ...process.env, DS_BOT_SHELL_DATA: work },+ stdio: ['ignore', 'pipe', 'pipe'],+ })+ child.stdout.setEncoding('utf8')+ child.stdout.on('data', reader())+ child.stderr.setEncoding('utf8')+ child.stderr.on('data', reader())+ const exited = new Promise((done) => { child.once('exit', (code, signal) => { done({ code, signal }) }) })+ const broken = new Promise((_, fail) => { child.once('error', error => fail(error)) })++ const first = await Promise.race([+ nextAnswer(60_000),+ exited.then(outcome => fail(`the app ended before it answered (${JSON.stringify(outcome)})`)),+ broken,+ ])++ connection = net.connect(Number(first.port), '127.0.0.1')+ await new Promise((done, fail) => {+ connection.once('connect', done)+ connection.once('error', fail)+ })+ connection.setEncoding('utf8')+ connection.on('data', reader(false))+ const ask = async (command, timeout = 30_000) => {+ const answer = nextAnswer(timeout)+ connection.write(`${command}\n`)+ return answer+ }++ if (!first.ready) fail('the window did not start')+ if (first.visible !== true) fail('the window is not on the screen')+ if (!first.url?.startsWith('http://127.0.0.1:')) fail(`the window did not reach the Host: ${String(first.url)}`)+ if (first.title !== 'DeepSeek Bot') fail(`the page did not load: ${String(first.title)}`)+ if (first.hasTray !== true) fail('the tray is not there')+ console.log('check-lifecycle: the window shows the Host and the tray is there')++ const closed = await ask('close')+ if (closed.destroyed !== false) fail('the window was destroyed instead of hidden')+ if (closed.visible !== false) fail('the window is still on the screen')+ if (closed.quitting !== false) fail('the app ended with its window')+ console.log('check-lifecycle: the close hides the window and the app goes on')++ const opened = await ask('open')+ if (opened.visible !== true) fail('the tray did not open the window')+ if (opened.destroyed !== false) fail('the window was destroyed')+ console.log('check-lifecycle: the tray opens the window again')++ const gone = await ask('destroy')+ if (gone.destroyed !== null) fail('the window is still there')+ const rebuilt = await ask('open')+ if (rebuilt.visible !== true) fail('the tray did not build a new window')+ if (rebuilt.destroyed !== false) fail('the new window is not there')+ if (rebuilt.url?.includes('token=')) fail(`the new window used the launch URL again: ${String(rebuilt.url)}`)+ if (!rebuilt.url?.startsWith('http://127.0.0.1:')) fail(`the new window did not reach the Host: ${String(rebuilt.url)}`)+ if (rebuilt.hosts !== 1) fail('a second Host was started')+ console.log('check-lifecycle: a window that is gone is built anew and talks to the same Host')++ // The quit ends the app, so the answer never comes: the exit does.+ connection.write('quit\n')+ const outcome = await Promise.race([exited, sleep(20_000).then(() => undefined)])+ if (outcome === undefined) fail('the app did not end after the tray quit')+ if (outcome.code !== 0) fail(`the app ended with code ${String(outcome.code)}`)+ console.log('check-lifecycle: the tray quit ends the app')+ console.log('check-lifecycle: passed')+} catch (error) {+ console.error(`check-lifecycle: FAILED: ${error instanceof Error ? error.message : String(error)}`)+ if (output !== '') console.error(output)+ process.exitCode = 1+} finally {+ connection?.destroy()+ if (child !== undefined && child.exitCode === null && child.signalCode === null) {+ if (process.platform === 'win32') spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], { stdio: 'ignore' })+ else child.kill('SIGKILL')+ }+ rmSync(work, { recursive: true, force: true, maxRetries: 10, retryDelay: 500 })+}diff --git a/app/scripts/check-packed.mjs b/app/scripts/check-packed.mjsindex 9e22f315..6269bdc8 100644--- a/app/scripts/check-packed.mjs+++ b/app/scripts/check-packed.mjs@@ -1,9 +1,11 @@// Check a packaged app: start it on throwaway folders with the ds-bot mock model, choose a model,-// send a message, wait for the reply, then close the window the way a user does and wait until-// the app has exited. Fails on a page error or a non-zero exit.+// send a message, wait for the reply, then close the window the way a user does: the window hides+// and the app goes on. The window comes back when the app is started again, and the app ends the+// way the tray's Quit ends it. Fails on a page error or a non-zero exit.// Usage: node scripts/check-packed.mjs [app executable] [screenshot.png]// The executable defaults to the one that `npm run pack` or `npm run dist` writes into dist-pack/.import { spawn, spawnSync } from 'node:child_process'+import { connect } from 'node:net'import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'@@ -91,6 +93,29 @@ async function appPage(port, deadline) {throw new Error('the app window did not appear')}+// The Host goes on while the window is hidden: its port answers.+async function hostAlive() {+ const { port } = JSON.parse(readFileSync(join(work, 'shell', 'host-port.json'), 'utf8'))+ await new Promise((done, reject) => {+ const socket = connect(port, '127.0.0.1')+ socket.once('connect', () => { socket.destroy(); done() })+ socket.once('error', reject)+ })+}++// The tray's Quit ends the app. The check cannot click the tray icon, so it asks the browser+// target of the debugging port to close, which ends the app gracefully.+async function browserClose(port) {+ const version = await (await fetch(`http://127.0.0.1:${String(port)}/json/version`)).json()+ const socket = new WebSocket(version.webSocketDebuggerUrl)+ await new Promise((done, reject) => {+ socket.addEventListener('open', done, { once: true })+ socket.addEventListener('error', reject, { once: true })+ })+ socket.send(JSON.stringify({ id: 1, method: 'Browser.close' }))+ socket.close()+}+function devtools(url, problems) {const socket = new WebSocket(url)const pending = new Map()@@ -244,12 +269,30 @@ try {writeFileSync(resolve(shotFile), Buffer.from(data, 'base64'))console.log(`check-packed: saved ${resolve(shotFile)}`)}- // Closed like a user closes it, also after a failure, so that the app stops its Host. The page- // goes away with the window, so this call gets no answer.+ if (chatError) throw chatError+ // Closed the way a user closes it: the window hides and the app goes on.void cdp.call('Runtime.evaluate', { expression: 'window.close()' }).catch(() => undefined)+ await sleep(4000)+ if (app.exitCode !== null) throw new Error('the app ended with its window')+ const hidden = await cdp.call('Runtime.evaluate', { expression: 'document.visibilityState', returnByValue: true })+ if (hidden.result?.value !== 'hidden') throw new Error('the window is not hidden')+ await hostAlive()+ console.log('check-packed: the window is hidden and the Host goes on')+ // Starting the app again brings the window back; the second copy ends at once, because the+ // first one holds the lock.+ const second = spawn(outsideCheckout(resolve(executable)), [`--remote-debugging-port=${String(port + 1)}`], { stdio: 'ignore', env })+ children.push(second)+ const secondExit = await Promise.race([new Promise((done) => { second.once('exit', (code) => { done(code) }) }), sleep(30_000).then(() => undefined)])+ if (secondExit === undefined) throw new Error('the second copy of the app did not end')+ if (app.exitCode !== null) throw new Error('the app ended when it was started again')+ const shown = await cdp.call('Runtime.evaluate', { expression: 'document.visibilityState', returnByValue: true })+ if (shown.result?.value !== 'visible') throw new Error('the window did not come back')+ console.log('check-packed: the window came back when the app was started again')+ // The tray's Quit is the way out; the check cannot click the tray, so it asks the browser+ // target to close, which ends the app gracefully.+ await browserClose(port)const outcome = await Promise.race([exited, sleep(40_000).then(() => undefined)])- if (chatError) throw chatError- if (outcome === undefined) throw new Error('the app did not exit after its window closed')+ if (outcome === undefined) throw new Error('the app did not exit after the quit')console.log(`check-packed: app exited (code ${String(outcome.code)}, signal ${String(outcome.signal)})`)if (outcome.code !== 0) throw new Error(`the app exited with code ${String(outcome.code)}`)if (problems.length > 0) throw new Error(`page problems:\n ${problems.join('\n ')}`)diff --git a/app/scripts/check-update.mjs b/app/scripts/check-update.mjsindex a500dd3c..391f3394 100644--- a/app/scripts/check-update.mjs+++ b/app/scripts/check-update.mjs@@ -56,9 +56,9 @@ const server = createServer((request, response) => {await new Promise((done) => { server.listen(0, '127.0.0.1', done) })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, waitForReady = false) {+// The tray's Quit ends the app. The check cannot click the tray icon, so it asks the browser+// target of the debugging port to close. Tray menu dispatch is covered by the main-process tests.+async function quitApp(port, waitForReady = false) {// Until the Host is ready the window shows a note of its own.const find = async () => {const targets = await (await fetch(`http://127.0.0.1:${String(port)}/json/list`)).json()@@ -95,7 +95,15 @@ async function closeWindow(port, waitForReady = false) {})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()' } }))+ socket.close()+ const version = await (await fetch(`http://127.0.0.1:${String(port)}/json/version`)).json()+ const browser = new WebSocket(version.webSocketDebuggerUrl)+ await new Promise((done, reject) => {+ browser.addEventListener('open', done, { once: true })+ browser.addEventListener('error', reject, { once: true })+ })+ browser.send(JSON.stringify({ id: 1, method: 'Browser.close' }))+ browser.close()}// taskkill /T takes the Host and Electron's helpers along; a unix kill ends the tree's root,@@ -135,21 +143,21 @@ try {if (releasePage && !served.includes('/')) throw new Error('the release feed was not requested')console.log(`check-update: ${updateLine}; the feed served ${served.join(', ')}`)if (releasePage) {- await closeWindow(port, true)+ await quitApp(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')+ console.log('check-update: the app quit without installing')} else if (mode === '--kill') {killApp()await exitedconsole.log('check-update: ended the app, so nothing was installed')} else {- await closeWindow(port)+ await quitApp(port)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)}, so it does not install the update`)- console.log('check-update: the app closed; its installer runs now')+ console.log('check-update: the app quit; its installer runs now')}console.log('check-update: passed')} catch (error) {diff --git a/app/scripts/icon.mjs b/app/scripts/icon.mjsindex 149e71e3..3295ef58 100644--- a/app/scripts/icon.mjs+++ b/app/scripts/icon.mjs@@ -1,5 +1,7 @@// Draws the app icon from the Main Bot's whale in ../ds-bot and writes assets/icon.svg,-// assets/icon.png (1024 px) and assets/icon.ico (Windows, 16 to 256 px).+// assets/icon.png (1024 px), assets/icon.ico (Windows, 16 to 256 px) and the tray marks:+// assets/tray.ico (Windows), assets/tray.png (Linux) and assets/trayTemplate.png with its+// @2x (macOS).// Usage: npm run icon. It runs itself again inside Electron, which turns the SVG into PNGs.import { spawnSync } from 'node:child_process'import { mkdirSync, writeFileSync } from 'node:fs'@@ -11,6 +13,13 @@ import { characterMarkup, MASK_ID } from '../../ds-bot/src/client/characters.js'const here = fileURLToPath(import.meta.url)const assets = join(dirname(here), '..', 'assets')const ICO_SIZES = [16, 20, 24, 32, 36, 40, 48, 64, 72, 96, 128, 256]+// The tray icon is small: the sizes a notification area shows, and one plain png for Linux.+const TRAY_ICO_SIZES = [16, 20, 24, 32]+const TRAY_PNG_SIZE = 24+// macOS draws a template image itself, in the colour of the menu bar: a black mark with the+// shape of the whale.+const TRAY_TEMPLATE_SIZES = [16, 32]+const DEEPSEEK_INK = '#4D6BFE'// The whale's body spans x 4..95.9 and y 20.9..79 of its 100 box.const WHALE = { cx: 49.95, cy: 49.95, width: 91.9 }@@ -38,7 +47,7 @@ function iconSvg(plate, size = 1024) {const x = size / 2 - WHALE.cx * scale - whaleWidth * 0.015const y = size / 2 - WHALE.cy * scale - whaleWidth * 0.018const path = tile(size, inset)- const whale = characterMarkup('whale', 'deepseek').replaceAll(MASK_ID, 'eyes').replaceAll('var(--bt-ink-deepseek)', '#4D6BFE')+ const whale = characterMarkup('whale', 'deepseek').replaceAll(MASK_ID, 'eyes').replaceAll('var(--bt-ink-deepseek)', DEEPSEEK_INK)return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"><defs><linearGradient id="plate" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#ffffff"/><stop offset="1" stop-color="#eef1f7"/></linearGradient>@@ -51,6 +60,21 @@ function iconSvg(plate, size = 1024) {`}+// The tray mark: the whale alone, so that it still reads at the size of a tray icon. The+// macOS template is the same shape in black, because macOS paints it in the colour of the+// menu bar itself.+function traySvg(size, ink) {+ const whaleWidth = size * 0.94+ const scale = whaleWidth / WHALE.width+ const x = size / 2 - WHALE.cx * scale - whaleWidth * 0.015+ const y = size / 2 - WHALE.cy * scale - whaleWidth * 0.018+ const whale = characterMarkup('whale', 'deepseek').replaceAll(MASK_ID, 'eyes').replaceAll('var(--bt-ink-deepseek)', ink)+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">+<g transform="translate(${x.toFixed(2)} ${y.toFixed(2)}) scale(${scale.toFixed(4)})">${whale}</g>+</svg>+`+}+// PNG entries in an .ico file, which Windows reads since Vista.function icoFile(images) {const head = Buffer.alloc(6 + 16 * images.length)@@ -92,12 +116,24 @@ async function renderInElectron(jobs) {}if (process.versions.electron) {- const jobs = [{ svg: iconSvg(0.805), size: 1024 }, ...ICO_SIZES.map(size => ({ svg: iconSvg(0.92, size), size }))]+ const jobs = [+ { svg: iconSvg(0.805), size: 1024 },+ ...ICO_SIZES.map(size => ({ svg: iconSvg(0.92, size), size })),+ ...TRAY_ICO_SIZES.map(size => ({ svg: traySvg(size, DEEPSEEK_INK), size })),+ { svg: traySvg(TRAY_PNG_SIZE, DEEPSEEK_INK), size: TRAY_PNG_SIZE },+ ...TRAY_TEMPLATE_SIZES.map(size => ({ svg: traySvg(size, '#000000'), size })),+ ]// Not awaited at the top: Electron is ready only after the main module has run.const { app } = await import('electron')- app.whenReady().then(() => renderInElectron(jobs)).then(([large, ...small]) => {+ app.whenReady().then(() => renderInElectron(jobs)).then(([large, ...rest]) => {+ const small = rest.slice(0, ICO_SIZES.length)+ const tray = rest.slice(ICO_SIZES.length)writeFileSync(join(assets, 'icon.png'), large)writeFileSync(join(assets, 'icon.ico'), icoFile(ICO_SIZES.map((size, index) => ({ size, png: small[index] }))))+ writeFileSync(join(assets, 'tray.ico'), icoFile(TRAY_ICO_SIZES.map((size, index) => ({ size, png: tray[index] }))))+ writeFileSync(join(assets, 'tray.png'), tray[TRAY_ICO_SIZES.length])+ writeFileSync(join(assets, 'trayTemplate.png'), tray[TRAY_ICO_SIZES.length + 1])+ writeFileSync(join(assets, '[email protected]'), tray[TRAY_ICO_SIZES.length + 2])app.exit(0)}).catch((error) => {console.error(error)@@ -111,5 +147,5 @@ if (process.versions.electron) {const electron = createRequire(import.meta.url)('electron')const run = spawnSync(electron, [here], { stdio: 'inherit', env })if (run.status !== 0) process.exit(run.status ?? 1)- console.log('icon: wrote assets/icon.svg, assets/icon.png and assets/icon.ico')+ console.log('icon: wrote assets/icon.svg, assets/icon.png, assets/icon.ico and the tray marks')}diff --git a/app/scripts/shot.mjs b/app/scripts/shot.mjsindex 6b3c7615..bab6e8b9 100644--- a/app/scripts/shot.mjs+++ b/app/scripts/shot.mjs@@ -1,5 +1,6 @@// Dev check: run the app on throwaway folders, save a screenshot of its window, print what the page shows,-// then close the window the way a user does and wait until the app has exited.+// then close the window the way a user does (it hides, and the app goes on) and end the app the way the+// tray's Quit ends it.// Usage: node scripts/shot.mjs <out.png> [seconds to wait before the screenshot]// Set DS_BOT_HOME and DS_BOT_SHELL_DATA to throwaway folders, plus the model variables for the Host// (for the ds-bot mock model: DEEPSEEK_BASE_URL=http://127.0.0.1:<port>/v1 and DEEPSEEK_API_KEY=mock-key).@@ -73,8 +74,19 @@ try {})console.log(`shot: saved ${resolve(out)}`)console.log(`shot: page ${String(result.value)}`)- // The page goes away with the window, so this call gets no answer.+ // The window closes the way a user closes it: it hides, and the app goes on.void cdp.call('Runtime.evaluate', { expression: 'window.close()' }).catch(() => undefined)+ await sleep(2000)+ // The tray's Quit ends the app. The script cannot click the tray icon, so it asks the browser+ // target of the debugging port to close, which ends the app gracefully.+ const version = await (await fetch(`http://127.0.0.1:${String(port)}/json/version`)).json()+ const browser = new WebSocket(version.webSocketDebuggerUrl)+ await new Promise((done, reject) => {+ browser.addEventListener('open', done, { once: true })+ browser.addEventListener('error', reject, { once: true })+ })+ browser.send(JSON.stringify({ id: 1, method: 'Browser.close' }))+ browser.close()} catch (error) {console.error(error)child.kill()@@ -82,7 +94,7 @@ try {}const outcome = await Promise.race([exited, sleep(40_000).then(() => undefined)])if (outcome === undefined) {- console.error('shot: the app did not exit after its window closed')+ console.error('shot: the app did not exit after the quit')child.kill()process.exitCode = 1} else {diff --git a/app/src/background-notice.mjs b/app/src/background-notice.mjsnew file mode 100644index 00000000..0c7cbbc0--- /dev/null+++ b/app/src/background-notice.mjs@@ -0,0 +1,79 @@+// The one-time confirmation before the window hides into the tray. The app goes on running+// after the window closes, so the user is told once, and only an explicit answer lets the+// window go; the answer is remembered under the app's own data.+import { existsSync, mkdirSync, writeFileSync } from 'node:fs'+import { dirname } from 'node:path'++export class BackgroundNotice {+ #marker+ #show+ #focus+ #message+ #confirm+ #log+ #acknowledged = false+ #pending = false+ #disposed = false++ /**+ * @param {{+ * marker: string,+ * show: (options: object) => Promise<{ response: number }>,+ * focus?: () => void,+ * message: string,+ * confirm: string,+ * log?: Pick<Console, 'warn'>,+ * }} options `marker` is where the acknowledgement is kept, `show` the shell dialog.+ */+ constructor(options) {+ this.#marker = options.marker+ this.#show = options.show+ this.#focus = options.focus ?? (() => {})+ this.#message = options.message+ this.#confirm = options.confirm+ this.#log = options.log ?? console+ }++ /**+ * Hide the window, asking once until the user has acknowledged it.+ * @param {() => void} hide - hides the window, once the answer allows it+ */+ close(hide) {+ if (this.#disposed) return+ // A second close while the box is open joins it instead of opening another one.+ if (this.#pending) { this.#focus(); return }+ if (this.#acknowledged || existsSync(this.#marker)) {+ this.#acknowledged = true+ hide()+ return+ }+ this.#pending = true+ void this.#ask(hide)+ }++ /** The app is on its way out: a late answer no longer hides anything. */+ dispose() { this.#disposed = true }++ async #ask(hide) {+ try {+ const { response } = await this.#show({+ type: 'info', title: 'DeepSeek Bot', message: this.#message,+ buttons: [this.#confirm], defaultId: 0, cancelId: -1, noLink: true,+ })+ // A cancelled box leaves the window where it is.+ if (this.#disposed || response !== 0) return+ this.#acknowledged = true+ try {+ mkdirSync(dirname(this.#marker), { recursive: true })+ writeFileSync(this.#marker, '')+ } catch (error) {+ this.#log.warn(`DeepSeek Bot: the tray notice was not remembered: ${error instanceof Error ? error.message : String(error)}`)+ }+ hide()+ } catch (error) {+ this.#log.warn(`DeepSeek Bot: the tray notice could not be shown: ${error instanceof Error ? error.message : String(error)}`)+ } finally {+ this.#pending = false+ }+ }+}diff --git a/app/src/bot-views.mjs b/app/src/bot-views.mjsindex 1ebb1a51..732aa2d8 100644--- a/app/src/bot-views.mjs+++ b/app/src/bot-views.mjs@@ -47,6 +47,8 @@ export class BotViews {#saved = {}#active = new Map()#held = new Set()+ // The tabs whose view waits for a window to belong to.+ #waiting = new Set()constructor({ window, WebContentsView, guests, origin, devTools = false, onChange = () => {}, statePath }) {this.#window = window@@ -118,7 +120,10 @@ export class BotViews {})const entry = { tabId, botId, view, createdByBot, openerId, sessions: new Map(), sessionMaps: new Map(), downloads: new Map(), downloadPath: this.#downloadPaths.get(botId), mainFrameId: undefined }this.#views.set(tabId, entry)- this.#window()?.contentView.addChildView(view)+ const owner = this.#window()+ if (owner !== undefined && owner !== null) owner.contentView.addChildView(view)+ // Without a window the view waits for the next one.+ else this.#waiting.add(tabId)view.setBounds(rectOf(null))view.setVisible(false)const contents = view.webContents@@ -330,10 +335,40 @@ export class BotViews {return [...this.#views.values()].filter(entry => entry.botId === botId).map(entry => this.#state(entry))}+ /**+ * The window that owned the views is gone. The views that went with it are dropped; the+ * ones that are still alive wait for the window that comes next.+ */+ release() {+ for (const [tabId, entry] of [...this.#views]) {+ if (!entry.view.webContents.isDestroyed()) { this.#waiting.add(tabId); continue }+ this.#views.delete(tabId)+ this.#waiting.delete(tabId)+ if (this.#active.get(entry.botId) === tabId) this.#active.delete(entry.botId)+ }+ }++ /** The views that waited for a window join it, so that the tabs go on. */+ attach(window) {+ if (window === undefined || window === null) return+ for (const [tabId, entry] of [...this.#views]) {+ if (!this.#waiting.has(tabId)) continue+ if (entry.view.webContents.isDestroyed()) {+ this.#views.delete(tabId)+ this.#waiting.delete(tabId)+ if (this.#active.get(entry.botId) === tabId) this.#active.delete(entry.botId)+ continue+ }+ window.contentView.addChildView(entry.view)+ this.#waiting.delete(tabId)+ }+ }+dispose() {this.#persist()for (const entry of this.#views.values()) entry.view.webContents.close()this.#views.clear()+ this.#waiting.clear()this.#tokens.clear()this.#wss.close()this.#server.close()diff --git a/app/src/downloads.mjs b/app/src/downloads.mjsindex 094fdef6..08ee8249 100644--- a/app/src/downloads.mjs+++ b/app/src/downloads.mjs@@ -5,8 +5,10 @@ import { join } from 'node:path'export function downloadSaver({ window, dialog, downloads }) {return (event, item, source) => {- if (source !== window.webContents) return- const file = dialog.showSaveDialogSync(window, { defaultPath: join(downloads, item.getFilename()) })+ // The window is asked for at the moment of the download: the app may build a new one.+ const owner = typeof window === 'function' ? window() : window+ if (owner === undefined || owner === null || source !== owner.webContents) return+ const file = dialog.showSaveDialogSync(owner, { defaultPath: join(downloads, item.getFilename()) })if (file === undefined) event.preventDefault()else item.setSavePath(file)}diff --git a/app/src/main.mjs b/app/src/main.mjsindex 6691ade5..d57c9f90 100644--- a/app/src/main.mjs+++ b/app/src/main.mjs@@ -1,7 +1,7 @@// Electron main process: one window for the Bot team, served by the app's own DSH Host.// The window loads the Host's loopback address as DSH Web does: DSH's sign-in sends the page's// origin as the address the browser comes back to, and accepts only a loopback one.-import { app, BrowserWindow, WebContentsView, dialog, ipcMain, Menu, nativeTheme, session, shell } from 'electron'+import { app, BrowserWindow, WebContentsView, dialog, ipcMain, Menu, nativeImage, nativeTheme, powerMonitor, session, shell as electronShell, Tray } from 'electron'import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'import { readFile, rm } from 'node:fs/promises'import { release } from 'node:os'@@ -23,7 +23,9 @@ import { HostProcess } from './host-process.mjs'import { copySessions, findTeam, importTeam, teamInUse, userDshHome } from './import.mjs'import { copyData, moveProblem } from './move-data.mjs'import { CHECK_PROFILE, PROFILE } from './profile.mjs'+import { createShell, SHELL_TEXT } from './shell.mjs'import { UPDATE_TEXT, watchReleases, watchUpdates } from './updates.mjs'+import { createDeferredPrompt } from './update-prompt.mjs'import { CAPTION_HEIGHT, cssColor, micaAvailable, nativeThemeSource } from './window-frame.mjs'const IPC = {@@ -49,8 +51,12 @@ const UPDATE_CHECK_WAIT_MS = 15_000const UPDATE_DOWNLOAD_WAIT_MS = 15 * 60_000const here = dirname(fileURLToPath(import.meta.url))+const assets = join(here, '..', 'assets')// Drawn by scripts/icon.mjs. Windows takes the .ico for its several sizes.-const iconFile = join(here, '..', 'assets', process.platform === 'win32' ? 'icon.ico' : 'icon.png')+const iconFile = join(assets, process.platform === 'win32' ? 'icon.ico' : 'icon.png')+// The tray icon of this platform: Windows takes the .ico, macOS the template and its @2x,+// Linux the plain png.+const trayIconFile = () => join(assets, process.platform === 'win32' ? 'tray.ico' : process.platform === 'darwin' ? 'trayTemplate.png' : 'tray.png')// Windows 11 draws Mica behind the page; mica.css lets it through the sidebar.const mica = micaAvailable(process.platform, release())if (process.env.DS_BOT_SHELL_DATA) app.setPath('userData', process.env.DS_BOT_SHELL_DATA)@@ -65,6 +71,18 @@ let stopping = falselet stopped = falselet failed = falselet places+// The Host answered and the window may talk to it without the launch URL.+let hostReady = false+// The Host's launch URL: the first window trades it for the Host's cookie.+let launchUrl+// The first load of the Host, which mints that cookie. It ends when the first load came+// through (true) or when it never did (false).+let bootstrap+// The launch URL is good for one use only: once a browser has carried it, no browser+// carries it again.+let tokenSpent = false+// The download handler of the app's session is bound once, not once per window.+let downloadsBound = false// Quitting while a first-run dialog is open stops the first run, and during the copy (of the// first run or of a data move) it waits for the copy to stop at a safe point, so that it leaves// no half team and no temporary copy.@@ -78,7 +96,34 @@ const botViews = new BotViews({onChange: state => mainWindow?.webContents.send(IPC.browserViewChanged, state),})const cookieImports = new CookieImports()-app.once('will-quit', () => botViews.dispose())++// The window and the tray: closing the window hides it, the tray is the way back to it and+// the tray's Quit is the one ordinary way out.+const shell = createShell({+ electron: { app, Menu, Tray, powerMonitor },+ platform: process.platform,+ messages: () => localeText(SHELL_TEXT),+ trayImage: () => trayImage(),+ window: () => mainWindow,+ build: () => rebuildWindow(),+ reveal: (target) => {+ if (failed) return+ // macOS: the application menu's Hide hides the app itself, so it comes back first.+ if (process.platform === 'darwin') app.show()+ target.show()+ target.focus()+ },+ quit: () => { app.quit() },+ busy: () => choosing !== undefined || copying !== undefined,+ // Before the first run has chosen its places there is no window to show, and before the+ // first load of the Host there is no address to load.+ ready: () => places !== undefined && origin !== undefined && bootstrap !== undefined,+ notice: { marker: () => join(app.getPath('userData'), 'tray-close-acknowledged'), show: (options) => dialog.showMessageBox(options) },+ // Without a tray the close asks whether the app should end.+ fallback: { show: (options) => dialog.showMessageBox(options) },+})+// The tray icon goes away with the app, and a late answer to the close notice hides nothing.+app.once('will-quit', () => { shell.dispose(); botViews.dispose(); updates?.stop() })// A packaged app started through an 8.3 short path or a junction restarts once on the// canonical path: the lock below and every path the Host sees then agree with the long@@ -90,27 +135,33 @@ if (canonical !== undefined) {} else if (!app.requestSingleInstanceLock()) {app.exit(0)} else {- app.on('second-instance', focusWindow)- app.on('window-all-closed', () => { app.quit() })+ app.on('second-instance', () => { shell.open() })app.on('before-quit', (event) => {if (choosing !== undefined) {+ // A first-run dialog is open: the quit waits for it, and the app goes on meanwhile.event.preventDefault()+ shell.cancelQuit()choosing.abort()return}if (copying !== undefined) {+ // A copy is under way: it stops at a safe point, and the app goes on meanwhile.event.preventDefault()+ shell.cancelQuit()if (copyAbort.signal.aborted) returncopyAbort.abort()void copying.finally(() => { copying = undefined; app.quit() })return}+ // The app is on its way out: the window may close for good.+ shell.beginQuit()if (stopped || host === undefined) returnevent.preventDefault()- if (stopping) return+ // The Host is already stopping: the quit follows it.+ if (stopping) { void (hostStop ?? Promise.resolve()).then(() => { app.quit() }); return }void stopHost().then(() => { app.quit() })})- app.whenReady().then(start).catch(fail)+ app.whenReady().then(async () => { shell.install(); await start() }).catch(fail)}function stopHost() {@@ -277,7 +328,7 @@ async function start() {assertWindow(event)const state = updates?.state()if (state?.phase === 'available' && typeof state.page === 'string' && state.page.startsWith('https://')) {- void shell.openExternal(state.page)+ void electronShell.openExternal(state.page)}})// The plugin keeps the team workspace; the app remembers it for its own checks.@@ -303,8 +354,19 @@ async function start() {// A packaged app has the icon in its bundle; Electron's own run shows Electron's.if (process.platform === 'darwin' && !app.isPackaged) app.dock?.setIcon(iconFile)createWindow()- // The launch URL trades its token for the Host's cookie and goes on to the page.- void ready.then(({ url }) => mainWindow?.loadURL(url)).catch(() => {})+ // The launch URL trades its token for the Host's cookie and goes on to the page. The cookie+ // is there once that load came through. The token is good for one browser only: it is spent+ // as soon as a window carries it.+ bootstrap = (async () => {+ const { url } = await ready+ launchUrl = url+ const win = mainWindow+ if (win === undefined) return false+ tokenSpent = true+ await win.loadURL(url)+ hostReady = true+ return true+ })().catch(() => false)}// The Host starts once on the new data location first: DSH then sets up its project list@@ -410,7 +472,7 @@ async function moveData(workspace) {const signal = copyAbort.signalcopying = (async () => {// The settings go away first, so that nothing moves the team workspace from here on.- void mainWindow?.loadURL(notePage(t.moving))+ void mainWindow?.loadURL(notePage(t.moving)).catch(() => {})await stopHost()// The app may have heard of a team workspace change while the Host stopped.if (await refused()) {@@ -459,7 +521,7 @@ function startUpdates() {if (!app.isPackaged || (throwaway && feed === undefined)) return undefinedif (process.platform === 'darwin') {return watchReleases({- current: app.getVersion(), arch: process.arch, feed, ask: throwaway ? undefined : askDownload, open: url => shell.openExternal(url),+ current: app.getVersion(), arch: process.arch, feed, ask: throwaway ? undefined : (version) => downloadPrompt.prompt(version), open: url => electronShell.openExternal(url),})}// electron-updater's Linux updater works only from inside an AppImage (APPIMAGE is set there);@@ -468,17 +530,28 @@ function startUpdates() {if (process.platform === 'linux' && process.env.APPIMAGE === undefined) {const debArch = { x64: 'amd64', arm64: 'arm64' }[process.arch] ?? process.archreturn watchReleases({- current: app.getVersion(), arch: process.arch, feed, ask: throwaway ? undefined : askDownload, open: url => shell.openExternal(url),+ current: app.getVersion(), arch: process.arch, feed, ask: throwaway ? undefined : (version) => downloadPrompt.prompt(version), open: url => electronShell.openExternal(url),asset: version => `DeepSeek-Bot-${version}-linux-${debArch}.deb`,})}if (process.platform === 'win32' || process.platform === 'linux') {- return watchUpdates({ updater: electronUpdater.autoUpdater, feed, ask: throwaway ? undefined : askRestart, beforeInstall: stopHost })+ // The update ends the app: the window closes for good, and the Host stops before the+ // installer replaces its files.+ return watchUpdates({+ updater: electronUpdater.autoUpdater, feed, ask: throwaway ? undefined : (version) => restartPrompt.prompt(version),+ beforeInstall: () => { shell.beginQuit(); return stopHost() },+ })}return undefined}-async function askRestart(version) {+// A prompt that belongs to a window is not asked while the window is hidden or minimized: it+// waits for the window to be on the screen again.+function windowShown() {+ return mainWindow !== undefined && !mainWindow.isDestroyed() && mainWindow.isVisible() && !mainWindow.isMinimized()+}++async function askRestartNow(version) {// After a failed start, fail() installs the update itself.if (failed) return falseconst t = localeText(UPDATE_TEXT)@@ -487,7 +560,7 @@ async function askRestart(version) {return response === 0}-async function askDownload(version) {+async function askDownloadNow(version) {if (failed) return falseconst 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 }@@ -495,10 +568,29 @@ async function askDownload(version) {return response === 0}+// What the updater does when the user says yes. The answer may come later, when the window+// is shown again; then the work is done here.+async function installUpdate() { await updates?.install() }++async function openUpdatePage() {+ const state = updates?.state()+ if (state?.phase === 'available' && typeof state.page === 'string' && state.page.startsWith('https://')) {+ await electronShell.openExternal(state.page)+ }+}++const restartPrompt = createDeferredPrompt({ ask: askRestartNow, shown: windowShown, onYes: installUpdate })+const downloadPrompt = createDeferredPrompt({ ask: askDownloadNow, shown: windowShown, onYes: openUpdatePage })++async function flushDeferredUpdate() {+ await restartPrompt.flush()+ await downloadPrompt.flush()+}+function createWindow() {const dark = nativeTheme.shouldUseDarkColorsconst win32 = process.platform === 'win32'- mainWindow = new BrowserWindow({+ const win = new BrowserWindow({width: 1320, height: 860, minWidth: 720, minHeight: 480,title: 'DeepSeek Bot', show: false, icon: iconFile,backgroundColor: mica ? '#00000000' : dark ? '#1b1b1c' : '#ffffff',@@ -514,18 +606,36 @@ function createWindow() {additionalArguments: [`--ds-bot-origin=${origin}`, ...(win32 ? [`--ds-bot-caption=${String(CAPTION_HEIGHT)}`, ...(mica ? ['--ds-bot-mica'] : [])] : [])],},})- mainWindow.once('ready-to-show', () => { mainWindow?.show() })- mainWindow.on('page-title-updated', (event) => { event.preventDefault() })- mainWindow.on('closed', () => { mainWindow = undefined })- browserGuests.bind(mainWindow)- const contents = mainWindow.webContents- contents.session.on('will-download', downloadSaver({ window: mainWindow, dialog, downloads: app.getPath('downloads') }))+ mainWindow = win+ // A window that the shell has hidden, or that the app is leaving, stays out of sight.+ win.once('ready-to-show', () => {+ if (win.isDestroyed() || shell.isQuitting() || shell.isHidden(win)) return+ win.show()+ })+ win.on('page-title-updated', (event) => { event.preventDefault() })+ win.on('closed', () => {+ if (mainWindow !== win) return+ mainWindow = undefined+ // The Bot browsers' tabs belonged to this window; they wait for the next one.+ botViews.release()+ })+ // The window hides instead of closing; the shell decides when it really goes.+ shell.watch(win)+ browserGuests.bind(win)+ // The tabs that outlived the last window join this one.+ botViews.attach(win)+ const contents = win.webContents+ // The session is the same for every window of the app, so the handler is bound once.+ if (!downloadsBound) {+ downloadsBound = true+ contents.session.on('will-download', downloadSaver({ window: () => mainWindow, dialog, downloads: app.getPath('downloads') }))+ }if (win32) {// Fullscreen hides the caption buttons, and the page drops its band meanwhile. A reload// registers the page's listener again, so the state goes out after every load too.- const sendFullscreen = () => { if (mainWindow !== undefined) contents.send(IPC.fullscreen, mainWindow.isFullScreen()) }- mainWindow.on('enter-full-screen', sendFullscreen)- mainWindow.on('leave-full-screen', sendFullscreen)+ const sendFullscreen = () => { if (mainWindow !== undefined) contents.send(IPC.fullscreen, win.isFullScreen()) }+ win.on('enter-full-screen', sendFullscreen)+ win.on('leave-full-screen', sendFullscreen)contents.on('did-finish-load', sendFullscreen)}if (mica) {@@ -558,19 +668,95 @@ function createWindow() {if (input.type === 'keyDown' && (input.key === 'F12' || (input.control && input.shift && input.key.toLowerCase() === 'i'))) contents.toggleDevTools()})}- void mainWindow.loadURL(notePage(text().starting))+ // The window that is shown again asks for the update that waited for it. A window that was+ // minimized asks for it when it comes back.+ win.on('show', () => { void flushDeferredUpdate().catch((error) => { console.error(error) }) })+ win.on('restore', () => { void flushDeferredUpdate().catch((error) => { console.error(error) }) })+ void win.loadURL(notePage(text().starting)).catch(() => {})+ return win}-function setMenu() {- if (process.platform !== 'darwin') { Menu.setApplicationMenu(null); return }- Menu.setApplicationMenu(Menu.buildFromTemplate([{ role: 'appMenu' }, { role: 'fileMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' }]))+// The window is gone for good: a new one takes its place and talks to the Host that runs.+function rebuildWindow() {+ const win = createWindow()+ void connectHost(win).catch((error) => { console.error(error) })+ return win+}++// The window talks to the Host that runs. The first one trades the launch URL for the Host's+// cookie; the later ones use the plain address, which that cookie carries. The launch URL is+// used again only when no browser carried it at all, so that a token is never spent twice.+async function connectHost(win) {+ if (hostReady) { await win.loadURL(`${origin}/`); return }+ // The first load of the Host decides how this window comes in.+ if (bootstrap !== undefined) await bootstrap+ if (hostReady) { await win.loadURL(`${origin}/`); return }+ // The first load never came through. The cookie may be there anyway: it belongs to the+ // session of the browser, which outlives the window.+ if (await hostCookie()) {+ hostReady = true+ await win.loadURL(`${origin}/`)+ return+ }+ // There is no cookie: the launch URL is the one way in, and only while it was not used.+ if (launchUrl !== undefined && !tokenSpent) {+ tokenSpent = true+ await win.loadURL(launchUrl)+ hostReady = true+ return+ }+ await win.loadURL(`${origin}/`)}-function focusWindow() {- if (mainWindow === undefined || failed) return- if (mainWindow.isMinimized()) mainWindow.restore()- mainWindow.show()- mainWindow.focus()+// The Host's cookie: the launch URL trades its token for it. The app does not need to know+// its name, only whether the browser holds one for the Host's address.+async function hostCookie() {+ try {+ const cookies = await session.defaultSession.cookies.get({ url: `${origin}/` })+ return cookies.length > 0+ } catch (error) {+ console.error(error)+ return false+ }+}++// The mark of the tray: the file of this platform, and on macOS the template that follows the+// colour of the menu bar.+function trayImage() {+ const file = trayIconFile()+ const image = nativeImage.createFromPath(file)+ if (image.isEmpty()) throw new Error(`the tray icon ${file} could not be read`)+ if (process.platform === 'darwin') {+ const retina = nativeImage.createFromPath(join(assets, '[email protected]'))+ const size = retina.getSize()+ if (!retina.isEmpty() && size.width > image.getSize().width) {+ image.addRepresentation({ scaleFactor: 2, buffer: retina.toPNG(), width: size.width, height: size.height })+ }+ image.setTemplateImage(true)+ }+ return image+}++function setMenu() {+ if (process.platform !== 'darwin') { Menu.setApplicationMenu(null); return }+ const t = localeText(SHELL_TEXT)+ // The application menu of macOS, without its Quit: the tray's Quit is the one ordinary way+ // out. Only when the tray is not there does the menu carry one, so that the app can still+ // be ended.+ const items = [+ { role: 'about' },+ { type: 'separator' },+ { role: 'services' },+ { type: 'separator' },+ { role: 'hide' }, { role: 'hideOthers' }, { role: 'unhide' },+ ]+ if (!shell.hasTray()) {+ items.push({ type: 'separator' }, { label: t.quit, click: () => { shell.quit() } })+ }+ Menu.setApplicationMenu(Menu.buildFromTemplate([+ { label: app.name, submenu: items },+ { role: 'fileMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' },+ ]))}function assertWindow(event) {@@ -584,7 +770,7 @@ function fromWindow(event) {}function openOutside(url) {- if (/^https?:\/\//iu.test(url)) void shell.openExternal(url)+ if (/^https?:\/\//iu.test(url)) void electronShell.openExternal(url)}// A new version may fix what keeps this one from starting.@@ -598,7 +784,7 @@ async function fail(error) {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)+ if (!throwaway) await electronShell.openExternal(found.page)app.quit()return}diff --git a/app/src/shell.mjs b/app/src/shell.mjsnew file mode 100644index 00000000..1760f7a9--- /dev/null+++ b/app/src/shell.mjs@@ -0,0 +1,233 @@+// The window and the tray share one life: closing the window hides it, the tray is the way+// back to it, and the tray's Quit is the one ordinary way out. The app itself decides when+// a close really ends it: an update, a data move, a failed start and the end of the+// operating system's session all close the window for good.+import { BackgroundNotice } from './background-notice.mjs'+import { createTray } from './tray.mjs'++export const SHELL_TEXT = {+ en: {+ tooltip: 'DeepSeek Bot',+ open: 'Open DeepSeek Bot',+ quit: 'Quit DeepSeek Bot',+ notice: 'DeepSeek Bot keeps running in the system tray. Its Bots go on working while the window is closed.',+ noticeConfirm: 'OK',+ fallback: 'The system tray is not available, so DeepSeek Bot cannot stay in the background. Do you want to end it?',+ cancel: 'Cancel',+ },+ zh: {+ tooltip: 'DeepSeek Bot',+ open: '打开 DeepSeek Bot',+ quit: '退出 DeepSeek Bot',+ notice: 'DeepSeek Bot 会留在系统托盘里继续运行,关掉窗口时 Bot 们照常工作。',+ noticeConfirm: '好',+ fallback: '系统托盘不可用,DeepSeek Bot 不能留在后台。要结束它吗?',+ cancel: '取消',+ },+}++/**+ * The window and the tray of the desktop app.+ *+ * @param {{+ * electron: { app: any, Menu: any, Tray: any, powerMonitor: any },+ * platform: string,+ * messages: () => { tooltip: string, open: string, quit: string, notice: string, noticeConfirm: string, fallback: string, cancel: string },+ * trayImage: () => any,+ * window: () => any,+ * build: () => any,+ * reveal: (window: any) => void,+ * quit: () => void,+ * busy: () => boolean,+ * ready: () => boolean,+ * notice: { marker: () => string, show: (options: object) => Promise<{ response: number }> },+ * fallback?: { show: (options: object) => Promise<{ response: number }> },+ * log?: Pick<Console, 'warn'>,+ * }} options the pieces of the app the shell drives+ */+export function createShell(options) {+ const { electron, platform, log = console } = options+ const { app, powerMonitor } = electron+ // The tray is kept here, so that it stays alive as long as the app runs.+ let tray+ let notice+ // The app is on its way out: the window may close for good.+ let quitting = false+ // A quit was asked for; the app may still refuse it (a first-run dialog, a copy).+ let quitAsked = false+ let sessionEnding = false+ // The windows the shell has hidden: they do not show themselves again.+ const hidden = new WeakSet()+ // The hides that wait for a fullscreen window to leave fullscreen.+ const pending = new WeakMap()++ const text = () => options.messages()+ const current = () => options.window()++ const hide = (target = current()) => {+ if (quitting || sessionEnding || target === undefined || target.isDestroyed()) return+ hidden.add(target)+ if (platform === 'darwin' && target.isFullScreen()) {+ // A fullscreen window leaves an empty black space behind when it is hidden.+ const onLeave = () => {+ pending.delete(target)+ if (quitting || sessionEnding || target.isDestroyed()) return+ // The window was opened again while it was leaving fullscreen: it stays.+ if (!hidden.has(target)) return+ target.hide()+ }+ pending.set(target, onLeave)+ target.once('leave-full-screen', onLeave)+ target.setFullScreen(false)+ return+ }+ target.hide()+ }++ /** The window is there: show it. It is gone: build one that talks to the running Host. */+ const open = () => {+ if (quitting) return+ const target = current()+ if (target !== undefined && !target.isDestroyed()) {+ if (target.isMinimized()) target.restore()+ // A hide that waits for the fullscreen to end is called off: the window stays.+ const waiting = pending.get(target)+ if (waiting !== undefined) {+ pending.delete(target)+ target.removeListener?.('leave-full-screen', waiting)+ }+ hidden.delete(target)+ options.reveal(target)+ return+ }+ // There is no window yet, and the app is still starting: nothing to show.+ if (!options.ready()) return+ const built = options.build()+ if (built !== undefined && !built.isDestroyed()) {+ hidden.delete(built)+ options.reveal(built)+ }+ }++ /**+ * The tray's Quit: the one ordinary way out of the app. The app may still refuse it (a+ * first-run dialog is open, a copy is under way); then it says so with {@link cancelQuit}.+ */+ const quit = () => {+ if (quitAsked) return+ quitAsked = true+ options.quit()+ }++ /** The app is on its way out; the window may close for good. */+ function beginQuit() { quitting = true; quitAsked = true }++ /** The app refused the quit: it goes on, and the tray works again. */+ function cancelQuit() { quitting = false; quitAsked = false }++ const buildTray = () => {+ try {+ const image = options.trayImage()+ tray = createTray({+ Tray: electron.Tray, Menu: electron.Menu, platform,+ image, tooltip: text().tooltip,+ open: { label: text().open, run: () => { open() } },+ quit: { label: text().quit, run: () => { quit() } },+ log,+ })+ } catch (error) {+ // Without a tray the window stays where the user can reach it; the app never vanishes.+ tray = undefined+ log.warn(`DeepSeek Bot: the system tray is not available: ${error instanceof Error ? error.message : String(error)}`)+ }+ }++ /**+ * Without a tray there is no Quit of its own: the close asks whether the app should end.+ * @param {any} target the window that stays reachable+ */+ const askFallback = async (target) => {+ const t = text()+ try {+ const { response } = await options.fallback.show({+ type: 'question', title: 'DeepSeek Bot', message: t.fallback,+ buttons: [t.quit, t.cancel], defaultId: 1, cancelId: 1, noLink: true,+ })+ if (response === 0) { quit(); return }+ } catch (error) {+ log.warn(`DeepSeek Bot: the fallback quit could not be asked: ${error instanceof Error ? error.message : String(error)}`)+ }+ // The window stays in the task bar, where the user can reach it.+ target.minimize()+ }++ /**+ * The window's close: it hides, unless the app is really leaving.+ * @param {{ preventDefault: () => void }} event the window's close event+ */+ const close = (event) => {+ if (quitting || sessionEnding) return+ event.preventDefault()+ const target = current()+ if (target === undefined) return+ // An import or a data move is under way: the close cancels it, as it did before.+ if (options.busy()) { quit(); return }+ // Without a tray there is no way back to a hidden window, and no Quit of its own: the+ // close asks whether the app should end.+ if (tray === undefined) { void askFallback(target); return }+ if (notice === undefined) { hide(target); return }+ notice.close(() => { hide(target) })+ }++ /** The window's own listeners. */+ const watch = (target) => {+ target.on('close', (event) => { close(event) })+ if (platform === 'win32') {+ // The session ends for good: the window may close.+ target.on('session-end', () => { sessionEnding = true })+ } else {+ // A shutdown that another application called off leaves the app running; the next focus+ // or show of the window says that the session goes on.+ target.on('focus', () => { sessionEnding = false })+ target.on('show', () => { sessionEnding = false })+ }+ }++ const install = () => {+ // The app stays in the tray: a closed window is not a closed app.+ app.on('window-all-closed', () => {})+ // macOS: the Dock icon opens the window again.+ app.on('activate', () => { sessionEnding = false; open() })+ if (platform !== 'win32') {+ // macOS and Linux: the power-off notification comes before the terminate request, and+ // another application can still call the shutdown off.+ powerMonitor.on('shutdown', () => { sessionEnding = true })+ }+ notice = new BackgroundNotice({+ marker: options.notice.marker(), show: options.notice.show, message: text().notice, confirm: text().noticeConfirm, log,+ })+ buildTray()+ }++ const dispose = () => {+ notice?.dispose()+ notice = undefined+ tray?.dispose()+ tray = undefined+ }++ return {+ install,+ watch,+ close,+ open,+ quit,+ beginQuit,+ cancelQuit,+ dispose,+ hasTray: () => tray !== undefined,+ isQuitting: () => quitting,+ isHidden: (target) => hidden.has(target),+ isSessionEnding: () => sessionEnding,+ }+}diff --git a/app/src/tray.mjs b/app/src/tray.mjsnew file mode 100644index 00000000..e17caf44--- /dev/null+++ b/app/src/tray.mjs@@ -0,0 +1,41 @@+// The system tray: the way back to a hidden window and the one ordinary way out.++/**+ * @param {{+ * Tray: new (image: object) => object,+ * Menu: { buildFromTemplate: (template: object[]) => object },+ * platform: string,+ * image: object,+ * tooltip: string,+ * open: { label: string, run: () => void },+ * quit: { label: string, run: () => void },+ * log?: Pick<Console, 'warn'>,+ * }} options the mark, the tooltip and the two entries of the menu+ * @returns {{ tray: object, relabel: () => void, dispose: () => void }}+ */+export function createTray({ Tray, Menu, platform, image, tooltip, open, quit, log = console }) {+ const tray = new Tray(image)+ let disposed = false+ const relabel = () => {+ tray.setToolTip(tooltip)+ tray.setContextMenu(Menu.buildFromTemplate([+ { label: open.label, click: () => { open.run() } },+ { type: 'separator' },+ { label: quit.label, click: () => { quit.run() } },+ ]))+ }+ // macOS opens the menu of the icon instead of a click of its own; there the menu is the+ // way back to the window.+ if (platform !== 'darwin') tray.on('click', () => { open.run() })+ relabel()+ return {+ tray,+ relabel,+ /** Take the icon away; the app leaves no dead icon behind. */+ dispose() {+ if (disposed) return+ disposed = true+ try { tray.destroy() } catch (error) { log.warn(`DeepSeek Bot: the tray icon did not go away: ${error instanceof Error ? error.message : String(error)}`) }+ },+ }+}diff --git a/app/src/update-prompt.mjs b/app/src/update-prompt.mjsnew file mode 100644index 00000000..3d0f38c9--- /dev/null+++ b/app/src/update-prompt.mjs@@ -0,0 +1,37 @@+// An update prompt belongs to a window: a hidden window has no box to show it in, so the+// prompt waits until the window is shown again.++/**+ * @param {{+ * ask: (version: string) => Promise<boolean>,+ * shown: () => boolean,+ * onYes?: (version: string) => Promise<void>,+ * log?: Pick<Console, 'info' | 'error'>,+ * }} options `ask` shows the prompt, `shown` tells whether the window is on the screen, and+ * `onYes` does the work of an answer that comes after the window was shown again+ * @returns {{ prompt: (version: string) => Promise<boolean>, flush: () => Promise<void>, waiting: () => string | undefined }}+ */+export function createDeferredPrompt({ ask, shown, onYes, log = console }) {+ let waiting+ const prompt = async (version) => {+ if (!shown()) {+ waiting = version+ log.info(`DeepSeek Bot: the update ${version} waits for the window`)+ return false+ }+ return ask(version)+ }+ const flush = async () => {+ if (waiting === undefined || !shown()) return+ const version = waiting+ waiting = undefined+ try {+ // The updater heard "no" while the prompt waited, so the answer the user gives now has+ // to do the work itself.+ if (await ask(version)) await onYes?.(version)+ } catch (error) {+ log.error(`DeepSeek Bot: the update ${version} could not be asked: ${error instanceof Error ? error.message : String(error)}`)+ }+ }+ return { prompt, flush, waiting: () => waiting }+}diff --git a/app/test/background-notice.test.mjs b/app/test/background-notice.test.mjsnew file mode 100644index 00000000..5657d878--- /dev/null+++ b/app/test/background-notice.test.mjs@@ -0,0 +1,100 @@+// The one-time confirmation before the window hides into the tray.+import assert from 'node:assert/strict'+import { existsSync, mkdtempSync, rmSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, test } from 'node:test'+import { BackgroundNotice } from '../src/background-notice.mjs'++const settle = () => new Promise(resolve => setImmediate(resolve))++function harness({ answer = 0, marker, show } = {}) {+ const folder = mkdtempSync(join(tmpdir(), 'ds-bot-notice-'))+ const asked = []+ const notice = new BackgroundNotice({+ marker: marker ?? join(folder, 'acknowledged'),+ show: show ?? (async options => { asked.push(options); return { response: answer } }),+ message: 'The app goes on.', confirm: 'OK',+ log: { warn: () => {} },+ })+ return { notice, asked, folder, cleanup: () => rmSync(folder, { recursive: true, force: true }) }+}++describe('the notice before the window hides', () => {+ test('an answered notice hides the window and is remembered', async (t) => {+ const app = harness()+ t.after(app.cleanup)+ let hidden = 0+ app.notice.close(() => { hidden += 1 })+ await settle()+ assert.equal(hidden, 1, 'the window is hidden')+ assert.equal(existsSync(join(app.folder, 'acknowledged')), true, 'the answer is kept')+ })++ test('a cancelled notice leaves the window where it is', async (t) => {+ const app = harness({ answer: -1 })+ t.after(app.cleanup)+ let hidden = 0+ app.notice.close(() => { hidden += 1 })+ await settle()+ assert.equal(hidden, 0, 'the window stays')+ assert.equal(existsSync(join(app.folder, 'acknowledged')), false, 'nothing is kept')+ })++ test('a notice that is answered once is not shown again', async (t) => {+ const app = harness()+ t.after(app.cleanup)+ let hidden = 0+ app.notice.close(() => { hidden += 1 })+ await settle()+ app.notice.close(() => { hidden += 1 })+ await settle()+ assert.equal(app.asked.length, 1, 'the notice is shown once')+ assert.equal(hidden, 2, 'the window hides every time')+ })++ test('a second close while the box is open joins it', async (t) => {+ const app = harness()+ t.after(app.cleanup)+ let focused = 0+ const notice = new BackgroundNotice({+ marker: join(app.folder, 'acknowledged'),+ show: async options => { app.asked.push(options); return { response: 0 } },+ focus: () => { focused += 1 },+ message: 'The app goes on.', confirm: 'OK',+ log: { warn: () => {} },+ })+ notice.close(() => {})+ notice.close(() => {})+ await settle()+ assert.equal(app.asked.length, 1, 'the notice is shown once')+ assert.equal(focused, 1, 'the open box is taken up again')+ })++ test('an answer that comes after the app left hides nothing', async (t) => {+ const app = harness()+ t.after(app.cleanup)+ let hidden = 0+ app.notice.close(() => { hidden += 1 })+ app.notice.dispose()+ await settle()+ assert.equal(hidden, 0, 'the window is not hidden')+ })++ test('a box that cannot be shown leaves the window where it is', async (t) => {+ const warnings = []+ const app = harness({ show: async () => { throw new Error('no box') } })+ t.after(app.cleanup)+ const notice = new BackgroundNotice({+ marker: join(app.folder, 'acknowledged'),+ show: async () => { throw new Error('no box') },+ message: 'The app goes on.', confirm: 'OK',+ log: { warn: message => warnings.push(message) },+ })+ let hidden = 0+ notice.close(() => { hidden += 1 })+ await settle()+ assert.equal(hidden, 0, 'the window stays')+ assert.equal(warnings.length, 1, 'the failure is logged')+ })+})diff --git a/app/test/bot-views.test.mjs b/app/test/bot-views.test.mjsindex b3ad9777..cb649daa 100644--- a/app/test/bot-views.test.mjs+++ b/app/test/bot-views.test.mjs@@ -7,6 +7,10 @@ import { test } from 'node:test'import { WebSocket } from 'ws'import { BotViews, isBotId } from '../src/bot-views.mjs'+// Windows makes a junction to a folder without special rights; elsewhere it is a plain+// symbolic link to the folder.+const folderLink = process.platform === 'win32' ? 'junction' : 'dir'+function fixture({ statePath } = {}) {const changes = []const handlers = new Map()@@ -49,9 +53,10 @@ function fixture({ statePath } = {}) {storageFor(key) { return { partition: `persist:${key}` } },setDownloadHandler(key, handler) { handlers.set(key, handler) },}- const window = { contentView: { addChildView() {} } }+ const added = []+ let window = { contentView: { addChildView(view) { added.push(view) } } }const manager = new BotViews({ window: () => window, WebContentsView, guests, origin: () => 'http://127.0.0.1:43117', statePath, onChange: change => changes.push(change) })- return { manager, handlers, views, changes }+ return { manager, handlers, views, changes, added, setWindow: (next) => { window = next } }}test('Bot endpoint identifiers follow DSH session.create IDs', () => {@@ -305,7 +310,7 @@ test('CDP rejects outside, traversal, and symlink download paths and cancels dowt.after(() => manager.dispose())const rootPath = mkdtempSync(join(tmpdir(), 'bot-views-download-root-'))const outsidePath = mkdtempSync(join(tmpdir(), 'bot-views-download-outside-'))- symlinkSync(outsidePath, join(rootPath, 'outside-link'))+ symlinkSync(outsidePath, join(rootPath, 'outside-link'), folderLink)t.after(() => {rmSync(rootPath, { recursive: true, force: true })rmSync(outsidePath, { recursive: true, force: true })@@ -389,7 +394,7 @@ test('a relay download is cancelled if its accepted directory is swapped for anassert.deepEqual(accepted.result, {})rmSync(downloadPath, { recursive: true, force: true })- symlinkSync(outsidePath, downloadPath)+ symlinkSync(outsidePath, downloadPath, folderLink)let prevented = falseconst item = Object.assign(new EventEmitter(), {setSavePath(path) { writeFileSync(path, 'outside') },@@ -501,3 +506,40 @@ test('load errors remain published until a real main-frame navigation starts', aassert.equal(changes.at(-1).error, null)assert.ok(entry)})++test('a tab whose window is gone joins the next window', async t => {+ const { manager, views, added } = fixture()+ t.after(() => manager.dispose())+ manager.create('a')+ assert.equal(added.length, 1, 'the view belongs to the window')+ // The window is gone, but its view is still alive.+ manager.release()+ const next = { contentView: { addChildView(view) { added.push(view) } } }+ manager.attach(next)+ assert.equal(added.length, 2, 'the view joins the next window')+ assert.equal(added[1], views[0], 'it is the same view')+})++test('a view that went with its window is dropped', async t => {+ const { manager, views, added } = fixture()+ t.after(() => manager.dispose())+ manager.create('a')+ views[0].webContents.isDestroyed = () => true+ manager.release()+ const next = { contentView: { addChildView(view) { added.push(view) } } }+ manager.attach(next)+ assert.equal(added.length, 1, 'the dead view is not attached again')+ assert.deepEqual(manager.sync('a'), [], 'the tab is gone')+})++test('a view that is built without a window waits for one', async t => {+ const { manager, views, added, setWindow } = fixture()+ t.after(() => manager.dispose())+ setWindow(undefined)+ manager.create('a')+ assert.equal(added.length, 0, 'there is no window to hold it')+ const next = { contentView: { addChildView(view) { added.push(view) } } }+ manager.attach(next)+ assert.equal(added.length, 1, 'the view joins the window that comes')+ assert.equal(added[0], views[0], 'it is the same view')+})diff --git a/app/test/downloads.test.mjs b/app/test/downloads.test.mjsindex 909a0e35..edd9c1f4 100644--- a/app/test/downloads.test.mjs+++ b/app/test/downloads.test.mjs@@ -51,3 +51,34 @@ test('a download from another contents passes through', () => {assert.equal(download.path, undefined)assert.equal(ev.prevented, false)})++test('the window is asked for at the moment of the download, because the app may build a new one', () => {+ const contents = {}+ const calls = []+ let window = { webContents: {} }+ const save = downloadSaver({+ window: () => window,+ dialog: { showSaveDialogSync: (win) => { calls.push(win); return '/picked/chart.png' } },+ downloads: '/downloads',+ })+ // A new window took the place of the old one.+ window = { webContents: contents }+ save(event(), item(), contents)+ assert.equal(calls.length, 1)+ assert.equal(calls[0], window, 'the dialog belongs to the current window')+})++test('a download without a window passes through', () => {+ let asked = false+ const save = downloadSaver({+ window: () => undefined,+ dialog: { showSaveDialogSync: () => { asked = true; return '/picked' } },+ downloads: '/downloads',+ })+ const ev = event()+ const download = item()+ save(ev, download, { webContents: {} })+ assert.equal(asked, false)+ assert.equal(download.path, undefined)+ assert.equal(ev.prevented, false)+})diff --git a/app/test/electron/lifecycle-main.mjs b/app/test/electron/lifecycle-main.mjsnew file mode 100644index 00000000..51ba7af3--- /dev/null+++ b/app/test/electron/lifecycle-main.mjs@@ -0,0 +1,138 @@+// The window and the tray in a real Electron, with a fake Host: no DSH, no model, no data.+// The check script drives it over stdin and reads the answers on stdout.+import { app, BrowserWindow, Menu, nativeImage, powerMonitor, Tray } from 'electron'+import { randomBytes } from 'node:crypto'+import { mkdirSync, writeFileSync } from 'node:fs'+import { createServer } from 'node:http'+import net from 'node:net'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { createShell } from '../../src/shell.mjs'++const here = dirname(fileURLToPath(import.meta.url))+const assets = join(here, '..', '..', 'assets')+// The data of this run is the folder the check script names, so that the check never writes+// into the data of the user. The path is set before the app is ready.+if (process.env.DS_BOT_SHELL_DATA !== undefined) app.setPath('userData', process.env.DS_BOT_SHELL_DATA)+const token = randomBytes(16).toString('hex')+const cookie = `dsh-auth=${token}`+let origin+let requests = 0+let hosts = 0++// The Host of the app, as far as the window is concerned: the launch URL trades its token for+// a cookie, and the plain address is served to whoever carries that cookie.+const host = createServer((request, response) => {+ requests += 1+ const url = new URL(request.url, 'http://127.0.0.1')+ if (url.searchParams.get('token') === token) {+ response.writeHead(302, { 'set-cookie': `${cookie}; Path=/`, location: '/' })+ response.end()+ return+ }+ if ((request.headers.cookie ?? '').includes(cookie)) {+ response.writeHead(200, { 'content-type': 'text/html' })+ response.end('<!doctype html><title>DeepSeek Bot</title><h1 id="ready">ready</h1>')+ return+ }+ response.writeHead(401).end('unauthorized')+})++let mainWindow+const shell = createShell({+ electron: { app, Menu, Tray, powerMonitor },+ platform: process.platform,+ messages: () => ({ tooltip: 'DeepSeek Bot', open: 'Open DeepSeek Bot', quit: 'Quit DeepSeek Bot', notice: 'The app goes on.', noticeConfirm: 'OK' }),+ trayImage: () => {+ const file = join(assets, process.platform === 'win32' ? 'tray.ico' : process.platform === 'darwin' ? 'trayTemplate.png' : 'tray.png')+ const image = nativeImage.createFromPath(file)+ if (image.isEmpty()) throw new Error(`the tray icon ${file} could not be read`)+ if (process.platform === 'darwin') image.setTemplateImage(true)+ return image+ },+ window: () => mainWindow,+ build: () => {+ const win = createWindow()+ // The Host runs already: the plain address is enough, the cookie carries the session.+ void win.loadURL(`${origin}/`).catch(() => {})+ return win+ },+ reveal: (target) => { target.show(); target.focus() },+ quit: () => { app.quit() },+ busy: () => false,+ ready: () => origin !== undefined,+ notice: { marker: () => join(app.getPath('userData'), 'tray-close-acknowledged'), show: async () => ({ response: 0 }) },+})++// The app is on its way out: the window may close for good. The app of the real desktop+// does the same in its before-quit.+app.on('before-quit', () => { shell.beginQuit() })++function createWindow() {+ const win = new BrowserWindow({ width: 900, height: 600, show: false })+ mainWindow = win+ win.once('ready-to-show', () => {+ if (win.isDestroyed() || shell.isQuitting() || shell.isHidden(win)) return+ win.show()+ })+ win.on('closed', () => { if (mainWindow === win) mainWindow = undefined })+ shell.watch(win)+ return win+}++const answer = (payload) => { process.stdout.write(`${JSON.stringify(payload)}\n`) }++const state = () => ({+ visible: mainWindow === undefined ? null : mainWindow.isVisible(),+ destroyed: mainWindow === undefined ? null : mainWindow.isDestroyed(),+ url: mainWindow === undefined ? null : mainWindow.webContents.getURL(),+ title: mainWindow === undefined ? null : mainWindow.webContents.getTitle(),+ requests,+ hosts,+ hasTray: shell.hasTray(),+ quitting: shell.isQuitting(),+})++async function handle(command) {+ if (command === 'close') mainWindow?.close()+ if (command === 'destroy') mainWindow?.destroy()+ if (command === 'open') shell.open()+ if (command === 'quit') shell.quit()+ await new Promise(resolve => setTimeout(resolve, 400))+ return state()+}++// The check script talks to the app over this socket: the main process of Electron does not+// read its standard input.+const commands = net.createServer((socket) => {+ socket.setEncoding('utf8')+ let buffer = ''+ socket.on('data', (chunk) => {+ buffer += chunk+ for (;;) {+ const index = buffer.indexOf('\n')+ if (index < 0) break+ const line = buffer.slice(0, index).trim()+ buffer = buffer.slice(index + 1)+ if (line === '') continue+ void handle(line).then(result => { socket.write(`${JSON.stringify(result)}\n`) })+ }+ })+})++app.whenReady().then(async () => {+ await new Promise(resolve => host.listen(0, '127.0.0.1', resolve))+ origin = `http://127.0.0.1:${String(host.address().port)}`+ hosts += 1+ // The one-time notice is answered in advance: the check is about the window and the tray.+ const folder = app.getPath('userData')+ mkdirSync(folder, { recursive: true })+ writeFileSync(join(folder, 'tray-close-acknowledged'), '')+ shell.install()+ await new Promise(resolve => commands.listen(0, '127.0.0.1', resolve))+ const win = createWindow()+ // The launch URL trades its token for the cookie of the Host.+ void win.loadURL(`${origin}/?token=${token}`).catch(() => {})+ await new Promise(resolve => setTimeout(resolve, 1200))+ answer({ ready: true, port: commands.address().port, ...state() })+})diff --git a/app/test/helpers/app-harness.mjs b/app/test/helpers/app-harness.mjsnew file mode 100644index 00000000..2a40999c--- /dev/null+++ b/app/test/helpers/app-harness.mjs@@ -0,0 +1,44 @@+// The main process of the app, with the Electron parts as a test double: the window, the+// tray and the Host, without a display, without DSH and without the data of the user.+// The loader (test/helpers/loader.mjs) puts the test doubles in place of "electron".+import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { paths, state } from './fake-electron.mjs'+import { hold } from './fake-host-process.mjs'++/** Wait until the app has done something, so that the test does not guess a moment. */+export const waitFor = async (check, what, timeout = 10_000) => {+ const until = Date.now() + timeout+ for (;;) {+ if (check()) return+ if (Date.now() > until) throw new Error(`the app did not ${what}`)+ await new Promise(resolve => { setTimeout(resolve, 10) })+ }+}++/**+ * Start the app on throwaway folders: the places are chosen already and the one-time notice+ * is answered, so that the app asks nothing. The Host answers when the test lets it.+ * @param {{ packaged?: boolean }} options whether the app is a packaged one, with an updater+ */+export const startApp = async ({ packaged = true } = {}) => {+ const home = mkdtempSync(join(tmpdir(), 'ds-bot-main-home-'))+ const workspace = join(home, 'workspace')+ mkdirSync(workspace, { recursive: true })+ mkdirSync(paths.userData, { recursive: true })+ writeFileSync(join(paths.userData, 'locations.json'), JSON.stringify({ dataDir: home, workspace }))+ writeFileSync(join(paths.userData, 'tray-close-acknowledged'), '')+ hold()+ await import('../../src/main.mjs')+ // The app is a packaged one, so that it has an updater. The flag comes after the start,+ // because a packaged app starts on the canonical path of its own.+ state.packaged = packaged+ return { home, workspace }+}++/** The window of the app: the last one it built. */+export const window = () => state.windows.at(-1)++/** The entries of the tray's menu: Open, a line, Quit. */+export const trayMenu = () => state.tray.menu.templatediff --git a/app/test/helpers/fake-app-boot.mjs b/app/test/helpers/fake-app-boot.mjsnew file mode 100644index 00000000..10ac1daf--- /dev/null+++ b/app/test/helpers/fake-app-boot.mjs@@ -0,0 +1,11 @@+// The boot of the profile, as a test double: the version of DSH the app reports, and the+// parts of a profile the app asks for. The app's own main process never calls them.+export const getDshRuntimeVersion = () => ({ release: { version: '0.2.1-rc.2' } })+export const loadLayeredEnv = () => ({})+export const reportSkippedBundles = () => {}+export const initProfile = () => {}+export const loadProfileDirectory = () => ({})+export const readProfileManifest = () => ({ dsh: { profile: { bundles: [] } } })+export const resolveProfileDir = (name) => name+export const writeProfileBundles = () => {}+export const composeEntries = (entries) => entries.flat()diff --git a/app/test/helpers/fake-electron.mjs b/app/test/helpers/fake-electron.mjsnew file mode 100644index 00000000..c7f17c55--- /dev/null+++ b/app/test/helpers/fake-electron.mjs@@ -0,0 +1,224 @@+// The Electron parts of the app, as a test double: enough of the API for the main process+// of src/main.mjs to run without a display, without DSH and without the user's data.+// The loader (test/helpers/loader.mjs) puts this module in place of "electron".+import { EventEmitter } from 'node:events'+import { mkdirSync, mkdtempSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++// The data of the app in this process: a folder of its own, so that a test never writes+// into the data of the user.+const root = mkdtempSync(join(tmpdir(), 'ds-bot-fake-user-data-'))+export const paths = {+ root,+ userData: join(root, 'userData'),+ downloads: join(root, 'downloads'),+ exe: join(root, 'DeepSeek Bot.exe'),+ // The folder of the app itself: the Host's pnpm lives in it.+ appPath: join(root, 'app'),+}+for (const folder of [paths.userData, paths.downloads]) mkdirSync(folder, { recursive: true })++export const state = {+ windows: [],+ menus: [],+ dialogs: [],+ quits: 0,+ relaunches: [],+ exits: [],+ ipc: new Map(),+ tray: undefined,+ // The tray cannot always be built; a test says so before the app starts.+ trayFails: false,+ // The app is a packaged one: it has an updater. It is set after the app starts, so that+ // the paths of the packaged app do not come into the way of the start.+ packaged: false,+ // No page of the browser comes through.+ rejectLoads: false,+ // The cookies of the browser: the Host's address keeps one after the launch URL was used.+ cookies: [],+ paths: {},+ dock: { setIcon: () => {} },+}++export class FakeWindow extends EventEmitter {+ constructor(options = {}) {+ super()+ this.options = options+ this.visible = false+ this.minimized = false+ this.fullScreen = false+ this.destroyed = false+ this.url = ''+ this.loaded = []+ this.shown = 0+ this.focused = 0+ this.webContents = new FakeWebContents(this)+ state.windows.push(this)+ }++ isDestroyed() { return this.destroyed }+ isVisible() { return this.visible }+ isMinimized() { return this.minimized }+ isFullScreen() { return this.fullScreen }+ setFullScreen(value) { this.fullScreen = value; if (!value) this.emit('leave-full-screen') }+ show() { this.visible = true; this.shown += 1; this.emit('show') }+ hide() { this.visible = false; this.emit('hide') }+ focus() { this.focused += 1 }+ restore() { this.minimized = false; this.visible = true; this.emit('restore') }+ minimize() { this.minimized = true }+ destroy() { this.destroyed = true; this.emit('closed') }+ close() { this.emit('close', { preventDefault: () => { this.prevented = true } }) }+ setTitleBarOverlay() {}+ setProgressBar() {}+ setMinimumSize() {}+ moveTop() {}+ getBounds() { return { x: 0, y: 0, width: 800, height: 600 } }+ async loadURL(url) {+ this.url = url+ this.loaded.push(url)+ if (state.rejectLoads || this.rejectLoads) throw new Error(`the page ${url} did not load`)+ // The Host trades the token of the launch URL for a cookie of the browser's session.+ try {+ const parsed = new URL(url)+ const token = parsed.searchParams.get('token')+ if (token !== null) state.cookies.push({ name: 'dsh-auth', value: token, domain: parsed.hostname, path: '/' })+ } catch { /* a page without an address of its own */ }+ // The window is on the screen once its first page is there.+ if (!this.ready) {+ this.ready = true+ setImmediate(() => { if (!this.destroyed) this.emit('ready-to-show') })+ }+ }+}++class FakeWebContents extends EventEmitter {+ constructor(win) {+ super()+ this.win = win+ this.session = new EventEmitter()+ this.mainFrame = {}+ this.isDestroyed = () => this.win.destroyed+ this.getURL = () => this.win.url+ this.getTitle = () => 'DeepSeek Bot'+ this.send = () => {}+ this.setWindowOpenHandler = () => {}+ this.insertCSS = async () => {}+ this.toggleDevTools = () => {}+ this.loadURL = async url => { await this.win.loadURL(url) }+ }+}++class FakeApp extends EventEmitter {+ constructor() {+ super()+ this.name = 'DeepSeek Bot'+ this.getVersion = () => '0.2.2'+ this.getLocale = () => 'en-US'+ this.getPath = (name) => paths[name] ?? join(root, String(name))+ this.getAppPath = () => paths.appPath+ this.setPath = (name, value) => { state.paths[name] = value }+ // The app starts a tick later, so that a test has its say before the app begins.+ this.whenReady = () => new Promise((done) => { setImmediate(done) })+ this.requestSingleInstanceLock = () => true+ this.relaunch = (options) => { state.relaunches.push(options) }+ this.exit = (code) => { state.exits.push(code); this.emit('exit', code) }+ this.quit = () => {+ state.quits += 1+ let prevented = false+ this.emit('before-quit', { preventDefault: () => { prevented = true } })+ state.quitPrevented = prevented+ if (!prevented) this.emit('will-quit')+ }+ this.show = () => { state.appShown = (state.appShown ?? 0) + 1 }+ this.hide = () => { state.appHidden = (state.appHidden ?? 0) + 1 }+ this.focus = () => {}+ this.setAboutPanelOptions = () => {}+ this.setAsDefaultProtocolClient = () => {}+ }++ get isPackaged() { return state.packaged === true }+}++export const app = new FakeApp()++export const BrowserWindow = FakeWindow++export const WebContentsView = class {+ constructor(options) { this.options = options; this.webContents = new FakeWebContents({ destroyed: false, url: '' }) }+ setBounds() {}+ setVisible() {}+}++export const Menu = {+ buildFromTemplate: (template) => ({ template }),+ setApplicationMenu: (menu) => { state.menus.push(menu) },+}++export const Tray = class extends EventEmitter {+ constructor(image) {+ super()+ if (state.trayFails) throw new Error('no system tray here')+ this.image = image+ this.menu = undefined+ state.tray = this+ }+ setToolTip(value) { this.tooltip = value }+ setContextMenu(menu) { this.menu = menu }+ destroy() { this.destroyed = true }+}++export const nativeImage = {+ createFromPath: () => ({+ empty: false,+ isEmpty: () => false,+ getSize: () => ({ width: 32, height: 32 }),+ toPNG: () => Buffer.alloc(8),+ addRepresentation() {},+ setTemplateImage() {},+ }),+}++export const nativeTheme = { shouldUseDarkColors: false, themeSource: 'system' }++export const powerMonitor = new EventEmitter()++// The cookies of the browser: the Host's address keeps one after the launch URL was used.+const cookieJar = {+ get: async ({ url } = {}) => {+ if (url === undefined) return state.cookies.map(entry => ({ ...entry }))+ const wanted = new URL(url)+ return state.cookies.filter(entry => entry.domain === wanted.hostname).map(entry => ({ ...entry }))+ },+}++export const session = {+ defaultSession: Object.assign(new EventEmitter(), { cookies: cookieJar }),+ fromPartition: () => Object.assign(new EventEmitter(), { cookies: cookieJar }),+}++export const ipcMain = {+ handle: (channel, handler) => { state.ipc.set(channel, handler) },+ on: (channel, handler) => { state.ipc.set(channel, handler) },+}++export const dialog = {+ showMessageBox: async (...args) => {+ // Electron takes the window as the first argument and the box as the second.+ const options = args.length > 1 ? args[1] : args[0]+ state.dialogs.push(options)+ const answer = state.dialogAnswer ?? { response: 1 }+ return typeof answer === 'function' ? answer(options) : answer+ },+ showErrorBox: (title, message) => { state.dialogs.push({ title, message }) },+ showOpenDialog: async (...args) => {+ const options = args.length > 1 ? args[1] : args[0]+ state.dialogs.push(options)+ const answer = state.openAnswer ?? { canceled: true, filePaths: [] }+ return typeof answer === 'function' ? answer(options) : answer+ },+}++export const shell = {+ openExternal: async (url) => { state.opened = (state.opened ?? []).concat(url) },+}diff --git a/app/test/helpers/fake-host-process.mjs b/app/test/helpers/fake-host-process.mjsnew file mode 100644index 00000000..f72d516e--- /dev/null+++ b/app/test/helpers/fake-host-process.mjs@@ -0,0 +1,52 @@+// The Host of the app, as a test double: it reports a launch URL and counts how often it was+// started, so that a test can see that no second Host was started.+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { paths } from './fake-electron.mjs'++// The port the app gave the Host: the launch URL is on the Host's own address.+const port = () => {+ try {+ return String(JSON.parse(readFileSync(join(paths.userData, 'host-port.json'), 'utf8')).port)+ } catch {+ return '43117'+ }+}++let gate+let open++export const state = {+ starts: 0,+ stops: 0,+ fail: false,+ // The Host waits for the test to let it answer.+ held: false,+ release: () => { if (open !== undefined) { open(); open = undefined } },+}++/** Keep the Host waiting until the test lets it answer. */+export const hold = () => {+ state.held = true+ gate = new Promise((done) => { open = done })+}++export class HostProcess {+ #options+ #messageListeners = new Set()++ constructor(options) { this.#options = options }++ async start() {+ state.starts += 1+ if (state.held) await gate+ if (state.fail) throw new Error('the Host did not start')+ return { url: `http://127.0.0.1:${port()}/?token=test-token`, injections: [] }+ }++ onMessage(listener) { this.#messageListeners.add(listener); return () => this.#messageListeners.delete(listener) }++ send() {}++ async stop() { state.stops += 1 }+}diff --git a/app/test/helpers/fake-updater.mjs b/app/test/helpers/fake-updater.mjsnew file mode 100644index 00000000..c2c3f36c--- /dev/null+++ b/app/test/helpers/fake-updater.mjs@@ -0,0 +1,14 @@+// The updater of the app, as a test double: it records what the app asked of it.+import { EventEmitter } from 'node:events'++export const state = { checks: 0, quitAndInstall: [], autoDownload: false, autoInstallOnAppQuit: false }++export class FakeUpdater extends EventEmitter {+ checkForUpdates() { state.checks += 1; return Promise.resolve({ isUpdateAvailable: false, updateInfo: { version: '0.2.2' } }) }+ setFeedURL() {}+ quitAndInstall(...args) { state.quitAndInstall.push(args) }+}++export const updater = new FakeUpdater()++export default { autoUpdater: updater }diff --git a/app/test/helpers/hooks.mjs b/app/test/helpers/hooks.mjsnew file mode 100644index 00000000..23c0797c--- /dev/null+++ b/app/test/helpers/hooks.mjs@@ -0,0 +1,21 @@+// The hooks of the main process test: they put the test doubles in place of the packages+// that would need a display, a DSH install or the network. These hooks run in the thread+// of the test (module.registerHooks).++const here = new URL('./', import.meta.url)++/**+ * @param {string} specifier the module the app asks for+ * @param {object} context what the loader knows about the request+ * @param {(specifier: string, context: object) => { url: string }} nextResolve the loader's own answer+ */+export function resolve(specifier, context, nextResolve) {+ const fake = (name) => ({ url: new URL(name, here).href, shortCircuit: true })+ if (specifier === 'electron') return fake('fake-electron.mjs')+ if (specifier === 'electron-updater') return fake('fake-updater.mjs')+ if (specifier === '@deepseek-ai/dsh-app-boot') return fake('fake-app-boot.mjs')+ const resolved = nextResolve(specifier, context)+ // The Host of the app is replaced, so that no DSH is booted.+ if (resolved.url.endsWith('/app/src/host-process.mjs')) return fake('fake-host-process.mjs')+ return resolved+}diff --git a/app/test/helpers/loader.mjs b/app/test/helpers/loader.mjsnew file mode 100644index 00000000..8f0e4215--- /dev/null+++ b/app/test/helpers/loader.mjs@@ -0,0 +1,15 @@+// The loader of the main process test: it puts the test doubles in place of the packages+// that would need a display, a DSH install or the network. This loader runs in a thread of+// its own (module.register), for the Node versions without module.registerHooks.+const here = new URL('./', import.meta.url)+const fake = (name) => ({ url: new URL(name, here).href, shortCircuit: true })++export async function resolve(specifier, context, nextResolve) {+ if (specifier === 'electron') return fake('fake-electron.mjs')+ if (specifier === 'electron-updater') return fake('fake-updater.mjs')+ if (specifier === '@deepseek-ai/dsh-app-boot') return fake('fake-app-boot.mjs')+ const resolved = await nextResolve(specifier, context)+ // The Host of the app is replaced, so that no DSH is booted.+ if (resolved.url.endsWith('/app/src/host-process.mjs')) return fake('fake-host-process.mjs')+ return resolved+}diff --git a/app/test/helpers/register.mjs b/app/test/helpers/register.mjsnew file mode 100644index 00000000..edbcfe18--- /dev/null+++ b/app/test/helpers/register.mjs@@ -0,0 +1,16 @@+// The loader of the main process test: it puts the test doubles in place of the packages+// that would need a display, a DSH install or the network. It is installed by the test+// files that need it, so that the other tests keep the real packages.+import { register, registerHooks } from 'node:module'++/** Put the test doubles in place of the packages the app cannot run here. */+export const installHooks = async () => {+ if (typeof registerHooks === 'function') {+ const { resolve } = await import('./hooks.mjs')+ registerHooks({ resolve })+ return+ }+ // The hooks of the older Node versions run in a thread of their own.+ register('./loader.mjs', import.meta.url)+ await new Promise(done => { setImmediate(done) })+}diff --git a/app/test/main-handshake.test.mjs b/app/test/main-handshake.test.mjsnew file mode 100644index 00000000..ba82b3fe--- /dev/null+++ b/app/test/main-handshake.test.mjs@@ -0,0 +1,41 @@+// The handshake of the Host: the first window trades the launch URL for the Host's cookie,+// and the token of that URL is good for one use only. When the first load never came+// through, no window carries the token again.+import assert from 'node:assert/strict'+import { before, test } from 'node:test'+import { state } from './helpers/fake-electron.mjs'+import { state as hostState } from './helpers/fake-host-process.mjs'+import { startApp, trayMenu, waitFor, window } from './helpers/app-harness.mjs'+import { installHooks } from './helpers/register.mjs'++await installHooks()++before(async () => {+ // No page of the browser comes through: the first load of the Host fails.+ state.rejectLoads = true+ await startApp()+})++test('a first load that never came through does not carry the token again', async () => {+ await waitFor(() => state.windows.length > 0, 'open the window')+ await waitFor(() => state.tray !== undefined, 'build the tray')+ const first = window()+ hostState.release()+ await waitFor(() => first.loaded.some(url => url.includes('token=')), 'try the Host')+ assert.equal(state.cookies.length, 0, 'the Host left no cookie')++ // The window is gone for good; the tray builds a new one.+ first.destroy()+ trayMenu()[0].click()+ await waitFor(() => state.windows.length === 2, 'build a new window')+ const second = window()+ await waitFor(() => second.loaded.some(url => url.startsWith('http://127.0.0.1:')), 'reach the Host')+ assert.equal(second.loaded.filter(url => url.includes('token=')).length, 0, 'the token is not used again')+ assert.equal(hostState.starts, 1, 'no second Host was started')+})++test('the app ends', async () => {+ trayMenu().at(-1).click()+ await waitFor(() => state.quits > 0, 'end the app')+ await waitFor(() => state.tray.destroyed === true, 'take the tray away')+})diff --git a/app/test/main-menu-fallback.test.mjs b/app/test/main-menu-fallback.test.mjsnew file mode 100644index 00000000..0b0ffefe--- /dev/null+++ b/app/test/main-menu-fallback.test.mjs@@ -0,0 +1,29 @@+// Without a system tray the app has no ordinary way out, so the application menu of macOS+// carries a Quit of its own. It is the only case in which the menu has one.+import assert from 'node:assert/strict'+import { before, test } from 'node:test'+import { state } from './helpers/fake-electron.mjs'+import { startApp, waitFor } from './helpers/app-harness.mjs'+import { installHooks } from './helpers/register.mjs'++await installHooks()++// The menu of macOS is the menu of the app on macOS.+Object.defineProperty(process, 'platform', { value: 'darwin' })++before(async () => {+ // The desktop has no tray.+ state.trayFails = true+ await startApp({ packaged: false })+})++test('the application menu of macOS carries a Quit when there is no tray', async () => {+ await waitFor(() => state.menus.length > 0, 'set the menu')+ assert.equal(state.tray, undefined, 'there is no tray')+ const items = state.menus.at(-1).template[0].submenu+ const quit = items.at(-1)+ assert.equal(quit.label, 'Quit DeepSeek Bot', 'the menu ends the app')+ assert.equal(typeof quit.click, 'function', 'the entry works')+ quit.click()+ await waitFor(() => state.quits > 0, 'end the app')+})diff --git a/app/test/main-menu.test.mjs b/app/test/main-menu.test.mjsnew file mode 100644index 00000000..7cd2fc6e--- /dev/null+++ b/app/test/main-menu.test.mjs@@ -0,0 +1,33 @@+// The application menu of macOS: the tray's Quit is the one ordinary way out, so the menu+// has none. Only when the tray is not there does the menu carry one.+import assert from 'node:assert/strict'+import { before, test } from 'node:test'+import { app, state } from './helpers/fake-electron.mjs'+import { startApp, waitFor } from './helpers/app-harness.mjs'+import { installHooks } from './helpers/register.mjs'++await installHooks()++// The menu of macOS is the menu of the app on macOS.+Object.defineProperty(process, 'platform', { value: 'darwin' })++before(async () => { await startApp({ packaged: false }) })++test('the application menu of macOS has no Quit', async () => {+ await waitFor(() => state.menus.length > 0, 'set the menu')+ await waitFor(() => state.tray !== undefined, 'build the tray')+ const menu = state.menus.at(-1).template+ const items = menu[0].submenu+ assert.equal(menu[0].label, 'DeepSeek Bot', 'the menu of the app')+ assert.equal(items.some(item => item.role === 'quit'), false, 'no Quit of its own')+ assert.equal(items.some(item => item.accelerator === 'CmdOrCtrl+Q' || item.accelerator === 'Command+Q'), false, 'no shortcut for it')+ assert.equal(items.some(item => item.label === 'Quit DeepSeek Bot'), false, 'no entry for it')+ // The menu keeps the rest of macOS: about, services and the hiding of the app.+ const roles = items.map(item => item.role).filter(Boolean)+ for (const role of ['about', 'services', 'hide', 'hideOthers', 'unhide']) assert.ok(roles.includes(role), `the menu keeps ${role}`)+})++test('the app ends', async () => {+ app.quit()+ await waitFor(() => state.tray.destroyed === true, 'take the tray away')+})diff --git a/app/test/main-update.test.mjs b/app/test/main-update.test.mjsnew file mode 100644index 00000000..8cafa4a9--- /dev/null+++ b/app/test/main-update.test.mjs@@ -0,0 +1,39 @@+// The update of the app belongs to the window: while the window is hidden or minimized, the+// box waits, and the answer the user gives when the window is back does the work itself.+import assert from 'node:assert/strict'+import { before, test } from 'node:test'+import { app, state } from './helpers/fake-electron.mjs'+import { state as hostState } from './helpers/fake-host-process.mjs'+import { state as updaterState, updater } from './helpers/fake-updater.mjs'+import { startApp, trayMenu, waitFor, window } from './helpers/app-harness.mjs'+import { installHooks } from './helpers/register.mjs'++await installHooks()++before(async () => { await startApp() })++test('the update waits for the window and is installed when the window comes back', async () => {+ await waitFor(() => state.windows.length > 0, 'open the window')+ await waitFor(() => state.tray !== undefined, 'build the tray')+ const win = window()+ hostState.release()+ await waitFor(() => win.visible === true, 'show the window')+ // The window goes away, and the update is downloaded while it is gone.+ win.close()+ await waitFor(() => win.visible === false, 'hide the window')+ updater.emit('update-downloaded', { version: '9.9.9' })+ await new Promise(resolve => { setTimeout(resolve, 50) })+ assert.equal(state.dialogs.length, 0, 'the box waits for the window')++ // The user says yes when the window is back.+ state.dialogAnswer = { response: 0 }+ trayMenu()[0].click()+ await waitFor(() => updaterState.quitAndInstall.length === 1, 'install the update')+ assert.equal(hostState.stops, 1, 'the Host stops for the installer')+ assert.equal(updaterState.quitAndInstall[0].length, 2, 'the installer takes over')+})++test('the app ends after the update', async () => {+ app.quit()+ await waitFor(() => state.tray.destroyed === true, 'take the tray away')+})diff --git a/app/test/main.test.mjs b/app/test/main.test.mjsnew file mode 100644index 00000000..db2cdf9d--- /dev/null+++ b/app/test/main.test.mjs@@ -0,0 +1,63 @@+// The main process of the app: the window hides instead of closing, the tray is the way+// back to it, and a window that is gone for good is built anew and talks to the Host that+// runs. The Electron parts are test doubles: no display, no DSH, no data of the user.+import assert from 'node:assert/strict'+import { before, test } from 'node:test'+import { state } from './helpers/fake-electron.mjs'+import { state as hostState } from './helpers/fake-host-process.mjs'+import { startApp, trayMenu, waitFor, window } from './helpers/app-harness.mjs'+import { installHooks } from './helpers/register.mjs'++await installHooks()++before(async () => { await startApp() })++test('the app starts with a window and a tray', async () => {+ await waitFor(() => state.windows.length > 0, 'open the window')+ await waitFor(() => state.tray !== undefined, 'build the tray')+ assert.equal(state.tray.tooltip, 'DeepSeek Bot')+ assert.equal(state.quits, 0, 'the app goes on')+})++test('the first window trades the launch URL for the Host\'s cookie', async () => {+ const win = window()+ hostState.release()+ await waitFor(() => win.loaded.some(url => url.includes('token=')), 'reach the Host')+ assert.equal(win.loaded.filter(url => url.includes('token=')).length, 1, 'the token is used once')+ assert.equal(state.cookies.length, 1, 'the Host left a cookie for its address')+})++test('a window that is gone for good is built anew and talks to the same Host', async () => {+ const first = window()+ first.destroy()+ trayMenu()[0].click()+ await waitFor(() => state.windows.length === 2, 'build a new window')+ const second = window()+ await waitFor(() => second.loaded.some(url => url.startsWith('http://127.0.0.1:')), 'reach the Host')+ assert.equal(second.loaded.filter(url => url.includes('token=')).length, 0, 'the token is not used again')+ assert.equal(hostState.starts, 1, 'no second Host was started')+})++test('closing the window hides it; the app goes on', async () => {+ const win = window()+ win.close()+ await waitFor(() => win.visible === false, 'hide the window')+ assert.equal(win.isDestroyed(), false, 'the window is there')+ assert.equal(state.quits, 0, 'the app goes on')+ assert.equal(hostState.stops, 0, 'the Host goes on')+ assert.equal(state.dialogs.length, 0, 'the notice was answered already')+})++test('the tray opens the window again', async () => {+ const win = window()+ trayMenu()[0].click()+ await waitFor(() => win.visible === true, 'show the window')+ assert.equal(win.focused > 0, true, 'the window has the focus')+})++test('the tray quit ends the app and stops the Host', async () => {+ trayMenu().at(-1).click()+ await waitFor(() => state.quits > 0, 'end the app')+ await waitFor(() => hostState.stops === 1, 'stop the Host')+ await waitFor(() => state.tray.destroyed === true, 'take the tray away')+})diff --git a/app/test/shell.test.mjs b/app/test/shell.test.mjsnew file mode 100644index 00000000..aae8baad--- /dev/null+++ b/app/test/shell.test.mjs@@ -0,0 +1,307 @@+// The window and the tray share one life: the close hides the window, the tray is the way+// back to it, and only the app itself ends the app.+import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'+import { existsSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { describe, test } from 'node:test'+import { createShell } from '../src/shell.mjs'++/** A window like Electron's: the shell shows, hides, focuses and minimizes it. */+class FakeWindow extends EventEmitter {+ constructor() {+ super()+ this.visible = true+ this.minimized = false+ this.fullScreen = false+ this.destroyed = false+ this.shown = 0+ this.focused = 0+ }+ isDestroyed() { return this.destroyed }+ isVisible() { return this.visible }+ isMinimized() { return this.minimized }+ isFullScreen() { return this.fullScreen }+ setFullScreen(value) { this.fullScreen = value; if (!value && !this.deferFullScreen) this.emit('leave-full-screen') }+ hide() { this.visible = false }+ show() { this.visible = true; this.shown += 1 }+ focus() { this.focused += 1 }+ restore() { this.minimized = false }+ minimize() { this.minimized = true }+}++// The notice answers in its own turn; the tests wait for it.+const settle = () => new Promise(resolve => setImmediate(resolve))++function harness({ platform = 'win32', trayFails = false, busy = false, ready = true, answer = 0, acknowledged = true, fallbackAnswer = 1 } = {}) {+ const app = new EventEmitter()+ const powerMonitor = new EventEmitter()+ const trays = []+ const menus = []+ const calls = { quit: 0, build: 0, reveal: 0 }+ const folder = mkdtempSync(join(tmpdir(), 'ds-bot-shell-'))+ const marker = join(folder, 'acknowledged')+ if (acknowledged) writeFileSync(marker, '')+ const asked = []+ const questions = []+ let window = new FakeWindow()+ const shell = createShell({+ electron: {+ app,+ powerMonitor,+ Menu: { buildFromTemplate: template => template },+ Tray: class {+ constructor(image) { this.image = image; this.handlers = {}; trays.push(this) }+ on(event, handler) { (this.handlers[event] ??= []).push(handler) }+ setToolTip(value) { this.tooltip = value }+ setContextMenu(menu) { this.menu = menu; menus.push(menu) }+ destroy() { this.destroyed = true }+ click() { for (const handler of this.handlers.click ?? []) handler() }+ },+ },+ platform,+ messages: () => ({+ tooltip: 'DeepSeek Bot', open: 'Open', quit: 'Quit', notice: 'The app goes on.', noticeConfirm: 'OK',+ fallback: 'The system tray is not available, so the app cannot stay in the background. Do you want to end it?', cancel: 'Cancel',+ }),+ trayImage: () => {+ if (trayFails) throw new Error('no system tray here')+ return { empty: false }+ },+ window: () => window,+ build: () => {+ calls.build += 1+ window = new FakeWindow()+ shell.watch(window)+ return window+ },+ reveal: (target) => { calls.reveal += 1; target.show(); target.focus() },+ quit: () => { calls.quit += 1 },+ busy: () => busy,+ ready: () => ready,+ notice: {+ marker: () => marker,+ show: async (options) => { asked.push(options); return { response: answer } },+ },+ // Without a tray the close asks whether the app should end.+ fallback: { show: async (options) => { questions.push(options); return { response: fallbackAnswer } } },+ log: { warn: () => {} },+ })+ shell.install()+ shell.watch(window)+ return {+ shell,+ app,+ powerMonitor,+ trays,+ menus,+ calls,+ asked,+ questions,+ marker,+ cleanup: () => rmSync(folder, { recursive: true, force: true }),+ window: () => window,+ close: () => {+ let prevented = false+ shell.close({ preventDefault: () => { prevented = true } })+ return prevented+ },+ }+}++describe('the window and the tray', () => {+ test('a normal close hides the window; the app goes on', (t) => {+ const app = harness()+ t.after(app.cleanup)+ assert.equal(app.close(), true, 'the close is held')+ assert.equal(app.window().visible, false, 'the window is hidden')+ assert.equal(app.calls.quit, 0, 'the app is still running')+ })++ test('the first close asks once, and a cancelled answer leaves the window visible', async (t) => {+ const app = harness({ acknowledged: false, answer: -1 })+ t.after(app.cleanup)+ app.close()+ await settle()+ assert.equal(app.asked.length, 1, 'the notice is shown')+ assert.equal(app.asked[0].cancelId, -1, 'the notice can be called off')+ assert.equal(app.window().visible, true, 'the window stays where it is')+ assert.equal(app.calls.quit, 0, 'the app is still running')+ })++ test('an answered notice hides the window and is remembered', async (t) => {+ const app = harness({ acknowledged: false })+ t.after(app.cleanup)+ app.close()+ await settle()+ assert.equal(app.window().visible, false, 'the window is hidden')+ assert.equal(existsSync(app.marker), true, 'the answer is kept')+ // The next close hides the window without another box.+ app.close()+ await settle()+ assert.equal(app.asked.length, 1, 'the notice is not shown again')+ assert.equal(app.window().visible, false)+ })++ test('two closes while the box is open ask once', async (t) => {+ const app = harness({ acknowledged: false })+ t.after(app.cleanup)+ app.close()+ app.close()+ await settle()+ assert.equal(app.asked.length, 1, 'the notice is shown once')+ })++ test('a close during an import or a data move ends the app instead of hiding', async (t) => {+ const app = harness({ busy: true })+ t.after(app.cleanup)+ app.close()+ assert.equal(app.calls.quit, 1, 'the copy is cancelled and the app ends')+ assert.equal(app.asked.length, 0, 'the notice is not shown')+ assert.equal(app.window().visible, true, 'the window is not hidden')+ })++ test('the tray opens the window again', (t) => {+ const app = harness()+ t.after(app.cleanup)+ app.close()+ assert.equal(app.window().visible, false)+ app.trays[0].click()+ assert.equal(app.window().visible, true, 'the window is back')+ assert.equal(app.window().focused, 1, 'the window has the focus')+ assert.equal(app.calls.build, 0, 'the window was not built again')+ })++ test('a window that is gone for good is built anew, and the app does not end', (t) => {+ const app = harness()+ t.after(app.cleanup)+ app.window().destroyed = true+ app.trays[0].click()+ assert.equal(app.calls.build, 1, 'a new window takes its place')+ assert.equal(app.calls.quit, 0, 'the app goes on')+ })++ test('before the first run has chosen its places there is no window to show', (t) => {+ const app = harness({ ready: false })+ t.after(app.cleanup)+ app.window().destroyed = true+ app.trays[0].click()+ assert.equal(app.calls.build, 0, 'no window is built while the app starts')+ })++ test('the tray quits the app once', (t) => {+ const app = harness()+ t.after(app.cleanup)+ const menu = app.menus.at(-1)+ assert.equal(menu[0].label, 'Open')+ assert.equal(menu.at(-1).label, 'Quit')+ menu.at(-1).click()+ menu.at(-1).click()+ assert.equal(app.calls.quit, 1, 'the app ends once')+ })++ test('without a tray the close keeps the window in the task bar', async (t) => {+ const app = harness({ trayFails: true })+ t.after(app.cleanup)+ assert.equal(app.shell.hasTray(), false)+ app.close()+ await settle()+ assert.equal(app.window().minimized, true, 'the window stays reachable')+ assert.equal(app.calls.quit, 0, 'the app does not end')+ })++ test('without a tray the close asks whether the app should end', async (t) => {+ const app = harness({ trayFails: true, fallbackAnswer: 0 })+ t.after(app.cleanup)+ app.close()+ await settle()+ assert.equal(app.questions.length, 1, 'the question is asked')+ assert.match(app.questions[0].message, /system tray/u, 'the question says why')+ assert.equal(app.calls.quit, 1, 'the app ends when the user says so')+ })++ test('without a tray a called-off question leaves the app alone', async (t) => {+ const app = harness({ trayFails: true, fallbackAnswer: 1 })+ t.after(app.cleanup)+ app.close()+ await settle()+ assert.equal(app.questions.length, 1, 'the question is asked')+ assert.equal(app.calls.quit, 0, 'the app goes on')+ })++ test('a refused quit leaves the tray at work', (t) => {+ const app = harness()+ t.after(app.cleanup)+ app.shell.beginQuit()+ app.shell.cancelQuit()+ const menu = app.menus.at(-1)+ menu.at(-1).click()+ assert.equal(app.calls.quit, 1, 'the tray ends the app')+ })++ test('no window closed does not end the app', (t) => {+ const app = harness()+ t.after(app.cleanup)+ app.app.emit('window-all-closed')+ assert.equal(app.calls.quit, 0, 'the app stays in the tray')+ })++ test('the end of the Windows session lets the window close', (t) => {+ const app = harness({ platform: 'win32' })+ t.after(app.cleanup)+ app.window().emit('session-end')+ assert.equal(app.close(), false, 'the window closes for good')+ assert.equal(app.window().visible, true, 'the window is not hidden')+ })++ test('a cancelled macOS shutdown leaves the app running', (t) => {+ const app = harness({ platform: 'darwin' })+ t.after(app.cleanup)+ app.powerMonitor.emit('shutdown')+ assert.equal(app.close(), false, 'the window closes for good')+ // Another application called the shutdown off; the user comes back to the window.+ app.window().emit('focus')+ assert.equal(app.close(), true, 'the window hides again')+ assert.equal(app.window().visible, false)+ })++ test('on macOS the Dock icon opens the window, and a fullscreen window leaves fullscreen first', (t) => {+ const app = harness({ platform: 'darwin' })+ t.after(app.cleanup)+ app.close()+ assert.equal(app.window().visible, false)+ app.app.emit('activate')+ assert.equal(app.window().visible, true, 'the window is back')++ const window = app.window()+ window.fullScreen = true+ app.close()+ assert.equal(window.fullScreen, false, 'the window left fullscreen')+ assert.equal(window.visible, false, 'the window is hidden after it')+ })++ test('the tray of macOS has no click of its own; its menu is the way back', (t) => {+ const app = harness({ platform: 'darwin' })+ t.after(app.cleanup)+ app.trays[0].click()+ assert.equal(app.calls.reveal, 0, 'the click does not open the window')+ app.menus.at(-1)[0].click()+ assert.equal(app.calls.reveal, 1, 'the menu opens it')+ })++ test('a window that is opened again while it leaves fullscreen stays', (t) => {+ const app = harness({ platform: 'darwin' })+ t.after(app.cleanup)+ const window = app.window()+ window.fullScreen = true+ window.deferFullScreen = true+ app.close()+ assert.equal(window.visible, true, 'the window waits for the fullscreen to end')+ // The tray opens the window again before the fullscreen has ended.+ app.menus.at(-1)[0].click()+ assert.equal(window.visible, true, 'the window is back')+ window.emit('leave-full-screen')+ assert.equal(window.visible, true, 'the window is not hidden after all')+ })+})diff --git a/app/test/tray.test.mjs b/app/test/tray.test.mjsnew file mode 100644index 00000000..bedc58b8--- /dev/null+++ b/app/test/tray.test.mjs@@ -0,0 +1,58 @@+// The system tray: the icon, its menu and the way it goes away.+import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'+import { describe, test } from 'node:test'+import { createTray } from '../src/tray.mjs'++function harness({ platform = 'win32' } = {}) {+ const trays = []+ const menus = []+ const Menu = { buildFromTemplate: template => template }+ const Tray = class extends EventEmitter {+ constructor(image) { super(); this.image = image; trays.push(this) }+ setToolTip(value) { this.tooltip = value }+ setContextMenu(menu) { this.menu = menu; menus.push(menu) }+ destroy() { this.destroyed = true }+ }+ const calls = { open: 0, quit: 0 }+ const tray = createTray({+ Tray, Menu, platform, image: { empty: false }, tooltip: 'DeepSeek Bot',+ open: { label: 'Open', run: () => { calls.open += 1 } },+ quit: { label: 'Quit', run: () => { calls.quit += 1 } },+ log: { warn: () => {} },+ })+ return { tray, trays, menus, calls }+}++describe('the tray', () => {+ test('the icon carries the tooltip and a menu with Open and Quit', () => {+ const app = harness()+ assert.equal(app.trays.length, 1)+ assert.equal(app.trays[0].tooltip, 'DeepSeek Bot')+ assert.deepEqual(app.menus[0].map(item => item.label ?? 'separator'), ['Open', 'separator', 'Quit'])+ })++ test('a click opens the window, and the menu opens and quits it', () => {+ const app = harness()+ app.trays[0].emit('click')+ assert.equal(app.calls.open, 1)+ app.menus[0][0].click()+ assert.equal(app.calls.open, 2)+ app.menus[0].at(-1).click()+ assert.equal(app.calls.quit, 1)+ })++ test('on macOS the menu of the icon is the way back, not a click', () => {+ const app = harness({ platform: 'darwin' })+ assert.equal(app.trays[0].listenerCount('click'), 0, 'the icon has no click of its own')+ app.menus[0][0].click()+ assert.equal(app.calls.open, 1)+ })++ test('the icon goes away once', () => {+ const app = harness()+ app.tray.dispose()+ app.tray.dispose()+ assert.equal(app.trays[0].destroyed, true)+ })+})diff --git a/app/test/update-prompt.test.mjs b/app/test/update-prompt.test.mjsnew file mode 100644index 00000000..103c0119--- /dev/null+++ b/app/test/update-prompt.test.mjs@@ -0,0 +1,70 @@+// An update prompt waits for the window: a hidden window has no box to show it in.+import assert from 'node:assert/strict'+import { describe, test } from 'node:test'+import { createDeferredPrompt } from '../src/update-prompt.mjs'++function harness({ answer = true } = {}) {+ const state = { shown: true }+ const asked = []+ const installed = []+ const deferred = createDeferredPrompt({+ ask: async version => { asked.push(version); return answer },+ shown: () => state.shown,+ onYes: async version => { installed.push(version) },+ log: { info: () => {} },+ })+ return { deferred, asked, installed, state }+}++describe('the update prompt', () => {+ test('a prompt for a visible window is asked at once', async () => {+ const app = harness()+ assert.equal(await app.deferred.prompt('0.2.3'), true)+ assert.deepEqual(app.asked, ['0.2.3'])+ assert.deepEqual(app.installed, [], 'the updater does the work itself')+ })++ test('a prompt for a hidden window waits, and is asked when the window is shown', async () => {+ const app = harness()+ app.state.shown = false+ assert.equal(await app.deferred.prompt('0.2.3'), false, 'the updater hears no for now')+ assert.deepEqual(app.asked, [], 'the box is not shown')+ assert.equal(app.deferred.waiting(), '0.2.3', 'the update waits')++ app.state.shown = true+ await app.deferred.flush()+ assert.deepEqual(app.asked, ['0.2.3'], 'the box is shown now')+ assert.deepEqual(app.installed, ['0.2.3'], 'the answer does the work')+ assert.equal(app.deferred.waiting(), undefined, 'the update does not wait any more')+ })++ test('a second showing does not ask again', async () => {+ const app = harness()+ app.state.shown = false+ await app.deferred.prompt('0.2.3')+ app.state.shown = true+ await app.deferred.flush()+ await app.deferred.flush()+ assert.deepEqual(app.asked, ['0.2.3'], 'the box is shown once')+ assert.deepEqual(app.installed, ['0.2.3'], 'the update is installed once')+ })++ test('a later answer of no does not install anything', async () => {+ const app = harness({ answer: false })+ app.state.shown = false+ await app.deferred.prompt('0.2.3')+ app.state.shown = true+ await app.deferred.flush()+ assert.deepEqual(app.asked, ['0.2.3'])+ assert.deepEqual(app.installed, [], 'the update waits for the next quit')+ })++ test('a prompt that waits does nothing while the window is still hidden', async () => {+ const app = harness()+ app.state.shown = false+ await app.deferred.prompt('0.2.3')+ await app.deferred.flush()+ assert.deepEqual(app.asked, [])+ assert.deepEqual(app.installed, [])+ })+})diff --git a/docs/plans/2026-10-16-desktop-app.md b/docs/plans/2026-10-16-desktop-app.mdindex 2bf44873..71a25c51 100644--- a/docs/plans/2026-10-16-desktop-app.md+++ b/docs/plans/2026-10-16-desktop-app.md@@ -34,6 +34,21 @@- 页面仍是 DSH 网页前端的网页模式,快捷键和网页版一样。- macOS:系统标题栏。+### 托盘和退出++- Windows、macOS、Linux 都有常驻的系统托盘图标,图标是应用自己的鲸鱼。托盘菜单是「打开 DeepSeek Bot」和「退出 DeepSeek Bot」。+- 关掉窗口不是退出:窗口藏起来,引擎和 Bot 照常工作,Bot 浏览器的标签页也还在。再打开一次应用,窗口回到桌面上(单实例锁把第二次启动交给已经在跑的那一个)。+- 窗口真的不在了的时候(渲染进程没了之类),托盘的「打开」重新建一个窗口,接着现在跑着的引擎:地址还是引擎的本机地址,第一次加载换来的 cookie 还在,不用启动第二个引擎,也不用再用一次启动用的令牌。+- 所有窗口都关掉不会退出应用。托盘里的「退出」是唯一的正常退出入口。+- 第一次关窗口时弹一次框,说明应用会留在托盘里继续运行。只有明确确认了窗口才藏起来;取消或者按 Esc,窗口留在原处。这个确认记在应用自己的数据里,以后不再问。+- 导入团队、搬数据位置的时候,关窗口是取消这些事,和以前一样:复制停在安全的地方,不留下半个团队。+- 这些时候窗口是真的关掉,不是藏起来:更新装好要重启、搬完数据要重启、启动失败、系统的关机和注销。+- macOS:点一下托盘图标出菜单,Dock 图标点一下窗口回来。全屏的窗口先退出全屏再藏起来,不然桌面上留下一块黑。+- 属于窗口的提示框(更新的提示)在窗口藏着或者最小化的时候不弹,等窗口回来了再弹。+- macOS 的应用菜单里没有「退出」,也没有 ⌘Q:托盘里的「退出」是唯一的正常退出入口。+- 托盘图标建不起来时(有的桌面环境没有托盘),应用还有一条明确的路出去:macOS 的应用菜单里多一个「退出」,别的系统上关窗口会问一句「要不要结束它」,答「不结束」就把窗口最小化,窗口留在任务栏里,不会消失,也不会退出应用。这是唯一的例外,别的情形应用不会自己问要不要退出。+- 引擎给的启动地址只能用一次。第一次的加载没成功(窗口在加载的时候没了),新窗口不会再用这个地址:它去引擎的本机地址,cookie 不在的时候引擎会拒绝,这时重新打开应用会有新的地址。+### 模型- 模型服务商和 key 在 DSH 自己的设置里配,存在桌面应用的数据位置里,和插件版一样。@@ -107,7 +122,9 @@## 已知限制- 第一次运行:Windows 会弹出 SmartScreen 警告,macOS 要在系统设置里手动放行。-- macOS 上关掉窗口就退出应用(和 Windows 一样),Dock 里不留着。+- Linux 上托盘图标看不看得见由桌面环境决定:GNOME 和 KDE 要有托盘扩展才画得出来。图标建起来了不等于看得见,这时再打开一次应用,窗口还是回到桌面上。+- Windows 上托盘图标由系统按缩放比例缩小,150% 以上会不清楚。+- 托盘的图标、菜单和「关窗口变藏窗口」在 Windows 上用真的 Electron 验过(`app/scripts/check-lifecycle.mjs`)。macOS 的 Dock 和全屏、Linux 的托盘可见性、系统的关机和注销,都还没有在真的机器上验过:代码按 DSH Desktop 的做法写,单元测试管的是规则本身。- macOS 上窗口还有系统标题栏。无边框要让页面进入 DSH 的 macOS 桌面模式,那时快捷键改由原生菜单输入,应用要提供 DSH Desktop 那样的键盘桥。- 会话里记着工作文件夹的完整路径,不能改。所以导入和搬工作文件夹都要换段。- 安装的 `@deepseek-ai/dsh` 包带着 Office 套件和语音包,所以安装包里仍有这些文件,只是不加载。@@ -133,3 +150,4 @@- 2026-10-20:设置里能换总工作区和数据位置;中文界面里「团队工作区」改叫「总工作区」,Issue #364。- 2026-10-20:窗口改为加载引擎的本机地址,不再用 `dsh-app://app`:DSH 的账号登录把页面地址当作浏览器登录完回来的地址,只接受本机 http 地址。DSH 打开的登录窗口交给系统浏览器,Issue #376。弹出对话框时标题栏一起变暗。- 2026-10-23:应用里接上 Bot 浏览器:应用自己提供 webview 桥,每个 Bot 的登录存在壳自己的数据里,删掉 Bot 时一起清掉,Issue #449。+- 2026-10-25:关掉窗口只是藏起来,应用留在系统托盘;托盘的「打开」找回窗口,「退出」是唯一的正常退出入口,Issue #500。