A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Ask the import and the app's questions on cards, not in message boxes
AdamPlatin123dad23536ce2c
diff --git a/app/scripts/start-assets.mjs b/app/scripts/start-assets.mjsindex 91514e79..0cd9f987 100644--- a/app/scripts/start-assets.mjs+++ b/app/scripts/start-assets.mjs@@ -5,6 +5,8 @@// is st-eyes, the clips st-tail-cut and st-torso-cut; the fill stays var(--bt-ink-deepseek).// - start.css, between /* tokens */ markers: the DeepSeek theme's light and dark colors.// - start.css, between /* springs */ markers: motion.js's springs as linear() curves.+// - ../page-card.css, between the same two markers: the same colors and springs, scoped to the+// card that the team window shows in place of a message box, so that the page's own are kept.// Usage: node scripts/start-assets.mjs [--check] (--check exits 1 when a block is stale and// writes nothing)import { readFileSync, writeFileSync } from 'node:fs'@@ -19,6 +21,8 @@ const THEME_TOKENS = ['--bt-main', '--bt-card', '--bt-ink', '--bt-ink-2', '--bt-// The status colors are the same in both modes; the plugin's base sheet defines them.const BASE_TOKENS = ['--bt-green', '--bt-danger']const SPRINGS = ['shape', 'tap', 'pop', 'stretch', 'list']+// The layer of the team window's card (preload.cjs).+const CARD_SCOPE = '.dsb-card-layer'// Wraps the one self-closing element that starts with `start` in <g id>.function wrap(markup, id, start) {@@ -78,15 +82,15 @@ function pick(vars, names, from) {}).join(';')}-function tokens() {+function tokens(scope = ':root') {const [light, dark] = rules(themeCss(allThemes().deepseek))const base = readFileSync(new URL('styles.js', client), 'utf8').match(/^body\{(--bt-[^}]*)\}$/mu)if (!base) throw new Error('styles.js: the base body rule was not found')const [ink, inkDark] = INKS.deepseekreturn ['/* Generated from the DeepSeek theme in ds-bot/src/client/themes.js, inks.js and styles.js by scripts/start-assets.mjs; do not edit. */',- `:root{color-scheme:light dark;${pick(light, THEME_TOKENS, 'themeCss')};--bt-ink-deepseek:${ink};${pick(rules(`{${base[1]}}`)[0], BASE_TOKENS, 'styles.js')}}`,- `@media (prefers-color-scheme:dark){:root{${pick(dark, THEME_TOKENS, 'themeCss')};--bt-ink-deepseek:${inkDark}}}`,+ `${scope}{color-scheme:light dark;${pick(light, THEME_TOKENS, 'themeCss')};--bt-ink-deepseek:${ink};${pick(rules(`{${base[1]}}`)[0], BASE_TOKENS, 'styles.js')}}`,+ `@media (prefers-color-scheme:dark){${scope}{${pick(dark, THEME_TOKENS, 'themeCss')};--bt-ink-deepseek:${inkDark}}}`,]}@@ -101,11 +105,11 @@ async function motion() {return import(`data:text/javascript,${encodeURIComponent(source.replace(imports[0], stub))}`)}-async function springs() {+async function springs(scope = ':root') {const curves = await motion()return ['/* Generated from ds-bot/src/client/motion.js by scripts/start-assets.mjs; do not edit. */',- ':root {',+ `${scope} {`,...SPRINGS.flatMap((name) => {const curve = curves[`SPRING_${name.toUpperCase()}`]if (!curve) throw new Error(`motion.js no longer exports SPRING_${name.toUpperCase()}`)@@ -129,6 +133,7 @@ function between(text, open, close, block) {const files = {'start.html': html => between(html, '<!-- whale -->', '<!-- /whale -->', rig()),'start.css': async css => between(between(css, '/* tokens */', '/* /tokens */', tokens()), '/* springs */', '/* /springs */', await springs()),+ '../page-card.css': async css => between(between(css, '/* tokens */', '/* /tokens */', tokens(CARD_SCOPE)), '/* springs */', '/* /springs */', await springs(CARD_SCOPE)),}const check = process.argv.includes('--check')const stale = []diff --git a/app/src/copy-tree.mjs b/app/src/copy-tree.mjsindex b4f5789d..23822dd2 100644--- a/app/src/copy-tree.mjs+++ b/app/src/copy-tree.mjs@@ -60,12 +60,13 @@ async function relink(source, path, roots, to) {* fails the copy.* @param {string} from* @param {string} into- * @param {{ force?: boolean, skip?: boolean, leave?: (path: string) => boolean, as?: string, signal?: AbortSignal }} [options]+ * @param {{ force?: boolean, skip?: boolean, leave?: (path: string) => boolean, as?: string, signal?: AbortSignal, seen?: (bytes: number) => void }} [options]* force: false keeps what is there already; leave: relative paths not to copy; as: where the- * copy will end up, when `into` is a staging folder that takes that name later+ * copy will end up, when `into` is a staging folder that takes that name later; seen: the size+ * of each file as it is about to be copied* @returns {Promise<string[]>} the relative paths that were skipped*/-export async function copyTree(from, into, { force = true, skip = false, leave = () => false, as = into, signal } = {}) {+export async function copyTree(from, into, { force = true, skip = false, leave = () => false, as = into, signal, seen } = {}) {// The folder can itself be a link; its contents are what is copied.const origin = real(from)const links = []@@ -81,6 +82,7 @@ export async function copyTree(from, into, { force = true, skip = false, leave =const info = await lstat(source).catch((error) => { if (!skip) throw error })if (info === undefined) skipped.push(path)else if (info.isSymbolicLink()) links.push(path)+ else if (info.isFile()) seen?.(info.size)return info?.isSymbolicLink() === false},})diff --git a/app/src/first-run.mjs b/app/src/first-run.mjsindex fc19c1b8..b286df21 100644--- a/app/src/first-run.mjs+++ b/app/src/first-run.mjs@@ -5,31 +5,21 @@ import { app, dialog } from 'electron'import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'import { homedir } from 'node:os'import { dirname, join, resolve } from 'node:path'-import { findTeam, newerSessions, teamInUse, userDshHome } from './import.mjs'+import { findTeam, userDshHome } from './import.mjs'import { installFolder } from './move-data.mjs'import { freeSpace } from './place.mjs'import { langOf, t } from './start/text.mjs'-// The system dialogs speak the language of the start page (main.mjs gives it the same locale).+// The system picker and the cards in the team window speak the language of the start page+// (main.mjs gives it the same locale).export const lang = () => langOf(app.getLocale())export const tx = (key, vars) => t(lang(), key, vars)-const PROFILE_NAMES = { desktop: 'DSH Desktop', web: 'DSH Web' }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.+// A quit request while the system picker is open stops the first run right after it.class Quit extends Error {}-// 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, from, signal, ui) {const { canceled, filePaths } = await ui.asking(dialog.showOpenDialog(ui.owner(), { title, defaultPath: existsSync(from) ? from : dirname(from), properties: ['openDirectory', 'createDirectory', 'promptToCreate'] }))await new Promise(resolve => setImmediate(resolve))@@ -74,29 +64,18 @@ export function teamsAt(dataDir = defaultPlaces().dataDir) {return { team, offered: team === undefined && teamIn(userDshHome()) !== undefined }}-/** @returns {Promise<{ offered: boolean, import?: { from: string, profile?: string }, quit?: true }>} */-async function offerImport(dataDir, signal, ui) {- const from = userDshHome()- let found+/**+ * The team that the user's own DSH offers to a data folder without one, if any. The start page+ * asks about it on the import card (import-flow.mjs).+ * @returns {ReturnType<typeof findTeam>}+ */+function offerOf(dataDir) {try {- found = teamIn(dataDir) === undefined ? findTeam(from) : undefined+ return teamIn(dataDir) === undefined ? findTeam(userDshHome()) : undefined} catch (error) {console.error(error)+ return undefined}- if (found === undefined) return { offered: false }- if (await ask({ type: 'question', message: tx('dialog.import.found', { bots: found.bots, groups: found.rooms }), detail: tx('dialog.import.foundDetail', { home: from }), buttons: [tx('btn.copy'), tx('btn.skipCopy')], defaultId: 0, cancelId: 1 }, signal, ui) === 1) return { offered: true }- while (teamInUse(from)) {- if (await ask({ type: 'warning', message: tx('dialog.import.inUse'), buttons: [tx('btn.retry'), tx('btn.skipCopy')], 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: tx('dialog.import.newer', { n: newer.length }), buttons: [tx('btn.quit'), tx('btn.startWithout')], 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: tx('dialog.import.whichModels'), buttons: profiles.map(entry => PROFILE_NAMES[entry.name] ?? entry.name), defaultId: 0, cancelId: 0 }, signal, ui)].name- return { offered: true, import: { from, profile } }}/**@@ -129,16 +108,14 @@ function readSaved(file) {/*** Where the app keeps its data and the Bots' files: the saved places, or at the first start the* default ones without a question (the start page says where the data goes and offers- * 「换个位置…」; windows-onboarding §3). The offer to copy a team is still a dialog that belongs- * 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;- * `freeAtStart` is the free space of the data's drive that saveLocations() kept, none when it- * kept none yet.- * @param {AbortSignal} signal- * @param {{ owner: () => import('electron').BrowserWindow | undefined, asking: <T>(answer: Promise<T>) => Promise<T> }} ui- * @returns {Promise<{ dataDir: string, workspace?: string, freeAtStart?: number, import?: { from: string, profile?: string }, offered?: boolean, quit?: true }>}+ * 「换个位置…」; windows-onboarding §3). A team in the user's own DSH comes back as `offer`: the+ * places are saved once the import card has its answer, so that quitting before that asks again.+ * A run on throwaway folders (DS_BOT_HOME, for development and tests) asks nothing and copies+ * nothing. `freeAtStart` is the free space of the data's drive that saveLocations() kept, none+ * when it kept none yet.+ * @returns {{ dataDir: string, workspace?: string, freeAtStart?: number, offer?: NonNullable<ReturnType<typeof findTeam>> }}*/-export async function chooseLocations(signal, ui) {+export function chooseLocations() {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)) {@@ -146,17 +123,9 @@ export async function chooseLocations(signal, ui) {return { dataDir: saved.dataDir, workspace: saved.workspace, freeAtStart: roomOf(saved.freeAtStart) }}const { dataDir, workspace } = defaultPlaces()- let offered- try {- const offer = await offerImport(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- }+ const offer = offerOf(dataDir)+ if (offer !== undefined) return { dataDir, workspace, offer }// There is nothing to copy, so the first run ends with the chosen places.saveLocations({ dataDir, workspace })- return { dataDir, workspace, offered }+ return { dataDir, workspace }}diff --git a/app/src/import-flow.mjs b/app/src/import-flow.mjsnew file mode 100644index 00000000..45f4ebd9--- /dev/null+++ b/app/src/import-flow.mjs@@ -0,0 +1,328 @@+// The first run's import on the start page's cards (windows-onboarding §4, start-window §6): the+// import card, the space and in-use cards, the check of the chats, the copy with its steps, its+// stop and its failure. What touches the disk, the engine and the window comes in as `io`, so+// that the order of the cards can be tested without any of them.+import { REGENERABLE_DEFAULT_BYTES } from './import.mjs'+import { formatBytes } from './place.mjs'++// The first stage needs this much more room than it copies (windows-onboarding §4).+export const SPARE_BYTES = 500e6+const CARD_EVERY_MS = 200+// The rate is not told before the copy has run this long.+const ETA_AFTER_MS = 3000++/**+ * The model settings an import offers, best first: those of DSH Desktop, then DSH Web, then the+ * profile with the most rows.+ * @param {{ name: string, rows: any[] }[]} profiles+ * @returns {{ id: string, label: string }[]}+ */+export function modelChoices(profiles) {+ const rank = name => ({ desktop: 0, web: 1 })[name] ?? 2+ const sorted = [...profiles].sort((a, b) => rank(a.name) - rank(b.name) || b.rows.length - a.rows.length)+ return sorted.map(profile => ({ id: profile.name, label: modelLabel(profile) }))+}++const PROFILE_NAMES = { desktop: 'DSH Desktop', web: 'DSH Web' }++function modelLabel({ name, rows }) {+ const model = rows.find(row => row?.id === 'agent-default-model')?.config?.model+ const from = PROFILE_NAMES[name] ?? name+ return typeof model === 'string' && model !== '' ? `${from} · ${model}` : from+}++/**+ * What the card counts and how much the copy takes with the options as they stand: the work files+ * without the regenerable folders when those are left out, and none when the work files wait.+ * @param {{ chats?: number, work?: number, regen?: number }} sizes+ * @param {{ regen: boolean, skipWork: boolean }} options+ */+export function copySize(sizes, options) {+ if (sizes.chats === undefined || sizes.work === undefined) return undefined+ const work = options.skipWork ? 0 : sizes.work - (options.regen ? sizes.regen ?? 0 : 0)+ return { chats: sizes.chats, work, total: sizes.chats + work }+}++/** The options the card starts with: regenerable folders of 200 MB and more stay behind. */+export const defaultOptions = sizes => ({ regen: (sizes.regen ?? 0) >= REGENERABLE_DEFAULT_BYTES, skipWork: false })++/**+ * The time left, in whole minutes: it changes only once it is a full minute away from the one on+ * the card, and under a minute it is 0 (「不到 1 分钟」), never counted down to nothing.+ * @param {number | null} shown the minutes on the card, null before there was a rate+ */+export function etaMinutes(shown, { done, total, elapsedMs }) {+ if (elapsedMs < ETA_AFTER_MS || done <= 0 || total <= 0) return shown+ const left = (Math.max(0, total - done) / done) * elapsedMs+ if (left < 60_000) return 0+ const minutes = Math.ceil(left / 60_000)+ return shown === null || shown === 0 || Math.abs(minutes - shown) >= 1 ? minutes : shown+}++/**+ * @typedef {{+ * from: string, bots: number, rooms: number, names: string[], sessions: number,+ * sizes: { chats?: number, work?: number, regen?: number }, profiles: { name: string, rows: any[] }[],+ * }} Offer+ * @typedef {{+ * offer: Offer,+ * ask: (card: object, options?: { settle?: Promise<unknown> }) => Promise<string | undefined>,+ * show: (card: object) => void,+ * room: () => { free?: number, drive?: string },+ * inUse: () => boolean,+ * until: (check: () => boolean, signal: AbortSignal) => Promise<void>,+ * check: (signal: AbortSignal, onProgress: (done: number, total: number) => void) => Promise<number>,+ * warmed: () => Promise<unknown>,+ * copy: (options: { profile?: string, leaveRegenerable: boolean, skipWork: boolean, signal: AbortSignal, onProgress: (bytes: number) => void }) => Promise<any>,+ * reasonOf: (error: unknown) => string,+ * progress?: (fraction: number) => void,+ * now?: () => number,+ * lang?: string,+ * signal: AbortSignal,+ * }} ImportIo+ */++/**+ * One import, from the card to the copied team. `act()` takes the card's acts that are not an+ * answer (a model, an option, the stop and its confirmation) while `run()` waits.+ */+export class ImportFlow {+ #io+ #now+ #models+ #profile+ #options+ #sizes+ // The check of the chats, started while the card is up (stale once a holder came meanwhile).+ #check+ #checkAbort+ // The copy under way, its stop, and the copying card as it stands.+ #copyAbort+ #copyCard+ #confirming = false+ #shownAt = 0+ #timer+ #lastStep = 0++ /** @param {ImportIo} io */+ constructor(io) {+ this.#io = io+ this.#now = io.now ?? Date.now+ this.#models = modelChoices(io.offer.profiles)+ this.#profile = this.#models[0]?.id+ this.#sizes = io.offer.sizes+ this.#options = defaultOptions(this.#sizes)+ }++ /** The import card as the options stand. */+ card() {+ const { offer } = this.#io+ const size = copySize(this.#sizes, this.#options)+ const model = this.#models.find(entry => entry.id === this.#profile)+ return {+ kind: 'import', bots: offer.bots, groups: offer.rooms, sessions: offer.sessions, path: offer.from,+ names: offer.names.slice(0, 3).join(this.#io.lang === 'en' ? ', ' : '、'),+ bare: size === undefined ? 'Bare' : '',+ ...(size === undefined ? {} : { chats: formatBytes(size.chats), work: formatBytes(size.work), total: formatBytes(size.total) }),+ model: model?.label ?? '', models: this.#models.length > 1 ? this.#models : [],+ options: { ...this.#options },+ }+ }++ /**+ * The acts of the import and copying cards that do not answer them.+ * @param {string} name @param {any} value+ */+ act(name, value) {+ if (name === 'importModel' && this.#models.some(entry => entry.id === value)) {+ this.#profile = value+ this.#io.show(this.card())+ } else if (name === 'importOption' && value !== null && typeof value === 'object' && ['regen', 'skipWork'].includes(value.option)) {+ this.#options = { ...this.#options, [value.option]: value.value === true }+ this.#io.show(this.card())+ } else if (name === 'stopCopy' && this.#copyAbort !== undefined) {+ if (value === 'confirm') { this.#copyAbort.abort(); return }+ this.#confirming = true+ this.#showCopy(true)+ } else if (name === 'keepCopying' && this.#copyAbort !== undefined) {+ this.#confirming = false+ this.#showCopy(true)+ }+ }++ /**+ * @returns {Promise<{ outcome: 'copied', summary: any } | { outcome: 'skipped' | 'pick' | 'gone', newer?: true }>}+ * 'skipped': the start goes on with a new team; 'pick': another place is to be picked;+ * 'gone': the app quits, another start replaced this one, or the failure page took over+ */+ async run() {+ const io = this.#io+ try {+ this.#startCheck()+ const answer = await io.ask(this.card())+ if (answer !== 'copy') return { outcome: answer === 'skip' ? 'skipped' : answer === 'pick' ? 'pick' : 'gone' }+ const short = this.#short()+ if (short !== undefined) {+ const next = await io.ask({ kind: 'importSpace', ...short })+ return { outcome: next === 'skip' ? 'skipped' : next === 'pick' ? 'pick' : 'gone' }+ }+ return await this.#copyLoop()+ } finally {+ clearTimeout(this.#timer)+ this.#checkAbort?.abort()+ io.progress?.(-1)+ }+ }++ // The space the first stage needs and the drive has, when it has too little.+ #short() {+ const size = copySize(this.#sizes, this.#options)+ const { free, drive } = this.#io.room()+ if (size === undefined || free === undefined) return undefined+ const need = size.total + SPARE_BYTES+ if (free >= need) return undefined+ return { need: formatBytes(need), free: formatBytes(free), short: formatBytes(need - free), drive: drive ?? '' }+ }++ // The chats are checked while the card is up, unless DSH holds the team: a check of chats that+ // are being written would say nothing. A holder that turns up meanwhile makes it stale.+ #startCheck() {+ this.#checkAbort?.abort()+ this.#check = undefined+ if (this.#io.inUse()) return+ const abort = new AbortController()+ this.#checkAbort = abort+ const signal = AbortSignal.any([abort.signal, this.#io.signal])+ const state = { progress: { done: 0, total: this.#io.offer.sessions }, listener: () => {}, stale: false }+ this.#check = state+ state.result = this.#io.check(signal, (done, total) => {+ state.progress = { done, total }+ state.listener(done, total)+ })+ // A rejected check that nobody waits for yet must not go unhandled.+ state.result.catch(() => {})+ void this.#io.until(() => this.#io.inUse(), signal).then(() => {+ if (signal.aborted) return+ state.stale = true+ abort.abort()+ })+ }++ // 「DeepSeek Harness 还在用这个团队」: looks again every 2 s and goes on by itself once DSH lets go.+ async #waitFree() {+ const io = this.#io+ const free = new AbortController()+ const next = await io.ask({ kind: 'inUse' }, { settle: io.until(() => !io.inUse(), AbortSignal.any([free.signal, io.signal])) })+ free.abort()+ return next === 'settled' ? undefined : { outcome: next === 'skip' ? 'skipped' : 'gone' }+ }++ async #copyLoop() {+ const io = this.#io+ for (;;) {+ this.#copyAbort = new AbortController()+ this.#confirming = false+ const stop = this.#copyAbort.signal+ const signal = AbortSignal.any([stop, io.signal])+ try {+ const unreadable = await this.#checked(signal)+ if (typeof unreadable === 'object') return unreadable+ if (unreadable > 0) {+ this.#copyAbort = undefined+ const next = await io.ask({ kind: 'newer', n: unreadable })+ return next === 'startWithout' ? { outcome: 'skipped', newer: true } : { outcome: 'gone' }+ }+ const size = copySize(this.#sizes, this.#options)+ const total = size?.total ?? 0+ const of = size === undefined ? '…' : formatBytes(total)+ const checkedStep = this.#copyCard?.steps?.[0] ?? {}+ let eta = null+ this.#setCopy({ step: 2, steps: [checkedStep, { a: formatBytes(0), b: of }, {}], fraction: 0, eta: null })+ await io.warmed()+ signal.throwIfAborted()+ const started = this.#now()+ const summary = await io.copy({+ profile: this.#profile, leaveRegenerable: this.#options.regen, skipWork: this.#options.skipWork, signal,+ onProgress: (bytes) => {+ const done = total > 0 ? Math.min(bytes, total) : bytes+ eta = etaMinutes(eta, { done, total, elapsedMs: this.#now() - started })+ this.#setCopy({ step: 2, steps: [checkedStep, { a: formatBytes(done), b: of }, {}], fraction: total > 0 ? done / total : 0, eta })+ },+ })+ this.#copyAbort = undefined+ this.#confirming = false+ this.#setCopy({ step: 3, steps: [checkedStep, { ...this.#copyCard.steps[1], a: of === '…' ? this.#copyCard.steps[1].a : of }, {}], fraction: 0, eta: null }, true)+ return { outcome: 'copied', summary }+ } catch (error) {+ this.#copyAbort = undefined+ this.#confirming = false+ if (io.signal.aborted) return { outcome: 'gone' }+ // 〔停止复制〕: nothing of the copy stays, and the start goes on with a new team.+ if (stop.aborted) return { outcome: 'skipped' }+ const message = error instanceof Error ? error.message : String(error)+ const next = await io.ask({ kind: 'importFailed', reason: io.reasonOf(error), log: message.split('\n') })+ if (next !== 'retry') return { outcome: next === 'startWithout' ? 'skipped' : 'gone' }+ this.#copyCard = undefined+ }+ }+ }++ // Step 1, the check: the one the card started while it is still good, else a new one, once DSH+ // has let go of the team. The unreadable chats, or the outcome when the user would not wait.+ async #checked(signal) {+ const step1 = (done, total) => {+ this.#setCopy({ step: 1, steps: [{ a: done, b: total }, {}, {}], fraction: total > 0 ? done / total : 0, eta: null })+ }+ for (;;) {+ if (this.#check === undefined || this.#check.stale) {+ if (this.#io.inUse()) {+ const away = await this.#waitFree()+ if (away !== undefined) return away+ }+ this.#startCheck()+ if (this.#check === undefined) continue+ }+ const check = this.#check+ check.listener = step1+ step1(check.progress.done, check.progress.total)+ const unreadable = await Promise.race([check.result, aborted(signal)])+ signal.throwIfAborted()+ if (!check.stale) return unreadable+ }+ }++ #setCopy(card, now = false) {+ this.#copyCard = card+ this.#showCopy(now)+ }++ // The copying card goes out at most every 200 ms; a new step or the stop goes at once.+ #showCopy(now) {+ const card = this.#copyCard+ if (card === undefined) return+ const send = () => {+ this.#timer = undefined+ this.#shownAt = this.#now()+ const { steps, step, fraction } = this.#copyCard+ this.#lastStep = step+ this.#io.progress?.(Math.min(1, (step - 1 + Math.max(0, Math.min(1, fraction))) / 3))+ this.#io.show({ ...this.#copyCard, kind: this.#confirming ? 'stopCopy' : 'copying', steps: steps.map(entry => ({ ...entry })) })+ }+ const due = this.#shownAt + CARD_EVERY_MS - this.#now()+ if (now || due <= 0 || this.#lastStep !== card.step) {+ clearTimeout(this.#timer)+ send()+ } else if (this.#timer === undefined) {+ this.#timer = setTimeout(send, due)+ }+ }+}++// Rejects once `signal` stops.+function aborted(signal) {+ return new Promise((resolve, reject) => {+ const away = () => { reject(signal.reason ?? new Error('stopped')) }+ if (signal.aborted) away()+ else signal.addEventListener('abort', away, { once: true })+ })+}diff --git a/app/src/import.mjs b/app/src/import.mjsindex 639677a9..e43db970 100644--- a/app/src/import.mjs+++ b/app/src/import.mjs@@ -1,6 +1,6 @@// The first-run import: a copy of the Bot team in the user's own DSH home. It only reads there.import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'-import { chmod, cp, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'+import { chmod, cp, lstat, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'import { homedir, hostname } from 'node:os'import { join, relative, resolve } from 'node:path'import { parseSessionFormatLogFilename } from '@deepseek-ai/dsh-session-format'@@ -17,6 +17,10 @@ export const MODEL_ROWS = ['llm-deepseek', 'llm-deepseek-account', 'llm-pi-ai',// The team's lock, its turns in flight and its workspace belong to the old home.const LEFT_BEHIND = new Set(['state.lock', 'inflight.json', 'workspace'])const LOCK_STALE_MS = 60_000+// Folders that a project makes again from its own files (windows-onboarding §4): the import card+// offers to leave them out of the work files, and does so by default from 200 MB on.+export const REGENERABLE = new Set(['node_modules', '.venv', '__pycache__', '.pnpm-store', '.next'])+export const REGENERABLE_DEFAULT_BYTES = 200e6/** The DSH home of the user's own DSH, read as DSH reads DSH_HOME. */export function userDshHome(env = process.env) {@@ -113,24 +117,86 @@ function sessionDirs(from, ids) {return { found, missing }}-async function copySessionDirs(from, to, sessions, signal) {- for (const { id, group } of sessions) {+// fs.cp that tells `seen` the size of each file it is about to copy.+function cpSeen(source, target, { filter = () => true, seen, ...options }) {+ return cp(source, target, {+ ...options,+ filter: async (path) => {+ if (!await filter(path)) return false+ if (seen !== undefined) {+ const info = await lstat(path).catch(() => undefined)+ if (info?.isFile()) seen(info.size)+ }+ return true+ },+ })+}++async function copySessionDirs(from, to, sessions, signal, seen, each = () => {}) {+ for (const [index, { id, group }] of sessions.entries()) {signal?.throwIfAborted()- await cp(join(from, 'sessions', group, id), join(to, 'sessions', group, id), { recursive: true })+ await cpSeen(join(from, 'sessions', group, id), join(to, 'sessions', group, id), { recursive: true, seen })+ each(index + 1, sessions.length)}}/*** Copy the team's Sessions into the DSH home `to`, as they lie in `from`; an abort stops it between Sessions.* @param {string} from @param {any} team @param {string} to @param {AbortSignal} [signal]+ * @param {(done: number, total: number) => void} [onProgress] after each Session* @returns {Promise<string[]>} their ids*/-export async function copySessions(from, team, to, signal) {+export async function copySessions(from, team, to, signal, onProgress) {const { found } = sessionDirs(from, sessionIdsOf(team))- await copySessionDirs(from, to, found, signal)+ await copySessionDirs(from, to, found, signal, undefined, onProgress)return found.map(({ id }) => id)}+// Thrown when measuring runs out of time.+const OVER = Symbol('over budget')++// The bytes under `path` into `tally`, links counted as themselves and what cannot be read as+// nothing; `tally.regen` takes the bytes inside the folders that REGENERABLE names.+async function measure(path, clock, tally, regen = false) {+ if (clock.now() > clock.until) throw OVER+ const entry = await lstat(path).catch(() => undefined)+ if (entry === undefined) return+ if (!entry.isDirectory()) {+ tally.bytes += entry.size+ if (regen) tally.regen += entry.size+ return+ }+ for (const name of await readdir(path).catch(() => [])) await measure(join(path, name), clock, tally, regen || REGENERABLE.has(name))+}++/**+ * What the import card says about the team (windows-onboarding §4): how many of its Sessions are+ * there, the bytes of its chats (the team's own files but its workspace, its Sessions and the+ * attachments), of its work files (the team workspace) and of the regenerable folders among+ * them. The sizes are left out when measuring takes longer than `budget` ms: a team workspace can+ * hold many a node_modules.+ * @returns {Promise<{ sessions: number, chats?: number, work?: number, regen?: number }>}+ */+export async function teamSizes(from, team, { budget = 2000, now = Date.now } = {}) {+ const { found } = sessionDirs(from, sessionIdsOf(team))+ const clock = { until: now() + budget, now }+ const chats = { bytes: 0, regen: 0 }+ const work = { bytes: 0, regen: 0 }+ try {+ const bot = join(from, 'bot')+ for (const name of await readdir(bot).catch(() => [])) {+ if (!LEFT_BEHIND.has(name)) await measure(join(bot, name), clock, chats)+ }+ for (const { id, group } of found) await measure(join(from, 'sessions', group, id), clock, chats)+ await measure(join(from, 'attachments'), clock, chats)+ await measure(join(bot, 'workspace'), clock, work)+ } catch (error) {+ if (error === OVER) return { sessions: found.length }+ throw error+ }+ return { sessions: found.length, chats: chats.bytes, work: work.bytes, regen: work.regen }+}+const logVersion = name => parseSessionFormatLogFilename(name.replace(/\.(zstd|zst|gz|br)$/u, ''))/** The Sessions whose log is in a newer format than the pinned DSH reads. */@@ -189,13 +255,16 @@ async function writeModelRows(to, rows) {* Copy the team of `from` into the data location `to`, which the Host has started on once,* so that DSH does not take the copied Sessions' folders for its own projects. The old team's* workspace files go into `workspace`, without replacing a file that is there, and the key- * files only where the data location has none of the user's own.+ * files only where the data location has none of the user's own. `leaveRegenerable` leaves the+ * REGENERABLE folders out of the workspace files, `skipWork` all of them; `onProgress` hears the+ * bytes copied so far as each file is about to be copied.* Everything but the keys, the model settings and the workspace files is put together in a* folder beside the data and moved in at the end. A copy that stops or fails removes that* folder; one that was killed leaves it behind, and the next copy removes it.- * @param {{ from: string, to: string, workspace: string, profile?: string, dsh?: string, signal?: AbortSignal }} options+ * @param {{ from: string, to: string, workspace: string, profile?: string, dsh?: string, signal?: AbortSignal,+ * leaveRegenerable?: boolean, skipWork?: boolean, onProgress?: (bytes: number) => void }} options*/-export async function importTeam({ from, to, workspace, profile, dsh, signal }) {+export async function importTeam({ from, to, workspace, profile, dsh, signal, leaveRegenerable = false, skipWork = false, onProgress }) {const found = findTeam(from)if (found === undefined) throw new Error(`There is no Bot team in ${from}`)const present = existsSync(join(to, 'bot', 'state.json')) ? readJson(join(to, 'bot', 'state.json')) : undefined@@ -205,16 +274,18 @@ export async function importTeam({ from, to, workspace, profile, dsh, signal })}const stage = join(to, `.import-${String(Date.now())}`)try {- return await copyThroughStage({ found, from, to, workspace, profile, dsh, signal, stage })+ let bytes = 0+ const seen = (size) => { bytes += size; onProgress?.(bytes) }+ return await copyThroughStage({ found, from, to, workspace, profile, dsh, signal, stage, leaveRegenerable, skipWork, seen })} finally {await rm(stage, { recursive: true, force: true, maxRetries: 5 }).catch((error) => { console.error(error) })}}-async function copyThroughStage({ found, from, to, workspace, profile, dsh, signal, stage }) {+async function copyThroughStage({ found, from, to, workspace, profile, dsh, signal, stage, leaveRegenerable, skipWork, seen }) {const oldBot = join(from, 'bot')signal?.throwIfAborted()- await cp(oldBot, join(stage, 'bot'), { recursive: true, filter: path => !LEFT_BEHIND.has(relative(oldBot, path).split(/[\\/]/u)[0]) })+ await cpSeen(oldBot, join(stage, 'bot'), { recursive: true, seen, filter: path => !LEFT_BEHIND.has(relative(oldBot, path).split(/[\\/]/u)[0]) })const team = readJson(join(stage, 'bot', 'state.json'))// The new data location registers its own team workspace. A DSH Agent's Sessions do not move// to a fresh part, so they would go on working in the old team folder in the user's DSH home.@@ -223,15 +294,16 @@ async function copyThroughStage({ found, from, to, workspace, profile, dsh, signawait writeFile(join(stage, 'bot', 'state.json'), JSON.stringify(team, null, 2))const { found: sessions, missing } = sessionDirs(from, sessionIdsOf(found.team))signal?.throwIfAborted()- await copySessionDirs(from, stage, sessions, signal)+ await copySessionDirs(from, stage, sessions, signal, seen)signal?.throwIfAborted()- if (existsSync(join(from, 'attachments'))) await cp(join(from, 'attachments'), join(stage, 'attachments'), { recursive: true })+ if (existsSync(join(from, 'attachments'))) await cpSeen(join(from, 'attachments'), join(stage, 'attachments'), { recursive: true, seen })signal?.throwIfAborted()await mkdir(workspace, { recursive: true })- if (existsSync(join(oldBot, 'workspace'))) {+ if (!skipWork && existsSync(join(oldBot, 'workspace'))) {+ const leave = leaveRegenerable ? path => path.split(/[\\/]/u).some(name => REGENERABLE.has(name)) : undefined// Bots that ran npm or pnpm there leave links, some of them to nothing.- const skipped = await copyTree(join(oldBot, 'workspace'), workspace, { force: false, skip: true, signal })+ const skipped = await copyTree(join(oldBot, 'workspace'), workspace, { force: false, skip: true, signal, leave, seen })if (skipped.length > 0) console.warn('DeepSeek Bot: the import skipped what it could not read in the old team workspace:', skipped)}signal?.throwIfAborted()@@ -259,6 +331,7 @@ async function copyThroughStage({ found, from, to, workspace, profile, dsh, signfrom, at: new Date().toISOString(), ...(dsh ? { dsh } : {}),bots: found.bots, rooms: found.rooms, sessions: sessions.length, missingSessions: missing,keys, keptKeys, modelSettings: rows.length > 0 ? profile : null,+ ...(skipWork ? { workFiles: 'skipped' } : leaveRegenerable ? { workFiles: 'regenerable left out' } : {}),}signal?.throwIfAborted()await writeFile(join(stage, 'bot', 'imported.json'), `${JSON.stringify(summary, null, 2)}\n`)diff --git a/app/src/main.mjs b/app/src/main.mjsindex e2367bf0..b7380f3d 100644--- a/app/src/main.mjs+++ b/app/src/main.mjs@@ -27,6 +27,7 @@ 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', motion: 'ds-bot:motion',+ card: 'ds-bot:app-card', cardShown: 'ds-bot:app-card-shown', cardAnswer: 'ds-bot:app-card-answer',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',@@ -45,6 +46,8 @@ const IMPORT_FILE_MAX = 32 * 1024 * 1024const MOVE_PROBLEMS = { drive: 'dialog.move.drive', nested: 'dialog.move.nested', workspace: 'dialog.move.workspace', program: 'dialog.move.inProgram', notEmpty: 'dialog.move.notEmpty' }// The same problems as the start page's 「这里放不了」 reasons (reason.place.*).const MOVE_REASONS = { drive: 'drive', nested: 'nested', workspace: 'workspace', dsh: 'dsh', program: 'program', notEmpty: 'foreign' }+// A team window that does not say within this time that it shows a card cannot show one.+const CARD_SHOWN_MS = 2000const UPDATE_CHECK_WAIT_MS = 15_000const UPDATE_DOWNLOAD_WAIT_MS = 15 * 60_000// Under this, the start page notes the drive's free space for the first 10 s (onboarding §3).@@ -64,8 +67,8 @@ 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, copyReason, moveProblem, CHECK_PROFILE, PROFILE+let downloadSaver, chooseLocations, defaultPlaces, lang, pickRoot, programFolder, saveLocations, teamIn, teamsAt, tx, HostProcess+let copySessions, findTeam, importTeam, teamInUse, teamSizes, userDshHome, copyData, copyReason, moveProblem, CHECK_PROFILE, PROFILE, ImportFlowlet watchReleases, watchUpdates, RELEASE_PAGE, getDshRuntimeVersion, electronUpdaterlet mainWindow@@ -93,16 +96,21 @@ let picking = falselet proposed// The folder a later start's move card asks about.let moveTo-// Takes the answer of the card that askCard() put up.+// Takes the answer of the card that askCard() put up, and that card's kind.let answering+let asked// The new version that the failure page's update banner offers.let offered// 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.-let pendingImport+// The team in the user's own DSH that the first run offers, until the import card has its+// answer, and the import that runs meanwhile (import-flow.mjs).+let importOffer+let importFlow// Each boot of the engine; a retry starts a new one, and what an old one still reports is dropped.let attempt = 0+// Aborted when the start begins again in another folder: the import card of the boot before goes.+let bootAbort = new AbortController()// The Host answered and the window may talk to it without the launch URL.let hostReady = false// The Host's launch URL: the first window trades it for the Host's cookie.@@ -115,10 +123,8 @@ let bootstraplet tokenSpent = false// The download handler of the app's session is bound once, not once per window.let downloadsBound = false-// Quitting while a first-run dialog is open stops the first run, and during the copy (of the-// first run or of a data move) it waits for the copy to stop at a safe point, so that it leaves-// no half team and no temporary copy.-let choosing+// Quitting during the first run's import (its card or its copy) or a data move waits for it to+// stop at a safe point, so that it leaves no half team and no temporary copy.let copyingconst copyAbort = new AbortController()let browserGuests@@ -143,13 +149,15 @@ const shell = createShell({target.focus()},quit: () => { app.quit() },- busy: () => choosing !== undefined || copying !== undefined,+ busy: () => copying !== undefined,// Before the first run has chosen its places there is no window to show, and before the// first load of the Host there is no address to load.ready: () => places !== undefined && origin !== undefined && bootstrap !== undefined,- notice: { marker: () => join(app.getPath('userData'), 'tray-close-acknowledged'), show: (options) => dialog.showMessageBox(options) },- // Without a tray the close asks whether the app should end.- fallback: { show: (options) => dialog.showMessageBox(options) },+ // The one-time notice is a card in the team window; a page that cannot show it lets the window+ // go to the tray, which is what the notice would have said.+ notice: { marker: () => join(app.getPath('userData'), 'tray-close-acknowledged'), show: options => boxInWindow(options, 0) },+ // Without a tray the close asks whether the app should end; unasked, the window minimizes.+ fallback: { show: options => boxInWindow(options, options.cancelId) },})// The tray icon goes away with the app, and a late answer to the close notice hides nothing.app.once('will-quit', () => { shell.dispose(); botViews?.dispose(); updates?.stop() })@@ -180,24 +188,22 @@ if (canonical !== undefined) {// the tray with.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) },+ onPick: () => {+ // On the import card and the cards of its own picker, the import picks the place itself.+ if (answering !== undefined && ['import', 'importSpace', 'rejected', 'picked'].includes(asked)) { answering('pick'); return }+ (startWindow.kind === 'later' ? moveFromStart() : changePlace()).catch(fail)+ },onAnswer: (value) => {if (answering !== undefined) { answering(value); return }(startWindow.kind === 'later' ? moveAnswer(value) : placeAnswer(value)).catch(fail)},onUpdate: (name) => { updateAct(name) },+ onImport: (name, value) => { importFlow?.act(name, value) },})// 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.app.on('second-instance', () => { if (!startWindow.focus()) shell.open() })app.on('before-quit', (event) => {- if (choosing !== undefined) {- // A first-run dialog is open: the quit waits for it, and the app goes on meanwhile.- event.preventDefault()- shell.cancelQuit()- choosing.abort()- return- }if (copying !== undefined) {// A copy is under way: it stops at a safe point, and the app goes on meanwhile.event.preventDefault()@@ -255,10 +261,10 @@ async function prepare() {}async function loadModules() {- const [browser, views, sources, cookies, cookieFiles, downloads, firstRun, hostProcess, imports, moves, profile, updatesModule, boot, updater] = await Promise.all([+ const [browser, views, sources, cookies, cookieFiles, downloads, firstRun, hostProcess, imports, flows, 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('./import.mjs'), import('./import-flow.mjs'), import('./move-data.mjs'), import('./profile.mjs'), import('./updates.mjs'),import('@deepseek-ai/dsh-app-boot'), import('electron-updater'),]);({ BotBrowserGuests, partitionOf } = browser)@@ -267,9 +273,10 @@ async function loadModules() {;({ applyCookies, CookieImports } = cookies);({ parseCookieFile } = cookieFiles);({ downloadSaver } = downloads)- ;({ chooseLocations, defaultPlaces, pickRoot, programFolder, saveLocations, teamIn, teamsAt, tx } = firstRun)+ ;({ chooseLocations, defaultPlaces, lang, pickRoot, programFolder, saveLocations, teamIn, teamsAt, tx } = firstRun);({ HostProcess } = hostProcess)- ;({ copySessions, findTeam, importTeam, teamInUse, userDshHome } = imports)+ ;({ copySessions, findTeam, importTeam, teamInUse, teamSizes, userDshHome } = imports)+ ;({ ImportFlow } = flows);({ copyData, copyReason, moveProblem } = moves);({ CHECK_PROFILE, PROFILE } = profile);({ watchReleases, watchUpdates, RELEASE_PAGE } = updatesModule)@@ -285,6 +292,7 @@ async function loadModules() {}function run() {+ bootAbort = new AbortController()const mine = (attempt += 1)boot(mine).catch((error) => { if (mine === attempt) void fail(error) })}@@ -341,11 +349,13 @@ function askCard(card, { signal, settle } = {}) {const done = (value) => {if (answering !== done) returnanswering = undefined+ asked = undefinedsignal?.removeEventListener('abort', gone)resolve(value)}const gone = () => { done(undefined) }answering = done+ asked = card.kindif (signal?.aborted || !startWindow.card(card)) { gone(); return }signal?.addEventListener('abort', gone, { once: true })void settle?.then(() => { done('settled') }, gone)@@ -369,12 +379,10 @@ async function boot(mine) {// A reinstall goes on with its data where it is; a new or copied team can still move.if (teams.team === undefined) tellPlace(defaultPlaces().dataDir)}- choosing = new AbortController()- const where = await chooseLocations(choosing.signal, ui()).finally(() => { choosing = undefined })- if (where.quit) { app.exit(0); return }+ const where = chooseLocations()setPlaces({ dataDir: where.dataDir, workspace: where.workspace })- pendingImport = where.import- if (first) startWindow.explain(explainOf({ offered: where.offered === true, team: teamIn(where.dataDir) }))+ importOffer = where.offer+ if (first) startWindow.explain(explainOf({ offered: importOffer !== undefined, team: teamIn(where.dataDir) }))else tellLowSpace(where.freeAtStart)}// Also the check that the data folder can be written.@@ -439,7 +447,7 @@ function tellLowSpace(freeAtStart) {// A cancelled picker leaves things as they were: the line, or the card it came from. Not during// the first run's copy, whose team would be left behind.async function changePlace() {- if (startWindow.kind !== 'first' || places === undefined || choosing !== undefined || copying !== undefined || picking || restarting || stopping || failed) return+ if (startWindow.kind !== 'first' || places === undefined || copying !== undefined || picking || restarting || stopping || failed) returnpicking = truetry {// One wait for the picker and what follows it: a team view that becomes ready meanwhile@@ -486,6 +494,7 @@ async function placeAnswer(value) {// that may be up on the default folder stops, what this start made there goes, and the boot runs// again. The places are saved at once: the import question has been answered by now.async function startOver(root) {+ bootAbort.abort()const mine = (attempt += 1)forgetHost()failed = false@@ -555,18 +564,11 @@ function newCheck(home, list) {* during the copy, or when a retry during the copy starts the engine itself*/async function startEngine(mine) {- if (pendingImport !== undefined) {- const where = { ...places, import: pendingImport }- pendingImport = undefined- // The team is about to live here; moving it is Settings' job (the data move).- startWindow.place(undefined)- // The copy's time is not the engine's: the start's clock stands still, and the 180 s- // question with it.- copying = startWindow.asking(copyTeam(where, copyAbort.signal))- const copied = await copying- copying = undefined- if (copied === 'quit') app.exit(0)- if (copied !== undefined || mine !== attempt) return undefined+ let warm+ if (importOffer !== undefined) {+ const imported = await importStep(mine)+ if (imported === undefined || mine !== attempt) return undefined+ warm = imported.warm}// 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.@@ -575,7 +577,7 @@ async function startEngine(mine) {updates = startUpdates()updates?.subscribe((state) => { mainWindow?.webContents.send(IPC.appUpdateChanged, state) })}- host = newHost()+ host = warm?.host ?? newHost()host.onMessage(message => {if (message?.type !== 'ds-bot:browser-endpoint' || typeof message.id !== 'string' || !isBotId(message.botId)) returnconst downloadRoots = message.downloadRoots@@ -587,7 +589,104 @@ async function startEngine(mine) {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()+ const engine = await (warm?.up ?? host.start())+ // The copying card stays on 「启动团队」 until the engine of the copied team is up.+ if (mine === attempt) startWindow.card(undefined)+ return engine+}++// The import card while the engine warms up on the new data location (windows-onboarding §4,+// start-window §6). The places are saved once the card has its answer. Undefined when this start+// gives way (a quit, another place, the failure page); else the engine that warmed up, when the+// start goes on with it: 〔先不复制〕 takes it as it is, without a restart.+async function importStep(mine) {+ const offer = importOffer+ const where = { ...places }+ const signal = AbortSignal.any([copyAbort.signal, bootAbort.signal])+ const warm = newHost()+ host = warm+ let warmStopped = false+ const up = warm.start()+ // The engine's arc fills once it is up; the team's waits for the answer.+ up.then(() => { if (mine === attempt && !warmStopped) startWindow.done('engine') }, () => {})+ const sizes = await teamSizes(offer.from, offer.team).catch((error) => { console.error(error); return { sessions: 0 } })+ let result+ for (;;) {+ if (signal.aborted || mine !== attempt) return undefined+ const flow = new ImportFlow({+ offer: { from: offer.from, bots: offer.bots, rooms: offer.rooms, names: botNames(offer.team), sessions: sizes.sessions, sizes, profiles: offer.profiles },+ ask: (card, options) => askCard(card, { signal, ...options }),+ show: (card) => { startWindow.card(card) },+ room: () => ({ free: freeSpace(where.dataDir), drive: driveOf(where.dataDir) }),+ inUse: () => teamInUse(offer.from),+ until,+ check: (checkSignal, onProgress) => checkTeam(where, checkSignal, onProgress),+ // The copy goes into the data location that the engine has started on once, and with the+ // engine stopped.+ warmed: async () => {+ await up+ warmStopped = true+ await warm.stop()+ if (host === warm) host = undefined+ },+ copy: options => importTeam({ from: offer.from, to: where.dataDir, workspace: where.workspace, dsh: getDshRuntimeVersion(), ...options }),+ reasonOf: copyReason,+ progress: setProgress,+ lang: lang(),+ signal,+ })+ importFlow = flow+ // The card's and the copy's time is not the engine's: the start's clock stands still, and+ // the 180 s question with it.+ copying = startWindow.asking(flow.run())+ try {+ result = await copying+ } finally {+ copying = undefined+ importFlow = undefined+ }+ if (result.outcome !== 'pick') break+ if (await importElsewhere(signal)) return undefined+ }+ if (result.outcome === 'gone' || signal.aborted || mine !== attempt) return undefined+ importOffer = undefined+ saveLocations(where)+ if (result.outcome === 'copied') {+ const { summary } = result+ console.log(`DeepSeek Bot: copied ${String(summary.bots)} Bots and ${String(summary.sessions)} Sessions from ${summary.from}`)+ // The team lives here now; moving it is Settings' job (the data move).+ startWindow.place(undefined)+ return {}+ }+ startWindow.card(undefined)+ return { warm: warmStopped ? undefined : { host: warm, up } }+}++const botNames = team => Object.values(team.bots ?? {}).map(bot => bot?.name).filter(name => typeof name === 'string' && name !== '')++// 〔选择其他位置…〕 on the import's space card, or 「换个位置…」 while the import card is up: the+// picker and the root rule as for 「换个位置…」 (changePlace), asked on cards that this import+// waits for. True once the start begins again in the new root; false to go back to the import+// card.+async function importElsewhere(signal) {+ for (;;) {+ const picked = await pickRoot(pickFrom(places.dataDir), signal, ui())+ if (signal.aborted || picked === undefined) return false+ const root = rootOf(picked, { dshHome: userDshHome(), program: app.isPackaged ? programFolder() : undefined, current: places })+ if (root.same) return false+ if (root.reason !== undefined) {+ console.log(`DeepSeek Bot: the place ${root.at} cannot be used (${root.reason})`)+ if (await askCard({ kind: 'rejected', reason: root.reason, path: root.at }, { signal }) === 'pick') continue+ return false+ }+ if (root.added) {+ const answer = await askCard({ kind: 'picked', path: root.root }, { signal })+ if (answer === 'pick') continue+ if (answer !== 'use') return false+ }+ await startOver(root)+ return true+ }}function handleIpc() {@@ -595,6 +694,8 @@ function handleIpc() {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, report) => { if (fromWindow(event)) startWindow.ready(report) })+ ipcMain.on(IPC.cardShown, (event, id) => { if (fromWindow(event)) cards.get(id)?.shown() })+ ipcMain.on(IPC.cardAnswer, (event, id, index) => { if (fromWindow(event)) cards.get(id)?.settle(Number.isInteger(index) ? index : -1) })// The start window takes the app's theme and the Bot animation tier at the next start, before// the team view has loaded; Mica and the caption buttons follow the theme at once.ipcMain.on(IPC.nativeTheme, (event, source) => {@@ -730,59 +831,20 @@ function handleIpc() {const owner = () => startWindow.owner() ?? mainWindowconst 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, signal) {- const unreadable = await checkTeam(where, signal)- if (signal.aborted) return 'stopped'- if (unreadable > 0) {- const { response } = await startWindow.asking(dialog.showMessageBox(owner(), { type: 'warning', title: 'DeepSeek Bot', noLink: true, message: tx('dialog.import.newer', { n: unreadable }), buttons: [tx('btn.quit'), tx('btn.startWithout')], defaultId: 0, cancelId: 0, signal }))- if (signal.aborted) return 'stopped'- if (response === 0) return 'quit'- saveLocations(where)- return undefined- }- const warm = newHost()- host = warm- const stopWarm = () => { void warm.stop() }- signal.addEventListener('abort', stopWarm, { once: true })- try {- await warm.start()- if (signal.aborted) return 'stopped'- setProgress(2)- await warm.stop()- host = undefined- const summary = await importTeam({ ...where.import, to: where.dataDir, workspace: where.workspace, dsh: getDshRuntimeVersion(), signal })- console.log(`DeepSeek Bot: copied ${String(summary.bots)} Bots and ${String(summary.sessions)} Sessions from ${summary.from}`)- } catch (error) {- if (signal.aborted) return 'stopped'- console.error(error)- await startWindow.asking(dialog.showMessageBox(owner(), { type: 'warning', title: 'DeepSeek Bot', message: tx('dialog.import.failed', { message: error instanceof Error ? error.message : String(error) }), signal }))- if (signal.aborted) return 'stopped'- } finally {- signal.removeEventListener('abort', stopWarm)- 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, signal) {+// Before the copy, the app's own DSH reads every chat of the team once, in a DSH home of its own+// so that nothing of the check stays in the data: a newer DSH can write records that this one+// refuses while the log format stays the same. The number of chats it cannot read; a check that+// fails lets the copy go on unchecked. `onProgress` counts the chats copied for it.+async function checkTeam(where, signal, onProgress) {// 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) })}const home = join(where.dataDir, `.import-check-${String(Date.now())}`)try {- const found = findTeam(where.import.from)- const ids = found === undefined ? [] : await copySessions(where.import.from, found.team, home, signal)+ const found = findTeam(importOffer?.from ?? userDshHome())+ const ids = found === undefined ? [] : await copySessions(found.from, found.team, home, signal, onProgress)if (ids.length === 0) return 0- setProgress(2)const list = join(home, 'check.json')writeFileSync(list, JSON.stringify(ids))const check = newCheck(home, list)@@ -801,7 +863,6 @@ async function checkTeam(where, signal) {if (!signal.aborted) console.error('DeepSeek Bot: the chats were not checked before the copy:', error)return 0} finally {- setProgress(-1)await rm(home, { recursive: true, force: true, maxRetries: 5 }).catch((error) => { console.error(error) })}}@@ -886,13 +947,14 @@ async function moveAnswer(value) {}// The folder picker, the checks and the question of a move from Settings: the folder, or none.+// The question and a refusal are cards in the team window; only the picker is a system window.async function askMove(workspace) {const { canceled, filePaths } = await dialog.showOpenDialog(owner(), { title: tx('dialog.pickMove'), defaultPath: dirname(places.dataDir), properties: ['openDirectory', 'createDirectory', 'promptToCreate'] })if (canceled || filePaths[0] === undefined) return undefinedconst to = resolve(filePaths[0])if (await moveRefused(to, workspace)) return undefined- const { response } = await dialog.showMessageBox(owner(), { type: 'question', title: 'DeepSeek Bot', noLink: true, message: tx('dialog.move.confirm', { to }), detail: tx('dialog.move.detail', { from: places.dataDir }), buttons: [tx('btn.move'), tx('btn.cancel')], defaultId: 0, cancelId: 1 })- if (response !== 0 || stopping || await moveRefused(to, workspace)) return undefined+ const answer = await askInWindow({ message: tx('dialog.move.confirm', { to }), detail: tx('dialog.move.detail', { from: places.dataDir }), buttons: [{ label: tx('btn.move'), primary: true }, { label: tx('btn.cancel') }], cancel: 1 })+ if (answer !== 0 || stopping || await moveRefused(to, workspace)) return undefinedreturn to}@@ -909,7 +971,7 @@ function moveProblemOf(to, workspace) {async function moveRefused(to, workspace) {const problem = moveProblemOf(to, workspace)if (problem === undefined) return false- await dialog.showMessageBox(owner(), { type: 'warning', title: 'DeepSeek Bot', message: problem === 'dsh' ? tx('dialog.move.inDsh', { home: userDshHome() }) : tx(MOVE_PROBLEMS[problem]), buttons: [tx('btn.ok')] })+ await askInWindow({ message: problem === 'dsh' ? tx('dialog.move.inDsh', { home: userDshHome() }) : tx(MOVE_PROBLEMS[problem]), buttons: [{ label: tx('btn.ok'), primary: true }], cancel: 0 })return true}@@ -1020,16 +1082,61 @@ function windowShown() {// question on it would go with it. After a failed start, fail() takes the update over.const afterHandoff = async () => { await startWindow.teamShown; return !failed }+// An update question that the page cannot show counts as 「以后再说」: the update installs at the+// next quit, and the About row still offers it.async function askRestartNow(version) {if (failed || !await afterHandoff()) return false- const { response } = await dialog.showMessageBox(owner(), { type: 'info', title: 'DeepSeek Bot', message: tx('dialog.update.ready', { version }), detail: tx('dialog.update.readyDetail'), buttons: [tx('btn.restart'), tx('btn.notNowRestart')], defaultId: 0, cancelId: 1, noLink: true })- return response === 0+ return await askInWindow({ message: tx('dialog.update.ready', { version }), detail: tx('dialog.update.readyDetail'), buttons: [{ label: tx('btn.restart'), primary: true }, { label: tx('btn.notNowRestart') }], cancel: 1 }) === 0}async function askDownloadNow(version) {if (failed || !await afterHandoff()) return false- const { response } = await dialog.showMessageBox(owner(), { type: 'info', title: 'DeepSeek Bot', message: tx('dialog.update.available', { version }), detail: tx('dialog.update.availableDetail'), buttons: [tx('btn.download'), tx('btn.notNowDownload')], defaultId: 0, cancelId: 1, noLink: true })- return response === 0+ return await askInWindow({ message: tx('dialog.update.available', { version }), detail: tx('dialog.update.availableDetail'), buttons: [{ label: tx('btn.download'), primary: true }, { label: tx('btn.notNowDownload') }], cancel: 1 }) === 0+}++// The cards that the team window shows, by id, until they have their answer.+const cards = new Map()+let cardCount = 0++/**+ * A question of the app in the team window, on a card over its page instead of a message box+ * (preload.cjs showCard, page-card.css): the index of the button the user clicks, -1 when a newer+ * card took its place, undefined when the page cannot show it (not loaded, gone, or silent for+ * CARD_SHOWN_MS) or goes away before the answer.+ * @param {{ message: string, detail?: string, buttons: { label: string, primary?: boolean }[], cancel?: number }} card+ * @returns {Promise<number | undefined>}+ */+function askInWindow(card) {+ const win = mainWindow+ const contents = win?.webContents+ if (win === undefined || win.isDestroyed() || contents.isLoading() || !contents.getURL().startsWith(`${origin}/`)) return Promise.resolve(undefined)+ const id = (cardCount += 1)+ return new Promise((resolve) => {+ let seen = false+ const settle = (value) => {+ if (!cards.has(id)) return+ cards.delete(id)+ clearTimeout(timer)+ contents.off('did-start-loading', away)+ contents.off('destroyed', away)+ resolve(value)+ }+ const away = () => { settle(undefined) }+ const timer = setTimeout(() => { if (!seen) away() }, CARD_SHOWN_MS)+ cards.set(id, { settle, shown: () => { seen = true } })+ contents.once('did-start-loading', away)+ contents.once('destroyed', away)+ contents.send(IPC.card, { id, ...card })+ })+}++// The shell's message-box questions (the tray notice, the close without a tray) on the team+// window's card; `unasked` is the answer when the page cannot show it.+async function boxInWindow(options, unasked) {+ const buttons = options.buttons.map((label, index) => ({ label, primary: index === options.defaultId }))+ const cancel = options.cancelId >= 0 ? options.cancelId : undefined+ const answer = await askInWindow({ message: options.message, detail: options.detail, buttons, cancel })+ return { response: answer === undefined ? unasked : answer }}// What the updater does when the user says yes. The answer may come later, when the window@@ -1109,6 +1216,8 @@ function createWindow() {}const fonts = readFileSync(join(here, 'fonts.css'), 'utf8')contents.on('dom-ready', () => { void contents.insertCSS(fonts) })+ const card = readFileSync(join(here, 'page-card.css'), 'utf8')+ contents.on('dom-ready', () => { void contents.insertCSS(card) })contents.setWindowOpenHandler(({ url }) => {// DSH's sign-in opens a blank window during the click and sends it to the sign-in page later.if (url === 'about:blank') return { action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { sandbox: true, webviewTag: false } } }diff --git a/app/src/page-card.css b/app/src/page-card.cssnew file mode 100644index 00000000..f58ac1b9--- /dev/null+++ b/app/src/page-card.css@@ -0,0 +1,48 @@+/* DeepSeek Bot's own questions in the team window: one card over the page in place of a message+ box (main.mjs askInWindow, preload.cjs showCard). The main process inserts this sheet; the+ colors and springs are the start window's, scoped to the card's layer so that the page's own+ stay as they are. */+/* tokens */+/* Generated from the DeepSeek theme in ds-bot/src/client/themes.js, inks.js and styles.js by scripts/start-assets.mjs; do not edit. */+.dsb-card-layer{color-scheme:light dark;--bt-main:#fcfcfc;--bt-card:#ffffff;--bt-ink:#141414;--bt-ink-2:rgba(20,20,20,0.6);--bt-line:rgba(20,20,20,0.08);--bt-line-2:rgba(20,20,20,0.15);--bt-hover:rgba(119,119,119,.09);--bt-accent:#4d6bfe;--bt-accent-ink:#ffffff;--bt-ink-deepseek:#4D6BFE;--bt-green:#00c972;--bt-danger:#e02135}+@media (prefers-color-scheme:dark){.dsb-card-layer{--bt-main:#141414;--bt-card:#1f1f1f;--bt-ink:#f2f2f2;--bt-ink-2:rgba(242,242,242,0.6);--bt-line:rgba(242,242,242,0.08);--bt-line-2:rgba(242,242,242,0.15);--bt-hover:rgba(160,160,160,.12);--bt-accent:#5b7bff;--bt-accent-ink:#141414;--bt-ink-deepseek:#6A84FF}}+/* /tokens */+/* springs */+/* Generated from ds-bot/src/client/motion.js by scripts/start-assets.mjs; do not edit. */+.dsb-card-layer {+ --spring-shape: linear(0.0000,0.0510,0.1692,0.3153,0.4639,0.6001,0.7163,0.8102,0.8823,0.9350,0.9717,0.9955,1.0098,1.0171,1.0198,1.0195,1.0175,1.0147,1.0117,1.0089,1.0064,1.0044,1.0028,1.0016,1.0000);+ --spring-shape-ms: 420ms;+ --spring-tap: linear(0.0000,0.0541,0.1776,0.3279,0.4784,0.6141,0.7281,0.8187,0.8874,0.9369,0.9709,0.9928,1.0057,1.0124,1.0150,1.0149,1.0134,1.0112,1.0089,1.0067,1.0048,1.0033,1.0021,1.0013,1.0000);+ --spring-tap-ms: 290ms;+ --spring-pop: linear(0.0000,0.0698,0.2385,0.4520,0.6677,0.8566,1.0027,1.1009,1.1539,1.1695,1.1578,1.1293,1.0931,1.0566,1.0245,0.9997,0.9830,0.9740,0.9713,0.9732,0.9781,0.9842,0.9904,0.9958,1.0000);+ --spring-pop-ms: 430ms;+ --spring-stretch: linear(0.0000,0.0740,0.2474,0.4594,0.6666,0.8422,0.9740,1.0602,1.1060,1.1202,1.1126,1.0924,1.0670,1.0419,1.0204,1.0042,0.9934,0.9875,0.9856,0.9863,0.9887,0.9917,0.9947,0.9974,1.0000);+ --spring-stretch-ms: 560ms;+ --spring-list: linear(0.0000,0.0138,0.0503,0.1030,0.1666,0.2367,0.3099,0.3836,0.4556,0.5244,0.5891,0.6489,0.7034,0.7525,0.7962,0.8347,0.8681,0.8969,0.9215,0.9421,0.9592,0.9733,0.9846,0.9936,1.0000);+ --spring-list-ms: 190ms;+}+/* /springs */++.dsb-card-layer{position:fixed;inset:0;z-index:2147483646;display:grid;place-items:center;padding:16px;box-sizing:border-box;background:rgba(0,0,0,.28);font:14px/22px -apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei UI",system-ui,sans-serif;color:var(--bt-ink);-webkit-app-region:no-drag;app-region:no-drag;opacity:0;transition:opacity .16s ease-in}+@media (prefers-color-scheme:dark){.dsb-card-layer{background:rgba(0,0,0,.5)}}+.dsb-card-layer[data-open]{opacity:1;transition:opacity .22s ease-out}+.dsb-card-layer *{box-sizing:border-box}+.dsb-card{width:min(440px,100%);max-height:calc(100vh - 32px);overflow:auto;padding:20px 24px;border:1px solid var(--bt-line-2);border-radius:12px;background:var(--bt-card);box-shadow:0 12px 40px rgba(0,0,0,.18);text-align:left;translate:0 8px;scale:.98;transition:translate .16s ease-in,scale .16s ease-in,filter .16s ease-in}+.dsb-card-layer[data-open] .dsb-card{translate:0 0;scale:1;transition:translate var(--spring-shape-ms) var(--spring-shape),scale var(--spring-shape-ms) var(--spring-shape)}+/* The way out is the start window's card exit: down 6 px, to .975, blurred 3 px. */+.dsb-card-layer[data-leaving] .dsb-card{translate:0 6px;scale:.975;filter:blur(3px)}+.dsb-card-title{margin:0;font-size:15px;line-height:22px;font-weight:600;color:var(--bt-ink);white-space:pre-line;overflow-wrap:anywhere}+.dsb-card-detail{margin:6px 0 0;font-size:14px;line-height:22px;color:var(--bt-ink-2);white-space:pre-line;overflow-wrap:anywhere}+.dsb-card-actions{display:flex;flex-wrap:wrap;justify-content:flex-end;gap:8px;margin-top:18px}+.dsb-card-btn{all:unset;display:inline-flex;align-items:center;justify-content:center;flex:none;height:36px;padding:0 16px;border-radius:999px;background:var(--bt-hover);color:var(--bt-ink);font:inherit;font-size:14px;line-height:20px;white-space:nowrap;cursor:pointer;transition:background-color .12s,color .12s,scale var(--spring-tap-ms) var(--spring-tap)}+.dsb-card-btn:hover{background:color-mix(in srgb,var(--bt-hover),var(--bt-ink) 6%)}+.dsb-card-btn:active{scale:.96}+.dsb-card-btn:focus-visible{outline:2px solid var(--bt-accent);outline-offset:2px}+.dsb-card-btn[data-look=primary]{background:var(--bt-accent);color:var(--bt-accent-ink)}+.dsb-card-btn[data-look=primary]:hover{background:color-mix(in srgb,var(--bt-accent),var(--bt-ink) 10%)}+/* start-window §9: fades only, .12 s in and .16 s out, without movement, scale or blur. */+@media (prefers-reduced-motion:reduce){+ .dsb-card-layer[data-open]{transition:opacity .12s ease-out}+ .dsb-card,.dsb-card-layer[data-open] .dsb-card,.dsb-card-layer[data-leaving] .dsb-card{translate:none;scale:none;filter:none;transition:none}+ .dsb-card-btn,.dsb-card-btn:active{transition:background-color .12s,color .12s;scale:none}+}diff --git a/app/src/preload.cjs b/app/src/preload.cjsindex 5495994d..8cd7e2ea 100644--- a/app/src/preload.cjs+++ b/app/src/preload.cjs@@ -48,6 +48,8 @@ if (startPage !== undefined) {else run()}loaded(reportLook)+ // The app's own questions (the tray notice, an update, a data move), on a card over the page.+ ipcRenderer.on('ds-bot:app-card', (_event, card) => { loaded(() => { showCard(card) }) })const caption = process.argv.find(value => value.startsWith('--ds-bot-caption='))if (caption !== undefined) {ipcRenderer.on('ds-bot:fullscreen', (_event, fullscreen) => {@@ -60,6 +62,80 @@ if (startPage !== undefined) {}}+// The card that the team window shows in place of a message box (main.mjs askInWindow): a line,+// an optional detail and the buttons, styled by page-card.css, which the main process inserts.+// The answer is the index of the button; -1 when a newer card takes its place. Enter is the+// focused button; Escape is `cancel`, when the card has one; Tab stays on the card's buttons.+let openCard+function showCard(card) {+ if (card === null || typeof card !== 'object' || !Number.isInteger(card.id) || !Array.isArray(card.buttons)) return+ openCard?.close(-1)+ const make = (tag, className, text) => Object.assign(document.createElement(tag), { className, ...(text === undefined ? {} : { textContent: String(text) }) })+ const layer = make('div', 'dsb-card-layer')+ const box = make('section', 'dsb-card')+ box.setAttribute('role', 'alertdialog')+ box.setAttribute('aria-modal', 'true')+ const title = make('h2', 'dsb-card-title', card.message ?? '')+ title.id = `dsb-card-title-${String(card.id)}`+ box.setAttribute('aria-labelledby', title.id)+ box.append(title)+ if (typeof card.detail === 'string' && card.detail !== '') {+ const detail = make('p', 'dsb-card-detail', card.detail)+ detail.id = `dsb-card-detail-${String(card.id)}`+ box.setAttribute('aria-describedby', detail.id)+ box.append(detail)+ }+ const actions = make('div', 'dsb-card-actions')+ const buttons = card.buttons.map((entry, index) => {+ const button = make('button', 'dsb-card-btn', entry?.label ?? '')+ button.type = 'button'+ button.dataset.look = entry?.primary ? 'primary' : 'soft'+ button.addEventListener('click', () => { close(index) })+ return button+ })+ actions.append(...buttons)+ box.append(actions)+ layer.append(box)+ const before = document.activeElement+ let done = false+ const keys = (event) => {+ if (event.key === 'Escape' && Number.isInteger(card.cancel) && card.cancel >= 0) {+ event.preventDefault()+ close(card.cancel)+ } else if (event.key === 'Tab' && buttons.length > 0) {+ const at = buttons.indexOf(document.activeElement)+ event.preventDefault()+ buttons[(at + (event.shiftKey ? -1 : 1) + buttons.length) % buttons.length].focus()+ }+ // The page's own shortcuts wait while the card is up.+ event.stopPropagation()+ }+ // Focus that leaves for the page comes back to the card.+ const keep = (event) => { if (!layer.contains(event.target)) (buttons.find(button => button.dataset.look === 'primary') ?? buttons[0])?.focus() }+ function close(index) {+ if (done) return+ done = true+ if (openCard?.close === close) openCard = undefined+ document.removeEventListener('keydown', keys, true)+ document.removeEventListener('focusin', keep, true)+ ipcRenderer.send('ds-bot:app-card-answer', card.id, index)+ delete layer.dataset.open+ layer.dataset.leaving = ''+ layer.inert = true+ setTimeout(() => { layer.remove() }, 220)+ if (before instanceof HTMLElement && before.isConnected) before.focus({ preventScroll: true })+ }+ document.addEventListener('keydown', keys, true)+ document.addEventListener('focusin', keep, true)+ ;(document.body ?? document.documentElement).append(layer)+ // The layer is laid out once before it opens, so that the opening transitions run.+ void layer.offsetWidth+ layer.dataset.open = ''+ ;(buttons.find(button => button.dataset.look === 'primary') ?? buttons[0])?.focus({ preventScroll: true })+ openCard = { close }+ ipcRenderer.send('ds-bot:app-card-shown', card.id)+}+// The app's theme (DSH's) and the Bot animation tier (ds-bot's), which the start window takes// at the next start.function reportLook() {diff --git a/app/src/start-window.mjs b/app/src/start-window.mjsindex 90ca426c..b7b1a5a2 100644--- a/app/src/start-window.mjs+++ b/app/src/start-window.mjs@@ -44,6 +44,11 @@ const ACT_VIEWS = {// (「会放在…」, a place that cannot be used).pick: ['boot', 'card', 'watchdog'],answer: ['card'],+ // The import card's model and options, and the copying card's stop (windows-onboarding §4).+ importModel: ['card'],+ importOption: ['card'],+ stopCopy: ['card'],+ keepCopying: ['card'],// The failure page's update banner: 〔下载〕 or 〔重试〕 on it, and 「手动下载」.installUpdate: ['failed'],manualDownload: ['failed'],@@ -251,6 +256,8 @@ export const detailsText = ({ version, platform, arch, reason, lines }) => [`Deeconst note = message => { console.log(`DeepSeek Bot: start window: ${message}`) }// The page sends a button's detail as { value }; anything else counts as none.const valueOf = payload => (payload !== null && typeof payload === 'object' && typeof payload.value === 'string' ? payload.value.slice(0, 40) : undefined)+// An option of the import card: its name and whether it is ticked.+const optionOf = payload => (payload !== null && typeof payload === 'object' && typeof payload.option === 'string' ? { option: payload.option.slice(0, 40), value: payload.value === true } : undefined)export class StartWindow {#o@@ -291,12 +298,14 @@ export class StartWindow {* onRetry: () => void, onReload: () => void, onClose: () => void,* onPick?: (value?: string) => void, onAnswer?: (value?: string) => void,* onUpdate?: (name: 'installUpdate' | 'manualDownload') => void,+ * onImport?: (name: 'importModel' | 'importOption' | 'stopCopy' | 'keepCopying', value: unknown) => void,* }} 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; `onPick` when* the page asks for the folder picker ('changePlace' from its place line, nothing from a* card's 〔重新选〕; on a later start the line's button moves the data), `onAnswer` with a* card's answer ('use' for 〔继续〕 on 「会放在…」), `onUpdate` with a button of the failure- * page's update banner.+ * page's update banner, `onImport` with the import card's model and options and the copying+ * card's stop.*/constructor(options) {this.#o = options@@ -705,6 +714,8 @@ export class StartWindow {else if (name === 'pick') this.#o.onPick?.(valueOf(payload))else if (name === 'answer') this.#o.onAnswer?.(valueOf(payload))else if (name === 'installUpdate' || name === 'manualDownload') this.#o.onUpdate?.(name)+ else if (name === 'importOption') this.#o.onImport?.(name, optionOf(payload))+ else if (name === 'importModel' || name === 'stopCopy' || name === 'keepCopying') this.#o.onImport?.(name, valueOf(payload))return true}diff --git a/app/src/start/start.html b/app/src/start/start.htmlindex e9efd5ad..7ed30d4b 100644--- a/app/src/start/start.html+++ b/app/src/start/start.html@@ -38,13 +38,13 @@<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="import" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.import"></h2><p class="lead" data-t="card.import.lead{bare}"></p><p class="small extra-row"><span data-t="card.import.extra{bare}"></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><section class="card" data-kind="inUse" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.inUse"></h2><p class="lead" data-t="card.inUse.lead"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="skip" data-t="btn.skipCopy"></button></div></section><section class="card" data-kind="newerUpdating" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.newer"></h2><p class="lead" data-t="card.newerUpdating.lead"></p><p class="small"><span data-t="card.update.slow"></span> <button class="btn" data-look="link" data-act="manualDownload" data-t="btn.manualDownload"></button></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="skip" data-t="btn.skipCopy"></button></div></section><section class="card" data-kind="newer" hidden><div class="card-scroll"><h2 class="card-title" data-t="say.newer"></h2><p class="lead" data-t="card.newer.lead"></p></div><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="startWithout" data-t="btn.startWithout"></button><p class="foot" data-t="note.copyAgain"></p></div></section>-<section class="card" data-kind="importFailed" hidden><div class="card-scroll"><p class="lead" data-t="card.importFailed.lead"></p><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="answer" data-detail="startWithout" data-t="btn.startWithout"></button><button class="btn" data-look="soft" data-act="copyDetails" data-t="btn.copyDetails"></button><button class="btn" data-look="soft" data-act="saveLog" data-t="btn.saveLog"></button><button class="btn disclose" data-look="link" data-act="toggleDetails" 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="importFailed" hidden><div class="card-scroll"><p class="lead" data-t="card.importFailed.lead"></p><div class="card-actions"><button class="btn" data-look="primary" data-act="answer" data-detail="retry" data-t="btn.retry"></button><button class="btn" data-look="soft" data-act="answer" data-detail="startWithout" data-t="btn.startWithout"></button><button class="btn" data-look="soft" data-act="copyDetails" data-t="btn.copyDetails"></button><button class="btn" data-look="soft" data-act="saveLog" data-t="btn.saveLog"></button><button class="btn disclose" data-look="link" data-act="toggleDetails" 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="watchdog" hidden><div class="card-actions"><button class="btn" data-look="primary" data-act="wait" data-t="btn.wait"></button><button class="btn" data-look="soft" data-act="retry" data-t="btn.retry"></button><button class="btn" data-look="soft" data-act="copyDetails" data-t="btn.copyDetails"></button><button class="btn" data-look="soft" data-act="saveLog" data-t="btn.saveLog"></button></div></section><section class="card" data-kind="failed" hidden><div class="card-scroll"><p class="lead" data-t="reason.start.{reason}"></p><div class="banner" hidden><div class="banner-row"><p class="lead" data-t="card.update.available"></p><button class="btn" data-look="primary" data-act="installUpdate" data-u="available" data-t="btn.download"></button></div><div class="banner-down" data-u="downloading"><p class="small banner-line"><span data-t="card.update.downloading"></span><span class="slow"><span data-t="card.update.slow"></span><button class="btn" data-look="link" data-act="manualDownload" data-t="btn.manualDownload"></button></span></p><div class="bar"><span class="bar-fill"></span></div></div><p class="small" data-u="installing" data-t="card.update.installing"></p><div class="banner-fail" data-u="failed"><p class="small danger" data-t="card.update.failed"></p><button class="btn" data-look="small" data-act="installUpdate" data-t="btn.retry"></button><button class="btn" data-look="small" data-act="manualDownload" data-t="btn.manualDownload"></button></div></div><div class="card-actions"><button class="btn" data-look="primary" data-act="retry" data-main data-t="btn.retry"></button><button class="btn" data-look="soft" data-act="pick" data-detail="changePlace" data-places data-t="btn.changePlace" hidden></button><button class="btn" data-look="soft" data-act="freshStart" data-places data-t="btn.freshStart" hidden></button><button class="btn" data-look="soft" data-act="copyDetails" data-t="btn.copyDetails"></button><button class="btn" data-look="soft" data-act="saveLog" data-t="btn.saveLog"></button><button class="btn disclose" data-look="link" data-act="toggleDetails" 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="viewFailed" hidden><div class="card-actions"><button class="btn" data-look="primary" data-act="reloadView" data-t="btn.reload"></button><button class="btn" data-look="soft" data-act="copyDetails" data-t="btn.copyDetails"></button><button class="btn" data-look="soft" data-act="saveLog" data-t="btn.saveLog"></button></div></section>diff --git a/app/src/start/start.js b/app/src/start/start.jsindex fb11af2b..7a7b3e78 100644--- a/app/src/start/start.js+++ b/app/src/start/start.js@@ -360,6 +360,8 @@ function copying(el) {const card = s.cardel.toggleAttribute('data-confirm', card.kind === 'stopCopy')el.querySelector('.confirm').hidden = card.kind !== 'stopCopy'+ // Once the team starts, the copy is done and there is nothing left to stop.+ el.querySelector('.btn.stop').hidden = card.step >= 3el.style.setProperty('--step', String(Math.max(0, card.step - 1)));[...el.querySelectorAll('.steps li')].forEach((li, k) => {const n = k + 1diff --git a/app/src/start/text.mjs b/app/src/start/text.mjsindex b331c321..326ac1fb 100644--- a/app/src/start/text.mjs+++ b/app/src/start/text.mjs@@ -52,6 +52,8 @@ export const TEXT = {'card.moveFailed.stay': '原来的 {dataDir} 没有变化。','card.import.lead': 'DeepSeek Harness 里有 {bots} 个 Bot 和 {groups} 个群聊(对话 {chats},工作文件 {work})。复制过来?','card.import.extra': '复制后会多占 {total},DeepSeek Harness 里的原件不动。',+ 'card.import.leadBare': 'DeepSeek Harness 里有 {bots} 个 Bot 和 {groups} 个群聊。复制过来?',+ 'card.import.extraBare': 'DeepSeek Harness 里的原件不动,复制以后两边各用各的。','card.import.found': '在 {path} 里找到 {bots} 个 Bot({names}等)和 {groups} 个群聊,{sessions} 段对话。','card.import.scope': '会复制:Bot、群聊、记忆、对话、附件、模型设置和 API Key。不会复制:MCP、技能和 DSH Agent。DeepSeek Harness 里的内容不会改动,复制以后两边各用各的。','card.import.model': '模型设置:{model}',@@ -159,12 +161,6 @@ export const TEXT = {'dialog.move.detail': 'DeepSeek Bot 会把数据复制过去,然后重新启动。{from} 会原样保留,确认一切正常后可以自己删掉。','dialog.move.inUse': '另一个 DeepSeek Harness 正在使用这份数据,所以没有移动。请先关掉它,再重试。','dialog.move.failed': '数据没有复制成功:{message}\n\nDeepSeek Bot 会继续使用原来位置的数据。',- 'dialog.import.found': 'DeepSeek Harness 里有 {bots} 个 Bot 和 {groups} 个群聊。要复制到 DeepSeek Bot 吗?',- 'dialog.import.foundDetail': '会复制 Bot、群聊、记忆、对话、附件、模型设置和 API Key。{home} 里的内容不会改变,复制以后两边各用各的。',- 'dialog.import.inUse': 'DeepSeek Harness 正在使用这个团队。请先关掉它,再重试。',- 'dialog.import.newer': '有 {n} 段对话是更新版本的 DeepSeek Harness 写的,这个版本的 DeepSeek Bot 读不了。请先更新 DeepSeek Bot,再打开它来复制团队。',- 'dialog.import.whichModels': 'DeepSeek Bot 用哪一份模型设置?',- 'dialog.import.failed': '团队没有复制完:{message}\n\nDeepSeek Bot 会用一个新团队开始。DeepSeek Harness 里的团队没有变化。','dialog.update.ready': 'DeepSeek Bot {version} 已经下载好。','dialog.update.readyDetail': '现在重启就能更新;不重启的话,下次退出时安装。','dialog.update.available': 'DeepSeek Bot {version} 已经发布。',@@ -203,6 +199,8 @@ export const TEXT = {'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.leadBare': 'DeepSeek Harness has {bots|Bot|Bots} and {groups|group chat|group chats}. Copy them over?',+ 'card.import.extraBare': 'The originals in DeepSeek Harness stay untouched; after the copy each side goes its own way.','card.import.found': 'Found {bots|Bot|Bots} ({names} and others), {groups|group chat|group chats} and {sessions|chat|chats} in {path}.','card.import.scope': 'Copied: Bots, group chats, memory, chats, attachments, model settings and API Keys. Not copied: MCP, skills and DSH Agent. Nothing in DeepSeek Harness changes; after the copy each side goes its own way.','card.import.model': 'Model settings: {model}',@@ -310,12 +308,6 @@ export const TEXT = {'dialog.move.detail': 'DeepSeek Bot copies its data there and starts again. {from} stays as it is; you can delete it yourself once everything works.','dialog.move.inUse': 'Another DeepSeek Harness is using this data, so it was not moved. Close it, then try again.','dialog.move.failed': 'The data was not copied: {message}\n\nDeepSeek Bot goes on with its data where it was.',- 'dialog.import.found': 'DeepSeek Harness has {bots|Bot|Bots} and {groups|group chat|group chats}. Copy them into DeepSeek Bot?',- 'dialog.import.foundDetail': 'Copied: Bots, group chats, memory, chats, attachments, model settings and API Keys. Nothing in {home} changes; after the copy each side goes its own way.',- 'dialog.import.inUse': 'DeepSeek Harness is using this team. Close it, then try again.',- 'dialog.import.newer': '{n|chat was|chats were} written by a newer DeepSeek Harness than this version of DeepSeek Bot can read. Update DeepSeek Bot first, then open it to copy the team.',- 'dialog.import.whichModels': 'Which model settings should DeepSeek Bot use?',- 'dialog.import.failed': 'The team wasn’t fully copied: {message}\n\nDeepSeek Bot starts with a new team. The team in DeepSeek Harness is unchanged.','dialog.update.ready': 'DeepSeek Bot {version} has finished downloading.','dialog.update.readyDetail': 'Restart now to update; if you don’t, it installs the next time you quit.','dialog.update.available': 'DeepSeek Bot {version} is out.',diff --git a/app/test/helpers/app-harness.mjs b/app/test/helpers/app-harness.mjsindex 87dd4749..8730d9f9 100644--- a/app/test/helpers/app-harness.mjs+++ b/app/test/helpers/app-harness.mjs@@ -20,16 +20,17 @@ export const waitFor = async (check, what, timeout = 10_000) => {/*** Start the app on throwaway folders: the places are chosen already and the one-time notice* is answered, so that the app asks nothing. The Host answers when the test lets it.- * @param {{ packaged?: boolean, saved?: object }} options whether the app is a packaged one, with- * an updater; what else locations.json keeps beside the places+ * @param {{ packaged?: boolean, saved?: object, acknowledged?: boolean }} options whether the app+ * is a packaged one, with an updater; what else locations.json keeps beside the places; whether+ * the tray notice was answered already*/-export const startApp = async ({ packaged = true, saved = {} } = {}) => {+export const startApp = async ({ packaged = true, saved = {}, acknowledged = true } = {}) => {const home = mkdtempSync(join(tmpdir(), 'ds-bot-main-home-'))const workspace = join(home, 'workspace')mkdirSync(workspace, { recursive: true })mkdirSync(paths.userData, { recursive: true })writeFileSync(join(paths.userData, 'locations.json'), JSON.stringify({ dataDir: home, workspace, ...saved }))- writeFileSync(join(paths.userData, 'tray-close-acknowledged'), '')+ if (acknowledged) writeFileSync(join(paths.userData, 'tray-close-acknowledged'), '')hold()await import('../../src/main.mjs')// The app is a packaged one, so that it has an updater. The flag comes after the start,@@ -79,6 +80,22 @@ export const startAct = async (name, value, start = startWindows().at(-1)) => {return state.ipc.get('ds-bot:start-act')({ sender: start.webContents, senderFrame: start.webContents.mainFrame }, name, value === undefined ? undefined : { value })}+/** The cards the app sent the team window in place of message boxes (preload.cjs showCard). */+export const windowCards = (win = window()) => win.webContents.sent.filter(([channel]) => channel === 'ds-bot:app-card').map(([, card]) => card)++/**+ * The team window's page shows its last card and the user clicks the button `index` on it, as+ * preload.cjs reports both.+ */+export const answerCard = (index, win = window()) => {+ const card = windowCards(win).at(-1)+ win.webContents.mainFrame.url = win.url+ const event = { sender: win.webContents, senderFrame: win.webContents.mainFrame }+ state.ipc.get('ds-bot:app-card-shown')(event, card.id)+ state.ipc.get('ds-bot:app-card-answer')(event, card.id, index)+ return card+}+/** The message boxes the app showed; the pickers have no message. */export const messageBoxes = () => state.dialogs.filter(options => 'message' in options)diff --git a/app/test/helpers/fake-electron.mjs b/app/test/helpers/fake-electron.mjsindex 3211b125..198d36ea 100644--- a/app/test/helpers/fake-electron.mjs+++ b/app/test/helpers/fake-electron.mjs@@ -112,6 +112,7 @@ class FakeWebContents extends EventEmitter {this.mainFrame = {}this.isDestroyed = () => this.win.destroyedthis.getURL = () => this.win.url+ this.isLoading = () => falsethis.getTitle = () => 'DeepSeek Bot'this.sent = []this.send = (...args) => { this.sent.push(args) }diff --git a/app/test/helpers/fake-host-process.mjs b/app/test/helpers/fake-host-process.mjsindex f72d516e..d2d846cd 100644--- a/app/test/helpers/fake-host-process.mjs+++ b/app/test/helpers/fake-host-process.mjs@@ -41,6 +41,8 @@ export class HostProcess {state.starts += 1if (state.held) await gateif (state.fail) throw new Error('the Host did not start')+ // The check of an import's chats (DS_BOT_CHECK) reads them all.+ if (this.#options.env?.DS_BOT_CHECK) return { unreadable: [] }return { url: `http://127.0.0.1:${port()}/?token=test-token`, injections: [] }}diff --git a/app/test/import-flow.test.mjs b/app/test/import-flow.test.mjsnew file mode 100644index 00000000..b85d1703--- /dev/null+++ b/app/test/import-flow.test.mjs@@ -0,0 +1,261 @@+// The first run's import on the start page's cards: what each card says, the order of the cards,+// and what the copy does with the answers. The disk, the engine and the window are test doubles.+import assert from 'node:assert/strict'+import { test } from 'node:test'+import { copySize, defaultOptions, etaMinutes, ImportFlow, modelChoices } from '../src/import-flow.mjs'++const GB = 2 ** 30+const tick = () => new Promise((resolve) => { setImmediate(resolve) })++// An import of six Bots with 1.2 GB of chats and 3.4 GB of work files, 0.4 GB of them regenerable.+function harness({ inUse = () => false, free = 100 * GB, check = async () => 0, copy, sizes, profiles } = {}) {+ const cards = []+ const shown = []+ const answers = []+ let respond+ const io = {+ offer: {+ from: '/home/u/.dsh', bots: 6, rooms: 2, names: ['Chief', 'Writer', 'Coder', 'Tester'], sessions: 3,+ sizes: sizes ?? { sessions: 3, chats: 1.2 * GB, work: 3.4 * GB, regen: 0.4 * GB },+ profiles: profiles ?? [{ name: 'web', rows: [{ id: 'llm-deepseek' }] }, { name: 'desktop', rows: [{ id: 'agent-default-model', config: { model: 'deepseek/v4' } }] }],+ },+ ask: (card, options) => {+ cards.push(card)+ return new Promise((resolve) => {+ respond = resolve+ void options?.settle?.then(() => { resolve('settled') })+ if (answers.length > 0) resolve(answers.shift())+ })+ },+ show: (card) => { shown.push(card) },+ room: () => ({ free, drive: 'C' }),+ inUse,+ until: async (check, signal) => { while (!signal.aborted && !check()) await tick() },+ check: async (signal, onProgress) => { onProgress(3, 3); return check(signal) },+ warmed: async () => {},+ copy: copy ?? (async ({ onProgress }) => { onProgress(2.6 * GB); return { bots: 6, sessions: 3, from: '/home/u/.dsh' } }),+ reasonOf: () => 'other',+ lang: 'zh',+ signal: new AbortController().signal,+ }+ return { io, cards, shown, answer: (value) => { if (respond) { const r = respond; respond = undefined; r(value) } else answers.push(value) } }+}++test('the model settings of DSH Desktop come first, then DSH Web, then the profile with most rows', () => {+ const choices = modelChoices([+ { name: 'other', rows: [{}, {}, {}] },+ { name: 'web', rows: [{}] },+ { name: 'spare', rows: [{}] },+ { name: 'desktop', rows: [{ id: 'agent-default-model', config: { model: 'deepseek/v4' } }] },+ ])+ assert.deepEqual(choices.map(choice => choice.id), ['desktop', 'web', 'other', 'spare'])+ assert.equal(choices[0].label, 'DSH Desktop · deepseek/v4')+ assert.equal(choices[1].label, 'DSH Web')+})++test('the regenerable folders stay behind by default from 200 MB on, and the sizes follow the options', () => {+ const sizes = { chats: 1.2 * GB, work: 3.4 * GB, regen: 0.4 * GB }+ assert.deepEqual(defaultOptions(sizes), { regen: true, skipWork: false })+ assert.deepEqual(defaultOptions({ ...sizes, regen: 0.1 * GB }), { regen: false, skipWork: false })+ assert.equal(copySize(sizes, { regen: true, skipWork: false }).work, 3 * GB)+ assert.equal(copySize(sizes, { regen: false, skipWork: false }).total, 4.6 * GB)+ assert.equal(copySize(sizes, { regen: true, skipWork: true }).total, 1.2 * GB)+ assert.equal(copySize({ chats: 1 }, { regen: false, skipWork: false }), undefined, 'sizes that ran out of time are not guessed')+})++test('the time left is in whole minutes, moves a full minute at a time and never counts down to 0', () => {+ assert.equal(etaMinutes(null, { done: 1, total: 10, elapsedMs: 1000 }), null, 'no rate in the first 3 s')+ assert.equal(etaMinutes(null, { done: 1, total: 10, elapsedMs: 60_000 }), 9)+ assert.equal(etaMinutes(9, { done: 1.05, total: 10, elapsedMs: 60_000 }), 9, 'under a minute of change keeps the number')+ assert.equal(etaMinutes(9, { done: 2, total: 10, elapsedMs: 60_000 }), 4)+ assert.equal(etaMinutes(4, { done: 99, total: 100, elapsedMs: 600_000 }), 0, 'under a minute is 「不到 1 分钟」')+})++test('the import card says what it found, what the copy takes and which model settings go along', async () => {+ const { io, cards, answer } = harness()+ const flow = new ImportFlow(io)+ const run = flow.run()+ await tick()+ const card = cards[0]+ assert.equal(card.kind, 'import')+ assert.deepEqual([card.bots, card.groups, card.sessions, card.path], [6, 2, 3, '/home/u/.dsh'])+ assert.equal(card.names, 'Chief、Writer、Coder')+ assert.deepEqual([card.chats, card.work, card.total, card.bare], ['1.2 GB', '3.0 GB', '4.2 GB', ''])+ assert.equal(card.model, 'DSH Desktop · deepseek/v4')+ assert.deepEqual(card.models.map(model => model.id), ['desktop', 'web'])+ assert.deepEqual(card.options, { regen: true, skipWork: false })+ answer('skip')+ assert.deepEqual(await run, { outcome: 'skipped' })+})++test('the card follows a changed model and options, and the copy takes them', async () => {+ let taken+ const { io, shown, answer } = harness({ copy: async (options) => { taken = options; return { bots: 6, sessions: 3 } } })+ const flow = new ImportFlow(io)+ const run = flow.run()+ await tick()+ flow.act('importModel', 'web')+ flow.act('importOption', { option: 'skipWork', value: true })+ flow.act('importOption', { option: 'elsewhere', value: true })+ flow.act('importModel', 'nowhere')+ assert.equal(shown.length, 2, 'unknown models and options change nothing')+ assert.equal(shown.at(-1).model, 'DSH Web')+ assert.equal(shown.at(-1).total, '1.2 GB')+ answer('copy')+ const result = await run+ assert.equal(result.outcome, 'copied')+ assert.equal(taken.profile, 'web')+ assert.equal(taken.skipWork, true)+ assert.equal(taken.leaveRegenerable, true)+})++test('sizes that took too long leave the numbers out of the card instead of guessing', async () => {+ const { io, cards, answer } = harness({ sizes: { sessions: 3 } })+ const run = new ImportFlow(io).run()+ await tick()+ assert.equal(cards[0].bare, 'Bare')+ assert.equal(cards[0].total, undefined)+ answer('copy')+ assert.equal((await run).outcome, 'copied', 'no space check without sizes')+})++test('a drive without room for the copy and 500 MB says how much is missing', async () => {+ const { io, cards, answer } = harness({ free: 4 * GB })+ const run = new ImportFlow(io).run()+ await tick()+ answer('copy')+ await tick()+ assert.equal(cards[1].kind, 'importSpace')+ assert.deepEqual([cards[1].need, cards[1].free, cards[1].short, cards[1].drive], ['4.6 GB', '4.0 GB', '681 MB', 'C'])+ answer('pick')+ assert.deepEqual(await run, { outcome: 'pick' })+})++test('「换个位置…」 on the import card picks another place for the import', async () => {+ const { io, answer } = harness()+ const run = new ImportFlow(io).run()+ await tick()+ answer('pick')+ assert.deepEqual(await run, { outcome: 'pick' })+})++test('a team that DSH holds waits on its card and the copy goes on by itself once DSH lets go', async () => {+ let held = true+ let checks = 0+ const { io, cards, answer } = harness({ inUse: () => held, check: async () => { checks += 1; return 0 } })+ const run = new ImportFlow(io).run()+ await tick()+ assert.equal(checks, 0, 'chats that DSH is writing are not checked')+ answer('copy')+ while (cards.length < 2) await tick()+ assert.equal(cards[1].kind, 'inUse')+ held = false+ assert.equal((await run).outcome, 'copied')+ assert.equal(checks, 1, 'the chats are checked once DSH let go')+})++test('a holder that comes while the card checks the chats makes that check count for nothing', async () => {+ let held = false+ let checks = 0+ const { io, cards, answer } = harness({+ inUse: () => held,+ check: async (signal) => {+ checks += 1+ if (checks === 1) await new Promise((resolve) => { signal.addEventListener('abort', resolve) })+ return 0+ },+ })+ const run = new ImportFlow(io).run()+ await tick()+ held = true+ await tick()+ await tick()+ answer('copy')+ while (cards.length < 2) await tick()+ assert.equal(cards[1].kind, 'inUse')+ held = false+ assert.equal((await run).outcome, 'copied')+ assert.equal(checks, 2)+})++test('the copying card counts the checked chats, then the bytes, then starts the team', async () => {+ const { io, shown, answer } = harness()+ const run = new ImportFlow(io).run()+ await tick()+ answer('copy')+ const result = await run+ assert.equal(result.outcome, 'copied')+ const copying = shown.filter(card => card.kind === 'copying')+ assert.deepEqual(copying[0].steps[0], { a: 3, b: 3 })+ assert.equal(copying.at(-1).step, 3)+ assert.equal(copying.at(-1).steps[1].b, '4.2 GB')+ assert.ok(copying.some(card => card.step === 2), 'the copy shows its own step')+})++test('〔停止复制〕 asks on the card, 〔继续复制〕 goes back, and the confirmed stop leaves no team', async () => {+ let release+ let stopped = false+ const { io, shown, answer } = harness({+ copy: ({ signal }) => new Promise((resolve, reject) => {+ release = () => { resolve({ bots: 6, sessions: 3 }) }+ signal.addEventListener('abort', () => { stopped = true; reject(new Error('stopped')) })+ }),+ })+ const flow = new ImportFlow(io)+ const run = flow.run()+ await tick()+ answer('copy')+ while (release === undefined) await tick()+ flow.act('stopCopy')+ assert.equal(shown.at(-1).kind, 'stopCopy')+ flow.act('keepCopying')+ assert.equal(shown.at(-1).kind, 'copying')+ flow.act('stopCopy')+ flow.act('stopCopy', 'confirm')+ assert.deepEqual(await run, { outcome: 'skipped' })+ assert.equal(stopped, true)+})++test('chats newer than this DSH reads say so, and the start goes on without the team', async () => {+ let copied = false+ const { io, cards, answer } = harness({ check: async () => 2, copy: async () => { copied = true } })+ const run = new ImportFlow(io).run()+ await tick()+ answer('copy')+ while (cards.length < 2) await tick()+ assert.deepEqual(cards[1], { kind: 'newer', n: 2 })+ answer('startWithout')+ assert.deepEqual(await run, { outcome: 'skipped', newer: true })+ assert.equal(copied, false)+})++test('a failed copy offers to try again, and the second copy can go through', async () => {+ let tries = 0+ const { io, cards, answer } = harness({+ copy: async () => {+ tries += 1+ if (tries === 1) throw new Error('EBUSY: resource busy\nmore')+ return { bots: 6, sessions: 3 }+ },+ })+ io.reasonOf = () => 'inUse'+ const run = new ImportFlow(io).run()+ await tick()+ answer('copy')+ while (cards.length < 2) await tick()+ assert.deepEqual(cards[1], { kind: 'importFailed', reason: 'inUse', log: ['EBUSY: resource busy', 'more'] })+ answer('retry')+ assert.equal((await run).outcome, 'copied')+ assert.equal(tries, 2)+})++test('a quit or another start while a card waits ends the import without an answer', async () => {+ const quit = new AbortController()+ const { io } = harness()+ io.signal = quit.signal+ io.ask = (card, options) => new Promise((resolve) => { quit.signal.addEventListener('abort', () => { resolve(undefined) }); void options })+ const run = new ImportFlow(io).run()+ await tick()+ quit.abort()+ assert.deepEqual(await run, { outcome: 'gone' })+})diff --git a/app/test/main-close-card.test.mjs b/app/test/main-close-card.test.mjsnew file mode 100644index 00000000..926d4eae--- /dev/null+++ b/app/test/main-close-card.test.mjs@@ -0,0 +1,51 @@+// The first close of the team window tells, once, that the app stays in the tray: on a card in+// the window's page, not in a message box. Only the card's answer lets the window go, and the+// answer is kept. The Electron parts are test doubles: no display, no DSH, no data of the user.+import assert from 'node:assert/strict'+import { existsSync } from 'node:fs'+import { join } from 'node:path'+import { before, test } from 'node:test'+import { paths, state } from './helpers/fake-electron.mjs'+import { state as hostState } from './helpers/fake-host-process.mjs'+import { answerCard, handOff, messageBoxes, startApp, trayMenu, waitFor, window, windowCards } from './helpers/app-harness.mjs'+import { installHooks } from './helpers/register.mjs'++await installHooks()++before(async () => { await startApp({ acknowledged: false }) })++test('the first close asks on a card in the window and hides it once the card is answered', async () => {+ await waitFor(() => window() !== undefined, 'open the window')+ await waitFor(() => state.tray !== undefined, 'build the tray')+ hostState.release()+ await handOff()+ const win = window()+ win.close()+ await waitFor(() => windowCards(win).length === 1, 'tell about the tray on a card')+ const card = windowCards(win)[0]+ assert.match(card.message, /system tray/u)+ assert.deepEqual(card.buttons, [{ label: 'OK', primary: true }])+ assert.equal(card.cancel, undefined, 'only the answer lets the window go')+ assert.equal(win.visible, true, 'the window stays until the answer')+ // A second close while the card is up asks nothing more.+ win.close()+ assert.equal(windowCards(win).length, 1)+ answerCard(0, win)+ await waitFor(() => win.visible === false, 'hide the window')+ assert.ok(existsSync(join(paths.userData, 'tray-close-acknowledged')), 'the answer is kept')+ assert.deepEqual(messageBoxes(), [], 'no message box')+})++test('later closes hide the window without asking', async () => {+ const win = window()+ trayMenu()[0].click()+ await waitFor(() => win.visible === true, 'show the window')+ win.close()+ await waitFor(() => win.visible === false, 'hide the window')+ assert.equal(windowCards(win).length, 1, 'no second card')+})++test('the tray quit ends the app', async () => {+ trayMenu().at(-1).click()+ await waitFor(() => state.tray.destroyed === true, 'take the tray away')+})diff --git a/app/test/main-import.test.mjs b/app/test/main-import.test.mjsnew file mode 100644index 00000000..ae748913--- /dev/null+++ b/app/test/main-import.test.mjs@@ -0,0 +1,68 @@+// The first start of an app whose user has a team in their own DSH: the start page offers it on+// the import card instead of message boxes, the copy shows its steps on the copying card, and the+// engine starts on the copied team. The home and the DSH home are throwaway folders, so the test+// never sees the user's own; the Electron parts and the Host are test doubles.+import assert from 'node:assert/strict'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { test } from 'node:test'+import { app, paths, state } from './helpers/fake-electron.mjs'+import { hold, state as hostState } from './helpers/fake-host-process.mjs'+import { handOff, messageBoxes, startAct, startState, startWindows, waitFor, window } from './helpers/app-harness.mjs'+import { installHooks } from './helpers/register.mjs'++const home = mkdtempSync(join(tmpdir(), 'ds-bot-import-home-'))+process.env.HOME = home+process.env.USERPROFILE = home+process.env.DSH_HOME = join(home, 'dsh')+delete process.env.DS_BOT_HOME+delete process.env.DS_BOT_WORKSPACE++const write = (path, text) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text) }+const dsh = process.env.DSH_HOME+write(join(dsh, 'bot', 'state.json'), JSON.stringify({ bots: { b1: { id: 'b1', name: 'Chief', sessionId: 's1' }, b2: { id: 'b2', name: 'Writer', sessionId: 's2' } }, rooms: {} }))+write(join(dsh, 'sessions', 'g', 's1', 'notes.txt'), 'one')+write(join(dsh, 'sessions', 'g', 's2', 'notes.txt'), 'two')+write(join(dsh, 'bot', 'workspace', 'draft.md'), 'work')+write(join(dsh, 'bot', 'workspace', 'node_modules', 'x', 'index.js'), 'regenerable')++await installHooks()++const cards = () => startWindows()[0].webContents.sent.filter(([channel, snapshot]) => channel === 'ds-bot:start-state' && snapshot.card).map(([, snapshot]) => snapshot.card)++test('the first start offers the DSH team on the import card, copies it on cards and starts on it', async () => {+ mkdirSync(paths.userData, { recursive: true })+ writeFileSync(join(paths.userData, 'tray-close-acknowledged'), '')+ hold()+ await import('../src/main.mjs')+ await waitFor(() => startState()?.card?.kind === 'import', 'offer the team on the import card')+ const offer = startState().card+ assert.deepEqual([offer.bots, offer.groups, offer.sessions, offer.names], [2, 0, 2, 'Chief, Writer'])+ assert.equal(offer.path, dsh)+ assert.equal(existsSync(join(paths.userData, 'locations.json')), false, 'the places wait for the answer')+ // The engine warms up on the new data location while the card is up.+ hostState.release()+ await waitFor(() => startState().done.includes('engine'), 'warm the engine up')+ assert.equal(startState().view, 'card', 'the card stays up')++ // 「不复制可以重新生成的文件夹」, ticked on the card.+ const start = startWindows()[0]+ start.webContents.mainFrame.url = start.url+ state.ipc.get('ds-bot:start-act')({ sender: start.webContents, senderFrame: start.webContents.mainFrame }, 'importOption', { option: 'regen', value: true })+ await waitFor(() => startState().card.options.regen === true, 'tick the option on the card')+ await startAct('answer', 'copy')+ await waitFor(() => existsSync(join(home, '.ds-bot', 'bot', 'imported.json')), 'copy the team')+ await waitFor(() => window()?.loaded.some(url => url.includes('token=')), 'start the copied team')+ const steps = cards().filter(card => card.kind === 'copying').map(card => card.step)+ assert.ok(steps.includes(1) && steps.includes(2) && steps.at(-1) === 3, `the copy shows its three steps (${steps.join(',')})`)+ assert.equal(startState().card, undefined, 'the copying card goes once the team\'s engine is up')+ assert.ok(existsSync(join(home, 'DeepSeek Bot', 'draft.md')), 'the work files came along')+ assert.equal(existsSync(join(home, 'DeepSeek Bot', 'node_modules')), false, 'the regenerable folders did not')+ assert.equal(JSON.parse(readFileSync(join(paths.userData, 'locations.json'), 'utf8')).dataDir, join(home, '.ds-bot'))+ assert.deepEqual(messageBoxes(), [], 'no message box on the way')+ assert.equal(hostState.starts, 3, 'the warm engine, the chats\' check and the team\'s engine')+ await handOff()+ app.quit()+ await waitFor(() => state.tray?.destroyed === true, 'end the app')+})diff --git a/app/test/main-room-left.test.mjs b/app/test/main-room-left.test.mjsindex 4a502b80..05cf9e7b 100644--- a/app/test/main-room-left.test.mjs+++ b/app/test/main-room-left.test.mjs@@ -10,7 +10,7 @@ import { join } from 'node:path'import { test } from 'node:test'import { paths, state } from './helpers/fake-electron.mjs'import { state as hostState } from './helpers/fake-host-process.mjs'-import { handOff, startApp, startWindows, waitFor, window } from './helpers/app-harness.mjs'+import { answerCard, handOff, messageBoxes, startApp, startWindows, waitFor, window, windowCards } from './helpers/app-harness.mjs'import { installHooks } from './helpers/register.mjs'await installHooks()@@ -36,11 +36,15 @@ test('a later start with room to spare shows no place line; Settings still movesstate.ipc.get('ds-bot:team-workspace')(event, workspace)assert.deepEqual({ workspace: saved().workspace, freeAtStart: saved().freeAtStart }, { workspace, freeAtStart: 1 })- // The move from Settings: its picker and its question.+ // The move from Settings: its picker, and its question on a card in the team window.const to = join(mkdtempSync(join(tmpdir(), 'ds-bot-move-')), 'data')state.openAnswer = { canceled: false, filePaths: [to] }- state.dialogAnswer = { response: 0 }- assert.equal(await state.ipc.get('ds-bot:move-data')(event, workspace), true)+ const moved = state.ipc.get('ds-bot:move-data')(event, workspace)+ await waitFor(() => windowCards(win).length === 1, 'ask about the move on a card')+ assert.match(windowCards(win)[0].message, /data/u)+ answerCard(0, win)+ assert.equal(await moved, true)+ assert.deepEqual(messageBoxes(), [], 'no message box')assert.equal(state.relaunches.length, 1)assert.ok(existsSync(to), 'the data was copied')assert.equal(saved().dataDir, to)diff --git a/app/test/main-update.test.mjs b/app/test/main-update.test.mjsindex 6c05e464..9996edb5 100644--- a/app/test/main-update.test.mjs+++ b/app/test/main-update.test.mjs@@ -1,11 +1,11 @@// The update of the app belongs to the window: while the window is hidden or minimized, the-// box waits, and the answer the user gives when the window is back does the work itself.+// card waits, and the answer the user gives when the window is back does the work itself.import assert from 'node:assert/strict'import { before, test } from 'node:test'import { app, state } from './helpers/fake-electron.mjs'import { state as hostState } from './helpers/fake-host-process.mjs'import { state as updaterState, updater } from './helpers/fake-updater.mjs'-import { handOff, startApp, trayMenu, waitFor, window } from './helpers/app-harness.mjs'+import { answerCard, handOff, startApp, trayMenu, waitFor, window, windowCards } from './helpers/app-harness.mjs'import { installHooks } from './helpers/register.mjs'await installHooks()@@ -27,14 +27,18 @@ test('the update waits for the window and is installed when the window comes bacawait waitFor(() => win.visible === false, 'hide the window')updater.emit('update-downloaded', { version: '9.9.9' })await new Promise(resolve => { setTimeout(resolve, 50) })- assert.equal(state.dialogs.length, 0, 'the box waits for the window')+ assert.equal(windowCards(win).length, 0, 'the card waits for the window')- // The user says yes when the window is back.- state.dialogAnswer = { response: 0 }+ // The user says yes on the card when the window is back; no message box comes up.trayMenu()[0].click()+ await waitFor(() => windowCards(win).length === 1, 'ask on a card in the team window')+ assert.match(windowCards(win)[0].message, /9\.9\.9/u)+ assert.equal(windowCards(win)[0].cancel, 1, 'Escape is 「以后再说」')+ answerCard(0, win)await waitFor(() => updaterState.quitAndInstall.length === 1, 'install the update')assert.equal(hostState.stops, 1, 'the Host stops for the installer')assert.equal(updaterState.quitAndInstall[0].length, 2, 'the installer takes over')+ assert.equal(state.dialogs.length, 0, 'no message box')})test('the app ends after the update', async () => {diff --git a/app/test/start-page.test.mjs b/app/test/start-page.test.mjsindex b8c3de5d..509fcd20 100644--- a/app/test/start-page.test.mjs+++ b/app/test/start-page.test.mjs@@ -306,10 +306,10 @@ test('t fills placeholders and falls back to zh, then to the key', () => {})test('t picks the English singular or plural by the value', () => {- assert.equal(t('en', 'dialog.import.found', { bots: 1, groups: 6 }), 'DeepSeek Harness has 1 Bot and 6 group chats. Copy them into DeepSeek Bot?')- assert.equal(t('en', 'dialog.import.found', { bots: 6, groups: 1 }), 'DeepSeek Harness has 6 Bots and 1 group chat. Copy them into DeepSeek Bot?')- assert.equal(t('zh', 'dialog.import.found', { bots: 6, groups: 1 }), 'DeepSeek Harness 里有 6 个 Bot 和 1 个群聊。要复制到 DeepSeek Bot 吗?')- assert.equal(t('en', 'dialog.import.found', { bots: 1 }), 'DeepSeek Harness has 1 Bot and {groups|group chat|group chats}. Copy them into DeepSeek Bot?')+ assert.equal(t('en', 'card.import.leadBare', { bots: 1, groups: 6 }), 'DeepSeek Harness has 1 Bot and 6 group chats. Copy them over?')+ assert.equal(t('en', 'card.import.leadBare', { bots: 6, groups: 1 }), 'DeepSeek Harness has 6 Bots and 1 group chat. Copy them over?')+ assert.equal(t('zh', 'card.import.leadBare', { bots: 6, groups: 1 }), 'DeepSeek Harness 里有 6 个 Bot 和 1 个群聊。复制过来?')+ assert.equal(t('en', 'card.import.leadBare', { bots: 1 }), 'DeepSeek Harness has 1 Bot and {groups|group chat|group chats}. Copy them over?')})test('langOf gives zh for every Chinese locale and en otherwise', () => {diff --git a/app/test/start-window.test.mjs b/app/test/start-window.test.mjsindex 5a4d7ae1..2f41bf87 100644--- a/app/test/start-window.test.mjs+++ b/app/test/start-window.test.mjs@@ -116,7 +116,12 @@ test('only a missing file of the app\'s own says that the install is incomplete'})test('the main process takes only its own acts, each in its own views', () => {- assert.deepEqual([...START_ACTS].sort(), ['answer', 'copyDetails', 'handoffDone', 'handoffShow', 'installUpdate', 'manualDownload', 'pick', 'reloadView', 'retry', 'saveLog', 'wait'])+ assert.deepEqual([...START_ACTS].sort(), ['answer', 'copyDetails', 'handoffDone', 'handoffShow', 'importModel', 'importOption', 'installUpdate', 'keepCopying', 'manualDownload', 'pick', 'reloadView', 'retry', 'saveLog', 'stopCopy', 'wait'])+ // The import card's model and options and the copying card's stop, on a card only.+ for (const name of ['importModel', 'importOption', 'stopCopy', 'keepCopying']) {+ assert.equal(acceptsAct(name, 'card'), true, name)+ for (const view of ['boot', 'failed', 'watchdog', 'handoff', 'moving']) assert.equal(acceptsAct(name, view), false, `${name} in ${view}`)+ }assert.equal(acceptsAct('handoffShow', 'handoff'), true)// 「换个位置…」 while the start boots and 〔重新选〕 on its cards; a card's answer only on a card.assert.equal(acceptsAct('pick', 'boot'), true)