Skip to content

A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.

Show a start window while the engine boots

AdamPlatin1230566dca30a66
diff --git a/app/src/first-run.mjs b/app/src/first-run.mjs
index 4a604954..00fa8cc6 100644
--- a/app/src/first-run.mjs
+++ b/app/src/first-run.mjs
@@ -25,8 +25,6 @@ const TEXT = {
moveConfirm: to => `Move DeepSeek Bot's data to ${to}?`,
moveDetail: from => `DeepSeek Bot copies its data there and starts again. ${from} stays as it is; you can delete it once everything works.`,
move: 'Move and restart', cancel: 'Cancel',
- moving: 'Copying DeepSeek Bot\'s data…',
- starting: 'Starting DeepSeek Bot…',
moveInUse: 'Another DeepSeek Harness is using this data, so it was not moved. Close it, then try again.',
moveFailed: message => `The data could not be copied: ${message}\n\nDeepSeek Bot goes on with its data where it was.`,
found: (bots, rooms) => `DeepSeek Harness has a Bot team: ${bots} Bot${bots === 1 ? '' : 's'}${rooms > 0 ? `, ${rooms} group${rooms === 1 ? '' : 's'}` : ''}. Copy it into DeepSeek Bot?`,
@@ -37,7 +35,6 @@ const TEXT = {
quit: 'Quit', startEmpty: 'Start without the team',
whichModels: 'Which model settings should DeepSeek Bot use?',
failed: message => `The team could not be copied: ${message}\n\nDeepSeek Bot starts with a new team. The team in DeepSeek Harness is unchanged.`,
- notStarted: 'DeepSeek Bot could not start.',
},
zh: {
welcome: '欢迎使用 DeepSeek Bot',
@@ -56,8 +53,6 @@ const TEXT = {
moveConfirm: to => `把 DeepSeek Bot 的数据移到 ${to} 吗?`,
moveDetail: from => `DeepSeek Bot 会把数据复制过去,然后重新启动。${from} 会原样保留,确认一切正常后可以自己删掉。`,
move: '移动并重启', cancel: '取消',
- moving: '正在复制 DeepSeek Bot 的数据…',
- starting: '正在启动 DeepSeek Bot…',
moveInUse: '另一个 DeepSeek Harness 正在使用这份数据,所以没有移动。请先关掉它,再重试。',
moveFailed: message => `数据没有复制成功:${message}\n\nDeepSeek Bot 会继续使用原来位置的数据。`,
found: (bots, rooms) => `DeepSeek Harness 里有一个 Bot 团队:${bots} 个 Bot${rooms > 0 ? `、${rooms} 个群` : ''}。要复制到 DeepSeek Bot 吗?`,
@@ -68,7 +63,6 @@ const TEXT = {
quit: '退出', startEmpty: '不带团队开始',
whichModels: 'DeepSeek Bot 用哪一份模型设置?',
failed: message => `团队没有复制成功:${message}\n\nDeepSeek Bot 会用一个新团队开始。DeepSeek Harness 里的团队没有变化。`,
- notStarted: 'DeepSeek Bot 没能启动。',
},
}
export const localeText = table => (app.getLocale().toLowerCase().startsWith('zh') ? table.zh : table.en)
@@ -80,16 +74,18 @@ const locationsFile = () => join(app.getPath('userData'), 'locations.json')
// A quit request while a first-run dialog is open stops the first run right after that dialog.
class Quit extends Error {}
-async function ask(options, signal) {
- const { response } = await dialog.showMessageBox({ title: 'DeepSeek Bot', noLink: true, ...options, signal })
+// The dialogs belong to `ui.owner()` (the start window); `ui.asking` holds the start's clock while
+// the user answers.
+async function ask(options, signal, ui) {
+ const { response } = await ui.asking(dialog.showMessageBox(ui.owner(), { title: 'DeepSeek Bot', noLink: true, ...options, signal }))
// A quit that arrived while a synchronous macOS box was open gets to run first.
await new Promise(resolve => setImmediate(resolve))
if (signal.aborted) throw new Quit()
return response
}
-async function pick(title, current, signal) {
- const { canceled, filePaths } = await dialog.showOpenDialog({ title, defaultPath: existsSync(current) ? current : dirname(current), properties: ['openDirectory', 'createDirectory', 'promptToCreate'] })
+async function pick(title, current, signal, ui) {
+ const { canceled, filePaths } = await ui.asking(dialog.showOpenDialog(ui.owner(), { title, defaultPath: existsSync(current) ? current : dirname(current), properties: ['openDirectory', 'createDirectory', 'promptToCreate'] }))
await new Promise(resolve => setImmediate(resolve))
if (signal.aborted) throw new Quit()
return canceled ? current : filePaths[0]
@@ -109,36 +105,50 @@ function placeProblem(t, dataDir, workspace) {
return undefined
}
-function hasTeam(dataDir) {
+/** The places a first start offers. */
+export const defaultPlaces = () => ({ dataDir: join(homedir(), '.ds-bot'), workspace: join(homedir(), 'DeepSeek Bot') })
+
+/** The Bot team in a data folder, if it has one. */
+export function teamIn(dataDir) {
try {
- return Object.keys(JSON.parse(readFileSync(join(dataDir, 'bot', 'state.json'), 'utf8')).bots ?? {}).length > 0
+ return findTeam(dataDir)
} catch {
- return false
+ return undefined
}
}
-async function offerImport(t, dataDir, signal) {
+/**
+ * What the start window can say before the first-run questions: the team that a reinstall keeps,
+ * or whether the user's own DSH has a team to offer.
+ */
+export function teamsAt(dataDir = defaultPlaces().dataDir) {
+ const team = teamIn(dataDir)
+ return { team, offered: team === undefined && teamIn(userDshHome()) !== undefined }
+}
+
+/** @returns {Promise<{ offered: boolean, import?: { from: string, profile?: string }, quit?: true }>} */
+async function offerImport(t, dataDir, signal, ui) {
const from = userDshHome()
let found
try {
- found = hasTeam(dataDir) ? undefined : findTeam(from)
+ found = teamIn(dataDir) === undefined ? findTeam(from) : undefined
} catch (error) {
console.error(error)
}
- if (found === undefined) return undefined
- if (await ask({ type: 'question', message: t.found(found.bots, found.rooms), detail: t.foundDetail(from), buttons: [t.copy, t.skip], defaultId: 0, cancelId: 1 }, signal) === 1) return undefined
+ if (found === undefined) return { offered: false }
+ if (await ask({ type: 'question', message: t.found(found.bots, found.rooms), detail: t.foundDetail(from), buttons: [t.copy, t.skip], defaultId: 0, cancelId: 1 }, signal, ui) === 1) return { offered: true }
while (teamInUse(from)) {
- if (await ask({ type: 'warning', message: t.inUse, buttons: [t.retry, t.skip], defaultId: 0, cancelId: 1 }, signal) === 1) return undefined
+ if (await ask({ type: 'warning', message: t.inUse, buttons: [t.retry, t.skip], defaultId: 0, cancelId: 1 }, signal, ui) === 1) return { offered: true }
}
const newer = newerSessions(from, found.team)
if (newer.length > 0) {
- if (await ask({ type: 'warning', message: t.newer(newer.length), buttons: [t.quit, t.startEmpty], defaultId: 0, cancelId: 0 }, signal) === 0) return { quit: true }
- return undefined
+ if (await ask({ type: 'warning', message: t.newer(newer.length), buttons: [t.quit, t.startEmpty], defaultId: 0, cancelId: 0 }, signal, ui) === 0) return { offered: true, quit: true }
+ return { offered: true }
}
const { profiles } = found
const profile = profiles.length < 2 ? profiles[0]?.name
- : profiles[await ask({ type: 'question', message: t.whichModels, buttons: profiles.map(entry => PROFILE_NAMES[entry.name] ?? entry.name), defaultId: 0, cancelId: 0 }, signal)].name
- return { from, profile }
+ : profiles[await ask({ type: 'question', message: t.whichModels, buttons: profiles.map(entry => PROFILE_NAMES[entry.name] ?? entry.name), defaultId: 0, cancelId: 0 }, signal, ui)].name
+ return { offered: true, import: { from, profile } }
}
/** Write the chosen places once the first run is finished; quitting before that asks again. */
@@ -151,11 +161,14 @@ export function saveLocations({ dataDir, workspace }) {
}
/**
- * Where the app keeps its data and the Bots' files, asked at the first start.
- * A run on throwaway folders (DS_BOT_HOME, for development and tests) asks nothing and copies nothing.
- * @returns {Promise<{ dataDir: string, workspace?: string, import?: { from: string, profile?: string }, quit?: true }>}
+ * Where the app keeps its data and the Bots' files, asked at the first start in dialogs that
+ * belong to `ui.owner()`. A run on throwaway folders (DS_BOT_HOME, for development and tests)
+ * asks nothing and copies nothing. `offered` says whether the first run offered to copy a team.
+ * @param {AbortSignal} signal
+ * @param {{ owner: () => import('electron').BrowserWindow | undefined, asking: <T>(answer: Promise<T>) => Promise<T> }} ui
+ * @returns {Promise<{ dataDir: string, workspace?: string, import?: { from: string, profile?: string }, offered?: boolean, quit?: true }>}
*/
-export async function chooseLocations(signal) {
+export async function chooseLocations(signal, ui) {
if (process.env.DS_BOT_HOME) return { dataDir: process.env.DS_BOT_HOME, workspace: process.env.DS_BOT_WORKSPACE || undefined }
const file = locationsFile()
if (existsSync(file)) {
@@ -163,29 +176,30 @@ export async function chooseLocations(signal) {
return { dataDir: saved.dataDir, workspace: saved.workspace }
}
const t = text()
- let dataDir = join(homedir(), '.ds-bot')
- let workspace = join(homedir(), 'DeepSeek Bot')
+ let { dataDir, workspace } = defaultPlaces()
+ let offered
try {
for (;;) {
- const choice = await ask({ type: 'info', message: t.welcome, detail: t.places(dataDir, workspace), buttons: [t.start, t.change, t.quit], defaultId: 0, cancelId: 2 }, signal)
+ const choice = await ask({ type: 'info', message: t.welcome, detail: t.places(dataDir, workspace), buttons: [t.start, t.change, t.quit], defaultId: 0, cancelId: 2 }, signal, ui)
if (choice === 2) return { quit: true }
if (choice === 1) {
- dataDir = await pick(t.pickData, dataDir, signal)
- workspace = await pick(t.pickWorkspace, workspace, signal)
+ dataDir = await pick(t.pickData, dataDir, signal, ui)
+ workspace = await pick(t.pickWorkspace, workspace, signal, ui)
continue
}
const problem = placeProblem(t, dataDir, workspace)
if (problem === undefined) break
- await ask({ type: 'warning', message: problem, buttons: ['OK'] }, signal)
+ await ask({ type: 'warning', message: problem, buttons: ['OK'] }, signal, ui)
}
- const imported = await offerImport(t, dataDir, signal)
- if (imported?.quit) return { quit: true }
- if (imported !== undefined) return { dataDir, workspace, import: imported }
+ const offer = await offerImport(t, dataDir, signal, ui)
+ if (offer.quit) return { quit: true }
+ if (offer.import !== undefined) return { dataDir, workspace, import: offer.import, offered: true }
+ offered = offer.offered
} catch (error) {
if (error instanceof Quit) return { quit: true }
throw error
}
// There is nothing to copy, so the first run ends with the chosen places.
saveLocations({ dataDir, workspace })
- return { dataDir, workspace }
+ return { dataDir, workspace, offered }
}
diff --git a/app/src/host-process.mjs b/app/src/host-process.mjs
index dba66e5c..d2f64cb1 100644
--- a/app/src/host-process.mjs
+++ b/app/src/host-process.mjs
@@ -23,8 +23,9 @@ export class HostProcess {
#messageListeners = new Set()
/**
- * @param {{ entry: string, cwd: string, env: NodeJS.ProcessEnv, pnpm: string, onFailure: (error: Error) => void }} options
- * `onFailure` receives the first unexpected failure, also after the Host was ready.
+ * @param {{ entry: string, cwd: string, env: NodeJS.ProcessEnv, pnpm: string, onFailure: (error: Error) => void, output?: (stream: 'stdout' | 'stderr', text: string) => void }} options
+ * `onFailure` receives the first unexpected failure, also after the Host was ready. `output`
+ * takes the Host's output with the launch token hidden; by default it goes to this process's.
*/
constructor(options) { this.#options = options }
@@ -34,16 +35,16 @@ export class HostProcess {
*/
start() {
this.#ready ??= new Promise((resolve, reject) => {
- const { entry, cwd, env, pnpm } = this.#options
+ const { entry, cwd, env, pnpm, output = (stream, text) => { process[stream].write(text) } } = this.#options
const child = spawn(process.execPath, ['--expose-internals', entry, pnpm], {
cwd, env: { ...env, ELECTRON_RUN_AS_NODE: '1' }, stdio: ['ignore', 'pipe', 'pipe', 'ipc'],
})
this.#child = child
child.stdout.setEncoding('utf8')
child.stderr.setEncoding('utf8')
- child.stdout.on('data', (chunk) => { process.stdout.write(redact(chunk)) })
+ child.stdout.on('data', (chunk) => { output('stdout', redact(chunk)) })
child.stderr.on('data', (chunk) => {
- process.stderr.write(redact(chunk))
+ output('stderr', redact(chunk))
this.#stderr = (this.#stderr + chunk).slice(-STDERR_TAIL_CHARS)
})
child.on('message', (message) => {
diff --git a/app/src/logs.mjs b/app/src/logs.mjs
new file mode 100644
index 00000000..c7be7c32
--- /dev/null
+++ b/app/src/logs.mjs
@@ -0,0 +1,184 @@
+// main.log: the main process's console output and the Host's, in the app's own userData
+// (%APPDATA%\DeepSeek Bot\logs on Windows), redacted before it is written and kept to three
+// files of 2 MB (docs/plans/2026-10-26-windows-onboarding.md §3).
+import { closeSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { join } from 'node:path'
+
+export const LOG_LIMIT = 2 * 1024 * 1024
+export const LOG_FILES = 3
+// A line without its end (a progress line redrawn with \r) is written once it gets this long.
+const PARTIAL_MAX = 8 * 1024
+
+/** main.log, then main.1.log and main.2.log, newest first. */
+export const logNames = (count = LOG_FILES) => Array.from({ length: count }, (_, index) => (index === 0 ? 'main.log' : `main.${String(index)}.log`))
+
+const escape = text => text.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')
+
+/**
+ * Removes what must not reach a log or a copied report: the launch token, API keys, the query of
+ * a sign-in callback and the user's home folder, which names the user.
+ * @param {{ home?: string, platform?: string }} [options]
+ * @returns {(text: string) => string}
+ */
+export function redactor({ home = homedir(), platform = process.platform } = {}) {
+ const parts = home.split(/[\\/]+/u).filter(Boolean)
+ // Any separator, doubled as in JSON, and on Windows any case: the same folder. A home of '/'
+ // or '' names nobody.
+ const lead = /^[\\/]/u.test(home) ? '[\\\\/]' : ''
+ const homePattern = parts.length > 0 ? new RegExp(`${lead}${parts.map(escape).join('[\\\\/]+')}(?=[\\\\/\\s"'\`<>|:;,)\\]}]|$)`, platform === 'win32' ? 'giu' : 'gu') : undefined
+ const label = platform === 'win32' ? '%USERPROFILE%' : '~'
+ return (text) => {
+ let out = text
+ .replace(/(token=)[^&\s"'<>]+/giu, '$1<hidden>')
+ .replace(/(\/oauth\/callback)\?[^\s"'<>]+/gu, '$1?<hidden>')
+ .replace(/\bsk-[A-Za-z0-9][\w-]*/gu, 'sk-<hidden>')
+ .replace(/\b(Bearer\s+)[\w.~+/=-]+/gu, '$1<hidden>')
+ if (homePattern !== undefined) out = out.replace(homePattern, label)
+ return out
+ }
+}
+
+/**
+ * Splits a chunk of output into whole lines; the rest waits for the next chunk.
+ * @returns {{ lines: string[], rest: string }}
+ */
+export function splitLines(rest, chunk) {
+ const pieces = (rest + chunk).split(/\r?\n/u)
+ let tail = pieces.pop() ?? ''
+ const lines = pieces.map(line => line.replace(/\r/gu, ''))
+ if (tail.length > PARTIAL_MAX) {
+ lines.push(tail.replace(/\r/gu, ''))
+ tail = ''
+ }
+ return { lines, rest: tail }
+}
+
+/** Whether a write of `add` bytes goes into a fresh file. */
+export const shouldRotate = (size, add, limit = LOG_LIMIT) => size > 0 && size + add > limit
+
+/** Shifts main.log to main.1.log and so on; the oldest is overwritten. */
+export function rotate(dir, count = LOG_FILES) {
+ const names = logNames(count)
+ for (let index = names.length - 1; index > 0; index -= 1) {
+ try {
+ renameSync(join(dir, names[index - 1]), join(dir, names[index]))
+ } catch (error) {
+ if (error?.code !== 'ENOENT') throw error
+ }
+ }
+}
+
+/** The last `count` lines of a text. */
+export function tailLines(text, count) {
+ const lines = text.split(/\r?\n/u)
+ if (lines.at(-1) === '') lines.pop()
+ return lines.slice(-count)
+}
+
+export class LogFile {
+ #dir
+ #file
+ #fd
+ #size = 0
+ #limit
+ #redact
+ #now
+ #rests = new Map()
+ #broken = false
+
+ /** @param {{ dir: string, limit?: number, redact?: (text: string) => string, now?: () => Date }} options */
+ constructor({ dir, limit = LOG_LIMIT, redact = redactor(), now = () => new Date() }) {
+ this.#dir = dir
+ this.#file = join(dir, logNames()[0])
+ this.#limit = limit
+ this.#redact = redact
+ this.#now = now
+ }
+
+ get dir() { return this.#dir }
+
+ /** Writes the whole lines of a chunk of output, each with the time and its source. */
+ write(source, chunk) {
+ const { lines, rest } = splitLines(this.#rests.get(source) ?? '', String(chunk))
+ this.#rests.set(source, rest)
+ for (const line of lines) this.#line(source, line)
+ }
+
+ /** Writes the lines still waiting for their end. */
+ flush() {
+ for (const [source, rest] of this.#rests) if (rest !== '') this.#line(source, rest)
+ this.#rests.clear()
+ }
+
+ /** The last `count` lines across the files, oldest first, redacted. */
+ tail(count) {
+ this.flush()
+ const texts = []
+ for (const name of logNames()) {
+ try {
+ texts.unshift(readFileSync(join(this.#dir, name), 'utf8'))
+ } catch {
+ break
+ }
+ if (tailLines(texts.join(''), count).length >= count) break
+ }
+ return tailLines(texts.join(''), count).map(this.#redact)
+ }
+
+ close() {
+ this.flush()
+ if (this.#fd !== undefined) closeSync(this.#fd)
+ this.#fd = undefined
+ }
+
+ #line(source, line) {
+ if (this.#broken) return
+ const text = `${this.#now().toISOString()} [${source}] ${this.#redact(line)}\n`
+ const bytes = Buffer.byteLength(text)
+ try {
+ if (this.#fd === undefined) this.#open()
+ if (shouldRotate(this.#size, bytes, this.#limit)) {
+ closeSync(this.#fd)
+ this.#fd = undefined
+ // Another process can still hold main.log open (the one that relaunched this one);
+ // then the file grows past the limit until the next start.
+ try { rotate(this.#dir) } catch { /* kept */ }
+ this.#open()
+ }
+ writeSync(this.#fd, text)
+ this.#size += bytes
+ } catch {
+ // A log that cannot be written must not stop the app.
+ this.#broken = true
+ }
+ }
+
+ #open() {
+ mkdirSync(this.#dir, { recursive: true })
+ this.#fd = openSync(this.#file, 'a')
+ this.#size = statSync(this.#file).size
+ }
+}
+
+/**
+ * Copies everything the main process writes to stdout and stderr into the log.
+ * @returns {{ stdout: (text: string) => void, stderr: (text: string) => void }} writers that bypass the log
+ */
+export function captureStdio(log, streams = { stdout: process.stdout, stderr: process.stderr }) {
+ const raw = {}
+ for (const [name, stream] of Object.entries(streams)) {
+ const write = stream.write.bind(stream)
+ raw[name] = (text) => { try { write(text) } catch { /* no console */ } }
+ stream.write = (chunk, encoding, callback) => {
+ log.write('main', typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString(typeof encoding === 'string' ? encoding : 'utf8'))
+ try {
+ return write(chunk, encoding, callback)
+ } catch {
+ // A packaged app on Windows can have no console behind stdout.
+ return true
+ }
+ }
+ }
+ return raw
+}
diff --git a/app/src/main.mjs b/app/src/main.mjs
index 607ea91b..a1e28104 100644
--- a/app/src/main.mjs
+++ b/app/src/main.mjs
@@ -1,34 +1,27 @@
-// 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 { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
+// Electron main process: a small start window while the app's own DSH Host boots, then one window
+// for the Bot team. The team 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. It loads hidden and shows once the team view is ready (start-window.mjs). Only
+// what the start window needs is imported up front; the rest loads once it is up
+// (docs/plans/2026-10-26-start-window.md §11).
+import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeTheme, screen, session, shell, systemPreferences, WebContentsView } from 'electron'
+import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { readFile, rm } from 'node:fs/promises'
import { release } from 'node:os'
import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
import { setTimeout as sleep } from 'node:timers/promises'
import { fileURLToPath } from 'node:url'
-import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot'
-import electronUpdater from 'electron-updater'
-import { BotBrowserGuests, partitionOf } from './bot-browser.mjs'
-import { BotViews, isBotId } from './bot-views.mjs'
-import { importFromBrowser, listSources } from './browser-sources.mjs'
-import { applyCookies, CookieImports } from './cookie-import.mjs'
-import { parseCookieFile } from './cookie-parse.mjs'
-import { downloadSaver } from './downloads.mjs'
import { canonicalExecPath } from './canonical-path.mjs'
-import { chooseLocations, localeText, programFolder, saveLocations, text } from './first-run.mjs'
import { hostPort } from './host-port.mjs'
-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 { UPDATE_TEXT, watchReleases, watchUpdates } from './updates.mjs'
+import { captureStdio, LogFile } from './logs.mjs'
+import { readStartFrame, writeStartFrame } from './start-frame.mjs'
+import { explainOf, StartWindow } from './start-window.mjs'
import { CAPTION_HEIGHT, cssColor, micaAvailable, nativeThemeSource } from './window-frame.mjs'
const IPC = {
caption: 'ds-bot:caption-colors', nativeTheme: 'ds-bot:native-theme', fullscreen: 'ds-bot:fullscreen',
dataLocation: 'ds-bot:data-location', moveData: 'ds-bot:move-data', teamWorkspace: 'ds-bot:team-workspace',
+ ready: 'ds-bot:ready', focus: 'ds-bot:focus',
browserAcquire: 'ds-bot:browser-acquire', browserRelease: 'ds-bot:browser-release', browserForget: 'ds-bot:browser-forget',
browserViewChanged: 'ds-bot:browser-view-changed', browserViewCreate: 'ds-bot:browser-view-create',
browserViewSync: 'ds-bot:browser-view-sync', browserViewPlace: 'ds-bot:browser-view-place',
@@ -54,31 +47,46 @@ const iconFile = join(here, '..', 'assets', process.platform === 'win32' ? 'icon
// 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)
+const frameFile = join(app.getPath('userData'), 'start-frame.json')
+
+// Loaded once the start window is up (loadModules).
+let BotBrowserGuests, partitionOf, BotViews, isBotId, importFromBrowser, listSources, applyCookies, CookieImports, parseCookieFile
+let downloadSaver, chooseLocations, localeText, programFolder, saveLocations, teamIn, teamsAt, text, HostProcess
+let copySessions, findTeam, importTeam, teamInUse, userDshHome, copyData, moveProblem, CHECK_PROFILE, PROFILE
+let UPDATE_TEXT, watchReleases, watchUpdates, getDshRuntimeVersion, electronUpdater
let mainWindow
+// Settles once the hidden team window exists.
+let mainCreated
+let startWindow
+let logs
+// Writers to the console that bypass the log: the Host's output goes into the log on its own.
+let rawOutput
let host
// The Host's loopback origin, which the window loads.
let origin
+let port
let hostStop
let updates
+let updatesStarted = false
let stopping = false
let stopped = false
let failed = false
let places
+// The first run's answer to the import; only the first boot copies.
+let pendingImport
+// Each boot of the engine; a retry starts a new one, and what an old one still reports is dropped.
+let attempt = 0
// 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.
let choosing
let copying
const copyAbort = new AbortController()
-const browserGuests = new BotBrowserGuests({ session, origin: () => origin, devTools: !app.isPackaged })
-const botViews = new BotViews({
- window: () => mainWindow, WebContentsView, guests: browserGuests, origin: () => origin, devTools: !app.isPackaged,
- statePath: join(app.getPath('userData'), 'bot-views.json'),
- onChange: state => mainWindow?.webContents.send(IPC.browserViewChanged, state),
-})
-const cookieImports = new CookieImports()
-app.once('will-quit', () => botViews.dispose())
+let browserGuests
+let botViews
+let cookieImports
+app.once('will-quit', () => { botViews?.dispose() })
// 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,6 +98,20 @@ if (canonical !== undefined) {
} else if (!app.requestSingleInstanceLock()) {
app.exit(0)
} else {
+ logs = new LogFile({ dir: join(app.getPath('userData'), 'logs') })
+ rawOutput = captureStdio(logs)
+ app.once('will-quit', () => { logs.flush() })
+ console.log(`DeepSeek Bot ${app.getVersion()} (${process.platform} ${process.arch}), Electron ${process.versions.electron}`)
+ startWindow = new StartWindow({
+ electron: { BrowserWindow, ipcMain, screen, shell, clipboard, nativeTheme, systemPreferences },
+ page: join(here, 'start', 'start.html'), preload: join(here, 'preload.cjs'), icon: iconFile, mica, devTools: !app.isPackaged,
+ lang: app.getLocale().toLowerCase().startsWith('zh') ? 'zh' : 'en', motion: readStartFrame(frameFile).motion,
+ version: app.getVersion(), log: logs, mainWindow: () => mainWindow,
+ onRetry: () => { retry().catch(fail) },
+ onReload: () => { mainWindow?.webContents.reload() },
+ // Closing the start window before the hand-off quits, as closing the team window does.
+ onClose: () => { app.quit() },
+ })
app.on('second-instance', focusWindow)
app.on('window-all-closed', () => { app.quit() })
app.on('before-quit', (event) => {
@@ -119,60 +141,171 @@ function stopHost() {
return hostStop
}
+// A throwaway run (DS_BOT_HOME) asks nothing and shows what a later start shows.
+const startKind = () => (process.env.DS_BOT_HOME || existsSync(join(app.getPath('userData'), 'locations.json')) ? 'later' : 'first')
+
async function start() {
- choosing = new AbortController()
- const where = await chooseLocations(choosing.signal).finally(() => { choosing = undefined })
- if (where.quit) { app.exit(0); return }
- places = { dataDir: where.dataDir, workspace: where.workspace }
- const port = await hostPort(join(app.getPath('userData'), 'host-port.json'))
- origin = `http://127.0.0.1:${String(port)}`
- const pnpm = join(app.getAppPath(), 'node_modules', 'pnpm', 'bin', 'pnpm.mjs')
- const profileDir = join(where.dataDir, 'profiles', PROFILE)
- mkdirSync(profileDir, { recursive: true })
- const newHost = () => new HostProcess({
+ setMenu()
+ nativeTheme.themeSource = readStartFrame(frameFile).themeSource
+ // 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)
+ await prepare()
+ run()
+}
+
+// What the boot needs; a retry after a failure here does what is still missing.
+async function prepare() {
+ // Before the windows: the team window's page is told the Host's origin.
+ if (port === undefined) {
+ port = await hostPort(join(app.getPath('userData'), 'host-port.json'))
+ origin = `http://127.0.0.1:${String(port)}`
+ }
+ startWindow.open(startKind())
+ if (browserGuests === undefined) {
+ await loadModules()
+ handleIpc()
+ }
+ // The team window is made once the start window has painted, already on its final rect.
+ mainCreated ??= startWindow.painted.then(createWindow)
+}
+
+async function loadModules() {
+ const [browser, views, sources, cookies, cookieFiles, downloads, firstRun, hostProcess, imports, moves, profile, updatesModule, boot, updater] = await Promise.all([
+ import('./bot-browser.mjs'), import('./bot-views.mjs'), import('./browser-sources.mjs'), import('./cookie-import.mjs'),
+ import('./cookie-parse.mjs'), import('./downloads.mjs'), import('./first-run.mjs'), import('./host-process.mjs'),
+ import('./import.mjs'), import('./move-data.mjs'), import('./profile.mjs'), import('./updates.mjs'),
+ import('@deepseek-ai/dsh-app-boot'), import('electron-updater'),
+ ])
+ ;({ BotBrowserGuests, partitionOf } = browser)
+ ;({ BotViews, isBotId } = views)
+ ;({ importFromBrowser, listSources } = sources)
+ ;({ applyCookies, CookieImports } = cookies)
+ ;({ parseCookieFile } = cookieFiles)
+ ;({ downloadSaver } = downloads)
+ ;({ chooseLocations, localeText, programFolder, saveLocations, teamIn, teamsAt, text } = firstRun)
+ ;({ HostProcess } = hostProcess)
+ ;({ copySessions, findTeam, importTeam, teamInUse, userDshHome } = imports)
+ ;({ copyData, moveProblem } = moves)
+ ;({ CHECK_PROFILE, PROFILE } = profile)
+ ;({ UPDATE_TEXT, watchReleases, watchUpdates } = updatesModule)
+ ;({ getDshRuntimeVersion } = boot)
+ electronUpdater = updater.default
+ browserGuests = new BotBrowserGuests({ session, origin: () => origin, devTools: !app.isPackaged })
+ botViews = new BotViews({
+ window: () => mainWindow, WebContentsView, guests: browserGuests, origin: () => origin, devTools: !app.isPackaged,
+ statePath: join(app.getPath('userData'), 'bot-views.json'),
+ onChange: state => mainWindow?.webContents.send(IPC.browserViewChanged, state),
+ })
+ cookieImports = new CookieImports()
+}
+
+function run() {
+ const mine = (attempt += 1)
+ boot(mine).catch((error) => { if (mine === attempt) void fail(error) })
+}
+
+// The engine starts again after a failure or the 180 s question; the places stay.
+async function retry() {
+ attempt += 1
+ failed = false
+ const old = host
+ host = undefined
+ await old?.stop().catch((error) => { console.error(error) })
+ await prepare()
+ run()
+}
+
+// The data folder (with the first run's questions on a first start), the engine, then the team
+// view in the hidden team window.
+async function boot(mine) {
+ if (places === undefined) {
+ const first = startWindow.kind === 'first'
+ if (first) startWindow.explain(explainOf(teamsAt()))
+ choosing = new AbortController()
+ const ui = { owner: () => startWindow.owner(), asking: answer => startWindow.asking(answer) }
+ const where = await chooseLocations(choosing.signal, ui).finally(() => { choosing = undefined })
+ if (where.quit) { app.exit(0); return }
+ places = { dataDir: where.dataDir, workspace: where.workspace }
+ pendingImport = where.import
+ if (first) startWindow.explain(explainOf({ offered: where.offered === true, team: teamIn(where.dataDir) }))
+ }
+ // Also the check that the data folder can be written.
+ mkdirSync(profileDir(), { recursive: true })
+ startWindow.done('data')
+ const engine = await startEngine()
+ if (engine === undefined || mine !== attempt) return
+ startWindow.done('engine')
+ await mainCreated
+ if (mine !== attempt || mainWindow === undefined) return
+ startWindow.teamLoading()
+ // The launch URL trades its token for the Host's cookie and goes on to the page.
+ void mainWindow.loadURL(engine.url).catch(() => {})
+}
+
+const profileDir = () => join(places.dataDir, 'profiles', PROFILE)
+const pnpmEntry = () => join(app.getAppPath(), 'node_modules', 'pnpm', 'bin', 'pnpm.mjs')
+const hostOutput = (stream, chunk) => {
+ logs.write('engine', chunk)
+ rawOutput[stream](chunk)
+}
+
+function newHost() {
+ return new HostProcess({
entry: join(here, 'host.mjs'),
- cwd: profileDir,
- env: { ...process.env, DSH_HOME: where.dataDir, DS_BOT_PORT: String(port), DS_BOT_APP: '1', DS_BOT_USER_DSH_HOME: userDshHome(), ...(where.workspace ? { DS_BOT_WORKSPACE: where.workspace } : {}) },
- pnpm,
+ cwd: profileDir(),
+ env: { ...process.env, DSH_HOME: places.dataDir, DS_BOT_PORT: String(port), DS_BOT_APP: '1', DS_BOT_USER_DSH_HOME: userDshHome(), ...(places.workspace ? { DS_BOT_WORKSPACE: places.workspace } : {}) },
+ pnpm: pnpmEntry(),
onFailure: fail,
+ output: hostOutput,
})
- // A failed check is not a failed start: start() rejects, and the copy goes on unchecked.
- const newCheck = (home, list) => {
- const cwd = join(home, 'profiles', CHECK_PROFILE)
- mkdirSync(cwd, { recursive: true })
- return new HostProcess({ entry: join(here, 'host.mjs'), cwd, env: { ...process.env, DSH_HOME: home, DS_BOT_CHECK: list }, pnpm, onFailure: () => {} })
- }
- const ready = (async () => {
- let copied
- if (where.import) {
- copying = copyTeam(where, newHost, newCheck, copyAbort.signal)
- copied = await copying
- copying = undefined
- }
+}
+
+// A failed check is not a failed start: start() rejects, and the copy goes on unchecked.
+function newCheck(home, list) {
+ const cwd = join(home, 'profiles', CHECK_PROFILE)
+ mkdirSync(cwd, { recursive: true })
+ return new HostProcess({ entry: join(here, 'host.mjs'), cwd, env: { ...process.env, DSH_HOME: home, DS_BOT_CHECK: list }, pnpm: pnpmEntry(), onFailure: () => {}, output: hostOutput })
+}
+
+/** @returns {Promise<{ url: string } | undefined>} the Host's launch URL; none when the app quits during the copy */
+async function startEngine() {
+ if (pendingImport !== undefined) {
+ const where = { ...places, import: pendingImport }
+ pendingImport = undefined
+ copying = copyTeam(where, copyAbort.signal)
+ const copied = await copying
+ copying = undefined
if (copied === 'quit') app.exit(0)
- // The window may be waiting for the Host; it goes away with the app.
- if (copied !== undefined) return new Promise(() => {})
- // Not during the import, which a restart would cut short; before the Host, so that an
- // update can still come when this version's Host does not start.
+ if (copied !== undefined) return undefined
+ }
+ // Not during the import, which a restart would cut short; before the Host, so that an
+ // update can still come when this version's Host does not start.
+ if (!updatesStarted) {
+ updatesStarted = true
updates = startUpdates()
updates?.subscribe((state) => { mainWindow?.webContents.send(IPC.appUpdateChanged, state) })
- host = newHost()
- host.onMessage(message => {
- if (message?.type !== 'ds-bot:browser-endpoint' || typeof message.id !== 'string' || !isBotId(message.botId)) return
- const downloadRoots = message.downloadRoots
- if (!Array.isArray(downloadRoots) || downloadRoots.length > 4 || !Array.from(downloadRoots).every(root => typeof root === 'string' && isAbsolute(root))) {
- host?.send({ type: 'ds-bot:browser-endpoint-response', id: message.id, error: 'Could not create the browser endpoint.' })
- return
- }
- void botViews.endpoint(message.botId, { downloadRoots }).then(url => {
- host?.send({ type: 'ds-bot:browser-endpoint-response', id: message.id, url })
- }).catch(() => host?.send({ type: 'ds-bot:browser-endpoint-response', id: message.id, error: 'Could not create the browser endpoint.' }))
- })
- return host.start()
- })()
- ready.catch(fail)
+ }
+ host = newHost()
+ host.onMessage(message => {
+ if (message?.type !== 'ds-bot:browser-endpoint' || typeof message.id !== 'string' || !isBotId(message.botId)) return
+ const downloadRoots = message.downloadRoots
+ if (!Array.isArray(downloadRoots) || downloadRoots.length > 4 || !Array.from(downloadRoots).every(root => typeof root === 'string' && isAbsolute(root))) {
+ host?.send({ type: 'ds-bot:browser-endpoint-response', id: message.id, error: 'Could not create the browser endpoint.' })
+ return
+ }
+ void botViews.endpoint(message.botId, { downloadRoots }).then(url => {
+ host?.send({ type: 'ds-bot:browser-endpoint-response', id: message.id, url })
+ }).catch(() => host?.send({ type: 'ds-bot:browser-endpoint-response', id: message.id, error: 'Could not create the browser endpoint.' }))
+ })
+ return host.start()
+}
+
+function handleIpc() {
// A throwaway run (DS_BOT_HOME) keeps its folders where it was told.
const fixed = Boolean(process.env.DS_BOT_HOME)
+ // The team view has mounted (ds-bot calls dsBotApp.ready()): the start window hands over.
+ ipcMain.on(IPC.ready, (event) => { if (fromWindow(event)) startWindow.ready() })
+ ipcMain.on(IPC.focus, (event) => { if (fromWindow(event)) focusWindow() })
ipcMain.handle(IPC.dataLocation, (event) => {
assertWindow(event)
return { path: places.dataDir, fixed }
@@ -259,8 +392,8 @@ async function start() {
assertWindow(event)
if (typeof id === 'string') cookieImports.drop(id)
})
- // The app's own update state, for the About row. `updates` exists once the ready block
- // created it; before that (and in runs without an updater) the state is null.
+ // The app's own update state, for the About row. `updates` exists once the engine's first
+ // start created it; before that (and in runs without an updater) the state is null.
ipcMain.handle(IPC.appUpdateState, (event) => {
assertWindow(event)
return updates?.state() ?? null
@@ -292,33 +425,33 @@ async function start() {
ipcMain.on(IPC.caption, (event, color, symbolColor) => {
if (fromWindow(event) && cssColor(color) && cssColor(symbolColor)) mainWindow.setTitleBarOverlay({ color, symbolColor })
})
- // Mica and the caption buttons follow the app's theme, not only the system's.
+ // Mica and the caption buttons follow the app's theme, not only the system's; the start
+ // window takes it at the next start, before the team view has loaded.
ipcMain.on(IPC.nativeTheme, (event, source) => {
const value = nativeThemeSource(source)
- if (fromWindow(event) && value !== undefined) nativeTheme.themeSource = value
+ if (!fromWindow(event) || value === undefined) return
+ nativeTheme.themeSource = value
+ writeStartFrame(frameFile, { themeSource: value })
})
}
-
- setMenu()
- // 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 window that a dialog belongs to: the start window while it shows, then the team window.
+const owner = () => startWindow.owner() ?? mainWindow
+const setProgress = (value) => { owner()?.setProgressBar(value) }
+
// The Host starts once on the new data location first: DSH then sets up its project list
// without the copied Sessions' folders, so the old team's folders are not offered as projects.
// Before that, the app's own DSH reads every chat of the team once: a newer DSH can write
// records that this one refuses while the log format stays the same. Such a chat stops the
// copy, as a newer log format does; 'quit' means the user updates DeepSeek Bot first, and
// 'stopped' that the app quit during the copy.
-async function copyTeam(where, newHost, newCheck, signal) {
- const unreadable = await checkTeam(where, newCheck, signal)
+async function copyTeam(where, signal) {
+ const unreadable = await checkTeam(where, signal)
if (signal.aborted) return 'stopped'
if (unreadable > 0) {
const t = text()
- const { response } = await dialog.showMessageBox({ type: 'warning', title: 'DeepSeek Bot', noLink: true, message: t.newer(unreadable), buttons: [t.quit, t.startEmpty], defaultId: 0, cancelId: 0, signal })
+ const { response } = await startWindow.asking(dialog.showMessageBox(owner(), { type: 'warning', title: 'DeepSeek Bot', noLink: true, message: t.newer(unreadable), buttons: [t.quit, t.startEmpty], defaultId: 0, cancelId: 0, signal }))
if (signal.aborted) return 'stopped'
if (response === 0) return 'quit'
saveLocations(where)
@@ -331,7 +464,7 @@ async function copyTeam(where, newHost, newCheck, signal) {
try {
await warm.start()
if (signal.aborted) return 'stopped'
- mainWindow?.setProgressBar(2)
+ setProgress(2)
await warm.stop()
host = undefined
const summary = await importTeam({ ...where.import, to: where.dataDir, workspace: where.workspace, dsh: getDshRuntimeVersion(), signal })
@@ -339,18 +472,18 @@ async function copyTeam(where, newHost, newCheck, signal) {
} catch (error) {
if (signal.aborted) return 'stopped'
console.error(error)
- await dialog.showMessageBox({ type: 'warning', title: 'DeepSeek Bot', message: text().failed(error instanceof Error ? error.message : String(error)), signal })
+ await startWindow.asking(dialog.showMessageBox(owner(), { type: 'warning', title: 'DeepSeek Bot', message: text().failed(error instanceof Error ? error.message : String(error)), signal }))
if (signal.aborted) return 'stopped'
} finally {
signal.removeEventListener('abort', stopWarm)
- mainWindow?.setProgressBar(-1)
+ setProgress(-1)
}
saveLocations(where)
return undefined
}
// A copy of the chats in a DSH home of its own, so that nothing of the check stays in the data.
-async function checkTeam(where, newCheck, signal) {
+async function checkTeam(where, signal) {
// A run that was killed can leave its temporary check home behind.
for (const name of readdirSync(where.dataDir).filter(entry => /^\.import-check-\d+$/u.test(entry))) {
await rm(join(where.dataDir, name), { recursive: true, force: true }).catch((error) => { console.error(error) })
@@ -360,7 +493,7 @@ async function checkTeam(where, newCheck, signal) {
const found = findTeam(where.import.from)
const ids = found === undefined ? [] : await copySessions(where.import.from, found.team, home, signal)
if (ids.length === 0) return 0
- mainWindow?.setProgressBar(2)
+ setProgress(2)
const list = join(home, 'check.json')
writeFileSync(list, JSON.stringify(ids))
const check = newCheck(home, list)
@@ -379,7 +512,7 @@ async function checkTeam(where, newCheck, signal) {
if (!signal.aborted) console.error('DeepSeek Bot: the chats were not checked before the copy:', error)
return 0
} finally {
- mainWindow?.setProgressBar(-1)
+ setProgress(-1)
await rm(home, { recursive: true, force: true, maxRetries: 5 }).catch((error) => { console.error(error) })
}
}
@@ -389,8 +522,7 @@ async function checkTeam(where, newCheck, signal) {
async function moveData(workspace) {
if (copying !== undefined || stopping || mainWindow === undefined) return false
const t = text()
- const owner = mainWindow
- const { canceled, filePaths } = await dialog.showOpenDialog(owner, { title: t.pickMove, defaultPath: dirname(places.dataDir), properties: ['openDirectory', 'createDirectory', 'promptToCreate'] })
+ const { canceled, filePaths } = await dialog.showOpenDialog(owner(), { title: t.pickMove, defaultPath: dirname(places.dataDir), properties: ['openDirectory', 'createDirectory', 'promptToCreate'] })
if (canceled || filePaths[0] === undefined) return false
const to = resolve(filePaths[0])
const dshHome = userDshHome()
@@ -399,18 +531,21 @@ async function moveData(workspace) {
for (const current of new Set([workspace, places.workspace])) {
const problem = moveProblem({ from: places.dataDir, to, workspace: current, dshHome, program: app.isPackaged ? programFolder() : undefined })
if (problem === undefined) continue
- await dialog.showMessageBox(owner, { type: 'warning', title: 'DeepSeek Bot', message: problem === 'dsh' ? t.inDsh(dshHome) : t[MOVE_PROBLEMS[problem]], buttons: ['OK'] })
+ await dialog.showMessageBox(owner(), { type: 'warning', title: 'DeepSeek Bot', message: problem === 'dsh' ? t.inDsh(dshHome) : t[MOVE_PROBLEMS[problem]], buttons: ['OK'] })
return true
}
return false
}
if (await refused()) return false
- const { response } = await dialog.showMessageBox(owner, { type: 'question', title: 'DeepSeek Bot', noLink: true, message: t.moveConfirm(to), detail: t.moveDetail(places.dataDir), buttons: [t.move, t.cancel], defaultId: 0, cancelId: 1 })
+ const { response } = await dialog.showMessageBox(owner(), { type: 'question', title: 'DeepSeek Bot', noLink: true, message: t.moveConfirm(to), detail: t.moveDetail(places.dataDir), buttons: [t.move, t.cancel], defaultId: 0, cancelId: 1 })
if (response !== 0 || stopping || await refused()) return false
const signal = copyAbort.signal
copying = (async () => {
- // The settings go away first, so that nothing moves the team workspace from here on.
- void mainWindow?.loadURL(notePage(t.moving))
+ // The settings go away first, so that nothing moves the team workspace from here on; the
+ // start window shows the move meanwhile.
+ void mainWindow?.loadURL('about:blank').catch(() => {})
+ mainWindow?.hide()
+ startWindow.open('moving')
await stopHost()
// The app may have heard of a team workspace change while the Host stopped.
if (await refused()) {
@@ -419,11 +554,11 @@ async function moveData(workspace) {
}
// Another DSH on the same data would go on writing while the copy is made.
if (teamInUse(places.dataDir)) {
- await dialog.showMessageBox({ type: 'warning', title: 'DeepSeek Bot', message: t.moveInUse })
+ await dialog.showMessageBox(owner(), { type: 'warning', title: 'DeepSeek Bot', message: t.moveInUse })
app.relaunch()
return
}
- mainWindow?.setProgressBar(2)
+ setProgress(2)
try {
await copyData(places.dataDir, to, signal)
try {
@@ -436,9 +571,9 @@ async function moveData(workspace) {
} catch (error) {
if (signal.aborted) return
console.error(error)
- await dialog.showMessageBox({ type: 'warning', title: 'DeepSeek Bot', message: t.moveFailed(error instanceof Error ? error.message : String(error)) })
+ await dialog.showMessageBox(owner(), { type: 'warning', title: 'DeepSeek Bot', message: t.moveFailed(error instanceof Error ? error.message : String(error)) })
} finally {
- mainWindow?.setProgressBar(-1)
+ setProgress(-1)
}
app.relaunch()
})()
@@ -448,9 +583,6 @@ async function moveData(workspace) {
return true
}
-const notePage = message => `data:text/html;charset=utf-8,${encodeURIComponent(`<!doctype html><meta charset="utf-8"><meta name="color-scheme" content="light dark">
-<body style="margin:0;height:100vh;display:grid;place-items:center;font:14px system-ui,sans-serif;background:Canvas;color:CanvasText">${message.replace(/[&<>]/gu, char => `&#${String(char.charCodeAt(0))};`)}</body>`)}`
-
// Windows and a Linux AppImage update themselves; macOS and a Linux deb ask to download the new
// version. Throwaway runs check only a given feed and never ask.
function startUpdates() {
@@ -482,24 +614,23 @@ async function askRestart(version) {
// After a failed start, fail() installs the update itself.
if (failed) return false
const t = localeText(UPDATE_TEXT)
- const options = { type: 'info', title: 'DeepSeek Bot', message: t.ready(version), detail: t.readyDetail, buttons: [t.restart, t.later], defaultId: 0, cancelId: 1, noLink: true }
- const { response } = await (mainWindow ? dialog.showMessageBox(mainWindow, options) : dialog.showMessageBox(options))
+ const { response } = await dialog.showMessageBox(owner(), { type: 'info', title: 'DeepSeek Bot', message: t.ready(version), detail: t.readyDetail, buttons: [t.restart, t.later], defaultId: 0, cancelId: 1, noLink: true })
return response === 0
}
async function askDownload(version) {
if (failed) return false
const t = localeText(UPDATE_TEXT)
- const options = { type: 'info', title: 'DeepSeek Bot', message: t.available(version), detail: t.availableDetail, buttons: [t.download, t.later], defaultId: 0, cancelId: 1, noLink: true }
- const { response } = await (mainWindow ? dialog.showMessageBox(mainWindow, options) : dialog.showMessageBox(options))
+ const { response } = await dialog.showMessageBox(owner(), { type: 'info', title: 'DeepSeek Bot', message: t.available(version), detail: t.availableDetail, buttons: [t.download, t.later], defaultId: 0, cancelId: 1, noLink: true })
return response === 0
}
+// Hidden, on the rect the start window grows into; the start window shows it at the hand-off.
function createWindow() {
const dark = nativeTheme.shouldUseDarkColors
const win32 = process.platform === 'win32'
mainWindow = new BrowserWindow({
- width: 1320, height: 860, minWidth: 720, minHeight: 480,
+ ...startWindow.mainBounds(), minWidth: 720, minHeight: 480,
title: 'DeepSeek Bot', show: false, icon: iconFile,
backgroundColor: mica ? '#00000000' : dark ? '#1b1b1c' : '#ffffff',
// Frameless as in DSH Desktop: the caption buttons overlay the page's band. They keep the
@@ -514,7 +645,7 @@ 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() })
+ startWindow.placeMain(mainWindow)
mainWindow.on('page-title-updated', (event) => { event.preventDefault() })
mainWindow.on('closed', () => { mainWindow = undefined })
browserGuests.bind(mainWindow)
@@ -558,7 +689,6 @@ 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))
}
function setMenu() {
@@ -566,9 +696,10 @@ function setMenu() {
Menu.setApplicationMenu(Menu.buildFromTemplate([{ role: 'appMenu' }, { role: 'fileMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' }]))
}
-// Also after a failed start: a second launch is how the user finds the window again.
+// The window that is showing: the start window until the hand-off (also after a failed start),
+// then the team window. A second launch is how the user finds it again.
function focusWindow() {
- if (mainWindow === undefined) return
+ if (startWindow.focus() || mainWindow === undefined) return
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.show()
mainWindow.focus()
@@ -588,27 +719,20 @@ function openOutside(url) {
if (/^https?:\/\//iu.test(url)) void shell.openExternal(url)
}
-// A new version may fix what keeps this one from starting.
+// The start window shows the failure page and stays. A new version may fix what keeps this one
+// from starting: one that installs itself does so once it is downloaded, unless the user has
+// tried again meanwhile; a release page (macOS, a Linux deb) waits for the page's update row.
async function fail(error) {
console.error(error)
if (failed || stopping) return
failed = true
+ const mine = attempt
+ startWindow.fail(error, startKind())
const found = await Promise.race([updates?.latest() ?? null, sleep(UPDATE_CHECK_WAIT_MS).then(() => null)])
- const throwaway = Boolean(process.env.DS_BOT_HOME)
- const t = localeText(UPDATE_TEXT)
- const next = found ? `\n\n${found.page ? t.onFailurePage(found.version) : t.onFailure(found.version)}` : ''
- dialog.showErrorBox('DeepSeek Bot', `${text().notStarted}\n\n${error instanceof Error ? error.message : String(error)}${next}`)
- if (found?.page) {
- if (!throwaway) await shell.openExternal(found.page)
- app.quit()
+ if (!found || mine !== attempt) return
+ if (found.page) {
+ console.log(`DeepSeek Bot: ${found.version} is out: ${found.page}`)
return
}
- if (found) {
- mainWindow?.hide()
- if (await Promise.race([found.downloaded, sleep(UPDATE_DOWNLOAD_WAIT_MS).then(() => false)])) {
- await updates.install()
- return
- }
- }
- app.quit()
+ if (await Promise.race([found.downloaded, sleep(UPDATE_DOWNLOAD_WAIT_MS).then(() => false)]) && failed && mine === attempt) await updates.install()
}
diff --git a/app/src/preload.cjs b/app/src/preload.cjs
index 7868b061..4413ac4e 100644
--- a/app/src/preload.cjs
+++ b/app/src/preload.cjs
@@ -1,14 +1,27 @@
-// Gives the page that the app's Host serves the app's own bridge. On Windows it also marks the
-// page for the frameless window the way DSH Desktop's preload does
+// Gives the page that the app's Host serves the app's own bridge, and the app's start page its
+// own, smaller one; each window's arguments name the one page that gets it. On Windows it also
+// marks the Host's page for the frameless window the way DSH Desktop's preload does
// (apps/desktop/src/preload-windows.ts, preload-platform.ts and preload-theme.ts; see NOTICE),
// but without data-platform: that puts DSH's shortcuts on native menu input, which this
// window does not have.
const { contextBridge, ipcRenderer } = require('electron')
-const host = process.argv.find(value => value.startsWith('--ds-bot-origin='))?.slice('--ds-bot-origin='.length)
-if (host !== undefined && location.origin === host) {
- // DS Bot's settings show and move the app's data location through this.
+const argument = name => process.argv.find(value => value.startsWith(`--${name}=`))?.slice(name.length + 3)
+const startPage = argument('ds-bot-start')
+const host = argument('ds-bot-origin')
+if (startPage !== undefined) {
+ if (location.href.split(/[?#]/u)[0] === startPage) contextBridge.exposeInMainWorld('dsBotStart', startBridge())
+} else if (host !== undefined && location.origin === host) {
+ let ready = false
contextBridge.exposeInMainWorld('dsBotApp', {
+ // The team view has mounted: the start window hands over to this one.
+ ready: () => {
+ if (ready) return
+ ready = true
+ ipcRenderer.send('ds-bot:ready')
+ },
+ focus: () => { ipcRenderer.send('ds-bot:focus') },
+ // DS Bot's settings show and move the app's data location through this.
dataLocation: () => ipcRenderer.invoke('ds-bot:data-location'),
moveData: (workspace) => ipcRenderer.invoke('ds-bot:move-data', typeof workspace === 'string' ? workspace : undefined),
teamWorkspaceChanged: (path) => { ipcRenderer.send('ds-bot:team-workspace', String(path)) },
@@ -33,6 +46,29 @@ if (host !== undefined && location.origin === host) {
}
}
+// The main process sends the whole state on every change; a page that subscribes late, or again,
+// gets the last one first.
+function startBridge() {
+ const listeners = new Set()
+ let last
+ const tell = (listener, state) => {
+ try { listener(state) } catch (error) { console.error('DeepSeek Bot: a start state listener failed', error) }
+ }
+ ipcRenderer.on('ds-bot:start-state', (_event, state) => {
+ last = state
+ for (const listener of [...listeners]) tell(listener, state)
+ })
+ return {
+ onState(listener) {
+ if (typeof listener !== 'function') return () => {}
+ listeners.add(listener)
+ if (last !== undefined) tell(listener, last)
+ return () => { listeners.delete(listener) }
+ },
+ act: (name, payload) => ipcRenderer.invoke('ds-bot:start-act', String(name), payload),
+ }
+}
+
function browserBridge() {
const listeners = new Map()
const viewListeners = new Set()
diff --git a/app/src/start-frame.mjs b/app/src/start-frame.mjs
new file mode 100644
index 00000000..f3cc8445
--- /dev/null
+++ b/app/src/start-frame.mjs
@@ -0,0 +1,42 @@
+// What the start window needs before the team view has loaded: the theme source and the motion
+// tier the team view reported last. Kept in the app's own userData, never in DSH_HOME or ~/.dsh
+// (docs/plans/2026-10-26-start-window.md §3, §10).
+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
+import { dirname } from 'node:path'
+
+const THEMES = new Set(['light', 'dark', 'system'])
+const MOTIONS = new Set(['quiet', 'normal', 'lively'])
+const DEFAULTS = { themeSource: 'system', motion: 'normal' }
+
+/** @returns {{ themeSource: 'light' | 'dark' | 'system', motion: 'quiet' | 'normal' | 'lively' }} */
+export function readStartFrame(file) {
+ let saved
+ try {
+ saved = JSON.parse(readFileSync(file, 'utf8'))
+ } catch {
+ return { ...DEFAULTS }
+ }
+ return {
+ themeSource: THEMES.has(saved?.themeSource) ? saved.themeSource : DEFAULTS.themeSource,
+ motion: MOTIONS.has(saved?.motion) ? saved.motion : DEFAULTS.motion,
+ }
+}
+
+/** Keeps the values of `change` that are valid; returns whether the file changed. */
+export function writeStartFrame(file, change) {
+ const current = readStartFrame(file)
+ const next = {
+ themeSource: THEMES.has(change.themeSource) ? change.themeSource : current.themeSource,
+ motion: MOTIONS.has(change.motion) ? change.motion : current.motion,
+ }
+ if (next.themeSource === current.themeSource && next.motion === current.motion) return false
+ try {
+ mkdirSync(dirname(file), { recursive: true })
+ writeFileSync(`${file}.tmp`, `${JSON.stringify(next)}\n`)
+ renameSync(`${file}.tmp`, file)
+ return true
+ } catch (error) {
+ console.error('DeepSeek Bot: the start window\'s theme was not saved:', error)
+ return false
+ }
+}
diff --git a/app/src/start-window.mjs b/app/src/start-window.mjs
new file mode 100644
index 00000000..c4fa6524
--- /dev/null
+++ b/app/src/start-window.mjs
@@ -0,0 +1,611 @@
+// The start window (docs/plans/2026-10-26-start-window.md §1, §8, §11; windows-onboarding §3): the
+// app's own small window that shows start/start.html while the engine boots. It holds the
+// start's state and sends the page the whole of it on every change; at the end it grows into the
+// team window's rect, and the hidden team window shows on the same rect. The rect maths, the
+// growth, the snapshot and the checks are plain functions, so the tests run without Electron.
+import { pathToFileURL } from 'node:url'
+
+export const START_STATE = 'ds-bot:start-state'
+export const START_ACT = 'ds-bot:start-act'
+
+export const START_SIZE = { width: 720, height: 540 }
+export const SHORT_START_SIZE = { width: 720, height: 500 }
+// Work areas lower than this get the short start window.
+const SHORT_WORK_AREA = 588
+export const MAIN_SIZE = { width: 1320, height: 860 }
+export const PHASES = ['data', 'engine', 'team']
+export const START_KINDS = ['first', 'later', 'moving']
+export const WATCHDOG_MS = 180_000
+export const TEAM_VIEW_MS = 20_000
+// handoffShow + 160 ms: the growth, 300 ms in steps of about 14 ms; the start window goes
+// 300 ms after the team window shows (§8).
+export const GROWTH = { delay: 160, duration: 300, step: 14 }
+export const DESTROY_AFTER_MS = 300
+export const FAILURE_LINES = 200
+// The DeepSeek theme's --bt-main and --bt-ink (ui-standard 2.1), as in start.css: the window's
+// own background and caption symbols, which show before the page paints and where Mica is not.
+const COLORS = { light: { main: '#fcfcfc', ink: '#141414' }, dark: { main: '#141414', ink: '#f2f2f2' } }
+const CAPTION_HEIGHT = 40
+const PAINT_WAIT_MS = 3000
+
+// What the page may ask, and in which views (null: in any). The cards of later pull requests
+// send other names, which are refused.
+const ACT_VIEWS = {
+ handoffShow: ['handoff'],
+ handoffDone: ['handoff'],
+ retry: ['failed', 'watchdog'],
+ wait: ['watchdog'],
+ reloadView: ['viewFailed'],
+ openLogs: null,
+ copyDetails: null,
+}
+export const START_ACTS = Object.freeze(Object.keys(ACT_VIEWS))
+
+/** Whether the main process takes this act from the start page in this view. */
+export function acceptsAct(name, view) {
+ if (typeof name !== 'string' || !Object.hasOwn(ACT_VIEWS, name)) return false
+ const views = ACT_VIEWS[name]
+ return views === null || views.includes(view)
+}
+
+/** Whether a frame shows exactly the start page that was loaded. */
+export function isStartPage(frameUrl, loadedUrl) {
+ try {
+ const frame = new URL(frameUrl)
+ return frame.protocol === 'file:' && frame.href === new URL(loadedUrl).href
+ } catch {
+ return false
+ }
+}
+
+export const startUrl = (page, kind) => `${pathToFileURL(page).href}?start=${kind}`
+
+/** The start window's content size on a display's work area. */
+export const startSize = workArea => ({ ...(workArea.height < SHORT_WORK_AREA ? SHORT_START_SIZE : START_SIZE) })
+
+export function centred(size, area) {
+ return {
+ x: area.x + Math.round((area.width - size.width) / 2),
+ y: area.y + Math.round((area.height - size.height) / 2),
+ width: size.width,
+ height: size.height,
+ }
+}
+
+/** A rect moved, and shrunk if it must be, to lie inside an area. */
+export function clampInto(rect, area) {
+ const width = Math.min(rect.width, area.width)
+ const height = Math.min(rect.height, area.height)
+ return {
+ x: Math.min(Math.max(rect.x, area.x), area.x + area.width - width),
+ y: Math.min(Math.max(rect.y, area.y), area.y + area.height - height),
+ width,
+ height,
+ }
+}
+
+/** The team window's rect: centred on the start window, inside the work area. */
+export function mainRect(start, area, size = MAIN_SIZE) {
+ const x = Math.round(start.x + start.width / 2 - size.width / 2)
+ const y = Math.round(start.y + start.height / 2 - size.height / 2)
+ return clampInto({ x, y, width: size.width, height: size.height }, area)
+}
+
+/** CSS's cubic-bezier() as a function of the time fraction. */
+export function cubicBezier(x1, y1, x2, y2) {
+ const curve = (p1, p2) => {
+ const c = 3 * p1
+ const b = 3 * (p2 - p1) - c
+ const a = 1 - c - b
+ return s => ((a * s + b) * s + c) * s
+ }
+ const x = curve(x1, x2)
+ const y = curve(y1, y2)
+ return (t) => {
+ if (t <= 0) return 0
+ if (t >= 1) return 1
+ // x is monotonic for control points inside [0, 1], so halving finds its parameter.
+ let low = 0
+ let high = 1
+ for (let step = 0; step < 40; step += 1) {
+ const mid = (low + high) / 2
+ if (x(mid) < t) low = mid
+ else high = mid
+ }
+ return y((low + high) / 2)
+ }
+}
+export const GROWTH_EASING = cubicBezier(0.2, 0.7, 0.2, 1)
+
+export function rectAt(from, to, progress) {
+ const at = key => Math.round(from[key] + (to[key] - from[key]) * progress)
+ return { x: at('x'), y: at('y'), width: at('width'), height: at('height') }
+}
+
+/** The rects of the growth, one per step; the last one is the target at the full duration. */
+export function growthSteps(from, to, { duration, step } = GROWTH) {
+ const steps = []
+ for (let at = step; ; at += step) {
+ const time = Math.min(at, duration)
+ steps.push({ at: time, rect: rectAt(from, to, GROWTH_EASING(time / duration)) })
+ if (time >= duration) return steps
+ }
+}
+
+// When the page never sends handoffShow, the main process shows the team window itself. A first
+// start and a celebrating hand-off take up to about 1.2 s, plus up to 600 ms of queued swimming.
+export const fallbackMs = ({ start, celebrate }) => (start === 'first' || celebrate ? 2500 : 800)
+
+// The five reasons of the failure page (windows-onboarding §3), most specific first: a Host
+// that stopped says so and carries its own error output, which names the cause.
+const REASONS = [
+ ['permission', /\b(?:EACCES|EPERM)\b|permission denied|operation not permitted|access is denied/iu],
+ ['space', /\b(?:ENOSPC|EDQUOT)\b|no space left|not enough space|disk (?:is )?full/iu],
+ ['files', /\b(?:ENOENT|MODULE_NOT_FOUND|ERR_MODULE_NOT_FOUND)\b|cannot find (?:module|package)|could not load its own bundles|not a valid Win32 application|0xC0000135|3221225781/iu],
+ ['engine', /DSH Host stopped|engine's web server/iu],
+]
+
+/** @returns {'permission' | 'space' | 'files' | 'engine' | 'other'} */
+export function failureReason(error) {
+ const code = typeof error?.code === 'string' ? error.code : ''
+ const message = error instanceof Error ? error.message : String(error ?? '')
+ const text = `${code} ${message}`
+ return REASONS.find(([, pattern]) => pattern.test(text))?.[0] ?? 'other'
+}
+
+// The Main Bot that a kept team's sidebar shows first (ds-bot's channel.js: mainBotIds[0]; an
+// older state.json has mainBotId), whose name the greeting says on a reinstall.
+export function mainBotName(state) {
+ const id = Array.isArray(state?.mainBotIds) ? state.mainBotIds[0] : state?.mainBotId
+ const name = typeof id === 'string' ? state.bots?.[id]?.name : undefined
+ return typeof name === 'string' && name.trim() !== '' ? name.trim() : undefined
+}
+
+// What the hint row can say at the second stop. previewNotice: DSH shows its preview notice when
+// the Session is ready and the main view has no non-empty Session (windows-onboarding §3, the
+// row of the third stop); the main process cannot tell before the team view has loaded, so the
+// stop-2 hint stays.
+export function explainOf({ offered = false, team } = {}) {
+ if (offered) return { mode: 'import', nextStep: false, previewNotice: false }
+ if (team !== undefined) {
+ const name = mainBotName(team.team)
+ return { mode: 'reinstall', bots: team.bots, groups: team.rooms, ...(name === undefined ? {} : { name }), nextStep: false, previewNotice: false }
+ }
+ return { mode: 'new', nextStep: true, previewNotice: false }
+}
+
+export const clockMs = (clock, now) => clock.base + (clock.running ? Math.max(0, now - clock.from) : 0)
+
+/** The whole state the page gets: the page computes the elapsed time from clock.ms at clock.at. */
+export function startSnapshot(state, now) {
+ const snapshot = {
+ v: 1,
+ lang: state.lang,
+ start: state.start,
+ motion: state.motion,
+ // Windows draws the caption buttons over the page's band; macOS and Linux a system title bar.
+ frame: state.frame,
+ view: state.view,
+ phase: PHASES.find(phase => !state.done.includes(phase)) ?? 'team',
+ done: PHASES.filter(phase => state.done.includes(phase)),
+ clock: { ms: Math.round(clockMs(state.clock, now)), at: now, running: state.clock.running, rate: 1 },
+ explain: { ...state.explain },
+ celebrate: state.celebrate,
+ }
+ if (state.hint !== undefined) snapshot.hint = { ...state.hint }
+ if (state.failure !== undefined) snapshot.failure = { reason: state.failure.reason, log: [...state.failure.log] }
+ return snapshot
+}
+
+export const detailsText = ({ version, platform, arch, reason, lines }) => [`DeepSeek Bot ${version} (${platform} ${arch})`, `reason: ${reason}`, '', ...lines].join('\n')
+
+const note = message => { console.log(`DeepSeek Bot: start window: ${message}`) }
+
+export class StartWindow {
+ #o
+ #window
+ #url
+ #painted = Promise.resolve()
+ #state
+ #explain = explainOf()
+ #asks = 0
+ #watchAt = WATCHDOG_MS
+ #timers = {}
+ #phaseAt = 0
+ #readyAt = 0
+ #showAt = 0
+ #from
+ #handing = false
+ #revealed = false
+
+ /**
+ * @param {{
+ * electron: { BrowserWindow: any, ipcMain: any, screen: any, shell: any, clipboard: any, nativeTheme: any, systemPreferences: any },
+ * page: string, preload: string, icon: string, mica: boolean, devTools: boolean,
+ * lang: 'zh' | 'en', motion: string, version: string,
+ * log: { dir: string, tail: (count: number) => string[] },
+ * mainWindow: () => any,
+ * onRetry: () => void, onReload: () => void, onClose: () => void,
+ * }} options `onClose` runs when the user closes the start window before the hand-off.
+ */
+ constructor(options) {
+ this.#o = options
+ options.electron.ipcMain.handle(START_ACT, (event, name, payload) => this.#act(event, name, payload))
+ }
+
+ get kind() { return this.#state?.start }
+
+ /** Settles once the current window has painted its first frame (or has had time to). */
+ get painted() { return this.#painted }
+
+ /** Opens the window, unless one is open, with a fresh state for this kind of start. */
+ open(kind) {
+ if (this.#open()) return
+ const { BrowserWindow, screen, nativeTheme } = this.#o.electron
+ const start = START_KINDS.includes(kind) ? kind : 'later'
+ this.#reset(start)
+ const area = screen.getDisplayNearestPoint(screen.getCursorScreenPoint()).workArea
+ const win32 = process.platform === 'win32'
+ const { mica } = this.#o
+ const colors = this.#colors()
+ const rect = centred(startSize(area), area)
+ const win = new BrowserWindow({
+ ...rect,
+ useContentSize: true, resizable: false, maximizable: false, fullscreenable: false, minimizable: true,
+ show: true, title: 'DeepSeek Bot', icon: this.#o.icon,
+ backgroundColor: mica ? '#00000000' : colors.main,
+ // Frameless with the system minimize and close buttons over the page's empty 40 px band.
+ ...(win32 ? {
+ titleBarStyle: 'hidden',
+ titleBarOverlay: { height: CAPTION_HEIGHT, color: mica ? '#00000000' : colors.main, symbolColor: colors.ink },
+ ...(mica ? { backgroundMaterial: 'mica' } : {}),
+ } : {}),
+ webPreferences: {
+ preload: this.#o.preload, contextIsolation: true, sandbox: true, nodeIntegration: false, webviewTag: false, spellcheck: false,
+ // The page paces the whale and the hand-off on timers, which a covered or minimized
+ // window would otherwise run once a second.
+ backgroundThrottling: false,
+ additionalArguments: [`--ds-bot-start=${pathToFileURL(this.#o.page).href}`],
+ },
+ })
+ // At a fractional display scale, Electron 44 on Windows makes a frameless window a few pixels
+ // larger than asked; setting the size again once it exists gives the size asked for.
+ win.setContentBounds(rect)
+ this.#window = win
+ this.#url = startUrl(this.#o.page, start)
+ const contents = win.webContents
+ this.#painted = new Promise((resolve) => {
+ win.once('ready-to-show', resolve)
+ contents.once('did-finish-load', resolve)
+ setTimeout(resolve, PAINT_WAIT_MS)
+ })
+ win.on('page-title-updated', (event) => { event.preventDefault() })
+ contents.on('will-navigate', (event) => { event.preventDefault() })
+ contents.setWindowOpenHandler(() => ({ action: 'deny' }))
+ // A reload loses what the preload kept, so the page gets the state again.
+ contents.on('dom-ready', () => { this.#send() })
+ contents.on('render-process-gone', (_event, details) => { note(`the page's renderer stopped (${String(details?.reason)})`) })
+ if (this.#o.devTools) {
+ contents.on('before-input-event', (_event, input) => {
+ if (input.type === 'keyDown' && (input.key === 'F12' || (input.control && input.shift && input.key.toLowerCase() === 'i'))) contents.toggleDevTools()
+ })
+ }
+ const recolor = () => {
+ if (win.isDestroyed()) return
+ const next = this.#colors()
+ if (win32) win.setTitleBarOverlay({ color: mica ? '#00000000' : next.main, symbolColor: next.ink })
+ if (!mica) win.setBackgroundColor(next.main)
+ }
+ nativeTheme.on('updated', recolor)
+ win.once('closed', () => {
+ nativeTheme.off('updated', recolor)
+ if (this.#window !== win) return
+ this.#window = undefined
+ this.#clearTimers()
+ if (!this.#revealed) this.#o.onClose()
+ })
+ void win.loadURL(this.#url).catch((error) => { note(`the start page did not load: ${error instanceof Error ? error.message : String(error)}`) })
+ }
+
+ /** The window that dialogs belong to, while it is the one showing. */
+ owner() { return this.#open() && !this.#revealed ? this.#window : undefined }
+
+ /** Brings the start window back while it is the one showing. */
+ focus() {
+ const win = this.owner()
+ if (win === undefined) return false
+ if (win.isMinimized()) win.restore()
+ win.show()
+ win.focus()
+ return true
+ }
+
+ explain(explain) {
+ this.#explain = { ...explain }
+ if (this.#open()) this.#update({ explain: this.#explain })
+ }
+
+ /** The clock stands still while the user answers a dialog: thinking time is not the engine's. */
+ async asking(promise) {
+ this.#asks += 1
+ this.#refresh()
+ try {
+ return await promise
+ } finally {
+ this.#asks -= 1
+ this.#refresh()
+ }
+ }
+
+ /** The data folder or the engine is ready. */
+ done(phase) {
+ if (!this.#open() || this.#state.done.includes(phase) || !['data', 'engine'].includes(phase)) return
+ note(`${phase} took ${String(Date.now() - this.#phaseAt)} ms`)
+ this.#phaseAt = Date.now()
+ // The engine came up while the 180 s question was open: the question goes.
+ this.#update({ done: [...this.#state.done, phase], ...(this.#state.view === 'watchdog' ? { view: 'boot' } : {}) })
+ }
+
+ /** The engine's page started loading in the hidden team window: it has 20 s to call ready(). */
+ teamLoading() {
+ if (!this.#open()) return
+ this.#later('teamView', TEAM_VIEW_MS, () => {
+ if (this.#state.view !== 'boot') return
+ note(`the team view did not call ready() within ${String(TEAM_VIEW_MS / 1000)} s`)
+ this.#update({ view: 'viewFailed', failure: { reason: 'other', log: this.#o.log.tail(FAILURE_LINES) } })
+ })
+ }
+
+ /** dsBotApp.ready() from the team view: the hand-off starts. */
+ ready() {
+ if (!this.#open() || !['boot', 'viewFailed'].includes(this.#state.view) || !this.#state.done.includes('engine')) return
+ this.#clear('teamView')
+ const now = Date.now()
+ note(`team took ${String(now - this.#phaseAt)} ms`)
+ this.#readyAt = now
+ // A team view that loads after its 20 s goes in without a celebration (§7).
+ const celebrate = this.#state.celebrate && this.#state.view !== 'viewFailed'
+ this.#update({ view: 'handoff', done: [...PHASES], celebrate, failure: undefined })
+ this.#later('fallback', fallbackMs(this.#state), () => {
+ note('the page did not send handoffShow')
+ this.#handoffShow({ grow: false })
+ })
+ }
+
+ /**
+ * The failure page: in this window, or in a new one when the team window was already showing.
+ * @param {string} kind the kind of start when no start window has opened yet
+ */
+ fail(error, kind = 'later') {
+ const showing = this.#revealed
+ if (showing) {
+ this.#destroy()
+ const main = this.#o.mainWindow()
+ if (main !== undefined && !main.isDestroyed()) main.hide()
+ }
+ if (!this.#open()) this.open(showing || this.#state === undefined ? kind : this.#state.start)
+ this.#cancelHandoff()
+ this.#clear('teamView')
+ this.#clear('fallback')
+ this.#update({ view: 'failed', failure: { reason: failureReason(error), log: this.#o.log.tail(FAILURE_LINES) } })
+ }
+
+ /** The team window's rect: centred on the start window, inside that display's work area. */
+ mainBounds() {
+ const { screen } = this.#o.electron
+ if (!this.#open()) return centred(clampInto({ x: 0, y: 0, ...MAIN_SIZE }, screen.getPrimaryDisplay().workArea), screen.getPrimaryDisplay().workArea)
+ const start = this.#window.getNormalBounds()
+ return mainRect(start, screen.getDisplayMatching(start).workArea)
+ }
+
+ /**
+ * Puts the hidden team window on its rect, also when made with it: the size it was made with
+ * can be off by a few pixels (see open()), the one set afterwards is exact.
+ * @returns the rect
+ */
+ placeMain(main = this.#o.mainWindow()) {
+ const rect = this.mainBounds()
+ if (main !== undefined && !main.isDestroyed()) main.setBounds(rect)
+ return rect
+ }
+
+ #open() { return this.#window !== undefined && !this.#window.isDestroyed() }
+
+ #colors() { return COLORS[this.#o.electron.nativeTheme.shouldUseDarkColors ? 'dark' : 'light'] }
+
+ #reset(start) {
+ this.#clearTimers()
+ this.#handing = false
+ this.#revealed = false
+ this.#watchAt = WATCHDOG_MS
+ const now = Date.now()
+ this.#phaseAt = now
+ this.#state = {
+ lang: this.#o.lang, start, motion: this.#o.motion, frame: process.platform === 'win32' ? 'band' : 'system',
+ view: start === 'moving' ? 'moving' : 'boot',
+ done: [], explain: this.#explain, celebrate: start === 'first',
+ clock: { base: 0, from: now, running: true },
+ hint: undefined, failure: undefined,
+ }
+ this.#refresh()
+ }
+
+ // Applies a change, keeps the clock running only while the start is booting and nobody is
+ // being asked, and sends the page the whole state.
+ #update(change) {
+ const now = Date.now()
+ const next = { ...this.#state, ...change }
+ const running = this.#asks === 0 && (next.view === 'boot' || next.view === 'moving')
+ const clock = next.clock
+ if (running !== clock.running) next.clock = { base: clockMs(clock, now), from: now, running }
+ this.#state = next
+ this.#armWatchdog()
+ this.#send()
+ }
+
+ #refresh() { if (this.#state !== undefined) this.#update({}) }
+
+ #send() {
+ if (this.#open() && this.#state !== undefined) this.#window.webContents.send(START_STATE, startSnapshot(this.#state, Date.now()))
+ }
+
+ // 180 s on the start's clock without the engine: the whale asks whether to try again.
+ #armWatchdog() {
+ this.#clear('watchdog')
+ const { start, view, clock, done } = this.#state
+ if (start === 'moving' || view !== 'boot' || !clock.running || done.includes('engine')) return
+ this.#later('watchdog', this.#watchAt - clockMs(clock, Date.now()), () => {
+ note(`no engine after ${String(Math.round(this.#watchAt / 1000))} s`)
+ this.#update({ view: 'watchdog' })
+ })
+ }
+
+ #act(event, name, payload) {
+ const win = this.#window
+ if (!this.#open() || event.sender !== win.webContents || event.senderFrame !== win.webContents.mainFrame
+ || !isStartPage(event.senderFrame?.url, this.#url)) return false
+ if (!acceptsAct(name, this.#state.view)) {
+ note(`refused the act ${typeof name === 'string' ? name.slice(0, 40) : typeof name} in ${this.#state.view}`)
+ return false
+ }
+ if (name === 'handoffShow') this.#handoffShow(payload)
+ else if (name === 'handoffDone') note(`handoffDone at handoffShow + ${String(Date.now() - this.#showAt)} ms`)
+ else if (name === 'retry') this.#retry()
+ else if (name === 'wait') this.#wait()
+ else if (name === 'reloadView') this.#reload()
+ else if (name === 'openLogs') this.#openLogs()
+ else if (name === 'copyDetails') this.#copyDetails()
+ return true
+ }
+
+ // The failed stage, or the engine after the 180 s question, starts again; the stages already
+ // done stay done, and the first success after this celebrates (§7).
+ #retry() {
+ note(`retry from ${this.#state.view}`)
+ this.#watchAt = WATCHDOG_MS
+ this.#phaseAt = Date.now()
+ this.#update({ view: 'boot', failure: undefined, celebrate: true, done: this.#state.done.filter(phase => phase !== 'team'), clock: { base: 0, from: Date.now(), running: true } })
+ this.#o.onRetry()
+ }
+
+ // 〔继续等待〕: the question comes back after another 180 s on the clock.
+ #wait() {
+ this.#watchAt = clockMs(this.#state.clock, Date.now()) + WATCHDOG_MS
+ this.#update({ view: 'boot' })
+ }
+
+ #reload() {
+ note('reloading the team view')
+ this.#update({ view: 'boot', failure: undefined })
+ this.#o.onReload()
+ this.teamLoading()
+ }
+
+ #openLogs() {
+ void this.#o.electron.shell.openPath(this.#o.log.dir).then((problem) => { if (problem) note(`the logs folder did not open: ${problem}`) })
+ }
+
+ #copyDetails() {
+ const { version } = this.#o
+ const reason = this.#state.failure?.reason ?? 'other'
+ const text = detailsText({ version, platform: process.platform, arch: process.arch, reason, lines: this.#o.log.tail(FAILURE_LINES) })
+ void Promise.resolve(this.#o.electron.clipboard.writeText(text)).catch((error) => { note(`the details were not copied: ${error instanceof Error ? error.message : String(error)}`) })
+ }
+
+ #handoffShow(payload) {
+ if (this.#handing || this.#state.view !== 'handoff') return
+ const main = this.#o.mainWindow()
+ if (main === undefined || main.isDestroyed()) return
+ this.#handing = true
+ this.#clear('fallback')
+ this.#showAt = Date.now()
+ note(`handoffShow at ready + ${String(this.#showAt - this.#readyAt)} ms`)
+ const win = this.#window
+ this.#from = win.getBounds()
+ // The start window may have been dragged since the team window was placed.
+ const target = this.placeMain(main)
+ const grow = !(payload !== null && typeof payload === 'object' && payload.grow === false) && !win.isMinimized() && !this.#reducedMotion()
+ if (!grow) { this.#reveal(); return }
+ this.#later('grow', GROWTH.delay, () => { this.#grow(this.#from, target) })
+ }
+
+ // Electron ignores setBounds' animate flag on Windows, so the growth is stepped here; each step
+ // eases from the time it really runs at, so a busy machine skips steps rather than stretching.
+ #grow(from, to) {
+ const began = Date.now()
+ note(`growing at handoffShow + ${String(began - this.#showAt)} ms`)
+ const step = () => {
+ if (!this.#open()) return
+ const time = Math.min(1, (Date.now() - began) / GROWTH.duration)
+ this.#window.setBounds(rectAt(from, to, GROWTH_EASING(time)))
+ if (time < 1) this.#later('grow', GROWTH.step, step)
+ else this.#reveal()
+ }
+ this.#later('grow', GROWTH.step, step)
+ }
+
+ // The team window shows on its rect: with the focus when the start window had it; otherwise
+ // behind nothing new, flashing its taskbar button; minimized when the start window was.
+ #reveal() {
+ if (this.#revealed || !this.#open()) return
+ const main = this.#o.mainWindow()
+ if (main === undefined || main.isDestroyed()) return
+ this.#revealed = true
+ this.#clear('fallback')
+ this.#clear('grow')
+ const win = this.#window
+ const how = win.isMinimized() ? 'minimized' : win.isFocused() ? 'focused' : 'behind'
+ if (how === 'focused') {
+ main.show()
+ main.focus()
+ } else if (how === 'minimized') {
+ main.minimize()
+ } else {
+ main.showInactive()
+ try { main.moveAbove(win.getMediaSourceId()) } catch { /* the order stays the system's */ }
+ }
+ if (how !== 'focused') {
+ main.flashFrame(true)
+ main.once('focus', () => { main.flashFrame(false) })
+ }
+ // Leaves the taskbar only now, so the app's button never goes away.
+ win.setSkipTaskbar(true)
+ note(`team window shown (${how}) at ready + ${String(Date.now() - this.#readyAt)} ms`)
+ this.#later('destroy', DESTROY_AFTER_MS, () => { this.#destroy() })
+ }
+
+ #cancelHandoff() {
+ if (!this.#handing || this.#revealed) return
+ this.#clear('grow')
+ this.#handing = false
+ if (this.#from !== undefined && this.#open()) this.#window.setBounds(this.#from)
+ }
+
+ #destroy() {
+ const win = this.#window
+ if (win !== undefined && !win.isDestroyed()) win.destroy()
+ }
+
+ #reducedMotion() {
+ try {
+ return this.#o.electron.systemPreferences.getAnimationSettings().prefersReducedMotion === true
+ } catch {
+ return false
+ }
+ }
+
+ #later(name, ms, run) {
+ this.#clear(name)
+ this.#timers[name] = setTimeout(() => {
+ delete this.#timers[name]
+ run()
+ }, Math.max(0, ms))
+ }
+
+ #clear(name) {
+ clearTimeout(this.#timers[name])
+ delete this.#timers[name]
+ }
+
+ #clearTimers() { for (const name of Object.keys(this.#timers)) this.#clear(name) }
+}
diff --git a/app/test/logs.test.mjs b/app/test/logs.test.mjs
new file mode 100644
index 00000000..363313ba
--- /dev/null
+++ b/app/test/logs.test.mjs
@@ -0,0 +1,109 @@
+import assert from 'node:assert/strict'
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { captureStdio, LogFile, logNames, redactor, rotate, shouldRotate, splitLines, tailLines } from '../src/logs.mjs'
+
+const folder = (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'ds-bot-logs-'))
+ t.after(() => { rmSync(dir, { recursive: true, force: true, maxRetries: 5 }) })
+ return dir
+}
+const at = () => new Date('2026-10-28T08:00:00.000Z')
+
+// The CI user of the onboarding acceptance has a space and Chinese in its name.
+const windows = redactor({ home: 'C:\\Users\\测试 用户', platform: 'win32' })
+
+test('the launch token, API keys and the sign-in callback do not reach the log', () => {
+ assert.equal(windows('GET http://127.0.0.1:52817/?token=Zm9v.YmFy&x=1'), 'GET http://127.0.0.1:52817/?token=<hidden>&x=1')
+ assert.equal(windows('access_token=abc refresh_Token=def'), 'access_token=<hidden> refresh_Token=<hidden>')
+ // The mock model's keys and the three DeepSeek-shaped ones of the acceptance.
+ for (const key of ['sk-test-ok', 'sk-test-bad', 'sk-test-empty', `sk-${'0123456789abcdef'.repeat(2).slice(0, 28)}0001`, `sk-${'a'.repeat(28)}0401`, `sk-${'b'.repeat(28)}0000`]) {
+ assert.equal(windows(`key "${key}" saved`), 'key "sk-<hidden>" saved')
+ }
+ assert.equal(windows('GET /oauth/callback?code=abc&state=def 302'), 'GET /oauth/callback?<hidden> 302')
+ assert.equal(windows('Authorization: Bearer eyJh.eyJz.c2ln'), 'Authorization: Bearer <hidden>')
+})
+
+test('the home folder becomes %USERPROFILE% in every spelling', () => {
+ assert.equal(windows('data C:\\Users\\测试 用户\\.ds-bot'), 'data %USERPROFILE%\\.ds-bot')
+ assert.equal(windows('url file:///c:/users/测试 用户/DeepSeek Bot'), 'url file:///%USERPROFILE%/DeepSeek Bot')
+ assert.equal(windows('{"dataDir":"C:\\\\Users\\\\测试 用户\\\\.ds-bot"}'), '{"dataDir":"%USERPROFILE%\\\\.ds-bot"}')
+ assert.equal(windows('cwd C:\\Users\\测试 用户'), 'cwd %USERPROFILE%')
+ // Another user whose name starts the same way is not this one.
+ assert.equal(windows('C:\\Users\\测试 用户2\\x'), 'C:\\Users\\测试 用户2\\x')
+ const posix = redactor({ home: '/home/calx', platform: 'linux' })
+ assert.equal(posix('/home/calx/.ds-bot and file:///home/calx'), '~/.ds-bot and file://~')
+ assert.equal(posix('/home/calxy/x /HOME/calx'), '/home/calxy/x /HOME/calx')
+ assert.equal(redactor({ home: '/', platform: 'linux' })('/usr/bin'), '/usr/bin')
+})
+
+test('redaction keeps ordinary words and can run twice', () => {
+ assert.equal(windows('desk-top task-runner risk-free'), 'desk-top task-runner risk-free')
+ const line = 'GET /oauth/callback?code=1 ?token=2 sk-test-ok Bearer x C:\\Users\\测试 用户\\a'
+ assert.equal(windows(windows(line)), windows(line))
+})
+
+test('output splits into whole lines; the rest waits', () => {
+ assert.deepEqual(splitLines('', 'one\r\ntwo\nthr'), { lines: ['one', 'two'], rest: 'thr' })
+ assert.deepEqual(splitLines('thr', 'ee\n'), { lines: ['three'], rest: '' })
+ const long = 'x'.repeat(9000)
+ assert.deepEqual(splitLines('', long), { lines: [long], rest: '' })
+ assert.deepEqual(tailLines('a\nb\nc\n', 2), ['b', 'c'])
+})
+
+test('a write that would pass 2 MB goes into a fresh file, three files at most', (t) => {
+ assert.equal(shouldRotate(0, 5 * 1024 * 1024), false)
+ assert.equal(shouldRotate(2 * 1024 * 1024 - 10, 10), false)
+ assert.equal(shouldRotate(2 * 1024 * 1024 - 10, 11), true)
+ assert.deepEqual(logNames(), ['main.log', 'main.1.log', 'main.2.log'])
+ const dir = folder(t)
+ writeFileSync(join(dir, 'main.log'), 'newest\n')
+ writeFileSync(join(dir, 'main.1.log'), 'older\n')
+ writeFileSync(join(dir, 'main.2.log'), 'oldest\n')
+ rotate(dir)
+ assert.deepEqual(readdirSync(dir).sort(), ['main.1.log', 'main.2.log'])
+ assert.equal(readFileSync(join(dir, 'main.1.log'), 'utf8'), 'newest\n')
+ assert.equal(readFileSync(join(dir, 'main.2.log'), 'utf8'), 'older\n')
+})
+
+test('the log rotates by size and its tail reads across the files', (t) => {
+ const dir = folder(t)
+ const log = new LogFile({ dir, limit: 400, redact: windows, now: at })
+ for (let index = 0; index < 40; index += 1) log.write('main', `line ${String(index)} C:\\Users\\测试 用户\n`)
+ log.write('engine', 'partial')
+ log.close()
+ assert.deepEqual(readdirSync(dir).sort(), ['main.1.log', 'main.2.log', 'main.log'])
+ for (const name of logNames()) assert.ok(readFileSync(join(dir, name)).length <= 400, name)
+ const last = readFileSync(join(dir, 'main.log'), 'utf8').trim().split('\n').at(-1)
+ assert.equal(last, '2026-10-28T08:00:00.000Z [engine] partial')
+ const tail = log.tail(12)
+ assert.equal(tail.length, 12)
+ assert.equal(tail.at(-2), '2026-10-28T08:00:00.000Z [main] line 39 %USERPROFILE%')
+ assert.ok(tail.every(line => !line.includes('测试')))
+})
+
+test('a log that cannot be written does not stop the app', (t) => {
+ const dir = folder(t)
+ const blocked = join(dir, 'file')
+ writeFileSync(blocked, '')
+ const log = new LogFile({ dir: join(blocked, 'logs'), now: at })
+ log.write('main', 'lost\n')
+ assert.deepEqual(log.tail(5), [])
+ assert.equal(existsSync(join(blocked, 'logs')), false)
+})
+
+test('the console goes on as before and into the log', (t) => {
+ const dir = folder(t)
+ const log = new LogFile({ dir, redact: windows, now: at })
+ const seen = []
+ const stream = { write: (chunk) => { seen.push(String(chunk)); return true } }
+ const raw = captureStdio(log, { stdout: stream })
+ stream.write('hello sk-test-ok\n')
+ stream.write(Buffer.from('bytes\n'))
+ raw.stdout('only the console\n')
+ log.close()
+ assert.deepEqual(seen, ['hello sk-test-ok\n', 'bytes\n', 'only the console\n'])
+ assert.equal(readFileSync(join(dir, 'main.log'), 'utf8'), '2026-10-28T08:00:00.000Z [main] hello sk-<hidden>\n2026-10-28T08:00:00.000Z [main] bytes\n')
+})
diff --git a/app/test/start-page.test.mjs b/app/test/start-page.test.mjs
index bac93ba0..de8e7542 100644
--- a/app/test/start-page.test.mjs
+++ b/app/test/start-page.test.mjs
@@ -3,6 +3,7 @@ import { spawnSync } from 'node:child_process'
import { existsSync, readFileSync } from 'node:fs'
import { test } from 'node:test'
import { fileURLToPath } from 'node:url'
+import { START_ACTS } from '../src/start-window.mjs'
import { TEXT, t } from '../src/start/text.mjs'
const dir = new URL('../src/start/', import.meta.url)
@@ -62,6 +63,8 @@ test('the page sends only the acts of the start window', () => {
...[...code['whale.js'].matchAll(/\bact\('(\w+)'\)/gu)].map(match => match[1]),
].filter(name => !local.has(name)))
assert.deepEqual([...sent].sort(), ['answer', 'copyDetails', 'freshStart', 'handoffDone', 'handoffShow', 'importModel', 'importOption', 'installUpdate', 'keepCopying', 'manualDownload', 'openLogs', 'pick', 'reloadView', 'retry', 'stopCopy', 'wait'])
+ // Every act the main process takes is one that the page sends, under the same name.
+ for (const name of START_ACTS) assert.ok(sent.has(name), `the main process takes ${name}, which the page never sends`)
})
test('zh and en carry the same keys and the same placeholders', () => {
diff --git a/app/test/start-window.test.mjs b/app/test/start-window.test.mjs
new file mode 100644
index 00000000..acfa8885
--- /dev/null
+++ b/app/test/start-window.test.mjs
@@ -0,0 +1,217 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { readStartFrame, writeStartFrame } from '../src/start-frame.mjs'
+import {
+ acceptsAct, centred, clampInto, clockMs, cubicBezier, detailsText, explainOf, failureReason, fallbackMs, GROWTH, GROWTH_EASING,
+ growthSteps, isStartPage, MAIN_SIZE, mainRect, START_ACTS, startSize, startSnapshot, startUrl,
+} from '../src/start-window.mjs'
+
+const AREA = { x: 0, y: 0, width: 1920, height: 1040 }
+
+test('the start window is 720 × 540, and 720 × 500 on a work area under 588 high', () => {
+ assert.deepEqual(startSize(AREA), { width: 720, height: 540 })
+ assert.deepEqual(startSize({ ...AREA, height: 588 }), { width: 720, height: 540 })
+ assert.deepEqual(startSize({ ...AREA, height: 587 }), { width: 720, height: 500 })
+})
+
+test('the start window is centred on the work area under the cursor', () => {
+ assert.deepEqual(centred(startSize(AREA), AREA), { x: 600, y: 250, width: 720, height: 540 })
+ // A second display left of the first, below a taskbar at the top.
+ assert.deepEqual(centred({ width: 720, height: 540 }, { x: -1280, y: 40, width: 1280, height: 984 }), { x: -1000, y: 262, width: 720, height: 540 })
+})
+
+test('the team window is centred on the start window and stays inside the work area', () => {
+ const start = centred(startSize(AREA), AREA)
+ assert.deepEqual(mainRect(start, AREA), { x: 300, y: 90, ...MAIN_SIZE })
+ // Dragged to the top left corner: the team window keeps to the work area.
+ assert.deepEqual(mainRect({ x: 10, y: 5, width: 720, height: 540 }, AREA), { x: 0, y: 0, ...MAIN_SIZE })
+ assert.deepEqual(mainRect({ x: 1190, y: 495, width: 720, height: 540 }, AREA), { x: 600, y: 180, ...MAIN_SIZE })
+ // A laptop's work area smaller than the team window: it fills the work area.
+ assert.deepEqual(mainRect({ x: 323, y: 94, width: 720, height: 540 }, { x: 0, y: 0, width: 1366, height: 728 }), { x: 23, y: 0, width: 1320, height: 728 })
+ assert.deepEqual(clampInto({ x: -50, y: 900, width: 2000, height: 300 }, AREA), { x: 0, y: 740, width: 1920, height: 300 })
+})
+
+test('the easing is CSS cubic-bezier()', () => {
+ const ease = cubicBezier(0.25, 0.1, 0.25, 1)
+ assert.ok(Math.abs(ease(0.5) - 0.8024) < 1e-3)
+ assert.equal(GROWTH_EASING(0), 0)
+ assert.equal(GROWTH_EASING(1), 1)
+ let previous = 0
+ for (let step = 1; step <= 100; step += 1) {
+ const value = GROWTH_EASING(step / 100)
+ assert.ok(value >= previous && value <= 1, `at ${String(step)}%`)
+ previous = value
+ }
+ // cubic-bezier(.2, .7, .2, 1) is quick at first: most of the way in the first half.
+ assert.ok(GROWTH_EASING(0.5) > 0.9)
+})
+
+test('the start window grows into the team window in about 14 ms steps over 300 ms', () => {
+ const from = centred(startSize(AREA), AREA)
+ const to = mainRect(from, AREA)
+ const steps = growthSteps(from, to)
+ assert.equal(GROWTH.duration, 300)
+ assert.equal(GROWTH.delay, 160)
+ assert.equal(steps.length, 22)
+ assert.deepEqual(steps.at(-1), { at: 300, rect: to })
+ assert.ok(steps.every((step, index) => index === 0 || step.at > steps[index - 1].at))
+ assert.ok(steps.slice(0, -1).every(step => step.at % 14 === 0))
+ for (const key of ['x', 'y', 'width', 'height']) {
+ const toward = Math.sign(to[key] - from[key])
+ let previous = from[key]
+ for (const { rect } of steps) {
+ assert.ok((rect[key] - previous) * toward >= 0, `${key} turns back`)
+ previous = rect[key]
+ }
+ }
+ // At least one size between the two: a growth, not a jump.
+ assert.ok(steps.some(({ rect }) => rect.width > from.width && rect.width < to.width))
+ // The same rects from wherever the start window was dragged to.
+ const dragged = { x: 40, y: 30, width: 720, height: 540 }
+ assert.deepEqual(growthSteps(dragged, mainRect(dragged, AREA)).at(-1).rect, { x: 0, y: 0, ...MAIN_SIZE })
+})
+
+test('the team window shows by itself after 2.5 s on a first start or a celebration, else 0.8 s', () => {
+ assert.equal(fallbackMs({ start: 'first', celebrate: true }), 2500)
+ assert.equal(fallbackMs({ start: 'first', celebrate: false }), 2500)
+ assert.equal(fallbackMs({ start: 'later', celebrate: true }), 2500)
+ assert.equal(fallbackMs({ start: 'later', celebrate: false }), 800)
+})
+
+test('a failure gets one of the five reasons of the failure page', () => {
+ const coded = (code, message) => Object.assign(new Error(message), { code })
+ assert.equal(failureReason(coded('EACCES', 'EACCES: permission denied, mkdir \'D:\\data\\profiles\'')), 'permission')
+ assert.equal(failureReason(new Error('EPERM: operation not permitted, open \'x\'')), 'permission')
+ assert.equal(failureReason(coded('ENOSPC', 'ENOSPC: no space left on device, write')), 'space')
+ assert.equal(failureReason(new Error('There is not enough space on the disk.')), 'space')
+ assert.equal(failureReason(coded('ENOENT', 'spawn C:\\Program Files\\DeepSeek Bot\\DeepSeek Bot.exe ENOENT')), 'files')
+ assert.equal(failureReason(new Error('The DSH Host stopped (exit 1):\nError: Cannot find module \'@deepseek-ai/dsh-base\'')), 'files')
+ assert.equal(failureReason(new Error('The app could not load its own bundles:\nds-bot: missing')), 'files')
+ assert.equal(failureReason(new Error('The DSH Host stopped (exit 1):\nError: EACCES: permission denied, open \'state.json\'')), 'permission')
+ assert.equal(failureReason(new Error('The DSH Host stopped (exit 3221225477)')), 'engine')
+ assert.equal(failureReason(new Error('The profile in D:\\x does not start the engine\'s web server and connection.')), 'engine')
+ assert.equal(failureReason(new Error('DeepSeek Bot: no free port on 127.0.0.1')), 'other')
+ assert.equal(failureReason('a string'), 'other')
+ assert.equal(failureReason(undefined), 'other')
+})
+
+test('the main process takes only its own acts, each in its own views', () => {
+ assert.deepEqual([...START_ACTS].sort(), ['copyDetails', 'handoffDone', 'handoffShow', 'openLogs', 'reloadView', 'retry', 'wait'])
+ assert.equal(acceptsAct('handoffShow', 'handoff'), true)
+ assert.equal(acceptsAct('handoffShow', 'boot'), false)
+ assert.equal(acceptsAct('handoffDone', 'handoff'), true)
+ assert.equal(acceptsAct('retry', 'failed'), true)
+ assert.equal(acceptsAct('retry', 'watchdog'), true)
+ assert.equal(acceptsAct('retry', 'boot'), false)
+ assert.equal(acceptsAct('retry', 'handoff'), false)
+ assert.equal(acceptsAct('wait', 'watchdog'), true)
+ assert.equal(acceptsAct('wait', 'failed'), false)
+ assert.equal(acceptsAct('reloadView', 'viewFailed'), true)
+ assert.equal(acceptsAct('reloadView', 'failed'), false)
+ for (const view of ['boot', 'failed', 'viewFailed', 'watchdog', 'handoff', 'moving']) {
+ assert.equal(acceptsAct('openLogs', view), true)
+ assert.equal(acceptsAct('copyDetails', view), true)
+ }
+ // The cards of later pull requests, and names that are not acts at all.
+ for (const name of ['reload', 'toggleDetails', 'answer', 'pick', 'freshStart', 'installUpdate', 'manualDownload', 'stopCopy', 'keepCopying', 'importModel', 'importOption', '__proto__', 'constructor', 'toString', '']) {
+ assert.equal(acceptsAct(name, 'failed'), false, name)
+ }
+ assert.equal(acceptsAct(undefined, 'failed'), false)
+ assert.equal(acceptsAct(42, 'failed'), false)
+})
+
+test('acts come only from the start page that was loaded', () => {
+ const page = 'C:\\Program Files\\DeepSeek Bot\\resources\\app.asar\\src\\start\\start.html'
+ const loaded = startUrl(page, 'first')
+ assert.equal(loaded, 'file:///C:/Program%20Files/DeepSeek%20Bot/resources/app.asar/src/start/start.html?start=first')
+ assert.equal(isStartPage(loaded, loaded), true)
+ assert.equal(isStartPage(`${loaded}#x`, loaded), false)
+ assert.equal(isStartPage(loaded.replace('first', 'later'), loaded), false)
+ assert.equal(isStartPage(loaded.replace('start.html', 'other.html'), loaded), false)
+ assert.equal(isStartPage('http://127.0.0.1:52817/src/start/start.html?start=first', loaded), false)
+ assert.equal(isStartPage('not a url', loaded), false)
+ assert.equal(isStartPage(undefined, loaded), false)
+})
+
+const state = (change = {}) => ({
+ lang: 'zh', start: 'first', motion: 'normal', frame: 'band', view: 'boot', done: [], celebrate: true,
+ explain: explainOf(), clock: { base: 0, from: 1000, running: true }, hint: undefined, failure: undefined, ...change,
+})
+
+test('the snapshot carries the phase, the stages done and the clock', () => {
+ const now = 1_700_000_000_000
+ const booting = startSnapshot(state({ clock: { base: 0, from: now - 6400, running: true } }), now)
+ assert.deepEqual(booting, {
+ v: 1, lang: 'zh', start: 'first', motion: 'normal', frame: 'band', view: 'boot', phase: 'data', done: [],
+ clock: { ms: 6400, at: now, running: true, rate: 1 },
+ explain: { mode: 'new', nextStep: true, previewNotice: false }, celebrate: true,
+ })
+ assert.equal(startSnapshot(state({ done: ['data'] }), now).phase, 'engine')
+ const ready = startSnapshot(state({ view: 'handoff', done: ['team', 'data', 'engine'] }), now)
+ assert.equal(ready.phase, 'team')
+ assert.deepEqual(ready.done, ['data', 'engine', 'team'])
+ // A paused clock (a dialog, the 180 s question, a failure) stays where it stopped.
+ assert.deepEqual(startSnapshot(state({ view: 'watchdog', clock: { base: 180_000, from: 5, running: false } }), now).clock, { ms: 180_000, at: now, running: false, rate: 1 })
+ assert.equal(clockMs({ base: 1000, from: now - 500, running: true }, now), 1500)
+ assert.equal(clockMs({ base: 1000, from: now + 500, running: true }, now), 1000)
+ const failed = startSnapshot(state({ view: 'failed', failure: { reason: 'engine', log: ['a', 'b'] } }), now)
+ assert.deepEqual(failed.failure, { reason: 'engine', log: ['a', 'b'] })
+ assert.equal('card' in failed, false)
+ assert.equal('hint' in failed, false)
+ assert.deepEqual(startSnapshot(state({ hint: { drive: 'C', free: '1.2 GB' } }), now).hint, { drive: 'C', free: '1.2 GB' })
+ // The page gets copies: it cannot change the main process's state.
+ const source = state({ failure: { reason: 'other', log: ['x'] } })
+ const sent = startSnapshot(source, now)
+ sent.explain.mode = 'import'
+ sent.failure.log.push('y')
+ assert.equal(source.explain.mode, 'new')
+ assert.deepEqual(source.failure.log, ['x'])
+})
+
+test('what the hint row can prepare for: a new team, a reinstall or an import', () => {
+ assert.deepEqual(explainOf(), { mode: 'new', nextStep: true, previewNotice: false })
+ assert.deepEqual(explainOf({ team: { bots: 6, rooms: 2 } }), { mode: 'reinstall', bots: 6, groups: 2, nextStep: false, previewNotice: false })
+ assert.deepEqual(explainOf({ offered: true }), { mode: 'import', nextStep: false, previewNotice: false })
+ assert.deepEqual(explainOf({ offered: true, team: { bots: 1, rooms: 0 } }).mode, 'import')
+ // The greeting names the kept team's first Main Bot; without a readable name it names none.
+ const state = { mainBotIds: ['b2', 'b1'], bots: { b1: { name: 'Chief' }, b2: { name: ' Ada ' } } }
+ assert.equal(explainOf({ team: { bots: 2, rooms: 0, team: state } }).name, 'Ada')
+ assert.equal(explainOf({ team: { bots: 1, rooms: 0, team: { mainBotId: 'b1', bots: state.bots } } }).name, 'Chief')
+ assert.equal(Object.hasOwn(explainOf({ team: { bots: 1, rooms: 0, team: { mainBotIds: ['gone'], bots: {} } } }), 'name'), false)
+ assert.equal(Object.hasOwn(explainOf({ team: { bots: 1, rooms: 0, team: { mainBotIds: ['b1'], bots: { b1: { name: ' ' } } } } }), 'name'), false)
+})
+
+test('the copied details name the version and the reason before the log', () => {
+ assert.equal(detailsText({ version: '0.2.2', platform: 'win32', arch: 'x64', reason: 'engine', lines: ['l1', 'l2'] }), 'DeepSeek Bot 0.2.2 (win32 x64)\nreason: engine\n\nl1\nl2')
+})
+
+test('the start window remembers the theme and the motion tier in its own file', (t) => {
+ const dir = mkdtempSync(join(tmpdir(), 'ds-bot-start-frame-'))
+ t.after(() => { rmSync(dir, { recursive: true, force: true }) })
+ const file = join(dir, 'start-frame.json')
+ assert.deepEqual(readStartFrame(file), { themeSource: 'system', motion: 'normal' })
+ assert.equal(writeStartFrame(file, { themeSource: 'dark' }), true)
+ assert.equal(writeStartFrame(file, { themeSource: 'dark' }), false)
+ assert.equal(writeStartFrame(file, { motion: 'lively', themeSource: 'moonlight' }), true)
+ assert.deepEqual(readStartFrame(file), { themeSource: 'dark', motion: 'lively' })
+ assert.deepEqual(readdirSync(dir), ['start-frame.json'])
+ writeFileSync(file, '{"themeSource":"neon","motion":7}')
+ assert.deepEqual(readStartFrame(file), { themeSource: 'system', motion: 'normal' })
+ writeFileSync(file, 'not json')
+ assert.deepEqual(readStartFrame(file), { themeSource: 'system', motion: 'normal' })
+})
+
+// Onboarding acceptance: no dialog during the first start without a window it belongs to.
+test('every dialog belongs to a window', () => {
+ const src = new URL('../src/', import.meta.url)
+ const files = readdirSync(src).filter(name => /\.m?js$/u.test(name))
+ const loose = files.flatMap((name) => {
+ const code = readFileSync(new URL(name, src), 'utf8')
+ return [...code.matchAll(/dialog\.(show\w+)\(\s*(\{|\))/gu)].map(match => `${name}: dialog.${match[1]}`)
+ })
+ assert.deepEqual(loose, [])
+ assert.ok(files.every(name => !readFileSync(new URL(name, src), 'utf8').includes('showErrorBox')))
+})