Skip to content

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

Turn off DSH's credential onboarding and harden import and downloads

AdamPlatin1230711c17225a9
diff --git a/app/README.md b/app/README.md
index eba9403c..be97b525 100644
--- a/app/README.md
+++ b/app/README.md
@@ -120,6 +120,7 @@ The script serves a releases list with one release of that version that has this
| `src/host-process.mjs` | Starts the Host in Electron's Node mode and owns its exit |
| `src/host.mjs` | The Host: boots the profile with `runProfile()` and reports the launch URL and the page injections; for the first-run check (`DS_BOT_CHECK`), the chats it cannot read |
| `src/profile.mjs` | The profiles: the app's own and the first-run check's, their bundles, and their creation and update |
+| `src/app-patch.mjs` | The app's own profile overlay (`profiles/app-onboarding.patch.yml`, passed through `patchFiles`): it turns off DSH Web's automatic credential step (`credentialOnboarding: false`), since models are set up in DS Bot's Models page and the Main Bot's key card |
| `src/session-check.mjs` | Which chats the pinned DSH refuses because a newer DSH wrote them |
| `src/first-run.mjs` | The first start's dialogs (the two folders and the offer to import) and the texts of the data move |
| `src/import.mjs` | The import of a Bot team from the user's DSH |
@@ -132,6 +133,7 @@ The script serves a releases list with one release of that version that has this
| `electron-builder.yml`, `build/` | The package and the installers: app identity, files, icons, the Windows installer, the macOS zip and the Linux AppImage and deb |
| `scripts/check-packed.mjs` | `npm run check-packed`: the check of a packaged app |
| `scripts/check-update.mjs` | The check of a packaged app's update from a feed folder (Windows, AppImage) or a mocked release (macOS, deb) |
+| `scripts/release-notes.mjs` | The release's `Download / 下载` table, `SHA256SUMS.txt` and the version-less package copies, run by the release workflow after every package is attached |
The Host installs plugins with the app's own pnpm (`node_modules/pnpm`).
diff --git a/app/src/app-patch.mjs b/app/src/app-patch.mjs
new file mode 100644
index 00000000..618bdf12
--- /dev/null
+++ b/app/src/app-patch.mjs
@@ -0,0 +1,29 @@
+// The app's own `--patch` overlay, written next to the profiles as search-patch.mjs does
+// (`<DSH_HOME>/profiles/app-onboarding.patch.yml`) and read by DSH only through `patchFiles`.
+// It turns off DSH Web's automatic credential step: the Bot team connects the model in its
+// own chat instead. `credentialOnboarding` is the documented switch of
+// @deepseek-ai/dsh-client-ui-settings-models.
+//
+// A patch replaces the targeted row's whole `config`, so this row is restated from the
+// pinned DSH whenever it changes. Overlays outrank the profile, and DSH refuses a settings
+// form write that an overlay overrides: the overlay holds no row the Settings page writes
+// (never `ui-settings-general`).
+import { dirname, join } from 'node:path'
+import { writeFileSync } from 'node:fs'
+import { stringify } from 'yaml'
+
+export const APP_PATCH_NAME = 'app-onboarding.patch.yml'
+export const APP_PATCH_ROWS = [
+ { id: 'ui-settings-models', name: '@deepseek-ai/dsh-client-ui-settings-models', config: { credentialOnboarding: false } },
+]
+
+/**
+ * Write the overlay for this launch; DSH stops when a `patchFiles` entry is missing.
+ * @param {import('@deepseek-ai/dsh-app-boot').Profile} profile
+ * @returns {string[]} its part of the `patchFiles` argument
+ */
+export function writeAppPatch(profile) {
+ const file = join(dirname(profile.dir), APP_PATCH_NAME)
+ writeFileSync(file, stringify(APP_PATCH_ROWS), 'utf8')
+ return [file]
+}
diff --git a/app/src/downloads.mjs b/app/src/downloads.mjs
index 094fdef6..df6d1716 100644
--- a/app/src/downloads.mjs
+++ b/app/src/downloads.mjs
@@ -1,13 +1,33 @@
// 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
// session's rules.
+import { homedir as osHomedir } from 'node:os'
import { join } from 'node:path'
-export function downloadSaver({ window, dialog, downloads }) {
+/**
+ * @param {{ window: any, dialog: any, getPath: (name: string) => string, homedir?: () => string }} options
+ * `getPath` is Electron's app.getPath, asked again for every download.
+ */
+export function downloadSaver({ window, dialog, getPath, homedir = osHomedir }) {
return (event, item, source) => {
if (source !== window.webContents) return
- const file = dialog.showSaveDialogSync(window, { defaultPath: join(downloads, item.getFilename()) })
+ const folder = startFolder(getPath, homedir)
+ const name = item.getFilename()
+ const file = dialog.showSaveDialogSync(window, { defaultPath: folder === undefined ? name : join(folder, name) })
if (file === undefined) event.preventDefault()
else item.setSavePath(file)
}
}
+
+// 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.
+function startFolder(getPath, homedir) {
+ for (const find of [() => getPath('downloads'), () => getPath('home'), homedir]) {
+ try {
+ const folder = find()
+ if (folder) return folder
+ } catch {}
+ }
+ return undefined
+}
diff --git a/app/src/host.mjs b/app/src/host.mjs
index d8608060..a1ae5bb8 100644
--- a/app/src/host.mjs
+++ b/app/src/host.mjs
@@ -6,6 +6,7 @@ import { readFileSync } from 'node:fs'
import { inspect } from 'node:util'
import { loadLayeredEnv, reportSkippedBundles } from '@deepseek-ai/dsh-app-boot'
import { runProfile } from '@deepseek-ai/dsh/profile-boot'
+import { writeAppPatch } from './app-patch.mjs'
import { CHECK_PROFILE, INSTALL_ANCHOR, loadAppProfile, loadCheckProfile, PROFILE } from './profile.mjs'
import { reconcileSearchSelector } from './search-patch.mjs'
import { unreadableSessions } from './session-check.mjs'
@@ -26,7 +27,7 @@ async function main() {
environment: loadLayeredEnv('dsh'),
profile: check === undefined ? PROFILE : CHECK_PROFILE,
resolvedProfile: { profile, installAnchor: INSTALL_ANCHOR },
- patchFiles: check === undefined ? reconcileSearchSelector(profile) : [],
+ patchFiles: check === undefined ? [...writeAppPatch(profile), ...reconcileSearchSelector(profile)] : [],
args: ['--no-open', '--port', process.env.DS_BOT_PORT || '0'],
...(pnpm === undefined ? {} : {
packageManager: { command: process.execPath, args: ['--expose-internals', pnpm], env: { ELECTRON_RUN_AS_NODE: '1' } },
diff --git a/app/src/import.mjs b/app/src/import.mjs
index d7f276f0..f13bef55 100644
--- a/app/src/import.mjs
+++ b/app/src/import.mjs
@@ -69,22 +69,31 @@ function modelProfiles(from) {
})
}
-/** Whether a running DSH holds the team, as ds-bot's own lock tells (src/host/home-lock.js). */
-export function teamInUse(from, { host = hostname(), now = Date.now() } = {}) {
+/**
+ * Whether a running DSH holds the team, by the rule of ds-bot's own lock (src/host/home-lock.js):
+ * the holder bumps the lock's mtime, so a stale lock is a holder that is gone, even when its pid
+ * now belongs to another process.
+ */
+export function teamInUse(from, { host = hostname(), now = Date.now(), isAlive = pidAlive } = {}) {
const path = join(from, 'bot', 'state.lock')
- if (!existsSync(path)) return false
- const fresh = now - statSync(path).mtimeMs < LOCK_STALE_MS
+ const lock = statSync(path, { throwIfNoEntry: false })
+ if (lock === undefined || now - lock.mtimeMs >= LOCK_STALE_MS) return false
let holder
try {
holder = JSON.parse(readFileSync(path, 'utf8'))
} catch {
- return fresh
+ // Being written right now.
+ return true
}
- if (holder?.host !== host) return fresh
+ return holder?.host !== host || isAlive(holder.pid)
+}
+
+function pidAlive(pid) {
try {
- process.kill(holder.pid, 0)
+ process.kill(pid, 0)
return true
} catch (error) {
+ // EPERM: the process exists but belongs to someone else.
return error?.code === 'EPERM'
}
}
@@ -130,12 +139,40 @@ export function newerSessions(from, team) {
.some(name => (logVersion(name) ?? 0) > sessionFormatCatalog.currentVersion)).map(({ id }) => id)
}
+// The Host's first start on the data location writes a .credentials.yaml of its own: the browser
+// session grant of the connection plugin, under client-connection/. A file with nothing else in
+// it holds no key of the user's.
+async function onlyHostRecords(file) {
+ let document
+ try {
+ document = parse(await readFile(file, 'utf8')) ?? {}
+ } catch {
+ // A file that does not read as DSH's is the user's to fix, not ours to replace.
+ return false
+ }
+ if (typeof document !== 'object' || Array.isArray(document)) return false
+ const { version, refs, records, ...other } = document
+ return (version === undefined || version === 1) && Object.keys(other).length === 0
+ && Object.keys(refs ?? {}).length === 0
+ && Object.keys(records ?? {}).every(key => key.startsWith('client-connection/'))
+}
+
+// A key file the data location has already is the user's own, saved there since, and stays;
+// a .credentials.yaml that only the Host wrote is not.
+// Returns 'copied', 'kept', or undefined when the old home has none.
async function copyKey(from, to, name) {
const source = join(from, name)
- if (!existsSync(source)) return false
- await cp(source, join(to, name))
- if (process.platform !== 'win32') await chmod(join(to, name), 0o600)
- return true
+ if (!existsSync(source)) return undefined
+ const target = join(to, name)
+ const replace = name === '.credentials.yaml' && existsSync(target) && await onlyHostRecords(target)
+ try {
+ await cp(source, target, { force: replace, errorOnExist: !replace })
+ } catch (error) {
+ if (error?.code === 'ERR_FS_CP_EEXIST') return 'kept'
+ throw error
+ }
+ if (process.platform !== 'win32') await chmod(target, 0o600)
+ return 'copied'
}
async function writeModelRows(to, rows) {
@@ -150,10 +187,11 @@ async function writeModelRows(to, rows) {
/**
* Copy the team of `from` into the data location `to`, which the Host has started on once,
* so that DSH does not take the copied Sessions' folders for its own projects. The old team's
- * workspace files go into `workspace`, without replacing a file that is there.
+ * workspace files go into `workspace`, without replacing a file that is there, and the key
+ * files only where the data location has none of the user's own.
* Everything but the keys, the model settings and the workspace files is put together in a
- * folder beside the data and moved in at the end; a copy that stopped or failed leaves that
- * folder behind, and the next copy removes it.
+ * folder beside the data and moved in at the end. A copy that stops or fails removes that
+ * folder; one that was killed leaves it behind, and the next copy removes it.
* @param {{ from: string, to: string, workspace: string, profile?: string, dsh?: string, signal?: AbortSignal }} options
*/
export async function importTeam({ from, to, workspace, profile, dsh, signal }) {
@@ -165,6 +203,14 @@ export async function importTeam({ from, to, workspace, profile, dsh, signal })
await rm(join(to, name), { recursive: true, force: true })
}
const stage = join(to, `.import-${String(Date.now())}`)
+ try {
+ return await copyThroughStage({ found, from, to, workspace, profile, dsh, signal, stage })
+ } finally {
+ await rm(stage, { recursive: true, force: true, maxRetries: 5 }).catch((error) => { console.error(error) })
+ }
+}
+
+async function copyThroughStage({ found, from, to, workspace, profile, dsh, signal, stage }) {
const oldBot = join(from, 'bot')
signal?.throwIfAborted()
await cp(oldBot, join(stage, 'bot'), { recursive: true, filter: path => !LEFT_BEHIND.has(relative(oldBot, path).split(/[\\/]/u)[0]) })
@@ -189,7 +235,13 @@ export async function importTeam({ from, to, workspace, profile, dsh, signal })
}
signal?.throwIfAborted()
const keys = []
- for (const name of ['.credentials.yaml', '.env']) if (await copyKey(from, to, name)) keys.push(name)
+ const keptKeys = []
+ for (const name of ['.credentials.yaml', '.env']) {
+ const done = await copyKey(from, to, name)
+ if (done === 'copied') keys.push(name)
+ if (done === 'kept') keptKeys.push(name)
+ }
+ if (keptKeys.length > 0) console.warn(`DeepSeek Bot: the import kept the ${keptKeys.join(' and ')} that the data location has`)
const rows = found.profiles.find(entry => entry.name === profile)?.rows ?? []
if (rows.length > 0) await writeModelRows(to, rows)
@@ -205,13 +257,12 @@ export async function importTeam({ from, to, workspace, profile, dsh, signal })
const summary = {
from, at: new Date().toISOString(), ...(dsh ? { dsh } : {}),
bots: found.bots, rooms: found.rooms, sessions: sessions.length, missingSessions: missing,
- keys, modelSettings: rows.length > 0 ? profile : null,
+ keys, keptKeys, modelSettings: rows.length > 0 ? profile : null,
}
signal?.throwIfAborted()
await writeFile(join(stage, 'bot', 'imported.json'), `${JSON.stringify(summary, null, 2)}\n`)
// Until this rename the data has no Bot team, so a copy that stopped can run again.
await rm(join(to, 'bot'), { recursive: true, force: true })
await rename(join(stage, 'bot'), join(to, 'bot'))
- await rm(stage, { recursive: true, force: true })
return summary
}
diff --git a/app/src/main.mjs b/app/src/main.mjs
index 6691ade5..607ea91b 100644
--- a/app/src/main.mjs
+++ b/app/src/main.mjs
@@ -519,7 +519,7 @@ function createWindow() {
mainWindow.on('closed', () => { mainWindow = undefined })
browserGuests.bind(mainWindow)
const contents = mainWindow.webContents
- contents.session.on('will-download', downloadSaver({ window: mainWindow, dialog, downloads: app.getPath('downloads') }))
+ contents.session.on('will-download', downloadSaver({ window: mainWindow, dialog, getPath: name => app.getPath(name) }))
if (win32) {
// Fullscreen hides the caption buttons, and the page drops its band meanwhile. A reload
// registers the page's listener again, so the state goes out after every load too.
@@ -566,8 +566,9 @@ function setMenu() {
Menu.setApplicationMenu(Menu.buildFromTemplate([{ role: 'appMenu' }, { role: 'fileMenu' }, { role: 'editMenu' }, { role: 'viewMenu' }, { role: 'windowMenu' }]))
}
+// Also after a failed start: a second launch is how the user finds the window again.
function focusWindow() {
- if (mainWindow === undefined || failed) return
+ if (mainWindow === undefined) return
if (mainWindow.isMinimized()) mainWindow.restore()
mainWindow.show()
mainWindow.focus()
diff --git a/app/test/app-patch.test.mjs b/app/test/app-patch.test.mjs
new file mode 100644
index 00000000..e7bbb2d9
--- /dev/null
+++ b/app/test/app-patch.test.mjs
@@ -0,0 +1,76 @@
+import assert from 'node:assert/strict'
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { after, before, describe, test } from 'node:test'
+import { composeEntries } from '@deepseek-ai/dsh-app-boot'
+import { parse } from 'yaml'
+import { APP_PATCH_NAME, APP_PATCH_ROWS, writeAppPatch } from '../src/app-patch.mjs'
+import { loadAppProfile } from '../src/profile.mjs'
+
+// Every row of an entry list, with the rows inside groups.
+function rows(entries) {
+ return entries.flatMap((entry) => [
+ entry,
+ ...rows(Array.isArray(entry.config) ? entry.config : []),
+ ...rows(Array.isArray(entry.config?.plugins) ? entry.config.plugins : []),
+ ])
+}
+
+describe('writeAppPatch', () => {
+ let home
+ before(() => { home = mkdtempSync(join(tmpdir(), 'ds-bot-app-patch-')) })
+ after(() => { rmSync(home, { recursive: true, force: true }) })
+
+ test('writes one row that turns off the automatic credential step, next to the profiles', () => {
+ const dir = join(home, 'profiles', 'ds-bot')
+ mkdirSync(dir, { recursive: true })
+ const [file, ...more] = writeAppPatch({ dir, patchPath: join(dir, 'cordis.patch.yml') })
+ assert.deepEqual(more, [])
+ // Outside the profile directory itself, so DSH only reads it through patchFiles.
+ assert.equal(file, join(home, 'profiles', APP_PATCH_NAME))
+ assert.deepEqual(parse(readFileSync(file, 'utf8')), [
+ { id: 'ui-settings-models', name: '@deepseek-ai/dsh-client-ui-settings-models', config: { credentialOnboarding: false } },
+ ])
+ })
+
+ test('writes the file again on every launch and never carries a Settings page row', () => {
+ const dir = join(home, 'profiles', 'ds-bot')
+ const file = join(home, 'profiles', APP_PATCH_NAME)
+ writeFileSync(file, '- id: ui-settings-general\n config:\n welcomeNoticeVersion: x\n')
+ writeAppPatch({ dir })
+ const written = parse(readFileSync(file, 'utf8'))
+ assert.deepEqual(written, APP_PATCH_ROWS)
+ assert.equal(written.some(row => row.id === 'ui-settings-general'), false)
+ })
+})
+
+describe('the overlay on the pinned DSH', () => {
+ let home
+ let profile
+ before(() => {
+ home = mkdtempSync(join(tmpdir(), 'ds-bot-app-patch-profile-'))
+ process.env.DSH_HOME = home
+ profile = loadAppProfile()
+ })
+ after(() => { rmSync(home, { recursive: true, force: true }) })
+
+ // A row DSH renamed would only log a warning, and a config key DSH added would be wiped.
+ test('targets a row the app profile mounts, whose whole config it restates', () => {
+ const entries = rows(composeEntries([...profile.layers.map(layer => layer.patches), profile.patches]))
+ const [patched] = APP_PATCH_ROWS
+ const row = entries.find(entry => entry.id === patched.id)
+ assert.ok(row, `${patched.id} is in the app profile`)
+ assert.equal(row.name, patched.name)
+ assert.notEqual(row.disabled, true)
+ assert.deepEqual(Object.keys(row.config ?? {}).filter(key => !(key in patched.config)), [])
+ })
+
+ test('sets credentialOnboarding to false once laid over the profile', () => {
+ const [file] = writeAppPatch(profile)
+ assert.equal(dirname(file), dirname(profile.dir))
+ const layers = [...profile.layers.map(layer => layer.patches), profile.patches, parse(readFileSync(file, 'utf8'))]
+ const row = rows(composeEntries(layers)).find(entry => entry.id === 'ui-settings-models')
+ assert.deepEqual(row.config, { credentialOnboarding: false })
+ })
+})
diff --git a/app/test/downloads.test.mjs b/app/test/downloads.test.mjs
index 909a0e35..6a082fbb 100644
--- a/app/test/downloads.test.mjs
+++ b/app/test/downloads.test.mjs
@@ -1,11 +1,24 @@
// 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.
import assert from 'node:assert/strict'
+import { join } from 'node:path'
import test from 'node:test'
import { downloadSaver } from '../src/downloads.mjs'
const item = () => ({ getFilename: () => 'chart.png', path: undefined, setSavePath(path) { this.path = path } })
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`) }
+
+// The folder the save dialog starts in when the main window downloads chart.png.
+function startPath({ getPath, homedir }) {
+ 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
+}
test('a download from the main window asks for a path and saves there', () => {
const contents = {}
@@ -14,7 +27,7 @@ test('a download from the main window asks for a path and saves there', () => {
const save = downloadSaver({
window,
dialog: { showSaveDialogSync: (win, options) => { calls.push({ win, options }); return '/picked/chart.png' } },
- downloads: '/downloads',
+ getPath,
})
const ev = event()
const download = item()
@@ -23,13 +36,34 @@ test('a download from the main window asks for a path and saves there', () => {
assert.equal(ev.prevented, false)
assert.equal(calls.length, 1)
assert.equal(calls[0].win, window)
- assert.match(calls[0].options.defaultPath, /chart\.png$/)
- assert.ok(calls[0].options.defaultPath.includes('downloads'), 'the dialog starts in the downloads folder')
+ assert.equal(calls[0].options.defaultPath, join('/downloads', 'chart.png'), 'the dialog starts in the downloads folder')
+})
+
+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('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('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 cancelled dialog drops the download', () => {
const contents = {}
- const save = downloadSaver({ window: { webContents: contents }, dialog: { showSaveDialogSync: () => undefined }, downloads: '/downloads' })
+ const save = downloadSaver({ window: { webContents: contents }, dialog: { showSaveDialogSync: () => undefined }, getPath })
const ev = event()
const download = item()
save(ev, download, contents)
@@ -42,7 +76,7 @@ test('a download from another contents passes through', () => {
const save = downloadSaver({
window: { webContents: {} },
dialog: { showSaveDialogSync: () => { asked = true; return '/picked' } },
- downloads: '/downloads',
+ getPath,
})
const ev = event()
const download = item()
diff --git a/app/test/import.test.mjs b/app/test/import.test.mjs
index 89682ad9..dea1210d 100644
--- a/app/test/import.test.mjs
+++ b/app/test/import.test.mjs
@@ -13,6 +13,8 @@ const write = (path, text) => {
writeFileSync(path, text)
}
const readJson = path => JSON.parse(readFileSync(path, 'utf8'))
+// The import's stage folders in a data location.
+const staged = to => readdirSync(to).filter(name => /^\.import-\d+$/u.test(name))
function treeHash(dir) {
const hash = createHash('sha256')
@@ -71,11 +73,19 @@ function oldHome(root) {
return from
}
+// What the Host's first start writes to the data location's .credentials.yaml: the connection
+// plugin's browser session grant, and nothing else.
+const HOST_CREDENTIALS = [
+ 'version: 1', 'records:', ' client-connection/browser-session:', ' kind: grant', ' payload:',
+ ' version: 1', ` secret: ${'A'.repeat(43)}`, '',
+].join('\n')
+
// The app's data location after the Host's first start, and the folder chosen for the Bots' files.
function newHome(root) {
const to = join(root, 'ds-bot')
write(join(to, 'bot', 'state.json'), JSON.stringify({ version: 1, mainBotIds: [], bots: {}, rooms: {} }))
- write(join(to, 'profiles', 'ds-bot', 'cordis.patch.yml'), '- id: llm-pi-ai\n config:\n providers: {}\n- id: webserver\n config:\n port: 0\n')
+ write(join(to, '.credentials.yaml'), HOST_CREDENTIALS)
+ write(join(to, 'profiles', 'ds-bot', 'cordis.patch.yml'), '- id: llm-pi-ai\n config:\n providers: {}\n- id: webserver\n config:\n port: 0\n- id: ui-settings-general\n config:\n welcomeNoticeVersion: seen\n')
const workspace = join(root, 'DeepSeek Bot')
write(join(workspace, 'kept.txt'), 'new kept')
return { to, workspace }
@@ -113,8 +123,10 @@ describe('importTeam', () => {
assert.equal(readFileSync(join(to, '.credentials.yaml'), 'utf8'), 'DEEPSEEK_API_KEY: fake\n')
assert.equal(readFileSync(join(to, '.env'), 'utf8'), 'X=1\n')
const patch = parse(readFileSync(join(to, 'profiles', 'ds-bot', 'cordis.patch.yml'), 'utf8'))
- assert.deepEqual(patch.map(row => row.id), ['webserver', 'llm-pi-ai', 'agent-default-model'])
- assert.deepEqual(patch[1].config.providers, { moonshotai: { apiKeyEnv: 'MOONSHOTAI_API_KEY' } })
+ // The data location's other rows stay, such as the Settings page's own.
+ assert.deepEqual(patch.map(row => row.id), ['webserver', 'ui-settings-general', 'llm-pi-ai', 'agent-default-model'])
+ assert.deepEqual(patch[1].config, { welcomeNoticeVersion: 'seen' })
+ assert.deepEqual(patch[2].config.providers, { moonshotai: { apiKeyEnv: 'MOONSHOTAI_API_KEY' } })
})
test('puts the old workspace files in the chosen folder without replacing one that is there', () => {
@@ -126,7 +138,7 @@ describe('importTeam', () => {
const record = readJson(join(to, 'bot', 'imported.json'))
assert.deepEqual({ ...record, at: undefined }, {
from, at: undefined, dsh: '0.2.0-rc.2', bots: 2, rooms: 1, sessions: 5, missingSessions: ['session-gone'],
- keys: ['.credentials.yaml', '.env'], modelSettings: 'desktop',
+ keys: ['.credentials.yaml', '.env'], keptKeys: [], modelSettings: 'desktop',
})
assert.deepEqual(readdirSync(to).filter(name => name.startsWith('.import-')), [])
assert.equal(treeHash(from), oldTree)
@@ -153,7 +165,7 @@ describe('a copy that stopped', () => {
assert.equal(summary.sessions, 5)
assert.deepEqual(Object.keys(readJson(join(to, 'bot', 'state.json')).bots), ['session-a', 'session-b'])
assert.equal(readFileSync(join(to, 'sessions', '--site--', 'session-b', 'session.v4.jsonl.zstd'), 'utf8'), 'session-b')
- assert.deepEqual(readdirSync(to).filter(name => /^\.import-\d+$/u.test(name)), [])
+ assert.deepEqual(staged(to), [])
})
test('a stopped copy leaves no Bot team', async () => {
@@ -161,6 +173,7 @@ describe('a copy that stopped', () => {
mkdirSync(to, { recursive: true })
await assert.rejects(importTeam({ from, to, workspace: join(root, 'stopped-files'), signal: AbortSignal.abort() }), { name: 'AbortError' })
assert.equal(existsSync(join(to, 'bot')), false)
+ assert.deepEqual(staged(to), [])
})
test('a quit during the move-in leaves no Bot team, and the next copy finishes', async () => {
@@ -177,11 +190,64 @@ describe('a copy that stopped', () => {
await assert.rejects(importTeam({ from, to, workspace, signal }), { name: 'AbortError' })
assert.equal(Object.keys(readJson(join(to, 'bot', 'state.json')).bots).length, 0)
assert.equal(existsSync(movedIn), true)
+ assert.deepEqual(staged(to), [])
const summary = await importTeam({ from, to, workspace })
assert.equal(summary.sessions, 5)
assert.deepEqual(Object.keys(readJson(join(to, 'bot', 'state.json')).bots), ['session-a', 'session-b'])
assert.equal(readFileSync(join(movedIn, 'session.v4.jsonl.zstd'), 'utf8'), 'session-a')
- assert.deepEqual(readdirSync(to).filter(name => /^\.import-\d+$/u.test(name)), [])
+ assert.deepEqual(staged(to), [])
+ })
+
+ test('a copy that failed part way removes what it staged and leaves no Bot team', async () => {
+ const { to } = newHome(join(root, 'failed'))
+ // The folder for the Bots' files is a file: the copy fails once the team is staged.
+ const workspace = join(root, 'failed', 'a-file')
+ write(workspace, 'not a folder')
+ await assert.rejects(importTeam({ from, to, workspace }))
+ assert.deepEqual(staged(to), [])
+ assert.equal(Object.keys(readJson(join(to, 'bot', 'state.json')).bots).length, 0)
+ })
+})
+
+describe('keys the data location has already', () => {
+ let root
+ before(() => { root = mkdtempSync(join(tmpdir(), 'ds-bot-app-keys-')) })
+ after(() => { rmSync(root, { recursive: true, force: true }) })
+
+ const importOver = async (name, credentials) => {
+ const from = oldHome(join(root, name))
+ const { to, workspace } = newHome(join(root, name))
+ write(join(to, '.credentials.yaml'), credentials)
+ return { to, summary: await importTeam({ from, to, workspace }) }
+ }
+
+ test('copies the old keys over the .credentials.yaml that only the Host\'s first start wrote', async () => {
+ const { to, summary } = await importOver('host', HOST_CREDENTIALS)
+ assert.equal(readFileSync(join(to, '.credentials.yaml'), 'utf8'), 'DEEPSEEK_API_KEY: fake\n')
+ assert.deepEqual(summary.keys, ['.credentials.yaml', '.env'])
+ assert.deepEqual(summary.keptKeys, [])
+ })
+
+ test('keeps a .credentials.yaml with a key saved since, copies the rest and reports which it kept', async () => {
+ const saved = `${HOST_CREDENTIALS}refs:\n DEEPSEEK_API_KEY: saved-since\n`
+ const { to, summary } = await importOver('saved', saved)
+ assert.equal(readFileSync(join(to, '.credentials.yaml'), 'utf8'), saved)
+ assert.equal(readFileSync(join(to, '.env'), 'utf8'), 'X=1\n')
+ assert.deepEqual(summary.keys, ['.env'])
+ assert.deepEqual(summary.keptKeys, ['.credentials.yaml'])
+ assert.deepEqual(readJson(join(to, 'bot', 'imported.json')).keptKeys, ['.credentials.yaml'])
+ })
+
+ test('keeps one with an account sign-in, in the old flat layout or that does not read as YAML', async () => {
+ for (const [name, text] of [
+ ['account', `${HOST_CREDENTIALS} deepseek-account-platform/default:\n kind: grant\n payload:\n token: saved-since\n`],
+ ['flat', 'DEEPSEEK_API_KEY: saved-since\n'],
+ ['broken', 'refs: [unclosed\n'],
+ ]) {
+ const { to, summary } = await importOver(name, text)
+ assert.equal(readFileSync(join(to, '.credentials.yaml'), 'utf8'), text, name)
+ assert.deepEqual(summary.keptKeys, ['.credentials.yaml'], name)
+ }
})
})
@@ -263,6 +329,23 @@ describe('finding the team', () => {
const old = new Date(Date.now() - 120_000)
utimesSync(lock, old, old)
assert.equal(teamInUse(from, { host: 'here' }), false)
+ write(lock, '{"pid": ')
+ assert.equal(teamInUse(from, { host: 'here' }), true, 'a lock being written')
+ rmSync(lock)
+ assert.equal(teamInUse(from, { host: 'here' }), false)
+ })
+
+ // #428: the pid of a holder that crashed long ago now belongs to another process.
+ test('does not take a stale lock on this machine for in use, even when its pid is alive', () => {
+ const lock = join(from, 'bot', 'state.lock')
+ write(lock, JSON.stringify({ pid: process.pid, host: 'here' }))
+ const at = statSync(lock).mtimeMs
+ assert.equal(teamInUse(from, { host: 'here', now: at + 59_000 }), true)
+ assert.equal(teamInUse(from, { host: 'here', now: at + 60_000 }), false)
+ assert.equal(teamInUse(from, { host: 'here', now: at + 59_000, isAlive: () => false }), false)
+ const asked = []
+ assert.equal(teamInUse(from, { host: 'here', now: at + 120_000, isAlive: (pid) => { asked.push(pid); return true } }), false)
+ assert.deepEqual(asked, [])
})
test('reads DSH_HOME as DSH does', () => {