Skip to content

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

Say on the moving page why a data move did not go through

AdamPlatin12327a6f430d370
diff --git a/app/src/copy-tree.mjs b/app/src/copy-tree.mjs
index bad02c38..b4f5789d 100644
--- a/app/src/copy-tree.mjs
+++ b/app/src/copy-tree.mjs
@@ -8,6 +8,19 @@ export const within = (inner, outer) => {
return path === '' || (!path.startsWith('..') && !path.startsWith(sep) && !/^[a-z]:/iu.test(path))
}
+/**
+ * Why a copy failed, in the words of the start page's cards (reason.copy.*); the rest goes into
+ * the details.
+ * @returns {'inUse' | 'permission' | 'full' | 'other'}
+ */
+export function copyReason(error) {
+ const code = typeof error?.code === 'string' ? error.code : ''
+ if (code === 'EBUSY') return 'inUse'
+ if (code === 'EACCES' || code === 'EPERM') return 'permission'
+ if (code === 'ENOSPC' || code === 'EDQUOT') return 'full'
+ return 'other'
+}
+
// The path as the file system has it: through links and junctions, from the deepest part that
// exists. A link can make a path that looks apart from a folder lead into it.
export function real(path) {
diff --git a/app/src/main.mjs b/app/src/main.mjs
index e920269a..37cc37ac 100644
--- a/app/src/main.mjs
+++ b/app/src/main.mjs
@@ -65,7 +65,7 @@ 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, defaultPlaces, pickRoot, programFolder, saveLocations, teamIn, teamsAt, tx, HostProcess
-let copySessions, findTeam, importTeam, teamInUse, userDshHome, copyData, moveProblem, CHECK_PROFILE, PROFILE
+let copySessions, findTeam, importTeam, teamInUse, userDshHome, copyData, copyReason, moveProblem, CHECK_PROFILE, PROFILE
let watchReleases, watchUpdates, getDshRuntimeVersion, electronUpdater
let mainWindow
@@ -93,6 +93,8 @@ let picking = false
let proposed
// The folder a later start's move card asks about.
let moveTo
+// Takes the answer of the card that askCard() put up.
+let answering
// A retry or a start over is stopping the old engine: no second one starts meanwhile.
let restarting = false
// The first run's answer to the import; only the first boot copies.
@@ -177,7 +179,10 @@ if (canonical !== undefined) {
onClose: () => { app.quit() },
// 「换个位置…」: a first start picks the place again; a later start moves the data there.
onPick: () => { (startWindow.kind === 'later' ? moveFromStart() : changePlace()).catch(fail) },
- onAnswer: (value) => { (startWindow.kind === 'later' ? moveAnswer(value) : placeAnswer(value)).catch(fail) },
+ onAnswer: (value) => {
+ if (answering !== undefined) { answering(value); return }
+ (startWindow.kind === 'later' ? moveAnswer(value) : placeAnswer(value)).catch(fail)
+ },
})
// A second launch shows the window that is showing: the start window until the hand-off
// (also after a failed start), then the team window, built anew when it is gone.
@@ -262,7 +267,7 @@ async function loadModules() {
;({ chooseLocations, defaultPlaces, pickRoot, programFolder, saveLocations, teamIn, teamsAt, tx } = firstRun)
;({ HostProcess } = hostProcess)
;({ copySessions, findTeam, importTeam, teamInUse, userDshHome } = imports)
- ;({ copyData, moveProblem } = moves)
+ ;({ copyData, copyReason, moveProblem } = moves)
;({ CHECK_PROFILE, PROFILE } = profile)
;({ watchReleases, watchUpdates } = updatesModule)
;({ getDshRuntimeVersion } = boot)
@@ -319,6 +324,37 @@ async function stopOld(options) {
// The dialogs of the first run belong to the start window and stop its clock.
const ui = () => ({ owner: () => startWindow.owner(), asking: answer => startWindow.asking(answer) })
+/**
+ * A card on the start page that waits for the user, in place of a message box: the value of the
+ * button they click. 'settled' when `settle` comes first (what the card waited for happened by
+ * itself); undefined when the card cannot show, the app quits, or the failure page takes its
+ * place. The card stays up for the caller to replace or take away.
+ * @param {{ kind: string }} card @param {{ signal?: AbortSignal, settle?: Promise<unknown> }} [options]
+ * @returns {Promise<string | undefined>}
+ */
+function askCard(card, { signal, settle } = {}) {
+ answering?.(undefined)
+ return new Promise((resolve) => {
+ const done = (value) => {
+ if (answering !== done) return
+ answering = undefined
+ signal?.removeEventListener('abort', gone)
+ resolve(value)
+ }
+ const gone = () => { done(undefined) }
+ answering = done
+ if (signal?.aborted || !startWindow.card(card)) { gone(); return }
+ signal?.addEventListener('abort', gone, { once: true })
+ void settle?.then(() => { done('settled') }, gone)
+ })
+}
+
+/** Resolves once `check` holds, looking every 2 s, or never once `signal` stops it. */
+async function until(check, signal) {
+ while (!signal.aborted && !check()) await sleep(2000, undefined, { signal }).catch(() => {})
+ if (signal.aborted) await new Promise(() => {})
+}
+
// The data folder (with the first run's question on a first start), the engine, then the team
// view in the hidden team window.
async function boot(mine) {
@@ -813,9 +849,9 @@ function moveCard(to) {
}
// A folder the checks cannot read counts as one without permission, as on a first start.
-function moveReason(to) {
+function moveReason(to, workspace = places.workspace) {
try {
- const problem = moveProblemOf(to, places.workspace)
+ const problem = moveProblemOf(to, workspace)
return problem === undefined ? undefined : MOVE_REASONS[problem]
} catch (error) {
console.error(error)
@@ -872,6 +908,10 @@ async function moveRefused(to, workspace) {
return true
}
+// The move itself, on the start window's moving page. What keeps it from going through is said on
+// a card there, 「没有搬成」, and the app starts again on the old folder: a folder that cannot be
+// used after all, another DSH on the data (the move goes on by itself once it is closed), a copy
+// that failed (〔重试〕 copies again). Quitting meanwhile stops it without a new start.
async function runMove(to, workspace) {
const signal = copyAbort.signal
copying = (async () => {
@@ -881,33 +921,50 @@ async function runMove(to, workspace) {
mainWindow?.hide()
startWindow.open('moving')
await stopHost()
+ const from = places.dataDir
+ const stay = { kind: 'moveFailed', dataDir: from }
// The app may have heard of a team workspace change while the Host stopped.
- if (await moveRefused(to, workspace)) {
- app.relaunch()
+ const reason = moveReason(to, workspace)
+ if (reason !== undefined) {
+ await askCard({ ...stay, why: 'place', place: reason, path: to }, { signal })
+ if (!signal.aborted) app.relaunch()
return
}
// Another DSH on the same data would go on writing while the copy is made.
- if (teamInUse(places.dataDir)) {
- await dialog.showMessageBox(owner(), { type: 'warning', title: 'DeepSeek Bot', message: tx('dialog.move.inUse') })
- app.relaunch()
- return
+ if (teamInUse(from)) {
+ const free = new AbortController()
+ const answer = await askCard({ ...stay, why: 'inUse' }, { signal, settle: until(() => !teamInUse(from), free.signal) })
+ free.abort()
+ if (answer !== 'settled') {
+ if (!signal.aborted) app.relaunch()
+ return
+ }
+ startWindow.card(undefined)
}
- setProgress(2)
- try {
- await copyData(places.dataDir, to, signal)
+ for (;;) {
+ setProgress(2)
try {
- saveLocations({ dataDir: to, workspace: places.workspace ?? workspace })
+ await copyData(from, to, signal)
+ try {
+ saveLocations({ dataDir: to, workspace: places.workspace ?? workspace })
+ } catch (error) {
+ // Unused, the copy would only keep the folder from being chosen again.
+ await rm(to, { recursive: true, force: true, maxRetries: 5 }).catch((failure) => { console.error(failure) })
+ throw error
+ }
+ break
} catch (error) {
- // Unused, the copy would only keep the folder from being chosen again.
- await rm(to, { recursive: true, force: true, maxRetries: 5 }).catch((failure) => { console.error(failure) })
- throw error
+ if (signal.aborted) return
+ console.error(error)
+ setProgress(-1)
+ const message = error instanceof Error ? error.message : String(error)
+ const answer = await askCard({ ...stay, why: 'copy', reason: copyReason(error), log: message.split('\n') }, { signal })
+ if (signal.aborted) return
+ if (answer !== 'retry') break
+ startWindow.card(undefined)
+ } finally {
+ setProgress(-1)
}
- } catch (error) {
- if (signal.aborted) return
- console.error(error)
- await dialog.showMessageBox(owner(), { type: 'warning', title: 'DeepSeek Bot', message: tx('dialog.move.failed', { message: error instanceof Error ? error.message : String(error) }) })
- } finally {
- setProgress(-1)
}
app.relaunch()
})()
@@ -1193,6 +1250,8 @@ async function fail(error) {
failed = true
const mine = attempt
startWindow.fail(error, startKind())
+ // The failure page takes the place of a card that waited.
+ answering?.(undefined)
const found = await Promise.race([updates?.latest() ?? null, sleep(UPDATE_CHECK_WAIT_MS).then(() => null)])
if (!found || mine !== attempt) return
await dialog.showMessageBox(owner(), { type: 'info', title: 'DeepSeek Bot', message: tx(found.page ? 'dialog.update.onFailurePage' : 'dialog.update.onFailure', { version: found.version }) })
diff --git a/app/src/move-data.mjs b/app/src/move-data.mjs
index 78979ae3..fb8269b7 100644
--- a/app/src/move-data.mjs
+++ b/app/src/move-data.mjs
@@ -6,6 +6,8 @@ import { mkdir, rename, rm, rmdir, writeFile } from 'node:fs/promises'
import { basename, dirname, join, resolve } from 'node:path'
import { copyTree, real, within } from './copy-tree.mjs'
+export { copyReason } from './copy-tree.mjs'
+
// The engine's lock on the team belongs to the old folder; the first-run copy and its check
// leave their temporary folders only when they were cut short.
const LEFT_BEHIND = [/^bot[\\/]state\.lock$/u, /^\.import(-check)?-\d+$/u]
diff --git a/app/src/start-window.mjs b/app/src/start-window.mjs
index d3801d0e..cdab43e8 100644
--- a/app/src/start-window.mjs
+++ b/app/src/start-window.mjs
@@ -410,17 +410,21 @@ export class StartWindow {
}
/**
- * A card on the sheet while the start boots (the clock stands still), or none: back to the
- * boot. Only the cards of a place: 「会放在…」, a place that cannot be used, and a later start's
- * 「搬到这个文件夹?」.
- * @param {{ kind: 'picked' | 'rejected' | 'move', path: string, reason?: string, dataDir?: string } | undefined} card
+ * A card on the sheet while the start boots or the data moves (the clock stands still), or
+ * none: back to the boot or the move. The cards of a place (「会放在…」, a place that cannot be
+ * used, a later start's 「搬到这个文件夹?」), of the first run's import and of a move that did
+ * not go through.
+ * @param {{ kind: string, [field: string]: unknown } | undefined} card
+ * @returns {boolean} whether the window shows it: not on the failure page or at the hand-off
*/
card(card) {
- if (!this.#open() || !['boot', 'card', 'watchdog'].includes(this.#state.view)) return
- if (card === undefined && this.#state.view !== 'card') return
+ if (!this.#open() || !['boot', 'card', 'watchdog', 'moving'].includes(this.#state.view)) return false
+ if (card === undefined && this.#state.view !== 'card') return false
// Back in the boot, a 180 s question that the card replaced comes straight back.
- this.#update(card === undefined ? { view: 'boot', card: undefined } : { view: 'card', card: { ...card } })
+ const back = this.#state.start === 'moving' ? 'moving' : 'boot'
+ this.#update(card === undefined ? { view: back, card: undefined } : { view: 'card', card: { ...card } })
if (card === undefined) this.#resume()
+ return true
}
/**
diff --git a/app/src/start/start.html b/app/src/start/start.html
index 762fff07..c623d275 100644
--- a/app/src/start/start.html
+++ b/app/src/start/start.html
@@ -36,6 +36,7 @@
<section class="card" data-kind="missing" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.missing"></h2><p class="lead" data-t="card.missing.lead"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="retry" data-t="btn.retry"></button><button class="btn" data-look="soft" data-act="pick" data-t="btn.relocate"></button><button class="btn" data-look="soft" data-act="freshStart" data-t="btn.freshStart"></button></div><p class="miss" data-t="card.missing.retryMissed" hidden></p><p class="foot" data-t="note.changeLater"></p></section>
<section class="card" data-kind="picked" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.picked"></h2><p class="lead" data-t="card.picked.lead"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="use" data-t="btn.continue"></button><button class="btn" data-look="soft" data-act="pick" data-t="btn.repick"></button><p class="foot" data-t="note.changeLater"></p></div></section>
<section class="card" data-kind="move" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.move"></h2><p class="lead" data-t="card.move.lead"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="move" data-t="btn.move"></button><button class="btn" data-look="soft" data-act="pick" data-t="btn.repick"></button><button class="btn" data-look="soft" data-act="answer" data-detail="cancel" data-t="btn.cancel"></button></div></section>
+<section class="card" data-kind="moveFailed" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.moveFailed"></h2><p class="lead"><span data-why="place" data-t="reason.place.{place}"></span><span data-why="inUse" data-t="card.moveFailed.inUse"></span><span data-why="copy" data-t="card.moveFailed.copy"></span> <span data-t="card.moveFailed.stay"></span></p><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="retry" data-why="copy" data-t="btn.retry"></button><button class="btn" data-look="soft" data-act="answer" data-detail="old" data-old data-t="btn.startOld"></button><button class="btn disclose" data-look="link" data-act="toggleDetails" data-why="copy" aria-expanded="false"><span data-t="btn.details"></span><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4.5 6.2 8 9.7l3.5-3.5"/></svg></button></div><div class="log" hidden><pre></pre></div></div></section>
<section class="card" data-kind="import" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.import"></h2><p class="lead" data-t="card.import.lead"></p><p class="small extra-row"><span data-t="card.import.extra"></span><button class="btn disclose" data-look="link" data-act="toggleMore" aria-expanded="false"><span data-t="btn.more"></span><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M4.5 6.2 8 9.7l3.5-3.5"/></svg></button></p><div class="more" hidden><p class="small ink" data-t="card.import.found"></p><p class="small" data-t="card.import.scope"></p><p class="small ink model-row"><span data-t="card.import.model"></span><button class="btn" data-look="link" data-act="toggleModels" aria-expanded="false" data-t="btn.changeModel"></button></p><ul class="models" hidden></ul><div class="opts"><label><input type="checkbox" data-opt="regen"><span data-t="card.import.optRegen"></span></label><label><input type="checkbox" data-opt="skipWork"><span data-t="card.import.optSkipWork"></span></label></div></div></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="copy" data-t="btn.copy"></button><button class="btn" data-look="soft" data-act="answer" data-detail="skip" data-t="btn.skipCopy"></button><p class="foot" data-t="note.copyLater"></p></div></section>
<section class="card" data-kind="importSpace" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.importSpace"></h2><p class="lead" data-t="card.importSpace.lead"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="pick" data-t="btn.pickPlace"></button><button class="btn" data-look="soft" data-act="answer" data-detail="skip" data-t="btn.skipCopy"></button></div></section>
<section class="card" data-kind="copying" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.copying"></h2><div class="copy-steps"><ol class="steps"><li data-step="1"><span class="mark" aria-hidden="true"><span class="dot"></span><svg class="check" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8"/><path d="M4.6 8.3 7 10.6l4.4-4.9"/></svg></span><span data-t="card.copying.step1"></span></li><li data-step="2"><span class="mark" aria-hidden="true"><span class="dot"></span><svg class="check" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8"/><path d="M4.6 8.3 7 10.6l4.4-4.9"/></svg></span><span data-t="card.copying.step2"></span></li><li data-step="3"><span class="mark" aria-hidden="true"><span class="dot"></span><svg class="check" viewBox="0 0 16 16"><circle cx="8" cy="8" r="8"/><path d="M4.6 8.3 7 10.6l4.4-4.9"/></svg></span><span data-t="card.copying.step3"></span></li></ol><div class="bar" aria-hidden="true"><span class="bar-fill"></span></div></div><div class="confirm" hidden><p class="lead" data-t="card.copying.stopConfirm"></p></div></div><div class="card-actions"><span class="eta small"></span><button class="btn stop" data-look="soft" data-act="stopCopy" data-t="btn.stopCopy"></button><button class="btn" data-look="primary" data-act="keepCopying" data-confirm data-t="btn.keepCopying"></button><button class="btn danger" data-look="soft" data-act="stopCopy" data-detail="confirm" data-confirm data-t="btn.stopCopy"></button></div></section>
diff --git a/app/src/start/start.js b/app/src/start/start.js
index cb06b95c..573f95f8 100644
--- a/app/src/start/start.js
+++ b/app/src/start/start.js
@@ -71,7 +71,7 @@ function varsOf(snap) {
const update = snap.update ?? {}
const vars = { ...card }
if (snap.view === 'failed' || snap.view === 'viewFailed') vars.reason = snap.failure?.reason ?? 'other'
- if (card.kind === 'importFailed') vars.reason = say(`reason.copy.${card.reason}`)
+ if ((card.kind === 'importFailed' || card.kind === 'moveFailed') && card.reason) vars.reason = say(`reason.copy.${card.reason}`)
if (card.kind === 'newerUpdating') vars.p = card.percent ?? 0
if (update.version) Object.assign(vars, { version: update.version, p: update.percent ?? 0, a: update.received ?? 0, b: update.total ?? 0 })
return vars
@@ -285,12 +285,19 @@ function fillBlock(name) {
const el = blockEl(name)
if (!el || !s) return
const vars = varsOf(s)
- for (const node of el.querySelectorAll('[data-t]')) if (!node.closest('.steps, .copied')) render(node, vars)
+ // A card with variants shows the parts of its own (data-why) only; the others stay empty, so
+ // that a screen reader does not read them.
+ for (const node of el.querySelectorAll('[data-why]')) {
+ node.hidden = node.dataset.why !== s.card?.why
+ if (node.hidden && node.dataset.t) { node.textContent = ''; sigs.delete(node) }
+ }
+ for (const node of el.querySelectorAll('[data-t]')) if (!node.closest('.steps, .copied, [data-why][hidden]')) render(node, vars)
if (name === 'missing') missing(el)
if (name === 'recommend' || name === 'rejected') recommend(el)
if (name === 'import') importCard(el)
if (name === 'copying') copying(el)
if (name === 'failed') failed(el)
+ if (name === 'moveFailed') el.querySelector('[data-old]').dataset.look = s.card?.why === 'copy' ? 'soft' : 'primary'
}
let missSeen = 0
let missTimer = 0
diff --git a/app/src/start/text.mjs b/app/src/start/text.mjs
index 04c5206f..e8bcca1c 100644
--- a/app/src/start/text.mjs
+++ b/app/src/start/text.mjs
@@ -41,6 +41,7 @@ export const TEXT = {
'say.newer': '这些对话比我新',
'say.copying': '正在搬过来',
'say.move': '搬到这个文件夹?',
+ 'say.moveFailed': '没有搬成',
// hint
'hint.space': '{drive} 盘只剩 {free}',
// card
@@ -49,6 +50,9 @@ export const TEXT = {
'card.missing.retryMissed': '还是找不到这个文件夹。',
'card.picked.lead': '会放在 {path}。',
'card.move.lead': '会把数据复制到 {path},然后重新启动。原来的 {dataDir} 原样留着,确认没问题后可以自己删掉。',
+ 'card.moveFailed.inUse': '另一个 DeepSeek Harness 正在使用这份数据。关掉它以后,这里会自动接着搬。',
+ 'card.moveFailed.copy': '数据没有复制完:{reason}。',
+ 'card.moveFailed.stay': '原来的 {dataDir} 没有变化。',
'card.import.lead': 'DeepSeek Harness 里有 {bots} 个 Bot 和 {groups} 个群聊(对话 {chats},工作文件 {work})。复制过来?',
'card.import.extra': '复制后会多占 {total},DeepSeek Harness 里的原件不动。',
'card.import.found': '在 {path} 里找到 {bots} 个 Bot({names}等)和 {groups} 个群聊,{sessions} 段对话。',
@@ -90,6 +94,7 @@ export const TEXT = {
'reason.copy.inUse': '文件被别的程序占用',
'reason.copy.permission': '没有权限读取',
'reason.copy.full': '磁盘满了',
+ 'reason.copy.other': '出了点意外',
// btn
'btn.retry': '重试',
'btn.wait': '继续等待',
@@ -117,6 +122,7 @@ export const TEXT = {
'btn.manualDownload': '手动下载',
'btn.reload': '重新载入',
'btn.move': '移动并重启',
+ 'btn.startOld': '用原来的位置启动',
'btn.cancel': '取消',
'btn.quit': '退出',
'btn.restart': '立即重启',
@@ -190,6 +196,7 @@ export const TEXT = {
'say.newer': 'These chats are newer than me',
'say.copying': 'Moving your team in',
'say.move': 'Move the data here?',
+ 'say.moveFailed': 'The data didn’t move',
// hint
'hint.space': 'Only {free} left on drive {drive}',
// card
@@ -198,6 +205,9 @@ export const TEXT = {
'card.missing.retryMissed': 'Still can’t find this folder.',
'card.picked.lead': 'It will go in {path}.',
'card.move.lead': 'DeepSeek Bot copies its data to {path} and starts again. {dataDir} stays as it is; once all is well you can delete it yourself.',
+ 'card.moveFailed.inUse': 'Another DeepSeek Harness is using this data. Once it is closed, the move goes on by itself.',
+ 'card.moveFailed.copy': 'The data wasn’t fully copied: {reason}.',
+ 'card.moveFailed.stay': '{dataDir} is unchanged.',
'card.import.lead': 'DeepSeek Harness has {bots|Bot|Bots} and {groups|group chat|group chats} (chats {chats}, work files {work}). Copy them over?',
'card.import.extra': 'The copy takes another {total}; the originals in DeepSeek Harness stay untouched.',
'card.import.found': 'Found {bots|Bot|Bots} ({names} and others), {groups|group chat|group chats} and {sessions|chat|chats} in {path}.',
@@ -239,6 +249,7 @@ export const TEXT = {
'reason.copy.inUse': 'a file is in use by another program',
'reason.copy.permission': 'no permission to read',
'reason.copy.full': 'the disk is full',
+ 'reason.copy.other': 'something unexpected happened',
// btn
'btn.retry': 'Try again',
'btn.wait': 'Keep waiting',
@@ -266,6 +277,7 @@ export const TEXT = {
'btn.manualDownload': 'Download manually',
'btn.reload': 'Reload',
'btn.move': 'Move and restart',
+ 'btn.startOld': 'Start in the old folder',
'btn.cancel': 'Cancel',
'btn.quit': 'Quit',
'btn.restart': 'Restart now',
diff --git a/app/test/helpers/app-harness.mjs b/app/test/helpers/app-harness.mjs
index 0dbc8551..87dd4749 100644
--- a/app/test/helpers/app-harness.mjs
+++ b/app/test/helpers/app-harness.mjs
@@ -68,3 +68,33 @@ export const handOff = async () => {
/** The entries of the tray's menu: Open, a line, Quit. */
export const trayMenu = () => state.tray.menu.template
+
+/** The last state the start window sent its page. */
+export const startState = (start = startWindows().at(-1)) => start?.webContents.sent.filter(([channel]) => channel === 'ds-bot:start-state').at(-1)?.[1]
+
+/** A click on the start page: the act with its button's detail, on a later task, as a click is. */
+export const startAct = async (name, value, start = startWindows().at(-1)) => {
+ await new Promise((resolve) => { setImmediate(resolve) })
+ start.webContents.mainFrame.url = start.url
+ return state.ipc.get('ds-bot:start-act')({ sender: start.webContents, senderFrame: start.webContents.mainFrame }, name, value === undefined ? undefined : { value })
+}
+
+/** The message boxes the app showed; the pickers have no message. */
+export const messageBoxes = () => state.dialogs.filter(options => 'message' in options)
+
+/**
+ * A later start whose drive runs low, and its place line's 〔换个位置…〕 to `to`, answered with
+ * 〔移动并重启〕: the start window becomes the move's.
+ * @returns {Promise<{ home: string, workspace: string }>}
+ */
+export const moveFromStart = async (to, { before = () => {} } = {}) => {
+ const places = await startApp({ saved: { freeAtStart: Number.MAX_SAFE_INTEGER } })
+ before(places)
+ await waitFor(() => startState()?.place !== undefined, 'show the place line')
+ state.openAnswer = { canceled: false, filePaths: [to] }
+ await startAct('pick', 'changePlace')
+ await waitFor(() => startState().card?.kind === 'move', 'ask about the move')
+ await startAct('answer', 'move')
+ await waitFor(() => startWindows()[0].url.endsWith('?start=moving'), 'turn the start window into the move\'s')
+ return places
+}
diff --git a/app/test/main-move-failed.test.mjs b/app/test/main-move-failed.test.mjs
new file mode 100644
index 00000000..2f23b93a
--- /dev/null
+++ b/app/test/main-move-failed.test.mjs
@@ -0,0 +1,41 @@
+// A move whose copy fails says why on a card on the moving page instead of a message box:
+// 〔重试〕 copies again, 〔用原来的位置启动〕 starts again on the old folder (start-window §5). The
+// Electron parts are test doubles: no display, no DSH, no data of the user.
+import assert from 'node:assert/strict'
+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { paths, state } from './helpers/fake-electron.mjs'
+import { messageBoxes, moveFromStart, startAct, startState, startWindows, waitFor } from './helpers/app-harness.mjs'
+import { installHooks } from './helpers/register.mjs'
+
+await installHooks()
+
+test('a failed copy asks on a card whether to copy again or start where the data was', async () => {
+ // A folder whose parent is a file passes the checks, but no copy can go there.
+ const parent = join(mkdtempSync(join(tmpdir(), 'ds-bot-move-')), 'a-file')
+ writeFileSync(parent, '')
+ const to = join(parent, 'data')
+ const { home } = await moveFromStart(to)
+ const failures = () => startWindows()[0].webContents.sent.filter(([channel, snapshot]) => channel === 'ds-bot:start-state' && snapshot.card?.kind === 'moveFailed' && snapshot.view === 'card').length
+ const shown = () => startWindows()[0].webContents.sent.filter(([channel]) => channel === 'ds-bot:start-state').length
+ await waitFor(() => startState().card?.kind === 'moveFailed', 'say that the copy failed')
+ const { log, ...card } = startState().card
+ assert.deepEqual(card, { kind: 'moveFailed', dataDir: home, why: 'copy', reason: 'other' })
+ assert.ok(log.length > 0 && log.every(line => typeof line === 'string'), 'the error goes into the details')
+
+ // 〔重试〕: the card goes, the copy fails again, and the card comes back.
+ const before = shown()
+ await startAct('answer', 'retry')
+ await waitFor(() => shown() > before && startState().view === 'card', 'copy again')
+ assert.ok(startWindows()[0].webContents.sent.slice(before).some(([, snapshot]) => snapshot.view === 'moving'), 'the card went while the copy ran')
+ assert.ok(failures() >= 2)
+ assert.equal(state.relaunches.length, 0)
+
+ // 〔用原来的位置启动〕: the app starts again on the old folder.
+ await startAct('answer', 'old')
+ await waitFor(() => state.relaunches.length === 1, 'start again where the data was')
+ assert.equal(JSON.parse(readFileSync(join(paths.userData, 'locations.json'), 'utf8')).dataDir, home)
+ assert.deepEqual(messageBoxes(), [], 'no message box on the way')
+})
diff --git a/app/test/main-move-in-use.test.mjs b/app/test/main-move-in-use.test.mjs
new file mode 100644
index 00000000..5b401fff
--- /dev/null
+++ b/app/test/main-move-in-use.test.mjs
@@ -0,0 +1,35 @@
+// A move that finds another DSH on the data says so on a card on the moving page instead of a
+// message box, and goes on by itself once that DSH is closed (start-window §5). The Electron
+// parts are test doubles: no display, no DSH, no data of the user.
+import assert from 'node:assert/strict'
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { hostname, tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { paths, state } from './helpers/fake-electron.mjs'
+import { messageBoxes, moveFromStart, startState, waitFor } from './helpers/app-harness.mjs'
+import { installHooks } from './helpers/register.mjs'
+
+await installHooks()
+
+test('a move waits on a card while another DSH uses the data, and goes on once it is closed', async () => {
+ const to = join(mkdtempSync(join(tmpdir(), 'ds-bot-move-')), 'data')
+ const lock = home => join(home, 'bot', 'state.lock')
+ const { home } = await moveFromStart(to, {
+ before: ({ home: dataDir }) => {
+ mkdirSync(join(dataDir, 'bot'), { recursive: true })
+ writeFileSync(lock(dataDir), JSON.stringify({ host: hostname(), pid: process.pid }))
+ },
+ })
+ await waitFor(() => startState().card?.kind === 'moveFailed', 'say that another DSH uses the data')
+ assert.equal(startState().start, 'moving')
+ assert.deepEqual(startState().card, { kind: 'moveFailed', dataDir: home, why: 'inUse' })
+ assert.equal(existsSync(to), false, 'nothing is copied meanwhile')
+ assert.equal(state.relaunches.length, 0)
+
+ rmSync(lock(home))
+ await waitFor(() => state.relaunches.length === 1, 'go on with the move once the data is free')
+ assert.ok(existsSync(to), 'the data was copied')
+ assert.equal(JSON.parse(readFileSync(join(paths.userData, 'locations.json'), 'utf8')).dataDir, to)
+ assert.deepEqual(messageBoxes(), [], 'no message box on the way')
+})
diff --git a/app/test/main-move-refused.test.mjs b/app/test/main-move-refused.test.mjs
new file mode 100644
index 00000000..41bf4692
--- /dev/null
+++ b/app/test/main-move-refused.test.mjs
@@ -0,0 +1,34 @@
+// A folder that can no longer take the data once the engine has stopped (something was put in it
+// meanwhile) is refused on a card on the moving page, not in a message box, and the app starts
+// again on the old folder (start-window §5). The Electron parts are test doubles: no display, no
+// DSH, no data of the user.
+import assert from 'node:assert/strict'
+import { mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { test } from 'node:test'
+import { paths, state } from './helpers/fake-electron.mjs'
+import { HostProcess } from './helpers/fake-host-process.mjs'
+import { messageBoxes, moveFromStart, startAct, startState, waitFor } from './helpers/app-harness.mjs'
+import { installHooks } from './helpers/register.mjs'
+
+await installHooks()
+
+test('a folder that cannot be used after the engine stopped is refused on a card', async () => {
+ const to = join(mkdtempSync(join(tmpdir(), 'ds-bot-move-')), 'data')
+ const stop = HostProcess.prototype.stop
+ HostProcess.prototype.stop = async function (...args) {
+ mkdirSync(to, { recursive: true })
+ writeFileSync(join(to, 'notes.txt'), '')
+ return stop.apply(this, args)
+ }
+ const { home } = await moveFromStart(to)
+ await waitFor(() => startState().card?.kind === 'moveFailed', 'refuse the folder')
+ assert.deepEqual(startState().card, { kind: 'moveFailed', dataDir: home, why: 'place', place: 'foreign', path: to })
+ assert.equal(state.relaunches.length, 0, 'the card waits for the user')
+
+ await startAct('answer', 'old')
+ await waitFor(() => state.relaunches.length === 1, 'start again where the data was')
+ assert.equal(JSON.parse(readFileSync(join(paths.userData, 'locations.json'), 'utf8')).dataDir, home)
+ assert.deepEqual(messageBoxes(), [], 'no message box on the way')
+})
diff --git a/app/test/start-page.test.mjs b/app/test/start-page.test.mjs
index daf8ad0c..41f4d8bd 100644
--- a/app/test/start-page.test.mjs
+++ b/app/test/start-page.test.mjs
@@ -148,6 +148,19 @@ test('the footer is the place line alone, centred with a grey button, on first a
assert.match(html, /<section class="card" data-kind="move" hidden>.*?data-t="say\.move".*?data-t="card\.move\.lead".*?data-detail="move" data-t="btn\.move".*?data-act="pick" data-t="btn\.repick".*?data-detail="cancel" data-t="btn\.cancel".*?<\/section>/u)
})
+// A move that does not go through says why on the moving page (start-window §5): a place that
+// cannot be used after all, another DSH on the data, a copy that failed. Each variant shows its own
+// parts only; 〔用原来的位置启动〕 is on all three, 〔重试〕 and the details only after a failed copy.
+test('a move that does not go through has one card with three variants', () => {
+ const card = html.match(/<section class="card" data-kind="moveFailed" hidden>.*?<\/section>/u)?.[0]
+ assert.ok(card, 'the moveFailed card is missing')
+ assert.match(card, /data-t="say\.moveFailed"/u)
+ assert.match(card, /<span data-why="place" data-t="reason\.place\.\{place\}"><\/span><span data-why="inUse" data-t="card\.moveFailed\.inUse"><\/span><span data-why="copy" data-t="card\.moveFailed\.copy"><\/span> <span data-t="card\.moveFailed\.stay"><\/span>/u)
+ assert.match(card, /data-detail="retry" data-why="copy" data-t="btn\.retry".*?data-detail="old" data-old data-t="btn\.startOld".*?data-act="toggleDetails" data-why="copy"/u)
+ assert.match(code['start.js'], /node\.hidden = node\.dataset\.why !== s\.card\?\.why/u)
+ assert.match(code['start.js'], /if \(name === 'moveFailed'\) el\.querySelector\('\[data-old\]'\)\.dataset\.look = s\.card\?\.why === 'copy' \? 'soft' : 'primary'/u)
+})
+
// docs/plans/2026-10-29-start-copy.md §2: the first part of a key says where the line is.
const LAYERS = ['voice', 'say', 'hint', 'card', 'reason', 'btn', 'note', 'foot', 'status', 'dialog']
const layerOf = key => key.split('.')[0]
@@ -262,7 +275,7 @@ test('every text key that the page uses exists', () => {
for (const key of ['voice.failed', 'voice.viewFailed', 'voice.watchdog', 'voice.moving', 'voice.slow45', 'voice.slowLater', 'status.phase.data', 'status.phase.engine', 'status.phase.team', 'status.state.pending', 'status.state.active', 'status.state.done', 'status.state.failed']) assert.ok(key in TEXT.zh, key)
assert.deepEqual(matching('reason.start.{reason}').sort(), ['reason.start.engine', 'reason.start.files', 'reason.start.other', 'reason.start.permission', 'reason.start.space'])
assert.deepEqual(matching('reason.place.{reason}').sort(), ['reason.place.drive', 'reason.place.dsh', 'reason.place.foreign', 'reason.place.nested', 'reason.place.onedrive', 'reason.place.permission', 'reason.place.program', 'reason.place.space', 'reason.place.workspace'])
- assert.deepEqual(matching('reason.copy.{reason}').sort(), ['reason.copy.full', 'reason.copy.inUse', 'reason.copy.permission'])
+ assert.deepEqual(matching('reason.copy.{reason}').sort(), ['reason.copy.full', 'reason.copy.inUse', 'reason.copy.other', 'reason.copy.permission'])
})
// §1: the main process takes its dialog copy from the same table.
diff --git a/app/test/start-window.test.mjs b/app/test/start-window.test.mjs
index 92a19bde..956bd921 100644
--- a/app/test/start-window.test.mjs
+++ b/app/test/start-window.test.mjs
@@ -736,6 +736,26 @@ test('a move from a later start turns the start window into the move\'s and drop
assert.equal(m.act('openLogs'), true)
m.tick(WATCHDOG_MS)
assert.equal(m.state().view, 'moving')
+ // A move that does not go through asks on a card of the moving page; the clock stands still
+ // meanwhile, and taking the card away goes back to the move, not to a boot.
+ assert.equal(m.start.card({ kind: 'moveFailed', why: 'inUse', dataDir: 'C:\\Data' }), true)
+ assert.equal(m.state().view, 'card')
+ assert.equal(m.state().clock.running, false)
+ assert.equal(m.act('answer', { value: 'old' }), true)
+ assert.deepEqual(m.calls.answer, ['old'])
+ assert.equal(m.start.card(undefined), true)
+ assert.equal(m.state().view, 'moving')
+ assert.equal(m.state().clock.running, true)
+ assert.equal('card' in m.state(), false)
+})
+
+test('a card shows only while the start boots or the data moves', (t) => {
+ const c = startWindow(t)
+ c.start.open('first')
+ c.start.fail(new Error('the Host did not start'), 'first')
+ assert.equal(c.start.card({ kind: 'importFailed', reason: 'other' }), false)
+ assert.equal(c.state().view, 'failed')
+ assert.equal(c.start.card(undefined), false)
})
test('the 20 s check\'s verdict waits for a card\'s answer instead of being lost', (t) => {