A team of long-lived bots for DeepSeek Harness, with main bots, bot-to-bot messages and group chats.
Pick folders and files on the app's own page, not in system pickers
AdamPlatin123e9675666075e
diff --git a/app/src/downloads.mjs b/app/src/downloads.mjsindex 69e7b9d1..907868ed 100644--- a/app/src/downloads.mjs+++ b/app/src/downloads.mjs@@ -1,29 +1,97 @@-// A file the main window downloads asks where it should go first. Downloads from-// any other contents (the sign-in child, a Bot browser guest) keep their own+// A file the main window downloads asks where it should go first, on the app's own picker.+// Downloads from any other contents (the sign-in child, a Bot browser guest) keep their own// session's rules.+//+// Electron needs the save path before will-download returns, and the picker answers later: the+// download starts into a staging folder of its own, and moves to the chosen file once both the+// answer and the download are in. A cancelled picker cancels the download.+import { randomUUID } from 'node:crypto'+import { copyFileSync, existsSync, mkdirSync, renameSync, rmSync } from 'node:fs'import { homedir as osHomedir } from 'node:os'-import { join } from 'node:path'+import { basename, extname, join } from 'node:path'/**- * @param {{ window: any, dialog: any, getPath: (name: string) => string, homedir?: () => string }} options- * `getPath` is Electron's app.getPath, asked again for every download.+ * @param {{+ * window: any,+ * ask: (name: string, folder: string | undefined) => Promise<string | null | undefined>,+ * staging: () => string,+ * getPath: (name: string) => string,+ * homedir?: () => string,+ * log?: Pick<Console, 'warn'>,+ * }} options `ask` shows the picker: the chosen file, null when cancelled, undefined when the+ * page cannot show it (the file then goes into the start folder under a free name). `getPath`+ * is Electron's app.getPath, asked again for every download.*/-export function downloadSaver({ window, dialog, getPath, homedir = osHomedir }) {+export function downloadSaver({ window, ask, staging, getPath, homedir = osHomedir, log = console }) {return (event, item, source) => {// The window is asked for at the moment of the download: the app may build a new one.const owner = typeof window === 'function' ? window() : windowif (owner === undefined || owner === null || source !== owner.webContents) returnconst folder = startFolder(getPath, homedir)- const name = item.getFilename()- const file = dialog.showSaveDialogSync(owner, { defaultPath: folder === undefined ? name : join(folder, name) })- if (file === undefined) event.preventDefault()- else item.setSavePath(file)+ const name = safeName(item.getFilename())+ const holding = join(staging(), randomUUID())+ try {+ mkdirSync(holding, { recursive: true })+ } catch (error) {+ log.warn(`DeepSeek Bot: a download could not start: ${message(error)}`)+ event.preventDefault()+ return+ }+ const staged = join(holding, name)+ item.setSavePath(staged)+ const finished = new Promise((resolve) => { item.once('done', (_event, state) => { resolve(state) }) })+ void (async () => {+ let target+ try {+ target = await ask(name, folder)+ } catch (error) {+ log.warn(`DeepSeek Bot: the save picker failed: ${message(error)}`)+ target = null+ }+ if (target === null) item.cancel()+ else if (target === undefined) target = folder === undefined ? undefined : freePath(folder, name)+ const state = await finished+ try {+ if (state === 'completed' && typeof target === 'string') move(staged, target)+ } catch (error) {+ log.warn(`DeepSeek Bot: a download could not be moved to ${target}: ${message(error)}`)+ } finally {+ rmSync(holding, { recursive: true, force: true })+ }+ })()+ }+}++const message = error => (error instanceof Error ? error.message : String(error))++// The name comes from the server; it names one file in the staging folder and nothing else.+function safeName(name) {+ const plain = basename(String(name ?? '').replace(/[\\/]+/gu, '_')).trim()+ return plain === '' || plain === '.' || plain === '..' ? 'download' : plain+}++// The picker asked before it replaced a file; a rename does not cross drives.+function move(from, to) {+ try {+ renameSync(from, to)+ } catch (error) {+ if (error?.code !== 'EXDEV' && error?.code !== 'EPERM' && error?.code !== 'EEXIST') throw error+ copyFileSync(from, to)+ }+}++/** `name` in `folder`, or `name (2)`, `name (3)`… when it is taken. */+export function freePath(folder, name) {+ const extension = extname(name)+ const stem = name.slice(0, name.length - extension.length)+ for (let count = 1; ; count += 1) {+ const path = join(folder, count === 1 ? name : `${stem} (${String(count)})${extension}`)+ if (!existsSync(path)) return path}}// getPath throws when a known folder does not resolve (Downloads deleted, or redirected to a-// drive that is not there). Without any folder the dialog gets only the file name and opens-// where it likes.+// drive that is not there). Without any folder the picker opens in the home folder.function startFolder(getPath, homedir) {for (const find of [() => getPath('downloads'), () => getPath('home'), homedir]) {try {diff --git a/app/src/first-run.mjs b/app/src/first-run.mjsindex b286df21..5dbb9ae7 100644--- a/app/src/first-run.mjs+++ b/app/src/first-run.mjs@@ -1,7 +1,7 @@// The first start: where the app keeps its data and the Bots' files (the default places, or the// one folder picked from the start page), and whether it copies the Bot team of the user's own// DSH. The answers are kept in the app's own data.-import { app, dialog } from 'electron'+import { app } from 'electron'import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'import { homedir } from 'node:os'import { dirname, join, resolve } from 'node:path'@@ -10,28 +10,41 @@ import { installFolder } from './move-data.mjs'import { freeSpace } from './place.mjs'import { langOf, t } from './start/text.mjs'-// The system picker and the cards in the team window speak the language of the start page+// The app's 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 locationsFile = () => join(app.getPath('userData'), 'locations.json')-// A quit request while the system picker is open stops the first run right after it.+const PICKER_LABELS = ['places', 'drives', 'home', 'desktop', 'documents', 'downloads', 'path', 'go', 'up', 'newFolder', 'newName', 'create', 'name', 'cancel', 'chooseFolder', 'open', 'save', 'replace', 'loading']+const PICKER_LINES = ['empty', 'noFolders', 'more']+const PICKER_ERRORS = ['missing', 'drive', 'denied', 'notFolder', 'notFile', 'tooLong', 'unreadable', 'name', 'exists', 'isFolder', 'replace']++/** The words of the app's picker (preload.cjs showPicker), which has no text of its own. */+export function pickerLabels() {+ return Object.fromEntries([+ ...PICKER_LABELS.map(key => [key, tx(`picker.${key}`)]),+ ...PICKER_LINES.map(key => [key, tx(`dialog.picker.${key}`)]),+ ...PICKER_ERRORS.map(key => [`error.${key}`, tx(`dialog.picker.${key}`)]),+ ])+}++// A quit request while the picker is open stops the first run right after it.class Quit extends Error {}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'] }))+ const picked = await ui.asking(ui.pick({ mode: 'folder', title, start: existsSync(from) ? from : dirname(from) }))await new Promise(resolve => setImmediate(resolve))if (signal.aborted) throw new Quit()- return canceled ? undefined : filePaths[0]+ return picked ?? undefined}export const programFolder = () => installFolder(app.getPath('exe'))/**- * The system picker of 「换个位置…」 on the start page: one folder, from which the root rule- * (place.mjs) makes the places. Undefined when the box was cancelled or the app is quitting.+ * The picker of 「换个位置…」 on the start page: one folder, from which the root rule+ * (place.mjs) makes the places. Undefined when the picker was cancelled or the app is quitting.* @param {string} from the folder the picker opens in*/export async function pickRoot(from, signal, ui) {diff --git a/app/src/folder-picker.mjs b/app/src/folder-picker.mjsnew file mode 100644index 00000000..d77f0e3f--- /dev/null+++ b/app/src/folder-picker.mjs@@ -0,0 +1,192 @@+// The app's own folder and file picker, in place of the system's: the file system side. The page+// only draws what these return (preload.cjs showPicker), and every path that it sends back is+// checked here again. Errors are answers, never throws: the page shows them in place.+import { access, mkdir, readdir, stat } from 'node:fs/promises'+import { homedir } from 'node:os'+import { basename, dirname, extname, isAbsolute, join, parse, resolve } from 'node:path'++// A folder with more entries than this lists the first ones and says so.+export const LIST_MAX = 2000+// A network drive that is gone can keep a check waiting for many seconds; it is listed instead,+// and opening it says what is wrong.+const DRIVE_WAIT_MS = 300+const KNOWN = ['home', 'desktop', 'documents', 'downloads']+const WINDOWS_BAD = /[<>:"/\\|?*]/u+const WINDOWS_RESERVED = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/iu++const within = (promise, ms, late) => Promise.race([promise, new Promise((done) => { setTimeout(() => { done(late) }, ms).unref?.() })])+const reachable = path => access(path).then(() => true, () => false)++/**+ * Where the picker's side column starts: the known folders that exist, and the drives (Windows)+ * or the root and the mounted volumes (macOS, Linux).+ * @param {{ getPath: (name: string) => string, platform?: string, home?: string }} options+ */+export async function roots({ getPath, platform = process.platform, home = homedir() }) {+ const places = []+ for (const key of KNOWN) {+ let path+ try { path = key === 'home' ? (getPath('home') || home) : getPath(key) } catch { continue }+ if (path && !places.some(place => place.path === path) && await reachable(path)) places.push({ key, path })+ }+ return { places, drives: await drives(platform) }+}++async function drives(platform) {+ if (platform === 'win32') {+ const letters = [...'ABCDEFGHIJKLMNOPQRSTUVWXYZ'].map(letter => `${letter}:\\`)+ const found = await Promise.all(letters.map(path => within(reachable(path), DRIVE_WAIT_MS, true)))+ return letters.filter((_path, index) => found[index]).map(path => ({ path, label: path.slice(0, 2) }))+ }+ const mounts = platform === 'darwin' ? ['/Volumes'] : [`/media/${user()}`, `/run/media/${user()}`, '/mnt']+ const volumes = [{ path: '/', label: '/' }]+ for (const folder of mounts) {+ for (const entry of await readdir(folder, { withFileTypes: true }).catch(() => [])) {+ const path = join(folder, entry.name)+ // macOS lists the start disk again under /Volumes, as a link to /.+ if (entry.isSymbolicLink() && platform === 'darwin') continue+ if (entry.isDirectory()) volumes.push({ path, label: entry.name })+ }+ }+ return volumes+}++function user() {+ try { return basename(homedir()) } catch { return '' }+}++/** The steps from the path's root down to it, for the breadcrumb. */+export function crumbs(path) {+ const { root } = parse(path)+ const steps = [{ name: root.replace(/[\\/]+$/u, '') || root, path: root }]+ let at = root+ for (const part of path.slice(root.length).split(/[\\/]+/u).filter(Boolean)) {+ at = join(at, part)+ steps.push({ name: part, path: at })+ }+ return steps+}++/** A path that the user typed: `~` is the home folder, a relative one starts at `from`. */+export function typed(text, from, home = homedir()) {+ const value = String(text).trim().replace(/^["']|["']$/gu, '')+ if (value === '~' || value.startsWith('~/') || value.startsWith('~\\')) return join(home, value.slice(1))+ return isAbsolute(value) ? resolve(value) : resolve(from, value)+}++/** What went wrong with a path, as the page names it. */+export async function problemOf(error, path) {+ switch (error?.code) {+ case 'ENOENT': return await reachable(parse(path).root) ? 'missing' : 'drive'+ case 'EACCES': case 'EPERM': return 'denied'+ case 'ENOTDIR': return 'notFolder'+ case 'ENAMETOOLONG': return 'tooLong'+ case 'ENODEV': case 'ENXIO': case 'EIO': case 'UNKNOWN': return 'drive'+ default: return 'unreadable'+ }+}++/**+ * One folder's entries, folders first, each sorted the way people read them. Hidden entries+ * (a leading dot, Windows' `$` system folders) are left out.+ * @param {string} path+ * @param {{ files?: boolean, extensions?: string[] }} [options] `files` lists the files too;+ * `extensions` (without the dot) keeps only those.+ */+export async function list(path, { files = false, extensions } = {}) {+ const folder = resolve(path)+ let entries+ try {+ entries = await readdir(folder, { withFileTypes: true })+ } catch (error) {+ return { path: folder, error: await problemOf(error, folder) }+ }+ const wanted = extensions?.length ? new Set(extensions.map(ext => `.${ext.toLowerCase()}`)) : undefined+ const rows = []+ for (const entry of entries) {+ if (entry.name.startsWith('.') || entry.name.startsWith('$') || entry.name === 'System Volume Information') continue+ const full = join(folder, entry.name)+ let dir = entry.isDirectory()+ // A link or a junction is what it points to; a broken one is left out.+ if (entry.isSymbolicLink()) {+ try { dir = (await stat(full)).isDirectory() } catch { continue }+ } else if (!dir && !entry.isFile()) continue+ if (!dir && (!files || (wanted !== undefined && !wanted.has(extname(entry.name).toLowerCase())))) continue+ rows.push({ name: entry.name, path: full, dir })+ }+ const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' })+ rows.sort((a, b) => (a.dir === b.dir ? collator.compare(a.name, b.name) : a.dir ? -1 : 1))+ return { path: folder, crumbs: crumbs(folder), parent: dirname(folder) === folder ? undefined : dirname(folder), entries: rows.slice(0, LIST_MAX), ...(rows.length > LIST_MAX ? { more: rows.length } : {}) }+}++/** Whether `name` can be one file or folder name here. */+export function nameOk(name, platform = process.platform) {+ if (typeof name !== 'string' || name.trim() === '' || name === '.' || name === '..' || name.length > 255) return false+ if (name.includes('/') || name.includes('\0')) return false+ if (platform === 'win32') return !WINDOWS_BAD.test(name) && ![...name].some(char => char.charCodeAt(0) < 32) && !WINDOWS_RESERVED.test(name) && !/[ .]$/u.test(name)+ return true+}++/**+ * A new folder in `parent`.+ * @returns {Promise<{ path: string } | { error: string }>}+ */+export async function makeFolder(parent, name, platform = process.platform) {+ if (!nameOk(name, platform)) return { error: 'name' }+ const path = join(resolve(parent), name)+ try {+ await mkdir(path)+ return { path }+ } catch (error) {+ if (error?.code === 'EEXIST') return { error: 'exists' }+ return { error: await problemOf(error, path) }+ }+}++/**+ * Where a save goes: a valid name in a folder that exists. `exists` says that a file of that name+ * is there already, which the page asks about before it replaces it.+ * @returns {Promise<{ path: string, exists?: true } | { error: string }>}+ */+export async function saveTarget(folder, name, platform = process.platform) {+ if (!nameOk(name, platform)) return { error: 'name' }+ const into = resolve(folder)+ try {+ if (!(await stat(into)).isDirectory()) return { error: 'notFolder' }+ } catch (error) {+ return { error: await problemOf(error, into) }+ }+ const path = join(into, name)+ try {+ const found = await stat(path)+ return found.isDirectory() ? { error: 'isFolder' } : { path, exists: true }+ } catch (error) {+ return error?.code === 'ENOENT' ? { path } : { error: await problemOf(error, path) }+ }+}++/** A path that the picker can choose: a folder (`folder` mode) or a file (`file` mode). */+export async function chosen(path, mode) {+ const target = resolve(path)+ try {+ const found = await stat(target)+ if (mode === 'folder' && !found.isDirectory()) return { error: 'notFolder' }+ if (mode === 'file' && !found.isFile()) return { error: 'notFile' }+ return { path: target }+ } catch (error) {+ return { error: await problemOf(error, target) }+ }+}++/** The folder a picker opens in: `from`, or the nearest folder above it that exists. */+export async function startIn(from, home = homedir()) {+ let at = typeof from === 'string' && from !== '' ? resolve(from) : home+ for (;;) {+ try {+ if ((await stat(at)).isDirectory()) return at+ } catch {}+ const up = dirname(at)+ if (up === at) return home+ at = up+ }+}diff --git a/app/src/main.mjs b/app/src/main.mjsindex 5e9557ed..6a39be37 100644--- a/app/src/main.mjs+++ b/app/src/main.mjs@@ -5,7 +5,7 @@// the team window hides it; the tray brings it back and its Quit ends the app (shell.mjs). Only// what the start window and the tray need is imported up front; the rest loads once the start// window is up (docs/plans/2026-10-26-start-window.md §11).-import { app, BrowserWindow, clipboard, dialog, ipcMain, Menu, nativeImage, nativeTheme, powerMonitor, screen, session, shell as electronShell, systemPreferences, Tray, WebContentsView } from 'electron'+import { app, BrowserWindow, clipboard, ipcMain, Menu, nativeImage, nativeTheme, powerMonitor, screen, session, shell as electronShell, systemPreferences, Tray, WebContentsView } from 'electron'import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'import { readFile, rm } from 'node:fs/promises'import { release } from 'node:os'@@ -15,6 +15,7 @@ import { fileURLToPath } from 'node:url'import { canonicalExecPath } from './canonical-path.mjs'import { hostPort } from './host-port.mjs'import { captureStdio, LogFile } from './logs.mjs'+import { Pickers } from './picker-host.mjs'import { currentRootOf, driveOf, formatBytes, freeSpace, isEmptyTree, pickFrom, placeOf, rootOf, runningLow } from './place.mjs'import { createShell, SHELL_TEXT } from './shell.mjs'import { readStartFrame, writeStartFrame } from './start-frame.mjs'@@ -67,7 +68,7 @@ const frameFile = join(app.getPath('userData'), 'start-frame.json')// Loaded once the start window is up (loadModules).let BotBrowserGuests, partitionOf, BotViews, isBotId, importFromBrowser, listSources, applyCookies, CookieImports, parseCookieFile-let downloadSaver, chooseLocations, defaultPlaces, lang, pickRoot, programFolder, saveLocations, teamIn, teamsAt, tx, HostProcess+let downloadSaver, chooseLocations, defaultPlaces, lang, pickerLabels, pickRoot, programFolder, saveLocations, teamIn, teamsAt, tx, HostProcesslet copySessions, findTeam, importTeam, teamInUse, teamSizes, userDshHome, copyData, copyReason, moveProblem, CHECK_PROFILE, PROFILE, ImportFlowlet watchReleases, watchUpdates, RELEASE_PAGE, getDshRuntimeVersion, electronUpdater@@ -130,6 +131,8 @@ const copyAbort = new AbortController()let browserGuestslet botViewslet cookieImports+// The app's own folder and file picker, on the page of the window that asks (picker-host.mjs).+const pickers = new Pickers({ ipcMain, getPath: name => app.getPath(name) })// The team window and the tray: closing the window hides it, the tray is the way back to it and// the tray's Quit is the one ordinary way out. Until the hand-off the start window is the one@@ -180,6 +183,7 @@ if (canonical !== undefined) {startWindow = new StartWindow({electron: { BrowserWindow, ipcMain, screen, shell: electronShell, clipboard, dialog, nativeTheme, systemPreferences },page: join(here, 'start', 'start.html'), preload: join(here, 'preload.cjs'), icon: iconFile, mica, devTools: !app.isPackaged,+ css: readFileSync(join(here, 'page-card.css'), 'utf8'),// On Windows the locale is known only once the app is ready.lang: () => langOf(app.getLocale()), motion: readStartFrame(frameFile).motion,version: app.getVersion(), program: [dirname(process.execPath), process.resourcesPath, app.getAppPath()], log: logs, mainWindow: () => mainWindow,@@ -274,7 +278,7 @@ async function loadModules() {;({ applyCookies, CookieImports } = cookies);({ parseCookieFile } = cookieFiles);({ downloadSaver } = downloads)- ;({ chooseLocations, defaultPlaces, lang, pickRoot, programFolder, saveLocations, teamIn, teamsAt, tx } = firstRun)+ ;({ chooseLocations, defaultPlaces, lang, pickerLabels, pickRoot, programFolder, saveLocations, teamIn, teamsAt, tx } = firstRun);({ HostProcess } = hostProcess);({ copySessions, findTeam, importTeam, teamInUse, teamSizes, userDshHome } = imports);({ ImportFlow } = flows)@@ -334,7 +338,7 @@ async function stopOld(options) {}// The dialogs of the first run belong to the start window and stop its clock.-const ui = () => ({ owner: () => startWindow.owner(), asking: answer => startWindow.asking(answer) })+const ui = () => ({ owner: () => startWindow.owner(), asking: answer => startWindow.asking(answer), pick: request => askPicker(startWindow.owner(), request) })/*** A card on the start page that waits for the user, in place of a message box: the value of the@@ -751,16 +755,14 @@ function handleIpc() {})ipcMain.handle(IPC.browserImportPick, async (event) => {assertWindow(event)- const picked = await dialog.showOpenDialog(mainWindow, {- properties: ['openFile'],- filters: [{ name: 'Cookie files', extensions: ['txt', 'json', 'cookies'] }, { name: 'All files', extensions: ['*'] }],- })- if (picked.canceled || !picked.filePaths[0]) return { canceled: true }- const buffer = await readFile(picked.filePaths[0])+ // Any file: a cookie export can have any name, and the parser says what it is.+ const picked = await askPicker(mainWindow, { mode: 'file', title: tx('dialog.pickCookies'), start: knownFolder('downloads') })+ if (picked === undefined) return { canceled: true }+ const buffer = await readFile(picked)if (buffer.length > IMPORT_FILE_MAX) return { error: 'too-large' }const parsed = parseCookieFile(buffer)if (!parsed.ok) return { error: parsed.error ?? 'unreadable', format: parsed.format }- return cookieImports.store(parsed, { kind: 'file', label: basename(picked.filePaths[0]) })+ return cookieImports.store(parsed, { kind: 'file', label: basename(picked) })})ipcMain.handle(IPC.browserImportLive, async (event, sourceId, close) => {assertWindow(event)@@ -894,14 +896,14 @@ async function moveFromStart() {// 「这里放不了」 with the reason, or 「搬到这个文件夹?」. A cancelled picker is no change: the card// that led here goes, and the start goes on.async function pickMove() {- const { canceled, filePaths } = await dialog.showOpenDialog(owner(), { title: tx('dialog.pickMove'), defaultPath: dirname(places.dataDir), properties: ['openDirectory', 'createDirectory', 'promptToCreate'] })+ const picked = await askPicker(owner(), { mode: 'folder', title: tx('dialog.pickMove'), start: dirname(places.dataDir) })if (stopping || startWindow.owner() === undefined) returnmoveTo = undefined- if (canceled || filePaths[0] === undefined) {+ if (picked === undefined) {startWindow.card(undefined)return}- moveCard(resolve(filePaths[0]))+ moveCard(resolve(picked))}function moveCard(to) {@@ -948,11 +950,11 @@ 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.+// The picker, the question and a refusal are all on the team window's page.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 undefined- const to = resolve(filePaths[0])+ const picked = await askPicker(owner(), { mode: 'folder', title: tx('dialog.pickMove'), start: dirname(places.dataDir) })+ if (picked === undefined) return undefined+ const to = resolve(picked)if (await moveRefused(to, workspace)) return undefinedconst 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 undefined@@ -1098,6 +1100,8 @@ async function askDownloadNow(version) {// The cards that the team window shows, by id, until they have their answer.const cards = new Map()let cardCount = 0+// Pickers open on the team window; the Bot browser views wait until the last one goes.+let pickerCount = 0/*** A question of the app in the team window, on a card over its page instead of a message box@@ -1124,7 +1128,7 @@ function askInWindow(card, { front = false } = {}) {clearTimeout(timer)contents.off('did-start-loading', away)contents.off('destroyed', away)- if (cards.size === 0) botViews?.cover(false)+ if (cards.size === 0 && pickerCount === 0) botViews?.cover(false)resolve(value)}const away = () => { settle(undefined) }@@ -1147,6 +1151,33 @@ async function boxInWindow(options, unasked) {return answer === undefined ? { response: unasked, unasked: true } : { response: answer }}+/**+ * The app's own picker on `win`'s page: the chosen path, null when the user cancels, undefined+ * when the page cannot show it. The Bot browser views are drawn above the page and would cover+ * it, so they wait, as for a card.+ * @param {any} win+ * @param {{ mode: 'folder' | 'file' | 'save', title: string, start?: string, name?: string }} request+ * @returns {Promise<string | null | undefined>}+ */+async function pickOn(win, request) {+ if (win === undefined || win === null || win.isDestroyed()) return undefined+ const covers = win === mainWindow+ if (covers) { pickerCount += 1; botViews?.cover(true) }+ try {+ return await pickers.ask(win.webContents, { ...request, labels: pickerLabels() })+ } finally {+ if (covers && (pickerCount -= 1) === 0 && cards.size === 0) botViews?.cover(false)+ }+}++// app.getPath throws for a known folder that does not resolve; the picker then starts at home.+function knownFolder(name) {+ try { return app.getPath(name) } catch { return undefined }+}++/** The picker's path, or undefined when it was cancelled or could not be shown. */+const askPicker = async (win, request) => (await pickOn(win, request)) ?? undefined+function toFront(win) {if (win === undefined || win.isDestroyed()) returnif (win.isMinimized()) win.restore()@@ -1215,7 +1246,12 @@ function createWindow() {// The session is the same for every window of the app, so the handler is bound once.if (!downloadsBound) {downloadsBound = true- contents.session.on('will-download', downloadSaver({ window: () => mainWindow, dialog, getPath: name => app.getPath(name) }))+ contents.session.on('will-download', downloadSaver({+ window: () => mainWindow,+ ask: (name, folder) => pickOn(mainWindow, { mode: 'save', title: tx('dialog.saveAs'), start: folder, name }),+ staging: () => join(app.getPath('userData'), 'downloading'),+ getPath: name => app.getPath(name),+ }))}if (win32) {// Fullscreen hides the caption buttons, and the page drops its band meanwhile. A reloaddiff --git a/app/src/page-card.css b/app/src/page-card.cssindex f58ac1b9..33187fb0 100644--- a/app/src/page-card.css+++ b/app/src/page-card.css@@ -1,5 +1,6 @@-/* 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+/* DeepSeek Bot's own questions and pickers: one card over the page in place of a message box+ or a system picker (main.mjs askInWindow and askPicker, preload.cjs showCard and showPicker).+ The main process inserts this sheet into the team window and the start window; thecolors and springs are the start window's, scoped to the card's layer so that the page's ownstay as they are. *//* tokens */@@ -40,9 +41,64 @@.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%)}+/* The app's own folder and file picker (preload.cjs showPicker): the card made wide and tall,+ places and drives on the left, the folder's entries on the right. */+.dsb-picker{display:flex;flex-direction:column;gap:10px;width:min(720px,100%);height:min(560px,calc(100vh - 32px));overflow:hidden;padding:18px 20px}+.dsb-picker[hidden],.dsb-picker [hidden]{display:none!important}+.dsb-picker-bar{display:flex;align-items:center;gap:6px;min-width:0}+.dsb-picker-up{all:unset;flex:none;display:grid;place-items:center;width:28px;height:28px;border-radius:999px;color:var(--bt-ink-2);cursor:pointer;transition:background-color .12s,scale var(--spring-tap-ms) var(--spring-tap)}+.dsb-picker-up::before{content:"";width:7px;height:7px;border-left:1.5px solid currentColor;border-top:1.5px solid currentColor;rotate:45deg;translate:0 2px}+.dsb-picker-up:hover{background:var(--bt-hover)}+.dsb-picker-up:active{scale:.9}+.dsb-picker-up:disabled{opacity:.35;cursor:default;scale:none;background:none}+.dsb-picker-crumbs{display:flex;align-items:center;min-width:0;overflow-x:auto;scrollbar-width:none;white-space:nowrap}+.dsb-picker-crumb{all:unset;flex:none;max-width:200px;overflow:hidden;text-overflow:ellipsis;padding:2px 6px;border-radius:6px;font-size:13px;line-height:20px;color:var(--bt-ink-2);cursor:pointer}+.dsb-picker-crumb+.dsb-picker-crumb::before{content:"/";margin:0 4px 0 -2px;color:var(--bt-line-2)}+.dsb-picker-crumb:hover{background:var(--bt-hover);color:var(--bt-ink)}+.dsb-picker-crumb[aria-current]{color:var(--bt-ink);font-weight:600}+.dsb-picker-row-form{display:flex;gap:8px}+.dsb-picker-input{all:unset;flex:1;min-width:0;height:36px;padding:0 10px;border:1px solid var(--bt-line-2);border-radius:8px;background:var(--bt-card);font:inherit;font-size:13px;line-height:20px;color:var(--bt-ink);box-sizing:border-box;transition:border-color .12s}+.dsb-picker-input:focus{border-color:var(--bt-accent)}+.dsb-picker-small{height:36px;padding:0 14px;font-size:13px}+.dsb-picker-main{flex:1;min-height:0;display:grid;grid-template-columns:168px minmax(0,1fr);gap:10px}+.dsb-picker-side{display:flex;flex-direction:column;gap:1px;min-height:0;overflow-y:auto;padding-right:2px}+.dsb-picker-head{margin:6px 8px 4px;font-size:12px;line-height:18px;font-weight:500;color:var(--bt-ink-2)}+.dsb-picker-head:first-child{margin-top:0}+.dsb-picker-root{all:unset;display:flex;align-items:center;gap:8px;min-height:30px;padding:0 8px;border-radius:6px;font-size:13px;line-height:20px;color:var(--bt-ink);overflow:hidden;white-space:nowrap;text-overflow:ellipsis;cursor:pointer}+.dsb-picker-root:hover{background:var(--bt-hover)}+.dsb-picker-root[aria-current]{background:color-mix(in srgb,var(--bt-accent) 12%,transparent)}+.dsb-picker-pane{display:flex;flex-direction:column;min-height:0;border:1px solid var(--bt-line-2);border-radius:10px;background:var(--bt-main);overflow:hidden}+.dsb-picker-note{margin:0;padding:8px 12px;font-size:13px;line-height:20px;color:var(--bt-ink-2);border-bottom:1px solid var(--bt-line)}+.dsb-picker-note[data-tone=error]{color:var(--bt-danger)}+.dsb-picker-list{flex:1;min-height:0;overflow-y:auto;padding:4px;outline:none}+.dsb-picker-list[aria-busy=true]{opacity:.6;transition:opacity .2s .15s}+.dsb-picker-list:focus-visible{box-shadow:inset 0 0 0 2px var(--bt-accent);border-radius:10px}+.dsb-picker-row{display:flex;align-items:center;gap:8px;min-height:30px;padding:0 8px;border-radius:6px;font-size:13px;line-height:20px;color:var(--bt-ink);cursor:default;user-select:none}+.dsb-picker-row[data-dir=false]{color:var(--bt-ink-2)}+.dsb-picker-row:hover{background:var(--bt-hover)}+.dsb-picker-row[aria-selected=true]{background:color-mix(in srgb,var(--bt-accent) 16%,transparent);color:var(--bt-ink)}+.dsb-picker-row-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.dsb-picker-glyph{flex:none;width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.2;stroke-linejoin:round;stroke-linecap:round;color:var(--bt-ink-2)}+.dsb-picker-side,.dsb-picker-list{scrollbar-width:thin;scrollbar-color:var(--bt-line-2) transparent}+.dsb-picker-row[data-dir=true] .dsb-picker-glyph,.dsb-picker-root .dsb-picker-glyph{color:var(--bt-accent)}+.dsb-picker-name{display:flex;align-items:center;gap:10px}+.dsb-picker-name-label{flex:none;font-size:13px;color:var(--bt-ink-2)}+.dsb-picker-ask{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:8px 8px 8px 12px;border-radius:10px;background:color-mix(in srgb,var(--bt-danger) 8%,transparent);font-size:13px;line-height:20px;color:var(--bt-ink)}+.dsb-picker-actions{margin-top:0}+.dsb-picker-newbtn{margin-right:auto}+.dsb-card-btn:disabled{opacity:.35;cursor:default;scale:none}+/* A narrow window (the start window, a small team window) drops the side column under the+ path field: the places stay one row that scrolls sideways. */+@media (max-width:560px){+ .dsb-picker-main{grid-template-columns:minmax(0,1fr);grid-template-rows:auto minmax(0,1fr)}+ .dsb-picker-side{flex-direction:row;overflow-x:auto;overflow-y:hidden;scrollbar-width:none;padding:0}+ .dsb-picker-head{display:none}+ .dsb-picker-root{flex:none}+}/* 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}+ .dsb-picker-up,.dsb-picker-up:active{transition:background-color .12s;scale:none}}diff --git a/app/src/picker-host.mjs b/app/src/picker-host.mjsnew file mode 100644index 00000000..4612bb48--- /dev/null+++ b/app/src/picker-host.mjs@@ -0,0 +1,92 @@+// The main process's half of the app's own picker: one open picker per id, tied to the page that+// shows it. The page asks for listings, new folders and the answer over IPC; a request from any+// other page, or for a picker that is no longer open, gets nothing.+import { chosen, list, makeFolder, roots, saveTarget, startIn, typed } from './folder-picker.mjs'++export const PICKER_IPC = {+ open: 'ds-bot:app-picker', shown: 'ds-bot:app-picker-shown', cancel: 'ds-bot:app-picker-cancel',+ roots: 'ds-bot:app-picker-roots', list: 'ds-bot:app-picker-list', folder: 'ds-bot:app-picker-folder', choose: 'ds-bot:app-picker-choose',+}++// A page that has not drawn the picker by then cannot (not loaded, gone, or hung).+export const PICKER_SHOWN_MS = 2000++export class Pickers {+ #open = new Map()+ #count = 0+ #getPath+ #platform+ #shownMs++ /**+ * @param {{ ipcMain: any, getPath: (name: string) => string, platform?: string, shownMs?: number }} options+ */+ constructor({ ipcMain, getPath, platform = process.platform, shownMs = PICKER_SHOWN_MS }) {+ this.#getPath = getPath+ this.#platform = platform+ this.#shownMs = shownMs+ const from = (event, id) => {+ const open = this.#open.get(id)+ return open !== undefined && event.sender === open.contents ? open : undefined+ }+ ipcMain.on(PICKER_IPC.shown, (event, id) => { from(event, id)?.shown() })+ ipcMain.on(PICKER_IPC.cancel, (event, id) => { from(event, id)?.settle(null) })+ ipcMain.handle(PICKER_IPC.roots, (event, id) => (from(event, id) === undefined ? undefined : roots({ getPath: this.#getPath, platform: this.#platform })))+ ipcMain.handle(PICKER_IPC.list, async (event, id, path, at) => {+ const open = from(event, id)+ if (open === undefined) return undefined+ return await list(typed(path, typeof at === 'string' ? at : open.start, this.#home()), { files: open.mode !== 'folder', extensions: open.extensions })+ })+ ipcMain.handle(PICKER_IPC.folder, async (event, id, parent, name) => {+ if (from(event, id) === undefined) return undefined+ return await makeFolder(String(parent), String(name), this.#platform)+ })+ ipcMain.handle(PICKER_IPC.choose, async (event, id, path, options) => {+ const open = from(event, id)+ if (open === undefined) return undefined+ const answer = open.mode === 'save'+ ? await saveTarget(String(path), String(options?.name ?? ''), this.#platform)+ : await chosen(String(path), open.mode)+ if ('error' in answer) return answer+ // A file of that name is there: the page asks first, and asks again with `replace`.+ if (answer.exists && options?.replace !== true) return answer+ open.settle(answer.path)+ return { path: answer.path }+ })+ }++ #home() {+ try { return this.#getPath('home') } catch { return undefined }+ }++ /**+ * Shows a picker on `contents`' page: the chosen path, null when the user cancels, undefined+ * when the page cannot show it or goes away first.+ * @param {any} contents the webContents whose page shows the picker+ * @param {{ mode: 'folder' | 'file' | 'save', title: string, start?: string, name?: string, extensions?: string[], labels: object }} request+ * @returns {Promise<string | null | undefined>}+ */+ async ask(contents, request) {+ if (contents === undefined || contents === null || contents.isDestroyed() || contents.isLoading()) return undefined+ const id = (this.#count += 1)+ const start = await startIn(request.start, this.#home())+ return await new Promise((resolve) => {+ let seen = false+ const away = () => { settle(undefined) }+ const settle = (value) => {+ if (!this.#open.has(id)) return+ this.#open.delete(id)+ clearTimeout(timer)+ contents.off?.('did-start-loading', away)+ contents.off?.('destroyed', away)+ resolve(value)+ }+ const timer = setTimeout(() => { if (!seen) away() }, this.#shownMs)+ this.#open.set(id, { contents, mode: request.mode, extensions: request.extensions, start, settle, shown: () => { seen = true } })+ contents.once('did-start-loading', away)+ contents.once('destroyed', away)+ contents.send(PICKER_IPC.open, { id, mode: request.mode, title: request.title, start, name: request.name, labels: request.labels })+ })+ }++}diff --git a/app/src/preload.cjs b/app/src/preload.cjsindex 8cd7e2ea..9857d5eb 100644--- a/app/src/preload.cjs+++ b/app/src/preload.cjs@@ -10,7 +10,11 @@ const argument = name => process.argv.find(value => value.startsWith(`--${name}=const startPage = argument('ds-bot-start')const host = argument('ds-bot-origin')if (startPage !== undefined) {- if (location.href.split(/[?#]/u)[0] === startPage) contextBridge.exposeInMainWorld('dsBotStart', startBridge())+ if (location.href.split(/[?#]/u)[0] === startPage) {+ contextBridge.exposeInMainWorld('dsBotStart', startBridge())+ // The start page's folder pickers (换个位置…, a data move) are the app's own too.+ ipcRenderer.on('ds-bot:app-picker', (_event, request) => { showPicker(request) })+ }} else if (host !== undefined && location.origin === host) {let ready = falsecontextBridge.exposeInMainWorld('dsBotApp', {@@ -50,6 +54,7 @@ if (startPage !== undefined) {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) }) })+ ipcRenderer.on('ds-bot:app-picker', (_event, request) => { loaded(() => { showPicker(request) }) })const caption = process.argv.find(value => value.startsWith('--ds-bot-caption='))if (caption !== undefined) {ipcRenderer.on('ds-bot:fullscreen', (_event, fullscreen) => {@@ -136,6 +141,329 @@ function showCard(card) {ipcRenderer.send('ds-bot:app-card-shown', card.id)}+// The app's own folder and file picker, in place of the system's (main.mjs askPicker,+// picker-host.mjs): the same card layer with a side column of places and drives, a breadcrumb, a+// path field, the folder's entries (folders first) and, to save, a file name. The page only+// draws: the main process lists, makes folders and checks the answer. What goes wrong (a folder+// without permission, a drive that is gone, a name that cannot be used) is said in place.+let openPicker+function showPicker(request) {+ if (request === null || typeof request !== 'object' || !Number.isInteger(request.id)) return+ openPicker?.close()+ const { id, mode } = request+ const label = key => String(request.labels?.[key] ?? key)+ const say = (key, vars) => label(key).replace(/\{(\w+)\}/gu, (all, name) => (name in vars ? String(vars[name]) : all))+ const call = (channel, ...args) => ipcRenderer.invoke(`ds-bot:app-picker-${channel}`, id, ...args)+ const make = (tag, className, text) => Object.assign(document.createElement(tag), { className, ...(text === undefined ? {} : { textContent: String(text) }) })+ const button = (className, text, look) => {+ const element = make('button', className, text)+ element.type = 'button'+ if (look !== undefined) element.dataset.look = look+ return element+ }+ const field = (className) => {+ const input = make('input', className)+ input.type = 'text'+ input.spellcheck = false+ input.autocomplete = 'off'+ return input+ }+ // A folder, a file or a drive, drawn in the page's ink.+ const glyph = (kind) => {+ const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg')+ svg.setAttribute('viewBox', '0 0 16 16')+ svg.setAttribute('aria-hidden', 'true')+ svg.classList.add('dsb-picker-glyph')+ const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')+ path.setAttribute('d', {+ dir: 'M1.5 4.5v8a1 1 0 0 0 1 1h11a1 1 0 0 0 1-1v-6.5a1 1 0 0 0-1-1H8L6.5 3.5h-4a1 1 0 0 0-1 1Z',+ file: 'M3.5 1.5h6l3 3v9a1 1 0 0 1-1 1h-8a1 1 0 0 1-1-1v-11a1 1 0 0 1 1-1Zm6 0v3h3',+ drive: 'M2.5 4.5h11a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1v-5a1 1 0 0 1 1-1ZM11.5 8h.01',+ }[kind])+ svg.append(path)+ return svg+ }++ const layer = make('div', 'dsb-card-layer')+ layer.dataset.kind = 'picker'+ const box = make('section', 'dsb-card dsb-picker')+ box.setAttribute('role', 'dialog')+ box.setAttribute('aria-modal', 'true')+ const title = make('h2', 'dsb-card-title', request.title ?? '')+ title.id = `dsb-picker-title-${String(id)}`+ box.setAttribute('aria-labelledby', title.id)++ const bar = make('div', 'dsb-picker-bar')+ const up = button('dsb-picker-up')+ up.setAttribute('aria-label', label('up'))+ up.title = label('up')+ const trail = make('nav', 'dsb-picker-crumbs')+ trail.setAttribute('aria-label', label('path'))+ bar.append(up, trail)++ const pathRow = make('form', 'dsb-picker-row-form')+ const pathField = field('dsb-picker-input')+ pathField.setAttribute('aria-label', label('path'))+ const go = button('dsb-card-btn dsb-picker-small', label('go'), 'soft')+ go.type = 'submit'+ pathRow.append(pathField, go)++ const main = make('div', 'dsb-picker-main')+ const side = make('nav', 'dsb-picker-side')+ side.setAttribute('aria-label', label('places'))+ const pane = make('div', 'dsb-picker-pane')+ const note = make('p', 'dsb-picker-note')+ note.hidden = true+ const rows = make('div', 'dsb-picker-list')+ rows.setAttribute('role', 'listbox')+ rows.setAttribute('aria-labelledby', title.id)+ rows.tabIndex = 0+ pane.append(note, rows)+ main.append(side, pane)++ const fresh = make('form', 'dsb-picker-row-form')+ fresh.hidden = true+ const freshName = field('dsb-picker-input')+ freshName.setAttribute('aria-label', label('newFolder'))+ const freshMake = button('dsb-card-btn dsb-picker-small', label('create'), 'soft')+ freshMake.type = 'submit'+ fresh.append(freshName, freshMake)++ const nameRow = make('label', 'dsb-picker-name')+ const nameField = field('dsb-picker-input')+ nameField.value = String(request.name ?? '')+ nameRow.append(make('span', 'dsb-picker-name-label', label('name')), nameField)++ const ask = make('div', 'dsb-picker-ask')+ ask.setAttribute('role', 'alert')+ ask.hidden = true++ const actions = make('div', 'dsb-card-actions dsb-picker-actions')+ const newFolder = button('dsb-card-btn dsb-picker-newbtn', label('newFolder'), 'soft')+ const cancel = button('dsb-card-btn', label('cancel'), 'soft')+ const primary = button('dsb-card-btn', label(mode === 'save' ? 'save' : mode === 'file' ? 'open' : 'chooseFolder'), 'primary')+ actions.append(newFolder, cancel, primary)++ box.append(title, bar, pathRow, main, fresh)+ if (mode === 'save') box.append(nameRow)+ box.append(ask, actions)+ layer.append(box)++ let here+ let entries = []+ let picked = -1+ let asked = 0+ let done = false++ const tell = (text, tone) => {+ note.textContent = text ?? ''+ note.hidden = !text+ if (tone === undefined) delete note.dataset.tone+ else note.dataset.tone = tone+ note.setAttribute('role', tone === 'error' ? 'alert' : 'status')+ }+ const hideAsk = () => {+ ask.hidden = true+ ask.replaceChildren()+ }+ const choice = () => entries[picked]+ const refresh = () => {+ const entry = choice()+ primary.disabled = here === undefined || (mode === 'file' && (entry === undefined || entry.dir))+ for (const [index, row] of [...rows.children].entries()) row.setAttribute('aria-selected', String(index === picked))+ if (entry === undefined) { rows.removeAttribute('aria-activedescendant'); return }+ rows.setAttribute('aria-activedescendant', rows.children[picked].id)+ rows.children[picked].scrollIntoView({ block: 'nearest' })+ }+ const select = (index) => {+ picked = Math.max(-1, Math.min(index, entries.length - 1))+ const entry = choice()+ if (mode === 'save' && entry !== undefined && !entry.dir) nameField.value = entry.name+ hideAsk()+ refresh()+ }+ const draw = (listing) => {+ here = listing.path+ pathField.value = listing.path+ up.disabled = listing.parent === undefined+ trail.replaceChildren(...listing.crumbs.map((step, index) => {+ const crumb = button('dsb-picker-crumb', step.name)+ crumb.title = step.path+ if (index === listing.crumbs.length - 1) crumb.setAttribute('aria-current', 'location')+ crumb.addEventListener('click', () => { void open(step.path) })+ return crumb+ }))+ trail.scrollLeft = trail.scrollWidth+ entries = listing.entries+ picked = -1+ rows.replaceChildren(...entries.map((entry, index) => {+ const row = make('div', 'dsb-picker-row')+ row.id = `dsb-picker-row-${String(id)}-${String(index)}`+ row.setAttribute('role', 'option')+ row.dataset.dir = String(entry.dir)+ row.title = entry.name+ row.append(glyph(entry.dir ? 'dir' : 'file'), make('span', 'dsb-picker-row-name', entry.name))+ row.addEventListener('click', () => { select(index) })+ row.addEventListener('dblclick', () => { void enter(index) })+ return row+ }))+ if (listing.more !== undefined) tell(say('more', { count: entries.length }))+ else if (entries.length === 0) tell(label(mode === 'folder' ? 'noFolders' : 'empty'))+ else tell()+ for (const root of side.querySelectorAll('.dsb-picker-root')) {+ if (root.dataset.path === here) root.setAttribute('aria-current', 'location')+ else root.removeAttribute('aria-current')+ }+ refresh()+ }+ // A listing that comes back after a newer one was asked for is dropped. A failed one keeps+ // the folder that was shown and says why next to it.+ const open = async (path) => {+ const turn = (asked += 1)+ rows.setAttribute('aria-busy', 'true')+ const listing = await call('list', String(path), here).catch(() => undefined)+ if (done || turn !== asked) return false+ rows.removeAttribute('aria-busy')+ if (listing === undefined || listing === null) return false+ if (listing.error !== undefined) {+ tell(label(`error.${listing.error}`), 'error')+ return false+ }+ hideAsk()+ draw(listing)+ return true+ }+ const enter = async (index) => {+ const entry = entries[index]+ if (entry === undefined) return+ if (entry.dir) await open(entry.path)+ else if (mode === 'file') await choose(entry.path)+ else select(index)+ }+ const choose = async (path, replace = false) => {+ if (done || path === undefined) return+ const name = nameField.value.trim()+ const answer = await call('choose', path, mode === 'save' ? { name, replace } : undefined).catch(() => undefined)+ if (done || answer === undefined || answer === null) return+ if (answer.error !== undefined) { tell(label(`error.${answer.error}`), 'error'); return }+ if (answer.exists) {+ const yes = button('dsb-card-btn dsb-picker-small', label('replace'), 'primary')+ yes.addEventListener('click', () => { void choose(path, true) })+ ask.replaceChildren(make('span', 'dsb-picker-ask-text', say('error.replace', { name })), yes)+ ask.hidden = false+ yes.focus()+ return+ }+ close(false)+ }+ const commit = () => {+ if (mode === 'save') { void choose(here); return }+ const entry = choice()+ if (mode === 'file') { if (entry !== undefined && !entry.dir) void choose(entry.path); return }+ void choose(entry?.dir ? entry.path : here)+ }++ up.addEventListener('click', () => { const steps = trail.children; if (steps.length > 1) steps[steps.length - 2].click() })+ pathRow.addEventListener('submit', (event) => { event.preventDefault(); void open(pathField.value) })+ newFolder.addEventListener('click', () => {+ fresh.hidden = false+ freshName.value = label('newName')+ freshName.focus()+ freshName.select()+ })+ fresh.addEventListener('submit', (event) => {+ event.preventDefault()+ void call('folder', here, freshName.value.trim()).catch(() => undefined).then(async (made) => {+ if (done || made === undefined || made === null) return+ if (made.error !== undefined) { tell(label(`error.${made.error}`), 'error'); freshName.focus(); return }+ fresh.hidden = true+ if (await open(here)) {+ select(entries.findIndex(entry => entry.path === made.path))+ rows.focus()+ }+ })+ })+ nameField.addEventListener('input', hideAsk)+ nameField.addEventListener('keydown', (event) => { if (event.key === 'Enter') { event.preventDefault(); commit() } })+ cancel.addEventListener('click', () => { close(true) })+ primary.addEventListener('click', commit)+ rows.addEventListener('keydown', (event) => {+ const step = { ArrowDown: 1, ArrowUp: -1, PageDown: 10, PageUp: -10 }[event.key]+ if (step !== undefined && !event.altKey) { event.preventDefault(); select(picked < 0 ? 0 : picked + step) }+ else if (event.key === 'Home') { event.preventDefault(); select(0) }+ else if (event.key === 'End') { event.preventDefault(); select(entries.length - 1) }+ else if (event.key === 'Enter') { event.preventDefault(); if (choice()?.dir) void enter(picked); else commit() }+ else if (event.key === 'Backspace' || (event.key === 'ArrowUp' && event.altKey)) { event.preventDefault(); up.click() }+ })++ const focusables = () => [...box.querySelectorAll('button, input, [tabindex="0"]')].filter(element => !element.disabled && element.offsetParent !== null)+ const keys = (event) => {+ if (event.key === 'Escape') {+ event.preventDefault()+ if (!ask.hidden) hideAsk()+ else if (!fresh.hidden) { fresh.hidden = true; rows.focus() } else close(true)+ } else if (event.key === 'Tab') {+ const list = focusables()+ const at = list.indexOf(document.activeElement)+ event.preventDefault()+ list[(at + (event.shiftKey ? -1 : 1) + list.length) % list.length]?.focus()+ }+ // The page's own shortcuts wait while the picker is up.+ event.stopPropagation()+ }+ const keep = (event) => { if (!layer.contains(event.target)) rows.focus() }+ const before = document.activeElement+ function close(cancelled) {+ if (done) return+ done = true+ if (openPicker?.close === quit) openPicker = undefined+ document.removeEventListener('keydown', keys, true)+ document.removeEventListener('focusin', keep, true)+ if (cancelled) ipcRenderer.send('ds-bot:app-picker-cancel', id)+ delete layer.dataset.open+ layer.dataset.leaving = ''+ layer.inert = true+ setTimeout(() => { layer.remove() }, 220)+ if (before instanceof HTMLElement && before.isConnected) before.focus({ preventScroll: true })+ }+ const quit = () => { close(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 = ''+ openPicker = { close: quit }+ ipcRenderer.send('ds-bot:app-picker-shown', id)+ refresh()+ if (mode === 'save') {+ nameField.focus({ preventScroll: true })+ const dot = nameField.value.lastIndexOf('.')+ nameField.setSelectionRange(0, dot > 0 ? dot : nameField.value.length)+ } else rows.focus({ preventScroll: true })++ void open(request.start ?? '').then((ok) => { if (!ok && !done && here === undefined && note.hidden) tell(label('error.unreadable'), 'error') })+ void call('roots').then((found) => {+ if (done || found === undefined || found === null) return+ const group = (heading, items, kind) => {+ if (items.length === 0) return []+ return [make('h3', 'dsb-picker-head', heading), ...items.map((item) => {+ const root = button('dsb-picker-root', item.label)+ root.dataset.path = item.path+ root.title = item.path+ root.prepend(glyph(kind))+ if (item.path === here) root.setAttribute('aria-current', 'location')+ root.addEventListener('click', () => { void open(item.path) })+ return root+ })]+ }+ side.replaceChildren(+ ...group(label('places'), found.places.map(place => ({ path: place.path, label: label(place.key) })), 'dir'),+ ...group(label('drives'), found.drives, 'drive'),+ )+ }, () => {})+}+// 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 b7b1a5a2..a097cf1b 100644--- a/app/src/start-window.mjs+++ b/app/src/start-window.mjs@@ -291,7 +291,7 @@ export class StartWindow {/*** @param {{* electron: { BrowserWindow: any, ipcMain: any, screen: any, shell: any, clipboard: any, dialog?: any, nativeTheme: any, systemPreferences: any },- * page: string, preload: string, icon: string, mica: boolean, devTools: boolean,+ * page: string, preload: string, icon: string, mica: boolean, devTools: boolean, css?: string,* lang: () => 'zh' | 'en', motion: string, version: string, program: string[],* log: { dir: string, tail: (count: number) => string[] },* mainWindow: () => any,@@ -370,7 +370,11 @@ export class StartWindow {contents.on('will-navigate', (event) => { event.preventDefault() })contents.setWindowOpenHandler(() => ({ action: 'deny' }))// A reload loses what the preload kept, so the page gets the state again.- contents.on('dom-ready', () => { this.#send() })+ // The page loads only its own files; the app's picker brings its sheet (page-card.css).+ contents.on('dom-ready', () => {+ if (this.#o.css) void contents.insertCSS(this.#o.css)+ this.#send()+ })contents.on('render-process-gone', (_event, details) => { note(`the page's renderer stopped (${String(details?.reason)})`) })if (this.#o.devTools) {contents.on('before-input-event', (_event, input) => {diff --git a/app/src/start/text.mjs b/app/src/start/text.mjsindex 326ac1fb..d2d894b9 100644--- a/app/src/start/text.mjs+++ b/app/src/start/text.mjs@@ -151,6 +151,42 @@ export const TEXT = {// dialog'dialog.pickRoot': '选择 DeepSeek Bot 放数据的位置','dialog.pickMove': '选择 DeepSeek Bot 数据的新文件夹',+ 'dialog.pickCookies': '选择 cookie 文件',+ 'dialog.saveAs': '保存下载的文件',+ // The app's own picker (preload.cjs showPicker): labels, then what went wrong, in place.+ 'picker.places': '位置',+ 'picker.drives': '磁盘',+ 'picker.home': '主文件夹',+ 'picker.desktop': '桌面',+ 'picker.documents': '文档',+ 'picker.downloads': '下载',+ 'picker.path': '路径',+ 'picker.go': '前往',+ 'picker.up': '上一级',+ 'picker.newFolder': '新建文件夹',+ 'picker.newName': '新建文件夹',+ 'picker.create': '新建',+ 'picker.name': '文件名',+ 'picker.cancel': '取消',+ 'picker.chooseFolder': '选择这个文件夹',+ 'picker.open': '打开',+ 'picker.save': '保存',+ 'picker.replace': '替换',+ 'picker.loading': '正在读取',+ 'dialog.picker.empty': '这个文件夹是空的。',+ 'dialog.picker.noFolders': '这里没有文件夹。',+ 'dialog.picker.more': '这里只列出前 {count} 项。',+ 'dialog.picker.missing': '找不到这个文件夹。',+ 'dialog.picker.drive': '这个磁盘现在不在。请连接它,或者换一个位置。',+ 'dialog.picker.denied': '没有权限打开这个文件夹。',+ 'dialog.picker.notFolder': '这不是一个文件夹。',+ 'dialog.picker.notFile': '请选择一个文件。',+ 'dialog.picker.tooLong': '这个路径太长,打不开。',+ 'dialog.picker.unreadable': '这个文件夹打不开。',+ 'dialog.picker.name': '这个名字不能用作文件名。',+ 'dialog.picker.exists': '已经有同名的文件夹了。',+ 'dialog.picker.isFolder': '这里有一个同名的文件夹,请换个名字。',+ 'dialog.picker.replace': '已经有「{name}」了。要替换它吗?','dialog.move.inDsh': '请选择 DeepSeek Harness 数据({home})以外的文件夹。','dialog.move.inProgram': '请选择程序文件夹以外的位置:卸载时会删掉程序文件夹。','dialog.move.drive': '请选择一个文件夹,不要选整个磁盘。',@@ -298,6 +334,41 @@ export const TEXT = {// dialog'dialog.pickRoot': 'Choose where DeepSeek Bot keeps its data','dialog.pickMove': 'Choose a new folder for DeepSeek Bot’s data',+ 'dialog.pickCookies': 'Choose a cookie file',+ 'dialog.saveAs': 'Save the download',+ 'picker.places': 'Places',+ 'picker.drives': 'Drives',+ 'picker.home': 'Home',+ 'picker.desktop': 'Desktop',+ 'picker.documents': 'Documents',+ 'picker.downloads': 'Downloads',+ 'picker.path': 'Path',+ 'picker.go': 'Go',+ 'picker.up': 'Up one level',+ 'picker.newFolder': 'New folder',+ 'picker.newName': 'New folder',+ 'picker.create': 'Create',+ 'picker.name': 'File name',+ 'picker.cancel': 'Cancel',+ 'picker.chooseFolder': 'Choose this folder',+ 'picker.open': 'Open',+ 'picker.save': 'Save',+ 'picker.replace': 'Replace',+ 'picker.loading': 'Reading',+ 'dialog.picker.empty': 'This folder is empty.',+ 'dialog.picker.noFolders': 'There are no folders here.',+ 'dialog.picker.more': 'Only the first {count} items are listed.',+ 'dialog.picker.missing': 'This folder does not exist.',+ 'dialog.picker.drive': 'This drive is not there. Connect it, or choose another place.',+ 'dialog.picker.denied': 'You don’t have permission to open this folder.',+ 'dialog.picker.notFolder': 'This is not a folder.',+ 'dialog.picker.notFile': 'Choose a file.',+ 'dialog.picker.tooLong': 'This path is too long to open.',+ 'dialog.picker.unreadable': 'This folder can’t be opened.',+ 'dialog.picker.name': 'This name can’t be used for a file.',+ 'dialog.picker.exists': 'A folder with this name already exists.',+ 'dialog.picker.isFolder': 'A folder here has this name. Choose another name.',+ 'dialog.picker.replace': '{name} already exists. Do you want to replace it?','dialog.move.inDsh': 'Choose a folder outside the DeepSeek Harness data ({home}).','dialog.move.inProgram': 'Choose a place outside the program folder: uninstalling removes the program folder.','dialog.move.drive': 'Choose a folder, not a whole drive.',diff --git a/app/test/downloads.test.mjs b/app/test/downloads.test.mjsindex 21de727b..b8b2ee19 100644--- a/app/test/downloads.test.mjs+++ b/app/test/downloads.test.mjs@@ -1,118 +1,177 @@-// The main window's will-download handler: a system save dialog picks the path,-// a cancelled dialog drops the download, other contents' downloads pass through.+// The main window's will-download handler: the download starts into a staging folder at once,+// the app's own picker says where it goes, and the file moves there when both are in. A+// cancelled picker cancels it; other contents' downloads pass through. Temp folders only.import assert from 'node:assert/strict'-import { join } from 'node:path'-import test from 'node:test'-import { downloadSaver } from '../src/downloads.mjs'+import { EventEmitter } from 'node:events'+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { after, test } from 'node:test'+import { downloadSaver, freePath } from '../src/downloads.mjs'-const item = () => ({ getFilename: () => 'chart.png', path: undefined, setSavePath(path) { this.path = path } })+const top = mkdtempSync(join(tmpdir(), 'ds-bot-downloads-'))+after(() => { rmSync(top, { recursive: true, force: true }) })+let runs = 0+const place = () => {+ runs += 1+ const at = join(top, String(runs))+ const downloads = join(at, 'downloads')+ mkdirSync(downloads, { recursive: true })+ return { staging: join(at, 'staging'), downloads, home: join(at, 'home') }+}++// A download item: it writes its bytes to the save path when it is done.+function item(name = 'chart.png') {+ const download = Object.assign(new EventEmitter(), {+ path: undefined, cancelled: false,+ getFilename: () => name,+ setSavePath(path) { this.path = path },+ cancel() { this.cancelled = true; this.emit('done', {}, 'cancelled') },+ finish(text = 'bytes') {+ if (this.cancelled) return+ mkdirSync(dirname(this.path), { recursive: true })+ writeFileSync(this.path, text)+ this.emit('done', {}, 'completed')+ },+ })+ return download+}const event = () => ({ prevented: false, preventDefault() { this.prevented = true } })-const folders = { downloads: '/downloads', home: '/home/me' }-const getPath = name => folders[name]-const unresolved = name => { throw new Error(`Failed to get '${name}' path`) }+const settle = () => new Promise(resolve => setImmediate(resolve))+const until = async (check) => { for (let turn = 0; turn < 50 && !check(); turn += 1) await settle() }-// The folder the save dialog starts in when the main window downloads chart.png.-function startPath({ getPath, homedir }) {+function saver(at, ask, extra = {}) {const contents = {}- let options- const save = downloadSaver({ window: { webContents: contents }, dialog: { showSaveDialogSync: (_win, given) => { options = given; return '/picked/chart.png' } }, getPath, homedir })- save(event(), item(), contents)- return options.defaultPath+ const save = downloadSaver({ window: { webContents: contents }, ask, staging: () => at.staging, getPath: name => ({ downloads: at.downloads, home: at.home })[name], log: { warn: () => {} }, ...extra })+ return { contents, save }}-test('a download from the main window asks for a path and saves there', () => {- const contents = {}- const window = { webContents: contents }- const calls = []- const save = downloadSaver({- window,- dialog: { showSaveDialogSync: (win, options) => { calls.push({ win, options }); return '/picked/chart.png' } },- getPath,- })+test('a download starts at once, asks where it goes, and lands there when both are in', async () => {+ const at = place()+ const asked = []+ let answer+ const { contents, save } = saver(at, (name, folder) => { asked.push({ name, folder }); return new Promise((resolve) => { answer = resolve }) })const ev = event()const download = item()save(ev, download, contents)- assert.equal(download.path, '/picked/chart.png')assert.equal(ev.prevented, false)- assert.equal(calls.length, 1)- assert.equal(calls[0].win, window)- assert.equal(calls[0].options.defaultPath, join('/downloads', 'chart.png'), 'the dialog starts in the downloads folder')+ assert.ok(download.path.startsWith(at.staging), 'it saves into the staging folder first')+ assert.deepEqual(asked, [{ name: 'chart.png', folder: at.downloads }], 'the picker starts in the downloads folder')+ // The download is done before the user has answered.+ download.finish('png')+ const target = join(at.downloads, 'picked.png')+ answer(target)+ await until(() => existsSync(target))+ assert.equal(readFileSync(target, 'utf8'), 'png')+ await until(() => readdirSync(at.staging).length === 0)+ assert.deepEqual(readdirSync(at.staging), [], 'the staging folder is cleared')})-test('the downloads folder is looked up for each download, not when the handler is made', () => {- const asked = []- const contents = {}- const save = downloadSaver({ window: { webContents: contents }, dialog: { showSaveDialogSync: () => undefined }, getPath: (name) => { asked.push(name); return folders[name] } })- assert.deepEqual(asked, [])- save(event(), item(), contents)- save(event(), item(), contents)- assert.deepEqual(asked, ['downloads', 'downloads'])+test('an answer before the download is done waits for it', async () => {+ const at = place()+ const target = join(at.downloads, 'early.png')+ const { contents, save } = saver(at, async () => target)+ const download = item()+ save(event(), download, contents)+ await settle()+ assert.equal(existsSync(target), false)+ download.finish('late')+ await until(() => existsSync(target))+ assert.equal(readFileSync(target, 'utf8'), 'late')})-test('a downloads folder that does not resolve falls back to the home folder', () => {- const homeOnly = name => name === 'home' ? folders.home : unresolved(name)- assert.equal(startPath({ getPath: homeOnly, homedir: () => '/os-home' }), join('/home/me', 'chart.png'))- assert.equal(startPath({ getPath: unresolved, homedir: () => '/os-home' }), join('/os-home', 'chart.png'))+test('a cancelled picker cancels the download and leaves nothing behind', async () => {+ const at = place()+ const { contents, save } = saver(at, async () => null)+ const download = item()+ save(event(), download, contents)+ await until(() => download.cancelled)+ assert.equal(download.cancelled, true)+ await until(() => readdirSync(at.staging).length === 0)+ assert.deepEqual(readdirSync(at.downloads), [])+ assert.deepEqual(readdirSync(at.staging), [])})-test('without any folder the dialog still opens, with only the file name', () => {- const noHome = () => { throw new Error('no home') }- assert.equal(startPath({ getPath: unresolved, homedir: noHome }), 'chart.png')- assert.equal(startPath({ getPath: () => '', homedir: () => '' }), 'chart.png')+test('a picker that cannot be shown saves into the downloads folder under a free name', async () => {+ const at = place()+ writeFileSync(join(at.downloads, 'chart.png'), 'old')+ const { contents, save } = saver(at, async () => undefined)+ const download = item()+ save(event(), download, contents)+ download.finish('new')+ const target = join(at.downloads, 'chart (2).png')+ await until(() => existsSync(target))+ assert.equal(readFileSync(target, 'utf8'), 'new')+ assert.equal(readFileSync(join(at.downloads, 'chart.png'), 'utf8'), 'old', 'the old file stays')})-test('a cancelled dialog drops the download', () => {- const contents = {}- const save = downloadSaver({ window: { webContents: contents }, dialog: { showSaveDialogSync: () => undefined }, getPath })- const ev = event()+test('a replace that the picker allowed overwrites the old file', async () => {+ const at = place()+ const target = join(at.downloads, 'chart.png')+ writeFileSync(target, 'old')+ const { contents, save } = saver(at, async () => target)const download = item()- save(ev, download, contents)- assert.equal(ev.prevented, true)- assert.equal(download.path, undefined)+ save(event(), download, contents)+ download.finish('new')+ await until(() => readFileSync(target, 'utf8') === 'new')+ assert.equal(readFileSync(target, 'utf8'), 'new')})-test('a download from another contents passes through', () => {- let asked = false- const save = downloadSaver({- window: { webContents: {} },- dialog: { showSaveDialogSync: () => { asked = true; return '/picked' } },- getPath,- })- const ev = event()- const download = item()- save(ev, download, { other: true })- assert.equal(asked, false)- assert.equal(download.path, undefined)- assert.equal(ev.prevented, false)+test('a server name cannot reach outside the staging folder', () => {+ const at = place()+ const { contents, save } = saver(at, () => new Promise(() => {}))+ const download = item('../../evil.txt')+ save(event(), download, contents)+ assert.equal(dirname(dirname(download.path)), at.staging)})-test('the window is asked for at the moment of the download, because the app may build a new one', () => {+test('a free name counts up past the taken ones', () => {+ const at = place()+ writeFileSync(join(at.downloads, 'a.txt'), '')+ writeFileSync(join(at.downloads, 'a (2).txt'), '')+ assert.equal(freePath(at.downloads, 'a.txt'), join(at.downloads, 'a (3).txt'))+ assert.equal(freePath(at.downloads, 'b'), join(at.downloads, 'b'))+})++test('the downloads folder is looked up for each download; a missing one falls back to home', () => {+ const at = place()+ const asked = []+ const folders = []const contents = {}- const calls = []- let window = { webContents: {} }const save = downloadSaver({- window: () => window,- dialog: { showSaveDialogSync: (win) => { calls.push(win); return '/picked/chart.png' } },- getPath,+ window: { webContents: contents }, ask: (_name, folder) => { folders.push(folder); return new Promise(() => {}) },+ staging: () => at.staging, homedir: () => '/os-home', log: { warn: () => {} },+ getPath: (name) => { asked.push(name); if (name === 'downloads') throw new Error('no downloads'); return at.home },})- // A new window took the place of the old one.- window = { webContents: contents }+ assert.deepEqual(asked, [])+ save(event(), item(), contents)save(event(), item(), contents)- assert.equal(calls.length, 1)- assert.equal(calls[0], window, 'the dialog belongs to the current window')+ assert.deepEqual(asked, ['downloads', 'home', 'downloads', 'home'])+ assert.deepEqual(folders, [at.home, at.home])})-test('a download without a window passes through', () => {+test('a download from another contents, or without a window, passes through', () => {+ const at = place()let asked = false- const save = downloadSaver({- window: () => undefined,- dialog: { showSaveDialogSync: () => { asked = true; return '/picked' } },- getPath,- })+ const ask = () => { asked = true; return Promise.resolve(null) }+ const other = saver(at, ask)const ev = event()const download = item()- save(ev, download, { webContents: {} })+ other.save(ev, download, { other: true })+ const none = downloadSaver({ window: () => undefined, ask, staging: () => at.staging, getPath: () => at.home })+ none(ev, download, {})assert.equal(asked, false)assert.equal(download.path, undefined)assert.equal(ev.prevented, false)})++test('the window is asked for at the moment of the download, because the app may build a new one', () => {+ const at = place()+ const contents = {}+ let asked = 0+ let window = { webContents: {} }+ const save = downloadSaver({ window: () => window, ask: () => { asked += 1; return new Promise(() => {}) }, staging: () => at.staging, getPath: () => at.downloads })+ window = { webContents: contents }+ save(event(), item(), contents)+ assert.equal(asked, 1)+})diff --git a/app/test/helpers/app-harness.mjs b/app/test/helpers/app-harness.mjsindex 8730d9f9..47f340fe 100644--- a/app/test/helpers/app-harness.mjs+++ b/app/test/helpers/app-harness.mjs@@ -101,16 +101,17 @@ export const messageBoxes = () => state.dialogs.filter(options => 'message' in o/*** A later start whose drive runs low, and its place line's 〔换个位置…〕 to `to`, answered with- * 〔移动并重启〕: the start window becomes the move's.+ * 〔移动并重启〕: the start window becomes the move's. `picked` runs once the move card is up.* @returns {Promise<{ home: string, workspace: string }>}*/-export const moveFromStart = async (to, { before = () => {} } = {}) => {+export const moveFromStart = async (to, { before = () => {}, picked = () => {} } = {}) => {const places = await startApp({ saved: { freeAtStart: Number.MAX_SAFE_INTEGER } })before(places)await waitFor(() => startState()?.place !== undefined, 'show the place line')state.openAnswer = { canceled: false, filePaths: [to] }await startAct('pick', 'changePlace')await waitFor(() => startState().card?.kind === 'move', 'ask about the move')+ picked()await startAct('answer', 'move')await waitFor(() => startWindows()[0].url.endsWith('?start=moving'), 'turn the start window into the move\'s')return placesdiff --git a/app/test/helpers/fake-electron.mjs b/app/test/helpers/fake-electron.mjsindex 198d36ea..d41772bf 100644--- a/app/test/helpers/fake-electron.mjs+++ b/app/test/helpers/fake-electron.mjs@@ -23,6 +23,7 @@ export const state = {windows: [],menus: [],dialogs: [],+ pickers: [],quits: 0,relaunches: [],exits: [],@@ -104,6 +105,28 @@ export class FakeWindow extends EventEmitter {}}+// The page's side of the app's picker (preload.cjs showPicker): it shows, then answers with+// state.openAnswer, the shape of the system picker's answer that the tests set.+function answerPicker(contents, request) {+ state.pickers.push(request)+ setImmediate(async () => {+ const event = { sender: contents, senderFrame: contents.mainFrame }+ state.ipc.get('ds-bot:app-picker-shown')(event, request.id)+ const answer = typeof state.openAnswer === 'function' ? state.openAnswer(request) : (state.openAnswer ?? { canceled: true, filePaths: [] })+ if (answer.canceled || answer.filePaths[0] === undefined) {+ state.ipc.get('ds-bot:app-picker-cancel')(event, request.id)+ return+ }+ // The user makes a folder that is not there yet with 〔新建文件夹〕, then chooses it.+ if (request.mode === 'folder') {+ try { mkdirSync(answer.filePaths[0], { recursive: true }) } catch {}+ }+ const chosen = await state.ipc.get('ds-bot:app-picker-choose')(event, request.id, answer.filePaths[0])+ // A path that the picker refuses leaves it open; the user then cancels.+ if (chosen?.error !== undefined) state.ipc.get('ds-bot:app-picker-cancel')(event, request.id)+ })+}+class FakeWebContents extends EventEmitter {constructor(win) {super()@@ -115,7 +138,10 @@ class FakeWebContents extends EventEmitter {this.isLoading = () => falsethis.getTitle = () => 'DeepSeek Bot'this.sent = []- this.send = (...args) => { this.sent.push(args) }+ this.send = (...args) => {+ this.sent.push(args)+ if (args[0] === 'ds-bot:app-picker') answerPicker(this, args[1])+ }this.setWindowOpenHandler = () => {}this.insertCSS = async () => {}this.toggleDevTools = () => {}diff --git a/app/test/main-low-space.test.mjs b/app/test/main-low-space.test.mjsindex bd282aa8..3e3e6722 100644--- a/app/test/main-low-space.test.mjs+++ b/app/test/main-low-space.test.mjs@@ -5,7 +5,7 @@// data is copied and the app starts again on the new folder. The Electron parts are test// doubles: no display, no DSH, no data of the user.import assert from 'node:assert/strict'-import { existsSync, mkdtempSync, readFileSync } from 'node:fs'+import { existsSync, mkdtempSync, readFileSync, readdirSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { test } from 'node:test'@@ -14,6 +14,9 @@ import { HostProcess, state as hostState } from './helpers/fake-host-process.mjsimport { startApp, startWindows, waitFor, window } from './helpers/app-harness.mjs'import { installHooks } from './helpers/register.mjs'+// The user makes the folder in the picker first, so a copy shows as what is in it.+const copied = path => existsSync(path) && readdirSync(path).length > 0+await installHooks()test('a later start on a drive that runs low shows the place line, and its button moves the data on cards', async () => {@@ -68,7 +71,7 @@ test('a later start on a drive that runs low shows the place line, and its buttoconst copiedAtStop = []const stop = HostProcess.prototype.stopHostProcess.prototype.stop = async function (...args) {- copiedAtStop.push(existsSync(to))+ copiedAtStop.push(copied(to))return stop.apply(this, args)}@@ -79,7 +82,7 @@ test('a later start on a drive that runs low shows the place line, and its buttoawait waitFor(() => start.url.endsWith('?start=moving'), 'turn the start window into the move\'s')await waitFor(() => state.relaunches.length === 1, 'start again on the new folder')assert.equal(copiedAtStop[0], false, 'the Host stopped before the copy')- assert.ok(existsSync(to), 'the data was copied')+ assert.ok(copied(to), 'the data was copied')const saved = JSON.parse(readFileSync(join(paths.userData, 'locations.json'), 'utf8'))assert.equal(saved.dataDir, to)assert.equal(saved.workspace, workspace)diff --git a/app/test/main-move-failed.test.mjs b/app/test/main-move-failed.test.mjsindex 2f23b93a..91734d1e 100644--- a/app/test/main-move-failed.test.mjs+++ b/app/test/main-move-failed.test.mjs@@ -2,7 +2,7 @@// 〔重试〕 copies again, 〔用原来的位置启动〕 starts again on the old folder (start-window §5). The// Electron parts are test doubles: no display, no DSH, no data of the user.import assert from 'node:assert/strict'-import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { test } from 'node:test'@@ -13,11 +13,16 @@ import { installHooks } from './helpers/register.mjs'await installHooks()test('a failed copy asks on a card whether to copy again or start where the data was', async () => {- // A folder whose parent is a file passes the checks, but no copy can go there.+ // The picked folder's parent turns into a file before the answer: the folder passes the+ // checks again, but no copy can go there.const parent = join(mkdtempSync(join(tmpdir(), 'ds-bot-move-')), 'a-file')- writeFileSync(parent, '')const to = join(parent, 'data')- const { home } = await moveFromStart(to)+ const { home } = await moveFromStart(to, {+ picked: () => {+ rmSync(parent, { recursive: true, force: true })+ writeFileSync(parent, '')+ },+ })const failures = () => startWindows()[0].webContents.sent.filter(([channel, snapshot]) => channel === 'ds-bot:start-state' && snapshot.card?.kind === 'moveFailed' && snapshot.view === 'card').lengthconst shown = () => startWindows()[0].webContents.sent.filter(([channel]) => channel === 'ds-bot:start-state').lengthawait waitFor(() => startState().card?.kind === 'moveFailed', 'say that the copy failed')diff --git a/app/test/main-move-in-use.test.mjs b/app/test/main-move-in-use.test.mjsindex 5b401fff..33acb000 100644--- a/app/test/main-move-in-use.test.mjs+++ b/app/test/main-move-in-use.test.mjs@@ -2,7 +2,7 @@// message box, and goes on by itself once that DSH is closed (start-window §5). The Electron// parts are test doubles: no display, no DSH, no data of the user.import assert from 'node:assert/strict'-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'import { hostname, tmpdir } from 'node:os'import { join } from 'node:path'import { test } from 'node:test'@@ -10,6 +10,9 @@ import { paths, state } from './helpers/fake-electron.mjs'import { messageBoxes, moveFromStart, startState, waitFor } from './helpers/app-harness.mjs'import { installHooks } from './helpers/register.mjs'+// The user makes the folder in the picker first, so a copy shows as what is in it.+const copied = path => existsSync(path) && readdirSync(path).length > 0+await installHooks()test('a move waits on a card while another DSH uses the data, and goes on once it is closed', async () => {@@ -24,12 +27,12 @@ test('a move waits on a card while another DSH uses the data, and goes on once iawait waitFor(() => startState().card?.kind === 'moveFailed', 'say that another DSH uses the data')assert.equal(startState().start, 'moving')assert.deepEqual(startState().card, { kind: 'moveFailed', dataDir: home, why: 'inUse' })- assert.equal(existsSync(to), false, 'nothing is copied meanwhile')+ assert.equal(copied(to), false, 'nothing is copied meanwhile')assert.equal(state.relaunches.length, 0)rmSync(lock(home))await waitFor(() => state.relaunches.length === 1, 'go on with the move once the data is free')- assert.ok(existsSync(to), 'the data was copied')+ assert.ok(copied(to), 'the data was copied')assert.equal(JSON.parse(readFileSync(join(paths.userData, 'locations.json'), 'utf8')).dataDir, to)assert.deepEqual(messageBoxes(), [], 'no message box on the way')})diff --git a/app/test/main-room-left.test.mjs b/app/test/main-room-left.test.mjsindex 05cf9e7b..f0e4424d 100644--- a/app/test/main-room-left.test.mjs+++ b/app/test/main-room-left.test.mjs@@ -4,7 +4,7 @@// copies and starts again on the new folder, which keeps its own. The Electron parts are test// doubles: no display, no DSH, no data of the user.import assert from 'node:assert/strict'-import { existsSync, mkdtempSync, readFileSync } from 'node:fs'+import { existsSync, mkdtempSync, readFileSync, readdirSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'import { test } from 'node:test'@@ -13,6 +13,9 @@ import { state as hostState } from './helpers/fake-host-process.mjs'import { answerCard, handOff, messageBoxes, startApp, startWindows, waitFor, window, windowCards } from './helpers/app-harness.mjs'import { installHooks } from './helpers/register.mjs'+// The user makes the folder in the picker first, so a copy shows as what is in it.+const copied = path => existsSync(path) && readdirSync(path).length > 0+await installHooks()const saved = () => JSON.parse(readFileSync(join(paths.userData, 'locations.json'), 'utf8'))@@ -41,12 +44,17 @@ test('a later start with room to spare shows no place line; Settings still movesstate.openAnswer = { canceled: false, filePaths: [to] }const moved = state.ipc.get('ds-bot:move-data')(event, workspace)await waitFor(() => windowCards(win).length === 1, 'ask about the move on a card')+ // The picker is the app's own, on the team window's page.+ const picker = win.webContents.sent.find(([channel]) => channel === 'ds-bot:app-picker')?.[1]+ assert.equal(picker?.mode, 'folder')+ assert.match(picker.title, /folder/u)+ assert.equal(picker.labels.chooseFolder, 'Choose this folder')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.ok(copied(to), 'the data was copied')assert.equal(saved().dataDir, to)assert.ok(saved().freeAtStart > 1, 'the new folder keeps its own free space')})diff --git a/app/test/picker.test.mjs b/app/test/picker.test.mjsnew file mode 100644index 00000000..7974ce4b--- /dev/null+++ b/app/test/picker.test.mjs@@ -0,0 +1,169 @@+// The app's own picker in place of the system's: what main lists and checks (folder-picker.mjs),+// and the IPC that only the page showing a picker may use (picker-host.mjs). Temp folders only.+import assert from 'node:assert/strict'+import { EventEmitter } from 'node:events'+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join, parse } from 'node:path'+import { after, test } from 'node:test'+import { crumbs, list, makeFolder, nameOk, roots, saveTarget, startIn, typed } from '../src/folder-picker.mjs'+import { PICKER_IPC, Pickers } from '../src/picker-host.mjs'++const top = mkdtempSync(join(tmpdir(), 'ds-bot-picker-'))+after(() => { rmSync(top, { recursive: true, force: true }) })+const folder = (...parts) => { const path = join(top, ...parts); mkdirSync(path, { recursive: true }); return path }+const file = (path, text = '') => { writeFileSync(path, text); return path }++test('a folder lists its folders first, each sorted as people read numbers, and hides hidden ones', async () => {+ const at = folder('sorted')+ for (const name of ['b', 'a10', 'a2', '.git', '$Recycle.Bin']) folder('sorted', name)+ file(join(at, 'z.txt'))+ file(join(at, 'c.json'))+ file(join(at, '.env'))+ const folders = await list(at)+ assert.deepEqual(folders.entries.map(entry => entry.name), ['a2', 'a10', 'b'], 'folders only, in reading order')+ assert.equal(folders.path, at)+ assert.equal(folders.parent, join(top))+ const all = await list(at, { files: true })+ assert.deepEqual(all.entries.map(entry => `${entry.name}${entry.dir ? '/' : ''}`), ['a2/', 'a10/', 'b/', 'c.json', 'z.txt'])+ const json = await list(at, { files: true, extensions: ['JSON'] })+ assert.deepEqual(json.entries.filter(entry => !entry.dir).map(entry => entry.name), ['c.json'])+})++test('the breadcrumb runs from the root down to the folder', () => {+ const path = join(top, 'one', 'two')+ const steps = crumbs(path)+ assert.equal(steps[0].path, parse(path).root)+ assert.deepEqual(steps.slice(-2).map(step => step.name), ['one', 'two'])+ assert.equal(steps.at(-1).path, path)+})++test('a folder that is gone, a file and a missing drive are answers, not throws', async () => {+ assert.equal((await list(join(top, 'nowhere'))).error, 'missing')+ assert.equal((await list(file(join(folder('plain'), 'note.txt')))).error, 'notFolder')+ if (process.platform === 'win32') {+ // A letter that no machine of the tests has: the drive is gone, not the folder.+ const free = [...'QRSTUVWXYZ'].map(letter => `${letter}:\\`).reverse()+ const { drives } = await roots({ getPath: () => top, platform: 'win32' })+ const missing = free.find(path => !drives.some(drive => drive.path === path))+ assert.equal((await list(join(missing, 'data'))).error, 'drive')+ }+})++test('a Windows long path lists like any other', { skip: process.platform !== 'win32' }, async () => {+ const deep = join(top, ...Array.from({ length: 14 }, (_value, index) => `a-rather-long-folder-name-${String(index)}`))+ mkdirSync(deep, { recursive: true })+ assert.ok(deep.length > 260)+ file(join(deep, 'inside.txt'))+ const listing = await list(deep, { files: true })+ assert.equal(listing.error, undefined)+ assert.deepEqual(listing.entries.map(entry => entry.name), ['inside.txt'])+})++test('a new folder is made once, and a bad or taken name says why', async () => {+ const at = folder('fresh')+ const made = await makeFolder(at, 'Reports')+ assert.equal(made.path, join(at, 'Reports'))+ assert.deepEqual(await makeFolder(at, 'Reports'), { error: 'exists' })+ assert.deepEqual(await makeFolder(at, ' '), { error: 'name' })+ assert.deepEqual(await makeFolder(at, 'a/b'), { error: 'name' })+ assert.deepEqual(await makeFolder(join(at, 'gone', 'deeper'), 'x'), { error: 'missing' })+})++test('Windows names keep to what Windows allows', () => {+ for (const bad of ['con', 'NUL.txt', 'a:b', 'what?', 'ends.', 'ends ', 'a\\b']) assert.equal(nameOk(bad, 'win32'), false, bad)+ for (const good of ['Reports', 'chart (2).png', '数据']) assert.equal(nameOk(good, 'win32'), true, good)+ assert.equal(nameOk('con', 'linux'), true)+})++test('a save into a taken name asks first; a folder of that name is no file', async () => {+ const at = folder('save')+ assert.deepEqual(await saveTarget(at, 'chart.png'), { path: join(at, 'chart.png') })+ file(join(at, 'chart.png'), 'old')+ assert.deepEqual(await saveTarget(at, 'chart.png'), { path: join(at, 'chart.png'), exists: true })+ folder('save', 'report')+ assert.deepEqual(await saveTarget(at, 'report'), { error: 'isFolder' })+ assert.deepEqual(await saveTarget(join(at, 'gone'), 'chart.png'), { error: 'missing' })+})++test('a typed path: ~ is home, a relative one starts where the picker is', () => {+ assert.equal(typed('~', top, '/home/me'), join('/home/me'))+ assert.equal(typed(' "sub" ', top, '/home/me'), join(top, 'sub'))+ assert.equal(typed(top, '/elsewhere', '/home/me'), top)+})++test('a picker opens in the nearest folder that exists', async () => {+ const at = folder('start')+ assert.equal(await startIn(join(at, 'not', 'yet')), at)+ assert.equal(await startIn(undefined, at), at)+})++// The IPC: the page that shows the picker lists, makes folders and answers; nobody else.+function host() {+ const handlers = new Map()+ const ipcMain = { handle: (channel, run) => { handlers.set(channel, run) }, on: (channel, run) => { handlers.set(channel, run) } }+ const pickers = new Pickers({ ipcMain, getPath: () => top, shownMs: 50 })+ const page = Object.assign(new EventEmitter(), { sent: [], isDestroyed: () => false, isLoading: () => false })+ page.send = (...args) => { page.sent.push(args) }+ const as = sender => ({ sender })+ const call = (channel, sender, ...args) => handlers.get(channel)(as(sender), ...args)+ return { pickers, page, call, request: () => page.sent.at(-1)[1] }+}+const tick = () => new Promise(resolve => setImmediate(resolve))+const opened = async (page) => { while (page.sent.length === 0) await tick() }++test('the page that shows a folder picker lists, makes a folder and chooses it', async () => {+ const { pickers, page, call, request } = host()+ const at = folder('ipc')+ const answer = pickers.ask(page, { mode: 'folder', title: 'Pick', start: join(at, 'missing'), labels: {} })+ await opened(page)+ const { id, start } = request()+ assert.equal(start, at, 'it opens where the folder would be')+ call(PICKER_IPC.shown, page, id)+ const made = await call(PICKER_IPC.folder, page, id, at, 'New')+ assert.equal(made.path, join(at, 'New'))+ const listing = await call(PICKER_IPC.list, page, id, 'New', at)+ assert.equal(listing.path, join(at, 'New'), 'a relative path starts at the folder shown')+ const roots = await call(PICKER_IPC.roots, page, id)+ assert.ok(Array.isArray(roots.drives) && roots.drives.length > 0)+ assert.deepEqual(await call(PICKER_IPC.choose, page, id, file(join(at, 'f.txt'))), { error: 'notFolder' })+ assert.deepEqual(await call(PICKER_IPC.choose, page, id, made.path), { path: made.path })+ assert.equal(await answer, made.path)+ assert.equal(await call(PICKER_IPC.list, page, id, at), undefined, 'a closed picker lists nothing')+})++test('another page gets nothing from a picker it does not show', async () => {+ const { pickers, page, call, request } = host()+ const answer = pickers.ask(page, { mode: 'folder', title: 'Pick', start: top, labels: {} })+ await opened(page)+ const { id } = request()+ call(PICKER_IPC.shown, page, id)+ const other = new EventEmitter()+ assert.equal(await call(PICKER_IPC.list, other, id, top), undefined)+ assert.equal(await call(PICKER_IPC.folder, other, id, top, 'x'), undefined)+ assert.equal(await call(PICKER_IPC.choose, other, id, top), undefined)+ call(PICKER_IPC.cancel, page, id)+ assert.equal(await answer, null, 'a cancel is null')+})++test('a save picker asks before it replaces, and answers once replace is said', async () => {+ const { pickers, page, call, request } = host()+ const at = folder('clash')+ file(join(at, 'chart.png'), 'old')+ const answer = pickers.ask(page, { mode: 'save', title: 'Save', start: at, name: 'chart.png', labels: {} })+ await opened(page)+ const { id, name } = request()+ assert.equal(name, 'chart.png')+ call(PICKER_IPC.shown, page, id)+ assert.deepEqual(await call(PICKER_IPC.choose, page, id, at, { name: 'chart.png' }), { path: join(at, 'chart.png'), exists: true })+ assert.deepEqual(await call(PICKER_IPC.choose, page, id, at, { name: 'bad:name' }), process.platform === 'win32' ? { error: 'name' } : { path: join(at, 'bad:name') })+ if (process.platform === 'win32') assert.deepEqual(await call(PICKER_IPC.choose, page, id, at, { name: 'chart.png', replace: true }), { path: join(at, 'chart.png') })+ assert.equal(await answer, join(at, process.platform === 'win32' ? 'chart.png' : 'bad:name'))+})++test('a page that does not show the picker in time gets no answer to wait for', async () => {+ const { pickers, page } = host()+ assert.equal(await pickers.ask(page, { mode: 'folder', title: 'Pick', start: top, labels: {} }), undefined)+ const loading = Object.assign(new EventEmitter(), { isDestroyed: () => false, isLoading: () => true, send() {} })+ assert.equal(await pickers.ask(loading, { mode: 'folder', title: 'Pick', labels: {} }), undefined)+})diff --git a/app/test/start-page.test.mjs b/app/test/start-page.test.mjsindex 509fcd20..c2fb0be2 100644--- a/app/test/start-page.test.mjs+++ b/app/test/start-page.test.mjs@@ -162,7 +162,7 @@ test('a move that does not go through has one card with three variants', () => {})// docs/plans/2026-10-29-start-copy.md §2: the first part of a key says where the line is.-const LAYERS = ['voice', 'say', 'hint', 'card', 'reason', 'btn', 'note', 'foot', 'status', 'dialog']+const LAYERS = ['voice', 'say', 'hint', 'card', 'reason', 'btn', 'note', 'foot', 'status', 'dialog', 'picker']const layerOf = key => key.split('.')[0]// {name} and {name|one|many} (an English count) both name one placeholder.const PLACEHOLDER = /\{(\w+)(?:\|[^}]*)?\}/gu@@ -173,7 +173,7 @@ test('zh and en carry the same keys and the same placeholders', () => {for (const [key, zh] of Object.entries(TEXT.zh)) assert.equal(placeholders(TEXT.en[key]), placeholders(zh), `${key}: placeholders differ`)})-test('every text key starts with one of the ten layers', () => {+test('every text key starts with one of the eleven layers', () => {for (const key of Object.keys(TEXT.zh)) assert.ok(LAYERS.includes(layerOf(key)), `${key}: unknown layer`)})@@ -189,10 +189,10 @@ test('the whale and the hint row have only the lines for when the user is needed// §2 and §4: a line that stands alone takes no full stop; card, reason, note and dialog text is// whole sentences.test('each layer ends its lines as its rule says', () => {- const BARE = new Set(['voice', 'say', 'hint', 'btn', 'foot', 'status'])+ const BARE = new Set(['voice', 'say', 'hint', 'btn', 'foot', 'status', 'picker'])// Not sentences: picker titles, progress lines and labels.const NOT_SENTENCES = new Set([- 'card.update.slow', 'card.update.downloading', 'dialog.pickRoot', 'dialog.pickMove',+ 'card.update.slow', 'card.update.downloading', 'dialog.pickRoot', 'dialog.pickMove', 'dialog.pickCookies', 'dialog.saveAs','card.copying.step1', 'card.copying.step2', 'card.copying.step3', 'card.copying.eta', 'card.copying.etaSoon','card.import.model', 'card.import.optRegen', 'card.import.optSkipWork',])@@ -212,7 +212,7 @@ test('each layer ends its lines as its rule says', () => {assert.match(zh, ends[0], `${key}: zh is not a whole sentence`)assert.match(en, ends[1], `${key}: en is not a whole sentence`)}- if (key === 'dialog.pickRoot' || key === 'dialog.pickMove') {+ if (['dialog.pickRoot', 'dialog.pickMove', 'dialog.pickCookies', 'dialog.saveAs'].includes(key)) {assert.doesNotMatch(zh, /。$/u, `${key}: a picker title ends with a full stop`)assert.doesNotMatch(en, /\.$/u, `${key}: a picker title ends with a full stop`)}@@ -244,7 +244,7 @@ test('a button that opens the system picker ends with …', () => {// docs/plans/2026-10-26-windows-onboarding.md, 用词: proper names and units only.test('the zh copy shows no English but the allowed names and units', () => {const NAMES = ['DS Bot', 'DSH Desktop', 'DSH Web']- const WORDS = new Set(['DeepSeek', 'Bot', 'API', 'Key', 'Harness', 'DSH', 'Agent', 'MCP', 'Windows', 'PowerShell', 'GitHub', 'SmartScreen', 'OneDrive', 'HTTP', 'SOCKS', 'KB', 'MB', 'GB'])+ const WORDS = new Set(['DeepSeek', 'Bot', 'API', 'Key', 'Harness', 'DSH', 'Agent', 'MCP', 'Windows', 'PowerShell', 'GitHub', 'SmartScreen', 'OneDrive', 'cookie', 'HTTP', 'SOCKS', 'KB', 'MB', 'GB'])const english = []for (const [key, value] of Object.entries(TEXT.zh)) {let rest = value.replace(PLACEHOLDER, ' ')