A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Guard a restarted engine and a failed hand-off in the start window
AdamPlatin12314727476c593
diff --git a/app/src/start-window.mjs b/app/src/start-window.mjsindex 0c6526b9..655a4a05 100644--- a/app/src/start-window.mjs+++ b/app/src/start-window.mjs@@ -4,6 +4,7 @@// 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'+import { within } from './copy-tree.mjs'export const START_STATE = 'ds-bot:start-state'export const START_ACT = 'ds-bot:start-act'@@ -141,16 +142,30 @@ export const fallbackMs = ({ start, celebrate }) => (start === 'first' || celebrconst 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],+ ['files', /\b(?: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) {+// Only a missing file of the program's own says that the install is incomplete: a data folder+// on a drive that is gone is missing too, and so is a workspace.+function missingOwnFile(error, text, program) {+ if (!/\bENOENT\b/u.test(text)) return false+ const paths = [error?.path, ...[...text.matchAll(/ENOENT: [^,\n]*, \w+ '([^'\n]+)'/gu)].map(match => match[1])]+ return paths.some(path => typeof path === 'string' && program.some(folder => within(path, folder)))+}++/**+ * @param {{ program?: string[] }} where `program`: the folders of the app's own files+ * @returns {'permission' | 'space' | 'files' | 'engine' | 'other'}+ */+export function failureReason(error, { program = [] } = {}) {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'+ for (const [reason, pattern] of REASONS) {+ if (pattern.test(text) || (reason === 'files' && missingOwnFile(error, text, program))) return reason+ }+ return 'other'}// The Main Bot that a kept team's sidebar shows first (ds-bot's channel.js: mainBotIds[0]; an@@ -161,17 +176,17 @@ export function mainBotName(state) {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.+// What the hint row can prepare for. 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), which a data folder without a team always has. A kept or copied team may have+// read it already, and the main process cannot tell before the team view has loaded.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 }+ return { mode: 'new', nextStep: true, previewNotice: true }}export const clockMs = (clock, now) => clock.base + (clock.running ? Math.max(0, now - clock.from) : 0)@@ -217,20 +232,26 @@ export class StartWindow {#from#handing = false#revealed = false+ // Whether the engine of this attempt is up; the stages done say where the whale is, which a+ // retry never moves back.+ #engineUp = false+ #teamShown+ #showTeam/*** @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,+ * lang: () => 'zh' | 'en', motion: string, version: string, program: string[],* log: { dir: string, tail: (count: number) => string[] },* mainWindow: () => any,* onRetry: () => void, onReload: () => void, onClose: () => void,- * }} options `lang` is asked at each open; `onClose` runs when the user closes the start window- * before the hand-off.+ * }} options `lang` is asked at each open; `program` names the folders of the app's own files;+ * `onClose` runs when the user closes the start window before the hand-off.*/constructor(options) {this.#o = options+ this.#teamShown = new Promise((resolve) => { this.#showTeam = resolve })options.electron.ipcMain.handle(START_ACT, (event, name, payload) => this.#act(event, name, payload))}@@ -239,6 +260,9 @@ export class StartWindow {/** Settles once the current window has painted its first frame (or has had time to). */get painted() { return this.#painted }+ /** Settles once the team window has shown at a hand-off. */+ get teamShown() { return this.#teamShown }+/** Opens the window, unless one is open, with a fresh state for this kind of start. */open(kind) {if (this.#open()) return@@ -342,13 +366,16 @@ export class StartWindow {}}- /** The data folder or the engine is ready. */+ /** The data folder or the engine is ready; the engine also again after a retry. */done(phase) {- if (!this.#open() || this.#state.done.includes(phase) || !['data', 'engine'].includes(phase)) return+ if (!this.#open() || !['data', 'engine'].includes(phase)) return+ const again = this.#state.done.includes(phase)+ if (again && (phase !== 'engine' || this.#engineUp)) return+ if (phase === 'engine') this.#engineUp = truenote(`${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' } : {}) })+ this.#update({ ...(again ? {} : { 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(). */@@ -363,7 +390,7 @@ export class StartWindow {/** 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+ if (!this.#open() || !['boot', 'viewFailed'].includes(this.#state.view) || !this.#engineUp) returnthis.#clear('teamView')const now = Date.now()note(`team took ${String(now - this.#phaseAt)} ms`)@@ -383,6 +410,9 @@ export class StartWindow {*/fail(error, kind = 'later') {const showing = this.#revealed+ // The page's hand-off empties it for the growth and cannot be undone there: a fresh page+ // draws the failure.+ const emptied = !showing && this.#open() && this.#state.view === 'handoff'if (showing) {this.#destroy()const main = this.#o.mainWindow()@@ -392,7 +422,8 @@ export class StartWindow {this.#cancelHandoff()this.#clear('teamView')this.#clear('fallback')- this.#update({ view: 'failed', failure: { reason: failureReason(error), log: this.#o.log.tail(FAILURE_LINES) } })+ this.#update({ view: 'failed', failure: { reason: failureReason(error, { program: this.#o.program }), log: this.#o.log.tail(FAILURE_LINES) } })+ if (emptied) this.#window.webContents.reload()}/** The team window's rect: centred on the start window, inside that display's work area. */@@ -422,6 +453,7 @@ export class StartWindow {this.#clearTimers()this.#handing = falsethis.#revealed = false+ this.#engineUp = falsethis.#watchAt = WATCHDOG_MSconst now = Date.now()this.#phaseAt = now@@ -457,8 +489,8 @@ export class StartWindow {// 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+ const { start, view, clock } = this.#state+ if (start === 'moving' || view !== 'boot' || !clock.running || this.#engineUp) returnthis.#later('watchdog', this.#watchAt - clockMs(clock, Date.now()), () => {note(`no engine after ${String(Math.round(this.#watchAt / 1000))} s`)this.#update({ view: 'watchdog' })@@ -484,9 +516,11 @@ export class StartWindow {}// 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).+ // done stay done, and the first success after this celebrates (§7). The engine starts again+ // in any case, so the 180 s question guards it again.#retry() {note(`retry from ${this.#state.view}`)+ this.#engineUp = falsethis.#watchAt = WATCHDOG_MSthis.#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 } })@@ -556,6 +590,7 @@ export class StartWindow {const main = this.#o.mainWindow()if (main === undefined || main.isDestroyed()) returnthis.#revealed = true+ this.#showTeam()this.#clear('fallback')this.#clear('grow')const win = this.#windowdiff --git a/app/src/start/start.js b/app/src/start/start.jsindex 926f6b88..994951f9 100644--- a/app/src/start/start.js+++ b/app/src/start/start.js@@ -76,7 +76,7 @@ const FADE_MS = 160const catchUp = resume ? performance.now() + 1000 : 0// key/text: the line chosen (on screen, or coming in once the old one has faded out); shown/at:// the line on screen and when it went up; last: the last line that really went up.-const v = { key: '', text: '', shown: '', at: 0, timer: 0, swap: 0, last: '', cards: false, readyAt: 0, waiters: [] }+const v = { key: '', text: '', shown: '', at: 0, timer: 0, swap: 0, renaming: false, last: '', cards: false, readyAt: 0, waiters: [] }const readyLine = () => (v.readyAt ? Promise.resolve(v.readyAt) : new Promise(resolve => v.waiters.push(resolve)))function voiceWant() {const view = s.view@@ -106,9 +106,9 @@ function voiceWant() {}// The greeting names the Main Bot the user is about to meet: the team's own on a reinstall, the// default name for a new team. A team to import has no name yet (the answer decides which Main-// Bot it is), and neither has a reinstall whose name could not be read. It stays one line+// Bot it is), and neither has a reinstall whose name could not be read. It stays one key// (voice.hello) whichever words it takes: the main process may learn the team after the window-// opens, and the greeting on screen then changes in place.+// opens, and the greeting on screen then fades over to the new words as a new line.function greeting() {const e = s.explain ?? {}if (e.mode === 'import' || (e.mode === 'reinstall' && !e.name)) return say('voice.helloBack')@@ -117,15 +117,19 @@ function greeting() {function speak() {clearTimeout(v.timer)if (!s) return- if (v.key === 'voice.hello' && v.shown === 'voice.hello' && !v.swap && greeting() !== v.text) {+ const [key, urgent] = voiceWant()+ if (!urgent && v.key === 'voice.hello' && v.shown === 'voice.hello' && !v.swap && voiceEl.hasAttribute('data-on') && greeting() !== v.text) {v.text = greeting()- voiceText.textContent = v.text+ delete voiceEl.dataset.on+ // The new greeting has not been read yet: no other line takes its place while it fades in.+ v.renaming = true+ v.swap = setTimeout(() => { v.renaming = false; put(); speak() }, reduced() ? 120 : FADE_MS)+ return}- const [key, urgent] = voiceWant()const text = key === 'voice.hello' ? greeting() : key ? say(key) : ''if (key === v.key) { if (text !== v.text) { v.text = text; if (!v.swap) voiceText.textContent = text } return }// The old line is already fading out: the new choice simply takes its place.- if (v.swap) { v.key = key; v.text = text; return }+ if (v.swap) { if (!v.renaming) { v.key = key; v.text = text } return }const hold = urgent ? 0 : key === 'voice.ready' ? READ_MS : HOLDS[v.shown] ?? HOLD_MSconst left = v.shown ? v.at + hold - performance.now() : 0if (left > 0) { v.timer = setTimeout(speak, left); return }diff --git a/app/test/start-window.test.mjs b/app/test/start-window.test.mjsindex acfa8885..404207ca 100644--- a/app/test/start-window.test.mjs+++ b/app/test/start-window.test.mjs@@ -1,4 +1,5 @@import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'import { mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'@@ -6,7 +7,8 @@ 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,+ growthSteps, isStartPage, MAIN_SIZE, mainRect, START_ACT, START_ACTS, START_STATE, startSize, startSnapshot, startUrl, StartWindow,+ TEAM_VIEW_MS, WATCHDOG_MS,} from '../src/start-window.mjs'const AREA = { x: 0, y: 0, width: 1920, height: 1040 }@@ -87,7 +89,6 @@ test('a failure gets one of the five reasons of the failure page', () => {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')@@ -98,6 +99,22 @@ test('a failure gets one of the five reasons of the failure page', () => {assert.equal(failureReason(undefined), 'other')})+test('only a missing file of the app\'s own says that the install is incomplete', () => {+ const program = join(tmpdir(), 'DeepSeek Bot')+ const where = { program: [join(tmpdir(), 'electron'), program] }+ const missing = (path, message) => Object.assign(new Error(message), { code: 'ENOENT', path })+ const exe = join(program, 'DeepSeek Bot.exe')+ assert.equal(failureReason(missing(exe, `spawn ${exe} ENOENT`), where), 'files')+ assert.equal(failureReason(missing(exe, `spawn ${exe} ENOENT`)), 'other')+ // A saved data folder on a drive that is gone.+ const data = join(tmpdir(), 'gone', 'DeepSeek Bot', 'data', 'profiles', 'ds-bot')+ assert.equal(failureReason(missing(data, `ENOENT: no such file or directory, mkdir '${data}'`), where), 'other')+ // A Host that stopped: its error output names the missing file.+ const bundle = join(program, 'resources', 'app.asar.unpacked', 'node_modules', 'x', 'index.js')+ assert.equal(failureReason(new Error(`The DSH Host stopped (exit 1):\nError: ENOENT: no such file or directory, open '${bundle}'`), where), 'files')+ assert.equal(failureReason(new Error(`The DSH Host stopped (exit 1):\nError: ENOENT: no such file or directory, open '${join(data, 'state.json')}'`), where), 'engine')+})+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)@@ -147,7 +164,7 @@ test('the snapshot carries the phase, the stages done and the clock', () => {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,+ explain: { mode: 'new', nextStep: true, previewNotice: true }, celebrate: true,})assert.equal(startSnapshot(state({ done: ['data'] }), now).phase, 'engine')const ready = startSnapshot(state({ view: 'handoff', done: ['team', 'data', 'engine'] }), now)@@ -172,7 +189,8 @@ test('the snapshot carries the phase, the stages done and the clock', () => {})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 })+ // DSH shows its preview notice on a data folder without a team, which has no Session yet.+ assert.deepEqual(explainOf(), { mode: 'new', nextStep: true, previewNotice: true })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')@@ -215,3 +233,299 @@ test('every dialog belongs to a window', () => {assert.deepEqual(loose, [])assert.ok(files.every(name => !readFileSync(new URL(name, src), 'utf8').includes('showErrorBox')))})++// Just enough of Electron for StartWindow: windows that record what is done to them, and the+// start page's act channel.+function fakeElectron() {+ const windows = []+ let act+ class Contents extends EventEmitter {+ sent = []+ reloads = 0+ mainFrame = { url: '' }+ send(channel, state) { if (channel === START_STATE) this.sent.push(state) }+ setWindowOpenHandler() {}+ toggleDevTools() {}+ reload() { this.reloads += 1; this.emit('dom-ready') }+ }+ class Window extends EventEmitter {+ webContents = new Contents()+ calls = []+ destroyed = false+ minimized = false+ focused = true+ constructor({ x = 0, y = 0, width = 800, height = 600, show = true } = {}) {+ super()+ this.bounds = { x, y, width, height }+ this.visible = show+ windows.push(this)+ }+ loadURL(url) { this.webContents.mainFrame.url = url; return Promise.resolve() }+ setContentBounds(rect) { this.bounds = { ...rect } }+ setBounds(rect) { this.bounds = { ...rect }; this.calls.push('setBounds') }+ getBounds() { return { ...this.bounds } }+ getNormalBounds() { return { ...this.bounds } }+ isDestroyed() { return this.destroyed }+ destroy() { if (!this.destroyed) { this.destroyed = true; this.emit('closed') } }+ isMinimized() { return this.minimized }+ isFocused() { return this.focused }+ restore() { this.minimized = false }+ minimize() { this.minimized = true; this.calls.push('minimize') }+ show() { this.visible = true; this.calls.push('show') }+ showInactive() { this.visible = true; this.calls.push('showInactive') }+ hide() { this.visible = false; this.calls.push('hide') }+ focus() { this.calls.push('focus') }+ flashFrame(on) { this.calls.push(`flash ${String(on)}`) }+ setSkipTaskbar(skip) { this.calls.push(`skipTaskbar ${String(skip)}`) }+ setTitleBarOverlay() {}+ setBackgroundColor() {}+ getMediaSourceId() { return 'window:1:0' }+ moveAbove() {}+ }+ const display = { workArea: AREA }+ const electron = {+ BrowserWindow: Window,+ ipcMain: { handle: (channel, handler) => { if (channel === START_ACT) act = handler } },+ screen: { getCursorScreenPoint: () => ({ x: 10, y: 10 }), getDisplayNearestPoint: () => display, getDisplayMatching: () => display, getPrimaryDisplay: () => display },+ shell: { openPath: async () => '' },+ clipboard: { writeText() {} },+ nativeTheme: Object.assign(new EventEmitter(), { shouldUseDarkColors: false }),+ systemPreferences: { getAnimationSettings: () => ({ prefersReducedMotion: false }) },+ }+ return { electron, windows, act: (event, name, payload) => act(event, name, payload) }+}++function startWindow(t) {+ t.mock.timers.enable({ apis: ['setTimeout', 'Date'], now: 1_000_000 })+ t.mock.method(console, 'log', () => {})+ const fake = fakeElectron()+ const main = new fake.electron.BrowserWindow({ show: false })+ const calls = { retry: 0, reload: 0, close: 0 }+ const start = new StartWindow({+ electron: fake.electron, page: join(tmpdir(), 'start', 'start.html'), preload: 'preload.cjs', icon: 'icon.ico', mica: false, devTools: false,+ lang: () => 'en', motion: 'normal', version: '0.0.0', program: [], log: { dir: 'logs', tail: () => ['a log line'] },+ mainWindow: () => main,+ onRetry: () => { calls.retry += 1 }, onReload: () => { calls.reload += 1 }, onClose: () => { calls.close += 1 },+ })+ const win = () => fake.windows.at(-1)+ const page = () => ({ sender: win().webContents, senderFrame: win().webContents.mainFrame })+ return {+ start, main, calls, win,+ tick: (ms) => { t.mock.timers.tick(ms) },+ state: () => win().webContents.sent.at(-1),+ act: (name, payload, event = page()) => fake.act(event, name, payload),+ other: () => new fake.electron.BrowserWindow(),+ }+}++test('the start window takes acts only from its own page, each in its own view', (t) => {+ const s = startWindow(t)+ s.start.open('first')+ const own = s.win()+ const ownFrame = { sender: own.webContents, senderFrame: own.webContents.mainFrame }+ const other = s.other()+ assert.equal(s.act('openLogs', undefined, { sender: other.webContents, senderFrame: other.webContents.mainFrame }), false)+ assert.equal(s.act('openLogs', undefined, { sender: own.webContents, senderFrame: { url: own.webContents.mainFrame.url } }), false)+ const loaded = own.webContents.mainFrame.url+ own.webContents.mainFrame.url = loaded.replace('first', 'later')+ assert.equal(s.act('openLogs', undefined, ownFrame), false)+ own.webContents.mainFrame.url = loaded+ assert.equal(s.act('openLogs', undefined, ownFrame), true)+ assert.equal(s.act('retry', undefined, ownFrame), false)+ assert.equal(s.act('freshStart', undefined, ownFrame), false)+ assert.equal(s.calls.retry, 0)+})++test('the 180 s question comes on the start\'s clock while the engine is not up', async (t) => {+ const s = startWindow(t)+ s.start.open('first')+ s.start.done('data')+ // A dialog stops the clock: the user's thinking time is not the engine's.+ let answer+ const asked = s.start.asking(new Promise((resolve) => { answer = resolve }))+ s.tick(WATCHDOG_MS)+ assert.equal(s.state().view, 'boot')+ answer()+ await asked+ s.tick(WATCHDOG_MS - 1)+ assert.equal(s.state().view, 'boot')+ s.tick(1)+ assert.equal(s.state().view, 'watchdog')+ assert.equal(s.state().clock.running, false)+ // 〔继续等待〕: another 180 s on the clock.+ assert.equal(s.act('wait'), true)+ assert.equal(s.state().view, 'boot')+ s.tick(WATCHDOG_MS - 1)+ assert.equal(s.state().view, 'boot')+ s.tick(1)+ assert.equal(s.state().view, 'watchdog')+ // The engine comes up meanwhile: the question goes, and does not come back.+ s.start.done('engine')+ assert.equal(s.state().view, 'boot')+ assert.deepEqual(s.state().done, ['data', 'engine'])+ s.tick(2 * WATCHDOG_MS)+ assert.equal(s.state().view, 'boot')+})++test('a retry after the engine was up guards the new engine, while the whale keeps its stop', (t) => {+ const s = startWindow(t)+ s.start.open('first')+ s.start.done('data')+ s.start.done('engine')+ s.start.teamLoading()+ s.start.fail(new Error('The DSH Host stopped (exit 1)'))+ assert.equal(s.state().view, 'failed')+ assert.equal(s.state().failure.reason, 'engine')+ assert.equal(s.act('retry'), true)+ assert.equal(s.calls.retry, 1)+ assert.deepEqual(s.state().done, ['data', 'engine'])+ assert.equal(s.state().phase, 'team')+ // The old team view cannot hand over before the new engine is up.+ s.start.ready()+ assert.equal(s.state().view, 'boot')+ s.tick(WATCHDOG_MS)+ assert.equal(s.state().view, 'watchdog')+ assert.equal(s.act('retry'), true)+ s.start.done('engine')+ s.tick(2 * WATCHDOG_MS)+ assert.equal(s.state().view, 'boot')+ s.start.ready()+ assert.equal(s.state().view, 'handoff')+ // The first success after a retry celebrates.+ assert.equal(s.state().celebrate, true)+})++test('the team view has 20 s to call ready(); a late ready() hands over without a celebration', (t) => {+ const s = startWindow(t)+ s.start.open('first')+ s.start.done('data')+ s.start.done('engine')+ s.start.teamLoading()+ s.tick(TEAM_VIEW_MS - 1)+ assert.equal(s.state().view, 'boot')+ s.tick(1)+ assert.equal(s.state().view, 'viewFailed')+ assert.deepEqual(s.state().failure, { reason: 'other', log: ['a log line'] })+ // 〔重新载入〕: the hidden team view loads again and has another 20 s.+ assert.equal(s.act('reloadView'), true)+ assert.equal(s.calls.reload, 1)+ assert.equal(s.state().view, 'boot')+ s.tick(TEAM_VIEW_MS)+ assert.equal(s.state().view, 'viewFailed')+ s.start.ready()+ assert.equal(s.state().view, 'handoff')+ assert.equal(s.state().celebrate, false)+ assert.equal('failure' in s.state(), false)+})++for (const [kind, wait] of [['first', 2500], ['later', 800]]) {+ test(`without handoffShow the team window shows by itself after ${String(wait)} ms on a ${kind} start`, async (t) => {+ const s = startWindow(t)+ s.start.open(kind)+ s.start.done('data')+ s.start.done('engine')+ s.start.ready()+ s.tick(wait - 1)+ assert.equal(s.main.visible, false)+ s.tick(1)+ assert.equal(s.main.visible, true)+ assert.deepEqual(s.main.calls.slice(-2), ['show', 'focus'])+ assert.ok(s.win().calls.includes('skipTaskbar true'))+ await s.start.teamShown+ s.tick(300)+ assert.equal(s.win().destroyed, true)+ // Gone after the hand-off, the start window does not quit the app.+ assert.equal(s.calls.close, 0)+ })+}++test('after handoffShow the start window grows into the team window\'s rect, and the team window shows on it', (t) => {+ const s = startWindow(t)+ s.start.open('later')+ s.start.done('data')+ s.start.done('engine')+ s.start.ready()+ const from = s.win().getBounds()+ assert.equal(s.act('handoffShow'), true)+ const target = mainRect(from, AREA)+ assert.deepEqual(s.main.bounds, target)+ s.tick(GROWTH.delay - 1)+ assert.deepEqual(s.win().bounds, from)+ s.tick(1)+ const widths = []+ for (let step = 0; step < 40 && !s.main.visible; step += 1) {+ s.tick(GROWTH.step)+ widths.push(s.win().bounds.width)+ }+ assert.equal(s.main.visible, true)+ assert.deepEqual(s.win().bounds, target)+ assert.ok(widths.some(width => width > from.width && width < target.width), 'the start window jumps instead of growing')+ // A second handoffShow does nothing.+ assert.equal(s.act('handoffShow'), true)+ assert.equal(s.main.calls.filter(call => call === 'show').length, 1)+})++for (const how of ['behind', 'minimized']) {+ test(`the team window comes up ${how} when the start window is`, (t) => {+ const s = startWindow(t)+ s.start.open('later')+ if (how === 'behind') s.win().focused = false+ else s.win().minimized = true+ s.start.done('data')+ s.start.done('engine')+ s.start.ready()+ s.act('handoffShow')+ for (let step = 0; step < 60 && !s.main.calls.includes('flash true'); step += 1) s.tick(GROWTH.step)+ assert.deepEqual(s.main.calls.slice(-2), [how === 'behind' ? 'showInactive' : 'minimize', 'flash true'])+ assert.equal(s.main.calls.includes('focus'), false)+ })+}++test('closing the start window before the hand-off quits, and its timers go with it', (t) => {+ const s = startWindow(t)+ s.start.open('first')+ s.start.done('data')+ const sent = s.win().webContents.sent.length+ s.win().destroy()+ assert.equal(s.calls.close, 1)+ s.tick(WATCHDOG_MS + TEAM_VIEW_MS)+ assert.equal(s.win().webContents.sent.length, sent)+ assert.equal(s.start.owner(), undefined)+})++test('a failure during the hand-off draws the failure page on a fresh page', (t) => {+ const s = startWindow(t)+ s.start.open('first')+ s.start.done('data')+ s.start.done('engine')+ s.start.ready()+ s.act('handoffShow')+ s.tick(GROWTH.delay + GROWTH.step)+ s.start.fail(new Error('The DSH Host stopped (exit 1)'))+ assert.equal(s.state().view, 'failed')+ assert.equal(s.win().webContents.reloads, 1)+ // The growth is undone, and the team window stays hidden.+ assert.deepEqual(s.win().bounds, centred(startSize(AREA), AREA))+ s.tick(5000)+ assert.equal(s.main.visible, false)+ assert.equal(s.act('handoffShow'), false)+})++test('a failure after the hand-off opens a fresh start window over the hidden team window', (t) => {+ const s = startWindow(t)+ s.start.open('first')+ s.start.done('data')+ s.start.done('engine')+ s.start.ready()+ s.tick(2500)+ const handed = s.win()+ assert.equal(s.main.visible, true)+ s.start.fail(new Error('The DSH Host stopped (exit 1)'), 'later')+ assert.equal(handed.destroyed, true)+ assert.notEqual(s.win(), handed)+ assert.equal(s.main.visible, false)+ assert.equal(s.state().view, 'failed')+ assert.equal(s.state().start, 'later')+ assert.equal(s.start.owner(), s.win())+ assert.equal(s.calls.close, 0)+})