Skip to content

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

Ask for the app's folders at its first start and import the user's team

Fei24114cffcfdaa2b7
diff --git a/app/README.md b/app/README.md
index 90b85a6c..203709c4 100644
--- a/app/README.md
+++ b/app/README.md
@@ -16,8 +16,15 @@ npm installs `ds-bot` from `../ds-bot` as a copy of its package files (`install-
| Variable | What it sets | Default |
|---|---|---|
-| `DS_BOT_HOME` | The data location: the `DSH_HOME` of the app | `~/.ds-bot` |
-| `DS_BOT_SHELL_DATA` | The app's own data (window, Chromium storage) | Electron's `userData` (Windows: `%APPDATA%\DeepSeek Bot`) |
+| `DS_BOT_HOME` | The data location: the `DSH_HOME` of the app. When it is set, the app asks nothing at its first start and imports nothing | The folder chosen at the first start |
+| `DS_BOT_WORKSPACE` | With `DS_BOT_HOME`: the folder for the files that Bots make | `bot/workspace` in the data location |
+| `DS_BOT_SHELL_DATA` | The app's own data (window, Chromium storage, `locations.json`) | Electron's `userData` (Windows: `%APPDATA%\DeepSeek Bot`) |
+
+## First start and import
+
+At its first start the app asks, in system dialogs, for the data location (`~/.ds-bot` by default) and the folder for the files that Bots make (`~/DeepSeek Bot`), and keeps the answer in `locations.json` in its own data. Neither folder may be inside the other or inside the user's DSH data.
+
+When the user's DSH (`DSH_HOME`, else `~/.dsh`) has a Bot team, the app offers to copy it (`src/import.mjs`). It only reads there. Before the copy it checks that no running DSH holds the team and that no chat is in a newer session format than the pinned DSH reads, and it starts the Host once on the new data location, so that DSH does not register the copied Sessions' folders as projects. The copy takes `bot/` (without its lock, turns in flight and workspace), every Session the team names, `attachments/`, `.credentials.yaml`, `.env`, the model rows of one profile's `cordis.patch.yml`, and the old team workspace's files, which go into the new folder without replacing a file there. `bot/imported.json` records it. At its next turn, each Bot and group moves on to a fresh part in the new folder.
The Host reads model settings and keys the way DSH does: environment variables such as `DEEPSEEK_API_KEY`, and `.env` and `.credentials.yaml` in the data location. DSH's settings in the window set up model providers and their keys; DSH keeps the providers in the profile's `cordis.patch.yml` and the keys in `.credentials.yaml`.
@@ -35,7 +42,7 @@ At every start the Host puts these three bundles at the head of the profile's bu
## Check a change
-`npm test` checks the composition of the profile, and that every package the app runs on is a dependency (see [Package](#package)).
+`npm test` checks the composition of the profile, the import on throwaway folders, and that every package the app runs on is a dependency (see [Package](#package)).
`scripts/shot.mjs` starts the app on throwaway folders, saves a screenshot of its window, prints the page text, closes the window the way a user does and waits until the app exits. Use the mock model of the plugin, `../ds-bot/dev/mock-llm.mjs` (`MOCK_PORT=<port> node ../ds-bot/dev/mock-llm.mjs`).
@@ -72,6 +79,8 @@ The Windows installer installs for the current user only, without administrator
| `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 |
| `src/profile.mjs` | The profile: its name, its bundles, and its creation and update |
+| `src/first-run.mjs` | The first start's dialogs: the two folders and the offer to import |
+| `src/import.mjs` | The import of a Bot team from the user's DSH |
| `engine/` | On hold, not installed: the bundle `deepseek-bot-engine` for the app's own window in `ui/` |
| `test/` | `npm test`: the composition of the profile, and the dependencies that the package needs |
| `src/web.mjs` | DSH's Web front end document, the launch-token cookie exchange and the request forwarding |
diff --git a/app/package-lock.json b/app/package-lock.json
index 8a28eae5..2729f40c 100644
--- a/app/package-lock.json
+++ b/app/package-lock.json
@@ -29,6 +29,8 @@
"@deepseek-ai/dsh-ptc-runtime": "0.2.0-rc.2",
"@deepseek-ai/dsh-sandbox": "0.2.0-rc.2",
"@deepseek-ai/dsh-sdk-protocol": "0.2.0-rc.2",
+ "@deepseek-ai/dsh-session-format": "0.2.0-rc.2",
+ "@deepseek-ai/dsh-session-format-catalog": "0.2.0-rc.2",
"@deepseek-ai/dsh-session-persistence": "0.2.0-rc.2",
"@deepseek-ai/dsh-session-query": "0.2.0-rc.2",
"@deepseek-ai/dsh-session-telemetry": "0.2.0-rc.2",
@@ -40,7 +42,8 @@
"@deepseek-ai/dsh-util-workspace-path": "0.2.0-rc.2",
"@deepseek-ai/dsh-workflow": "0.2.0-rc.2",
"ds-bot": "file:../ds-bot",
- "pnpm": "11.7.0"
+ "pnpm": "11.7.0",
+ "yaml": "2.9.1"
},
"devDependencies": {
"electron": "44.7.0",
diff --git a/app/package.json b/app/package.json
index 82c34e5a..c808b748 100644
--- a/app/package.json
+++ b/app/package.json
@@ -39,6 +39,8 @@
"@deepseek-ai/dsh-ptc-runtime": "0.2.0-rc.2",
"@deepseek-ai/dsh-sandbox": "0.2.0-rc.2",
"@deepseek-ai/dsh-sdk-protocol": "0.2.0-rc.2",
+ "@deepseek-ai/dsh-session-format": "0.2.0-rc.2",
+ "@deepseek-ai/dsh-session-format-catalog": "0.2.0-rc.2",
"@deepseek-ai/dsh-session-persistence": "0.2.0-rc.2",
"@deepseek-ai/dsh-session-query": "0.2.0-rc.2",
"@deepseek-ai/dsh-session-telemetry": "0.2.0-rc.2",
@@ -50,7 +52,8 @@
"@deepseek-ai/dsh-util-workspace-path": "0.2.0-rc.2",
"@deepseek-ai/dsh-workflow": "0.2.0-rc.2",
"ds-bot": "file:../ds-bot",
- "pnpm": "11.7.0"
+ "pnpm": "11.7.0",
+ "yaml": "2.9.1"
},
"devDependencies": {
"electron": "44.7.0",
diff --git a/app/src/first-run.mjs b/app/src/first-run.mjs
new file mode 100644
index 00000000..3919faf6
--- /dev/null
+++ b/app/src/first-run.mjs
@@ -0,0 +1,132 @@
+// The first start: where the app keeps its data and the Bots' files, 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 { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { homedir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { findTeam, newerSessions, teamInUse, userDshHome, within } from './import.mjs'
+
+const TEXT = {
+ en: {
+ welcome: 'Welcome to DeepSeek Bot',
+ places: (data, workspace) => `Data: ${data}\nFiles that Bots make: ${workspace}`,
+ start: 'Start', change: 'Change…',
+ pickData: 'Folder for DeepSeek Bot data', pickWorkspace: 'Folder for files that Bots make',
+ dataInWorkspace: 'The data folder cannot be inside the folder for Bot files.',
+ workspaceInData: 'The folder for Bot files cannot be inside the data folder.',
+ inDsh: home => `Choose a folder outside the DeepSeek Harness data (${home}).`,
+ inProgram: 'Choose a folder outside the program folder: uninstalling removes it.',
+ found: (bots, rooms) => `DeepSeek Harness has a Bot team: ${bots} Bot${bots === 1 ? '' : 's'}${rooms > 0 ? `, ${rooms} group${rooms === 1 ? '' : 's'}` : ''}. Copy it into DeepSeek Bot?`,
+ foundDetail: home => `The copy takes the Bots, groups, memories, chats, files, keys and model settings. Nothing in ${home} changes, and the two teams do not stay in step.`,
+ copy: 'Copy', skip: 'Do not copy',
+ inUse: 'DeepSeek Harness is using this team. Close it, then try again.', retry: 'Try again',
+ newer: count => `${count} chat${count === 1 ? ' was' : 's were'} written by a newer DeepSeek Harness than this DeepSeek Bot can read. Update DeepSeek Bot, then start it again to copy the team.`,
+ quit: 'Quit', startEmpty: 'Start without the team',
+ whichModels: 'Which model settings should DeepSeek Bot use?',
+ failed: message => `The team could not be copied: ${message}\n\nDeepSeek Bot starts with a new team. The team in DeepSeek Harness is unchanged.`,
+ },
+ zh: {
+ welcome: '欢迎使用 DeepSeek Bot',
+ places: (data, workspace) => `数据:${data}\nBot 写出的文件:${workspace}`,
+ start: '开始使用', change: '更改位置…',
+ pickData: '选择 DeepSeek Bot 的数据文件夹', pickWorkspace: '选择 Bot 写出的文件放在哪个文件夹',
+ dataInWorkspace: '数据文件夹不能放在 Bot 文件夹里面。',
+ workspaceInData: 'Bot 文件夹不能放在数据文件夹里面。',
+ inDsh: home => `请选择 DeepSeek Harness 数据(${home})以外的文件夹。`,
+ inProgram: '请选择程序文件夹以外的位置:卸载时会删掉程序文件夹。',
+ found: (bots, rooms) => `DeepSeek Harness 里有一个 Bot 团队:${bots} 个 Bot${rooms > 0 ? `、${rooms} 个群` : ''}。要复制到 DeepSeek Bot 吗?`,
+ foundDetail: home => `会复制 Bot、群、记忆、对话、文件、密钥和模型设置。${home} 里的内容不会改变;复制以后两个团队各自独立。`,
+ copy: '复制', skip: '不复制',
+ inUse: 'DeepSeek Harness 正在使用这个团队。请先关掉它,再重试。', retry: '重试',
+ newer: count => `有 ${count} 段对话是更新版本的 DeepSeek Harness 写的,这个版本的 DeepSeek Bot 读不了。请先更新 DeepSeek Bot,再打开它来复制团队。`,
+ quit: '退出', startEmpty: '不带团队开始',
+ whichModels: 'DeepSeek Bot 用哪一份模型设置?',
+ failed: message => `团队没有复制成功:${message}\n\nDeepSeek Bot 会用一个新团队开始。DeepSeek Harness 里的团队没有变化。`,
+ },
+}
+export const text = () => (app.getLocale().toLowerCase().startsWith('zh') ? TEXT.zh : TEXT.en)
+
+const PROFILE_NAMES = { desktop: 'DSH Desktop', web: 'DSH Web' }
+const ask = options => dialog.showMessageBoxSync({ title: 'DeepSeek Bot', noLink: true, ...options })
+
+function pick(title, current) {
+ const picked = dialog.showOpenDialogSync({ title, defaultPath: existsSync(current) ? current : dirname(current), properties: ['openDirectory', 'createDirectory', 'promptToCreate'] })
+ return picked?.[0] ?? current
+}
+
+function placeProblem(t, dataDir, workspace) {
+ const dsh = userDshHome()
+ const program = dirname(app.getPath('exe'))
+ if (within(dataDir, workspace)) return t.dataInWorkspace
+ if (within(workspace, dataDir)) return t.workspaceInData
+ for (const path of [dataDir, workspace]) {
+ if (within(path, dsh) || within(dsh, path)) return t.inDsh(dsh)
+ if (app.isPackaged && within(path, program)) return t.inProgram
+ }
+ return undefined
+}
+
+function hasTeam(dataDir) {
+ try {
+ return Object.keys(JSON.parse(readFileSync(join(dataDir, 'bot', 'state.json'), 'utf8')).bots ?? {}).length > 0
+ } catch {
+ return false
+ }
+}
+
+function offerImport(t, dataDir) {
+ const from = userDshHome()
+ let found
+ try {
+ found = hasTeam(dataDir) ? undefined : findTeam(from)
+ } catch (error) {
+ console.error(error)
+ }
+ if (found === undefined) return undefined
+ if (ask({ type: 'question', message: t.found(found.bots, found.rooms), detail: t.foundDetail(from), buttons: [t.copy, t.skip], defaultId: 0, cancelId: 1 }) === 1) return undefined
+ while (teamInUse(from)) {
+ if (ask({ type: 'warning', message: t.inUse, buttons: [t.retry, t.skip], defaultId: 0, cancelId: 1 }) === 1) return undefined
+ }
+ const newer = newerSessions(from, found.team)
+ if (newer.length > 0) {
+ if (ask({ type: 'warning', message: t.newer(newer.length), buttons: [t.quit, t.startEmpty], defaultId: 0, cancelId: 0 }) === 0) return { quit: true }
+ return undefined
+ }
+ const { profiles } = found
+ const profile = profiles.length < 2 ? profiles[0]?.name
+ : profiles[ask({ type: 'question', message: t.whichModels, buttons: profiles.map(entry => PROFILE_NAMES[entry.name] ?? entry.name), defaultId: 0, cancelId: 0 })].name
+ return { from, profile }
+}
+
+/**
+ * Where the app keeps its data and the Bots' files, asked at the first start.
+ * A run on throwaway folders (DS_BOT_HOME, for development and tests) asks nothing and copies nothing.
+ * @returns {{ dataDir: string, workspace?: string, import?: { from: string, profile?: string }, quit?: true }}
+ */
+export function chooseLocations() {
+ if (process.env.DS_BOT_HOME) return { dataDir: process.env.DS_BOT_HOME, workspace: process.env.DS_BOT_WORKSPACE || undefined }
+ const file = join(app.getPath('userData'), 'locations.json')
+ if (existsSync(file)) {
+ const saved = JSON.parse(readFileSync(file, 'utf8'))
+ return { dataDir: saved.dataDir, workspace: saved.workspace }
+ }
+ const t = text()
+ let dataDir = join(homedir(), '.ds-bot')
+ let workspace = join(homedir(), 'DeepSeek Bot')
+ for (;;) {
+ const choice = ask({ type: 'info', message: t.welcome, detail: t.places(dataDir, workspace), buttons: [t.start, t.change], defaultId: 0, cancelId: 0 })
+ if (choice === 1) {
+ dataDir = pick(t.pickData, dataDir)
+ workspace = pick(t.pickWorkspace, workspace)
+ continue
+ }
+ const problem = placeProblem(t, dataDir, workspace)
+ if (problem === undefined) break
+ ask({ type: 'warning', message: problem, buttons: ['OK'] })
+ }
+ const imported = offerImport(t, dataDir)
+ if (imported?.quit) return { dataDir, workspace, quit: true }
+ mkdirSync(dirname(file), { recursive: true })
+ writeFileSync(file, `${JSON.stringify({ dataDir, workspace }, null, 2)}\n`)
+ return { dataDir, workspace, ...(imported ? { import: imported } : {}) }
+}
diff --git a/app/src/import.mjs b/app/src/import.mjs
new file mode 100644
index 00000000..9599a50b
--- /dev/null
+++ b/app/src/import.mjs
@@ -0,0 +1,173 @@
+// The first-run import: a copy of the Bot team in the user's own DSH home. It only reads there.
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
+import { chmod, cp, mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
+import { homedir, hostname } from 'node:os'
+import { join, relative, resolve, sep } from 'node:path'
+import { parseSessionFormatLogFilename } from '@deepseek-ai/dsh-session-format'
+import { sessionFormatCatalog } from '@deepseek-ai/dsh-session-format-catalog'
+import { parse, stringify } from 'yaml'
+
+// The rows of a profile patch that hold model settings: DeepSeek's API and account, other
+// providers, the default model and the agent presets. Rows of other plugins may name plugins
+// that the app does not have.
+export const MODEL_ROWS = ['llm-deepseek', 'llm-deepseek-account', 'llm-pi-ai', 'agent-default-model', 'agent-preset-registry']
+// The team's lock, its turns in flight and its workspace belong to the old home.
+const LEFT_BEHIND = new Set(['state.lock', 'inflight.json', 'workspace'])
+const LOCK_STALE_MS = 60_000
+
+/** The DSH home of the user's own DSH, read as DSH reads DSH_HOME. */
+export function userDshHome(env = process.env) {
+ const value = env.DSH_HOME?.trim()
+ if (!value) return join(homedir(), '.dsh')
+ return resolve(value === '~' ? homedir() : /^~[\\/]/u.test(value) ? join(homedir(), value.slice(2)) : value)
+}
+
+export const within = (inner, outer) => {
+ const path = relative(resolve(outer), resolve(inner))
+ return path === '' || (!path.startsWith('..') && !path.startsWith(sep) && !/^[a-z]:/iu.test(path))
+}
+
+const readJson = path => JSON.parse(readFileSync(path, 'utf8'))
+
+/** Every Session the team names: each Bot's and group's parts and the group conversations. */
+export function sessionIdsOf(team) {
+ const parts = entry => (entry.segments ?? []).map(part => part.sessionId)
+ return [...new Set([
+ ...Object.values(team.bots ?? {}).flatMap(bot => [bot.id, bot.sessionId, ...parts(bot)]),
+ ...Object.values(team.rooms ?? {}).flatMap(room => [...Object.values(room.sessions ?? {}), ...parts(room)]),
+ ].filter(id => typeof id === 'string' && id !== ''))]
+}
+
+/**
+ * The team in a DSH home, with the profiles that hold model settings.
+ * @returns {{ from: string, team: any, bots: number, rooms: number, profiles: { name: string, rows: any[] }[] } | undefined}
+ */
+export function findTeam(from) {
+ const statePath = join(from, 'bot', 'state.json')
+ if (!existsSync(statePath)) return undefined
+ const team = readJson(statePath)
+ const bots = Object.keys(team.bots ?? {}).length
+ if (bots === 0) return undefined
+ return { from, team, bots, rooms: Object.keys(team.rooms ?? {}).length, profiles: modelProfiles(from) }
+}
+
+function modelProfiles(from) {
+ const dir = join(from, 'profiles')
+ if (!existsSync(dir)) return []
+ return readdirSync(dir, { withFileTypes: true }).filter(entry => entry.isDirectory()).flatMap((entry) => {
+ const file = join(dir, entry.name, 'cordis.patch.yml')
+ if (!existsSync(file)) return []
+ const patch = parse(readFileSync(file, 'utf8'))
+ const rows = Array.isArray(patch) ? patch.filter(row => MODEL_ROWS.includes(row?.id)) : []
+ return rows.length > 0 ? [{ name: entry.name, rows }] : []
+ })
+}
+
+/** 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() } = {}) {
+ const path = join(from, 'bot', 'state.lock')
+ if (!existsSync(path)) return false
+ const fresh = now - statSync(path).mtimeMs < LOCK_STALE_MS
+ let holder
+ try {
+ holder = JSON.parse(readFileSync(path, 'utf8'))
+ } catch {
+ return fresh
+ }
+ if (holder?.host !== host) return fresh
+ try {
+ process.kill(holder.pid, 0)
+ return true
+ } catch (error) {
+ return error?.code === 'EPERM'
+ }
+}
+
+// sessions/<group>/<id>/: the group is the folder the Session works in.
+function sessionDirs(from, ids) {
+ const root = join(from, 'sessions')
+ const groups = existsSync(root) ? readdirSync(root, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name) : []
+ const found = []
+ const missing = []
+ for (const id of ids) {
+ const group = groups.find(name => existsSync(join(root, name, id)))
+ if (group === undefined) missing.push(id)
+ else found.push({ id, group })
+ }
+ return { found, missing }
+}
+
+const logVersion = name => parseSessionFormatLogFilename(name.replace(/\.(zstd|zst|gz|br)$/u, ''))
+
+/** The Sessions whose log is in a newer format than the pinned DSH reads. */
+export function newerSessions(from, team) {
+ const { found } = sessionDirs(from, sessionIdsOf(team))
+ return found.filter(({ id, group }) => readdirSync(join(from, 'sessions', group, id))
+ .some(name => (logVersion(name) ?? 0) > sessionFormatCatalog.currentVersion)).map(({ id }) => id)
+}
+
+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
+}
+
+async function writeModelRows(to, rows) {
+ const file = join(to, 'profiles', 'ds-bot', 'cordis.patch.yml')
+ const current = existsSync(file) ? parse(await readFile(file, 'utf8')) : undefined
+ const ids = new Set(rows.map(row => row.id))
+ const kept = Array.isArray(current) ? current.filter(row => !ids.has(row?.id)) : []
+ await mkdir(join(to, 'profiles', 'ds-bot'), { recursive: true })
+ await writeFile(file, stringify([...kept, ...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.
+ * 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 failure leaves that folder behind.
+ * @param {{ from: string, to: string, workspace: string, profile?: string, dsh?: string }} options
+ */
+export async function importTeam({ from, to, workspace, profile, dsh }) {
+ const found = findTeam(from)
+ if (found === undefined) throw new Error(`There is no Bot team in ${from}`)
+ const present = existsSync(join(to, 'bot', 'state.json')) ? readJson(join(to, 'bot', 'state.json')) : undefined
+ if (Object.keys(present?.bots ?? {}).length > 0) throw new Error(`${to} already has a Bot team`)
+ const stage = join(to, `.import-${String(Date.now())}`)
+ const oldBot = join(from, 'bot')
+ await cp(oldBot, join(stage, 'bot'), { recursive: true, filter: path => !LEFT_BEHIND.has(relative(oldBot, path).split(/[\\/]/u)[0]) })
+ const team = readJson(join(stage, 'bot', 'state.json'))
+ // The new data location registers its own team workspace, and the app has no Agent mode.
+ delete team.workspaceId
+ team.agents = {}
+ await writeFile(join(stage, 'bot', 'state.json'), JSON.stringify(team, null, 2))
+ const { found: sessions, missing } = sessionDirs(from, sessionIdsOf(found.team))
+ for (const { id, group } of sessions) await cp(join(from, 'sessions', group, id), join(stage, 'sessions', group, id), { recursive: true })
+ if (existsSync(join(from, 'attachments'))) await cp(join(from, 'attachments'), join(stage, 'attachments'), { recursive: true })
+
+ await mkdir(workspace, { recursive: true })
+ if (existsSync(join(oldBot, 'workspace'))) await cp(join(oldBot, 'workspace'), workspace, { recursive: true, force: false })
+ const keys = []
+ for (const name of ['.credentials.yaml', '.env']) if (await copyKey(from, to, name)) keys.push(name)
+ const rows = found.profiles.find(entry => entry.name === profile)?.rows ?? []
+ if (rows.length > 0) await writeModelRows(to, rows)
+
+ await rm(join(to, 'bot'), { recursive: true, force: true })
+ await rename(join(stage, 'bot'), join(to, 'bot'))
+ for (const { id, group } of sessions) {
+ await mkdir(join(to, 'sessions', group), { recursive: true })
+ await rename(join(stage, 'sessions', group, id), join(to, 'sessions', group, id))
+ }
+ if (existsSync(join(stage, 'attachments'))) await cp(join(stage, 'attachments'), join(to, 'attachments'), { recursive: true, force: false })
+ 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,
+ }
+ await writeFile(join(to, 'bot', 'imported.json'), `${JSON.stringify(summary, null, 2)}\n`)
+ await rm(stage, { recursive: true, force: true })
+ return summary
+}
diff --git a/app/src/main.mjs b/app/src/main.mjs
index 67c13064..36670fb4 100644
--- a/app/src/main.mjs
+++ b/app/src/main.mjs
@@ -4,10 +4,12 @@
import { app, BrowserWindow, dialog, ipcMain, Menu, nativeTheme, protocol, session, shell } from 'electron'
import { mkdirSync } from 'node:fs'
import { createRequire } from 'node:module'
-import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
+import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot'
+import { chooseLocations, text } from './first-run.mjs'
import { HostProcess } from './host-process.mjs'
+import { importTeam } from './import.mjs'
import { APP_ORIGIN, authenticateWebHost, forwardWebRequest, serveWebDocument } from './web.mjs'
// DSH writes dsh-app://app/ into workspace file URLs and Markdown file links, so the window keeps that scheme.
@@ -19,7 +21,6 @@ const here = dirname(fileURLToPath(import.meta.url))
const webDist = join(dirname(createRequire(import.meta.url).resolve('@deepseek-ai/dsh-web-frontend/package.json')), 'dist')
// Drawn by scripts/icon.mjs. Windows takes the .ico for its several sizes.
const iconFile = join(here, '..', 'assets', process.platform === 'win32' ? 'icon.ico' : 'icon.png')
-const dataDir = process.env.DS_BOT_HOME || join(homedir(), '.ds-bot')
if (process.env.DS_BOT_SHELL_DATA) app.setPath('userData', process.env.DS_BOT_SHELL_DATA)
protocol.registerSchemesAsPrivileged([{
@@ -50,19 +51,24 @@ if (!app.requestSingleInstanceLock()) {
}
function start() {
- const profileDir = join(dataDir, 'profiles', 'ds-bot')
+ const where = chooseLocations()
+ if (where.quit) { app.exit(0); return }
+ const profileDir = join(where.dataDir, 'profiles', 'ds-bot')
mkdirSync(profileDir, { recursive: true })
- host = new HostProcess({
+ const newHost = () => new HostProcess({
entry: join(here, 'host.mjs'),
cwd: profileDir,
- env: { ...process.env, DSH_HOME: dataDir, DS_BOT_APP: '1' },
+ env: { ...process.env, DSH_HOME: where.dataDir, DS_BOT_APP: '1', ...(where.workspace ? { DS_BOT_WORKSPACE: where.workspace } : {}) },
pnpm: join(app.getAppPath(), 'node_modules', 'pnpm', 'bin', 'pnpm.mjs'),
onFailure: fail,
})
- const ready = host.start().then(async (started) => {
+ const ready = (async () => {
+ if (where.import) await copyTeam(where, newHost)
+ host = newHost()
+ const started = await host.start()
hostState = { ...started, cookie: await authenticateWebHost(started.url) }
return hostState
- })
+ })()
ready.catch(fail)
protocol.handle(SCHEME, (request) => {
@@ -99,6 +105,25 @@ function start() {
createWindow()
}
+// The Host starts once on the new data location first: DSH then sets up its project list
+// without the copied Sessions' folders, so the old team's folders are not offered as projects.
+async function copyTeam(where, newHost) {
+ host = newHost()
+ try {
+ await host.start()
+ mainWindow?.setProgressBar(2)
+ await host.stop()
+ host = undefined
+ const summary = await importTeam({ ...where.import, to: where.dataDir, workspace: where.workspace, dsh: getDshRuntimeVersion() })
+ console.log(`DeepSeek Bot: copied ${String(summary.bots)} Bots and ${String(summary.sessions)} Sessions from ${summary.from}`)
+ } catch (error) {
+ console.error(error)
+ await dialog.showMessageBox({ type: 'warning', title: 'DeepSeek Bot', message: text().failed(error instanceof Error ? error.message : String(error)) })
+ } finally {
+ mainWindow?.setProgressBar(-1)
+ }
+}
+
function createWindow() {
mainWindow = new BrowserWindow({
width: 1320, height: 860, minWidth: 720, minHeight: 480,
diff --git a/app/test/import.test.mjs b/app/test/import.test.mjs
new file mode 100644
index 00000000..ee5a3c68
--- /dev/null
+++ b/app/test/import.test.mjs
@@ -0,0 +1,180 @@
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, utimesSync, writeFileSync } from 'node:fs'
+import { homedir, tmpdir } from 'node:os'
+import { dirname, join, relative } from 'node:path'
+import { after, before, describe, test } from 'node:test'
+import { parse } from 'yaml'
+import { findTeam, importTeam, newerSessions, sessionIdsOf, teamInUse, userDshHome } from '../src/import.mjs'
+
+const write = (path, text) => {
+ mkdirSync(dirname(path), { recursive: true })
+ writeFileSync(path, text)
+}
+const readJson = path => JSON.parse(readFileSync(path, 'utf8'))
+
+function treeHash(dir) {
+ const hash = createHash('sha256')
+ const walk = (at) => {
+ for (const name of readdirSync(at).sort()) {
+ const path = join(at, name)
+ if (statSync(path).isDirectory()) walk(path)
+ else hash.update(relative(dir, path)).update(readFileSync(path))
+ }
+ }
+ walk(dir)
+ return hash.digest('hex')
+}
+
+// A user's DSH home: Chief in two parts, Writer, a group, the team's own files, two profiles.
+const TEAM = {
+ version: 1,
+ workspaceId: 'w-old',
+ mainBotIds: ['session-a'],
+ bots: {
+ 'session-a': { id: 'session-a', name: 'Chief', sessionId: 'session-a2', segments: [{ sessionId: 'session-a' }] },
+ 'session-b': { id: 'session-b', name: 'Writer', workDir: '/projects/site' },
+ },
+ rooms: { r1: { id: 'r1', name: 'Ops', members: ['session-a', 'session-b'], sessions: { 'session-a': 'session-g', 'session-b': 'session-gone' } } },
+ agents: { x: { id: 'x' } },
+}
+
+function oldHome(root) {
+ const from = join(root, 'dsh')
+ write(join(from, 'bot', 'state.json'), JSON.stringify(TEAM))
+ write(join(from, 'bot', 'state.lock'), '{}')
+ write(join(from, 'bot', 'inflight.json'), '{}')
+ write(join(from, 'bot', 'memory', 'session-a.md'), 'remember')
+ write(join(from, 'bot', 'workspace', 'notes.txt'), 'old notes')
+ write(join(from, 'bot', 'workspace', 'kept.txt'), 'old kept')
+ for (const [group, id] of [['--team--', 'session-a'], ['--team--', 'session-a2'], ['--team--', 'session-g'], ['--site--', 'session-b']]) {
+ write(join(from, 'sessions', group, id, 'session.v4.jsonl.zstd'), id)
+ }
+ write(join(from, 'sessions', '--team--', 'session-other', 'session.v4.jsonl.zstd'), 'not the team')
+ write(join(from, 'attachments', 'ab', 'cdef'), 'file')
+ write(join(from, '.credentials.yaml'), 'DEEPSEEK_API_KEY: fake\n')
+ write(join(from, '.env'), 'X=1\n')
+ write(join(from, 'profiles', 'desktop', 'cordis.patch.yml'), [
+ '- id: llm-pi-ai', ' config:', ' providers:', ' moonshotai:', ' apiKeyEnv: MOONSHOTAI_API_KEY',
+ '- id: agent-default-model', ' config:', ' model: deepseek-official/deepseek-flash',
+ '- id: some-plugin', ' name: some-plugin', '',
+ ].join('\n'))
+ write(join(from, 'profiles', 'web', 'cordis.patch.yml'), '- id: some-plugin\n name: some-plugin\n')
+ return from
+}
+
+// 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')
+ const workspace = join(root, 'DeepSeek Bot')
+ write(join(workspace, 'kept.txt'), 'new kept')
+ return { to, workspace }
+}
+
+describe('importTeam', () => {
+ let root, from, to, workspace, oldTree, summary
+ before(async () => {
+ root = mkdtempSync(join(tmpdir(), 'ds-bot-app-import-'))
+ from = oldHome(root);
+ ({ to, workspace } = newHome(root))
+ oldTree = treeHash(from)
+ summary = await importTeam({ from, to, workspace, profile: 'desktop', dsh: '0.2.0-rc.2' })
+ })
+ after(() => { rmSync(root, { recursive: true, force: true }) })
+
+ test('copies the team without its lock, its turns in flight, its workspace, its old workspace id or Agents', () => {
+ const team = readJson(join(to, 'bot', 'state.json'))
+ assert.deepEqual(Object.keys(team.bots), ['session-a', 'session-b'])
+ assert.equal(team.workspaceId, undefined)
+ assert.deepEqual(team.agents, {})
+ assert.equal(readFileSync(join(to, 'bot', 'memory', 'session-a.md'), 'utf8'), 'remember')
+ for (const name of ['state.lock', 'inflight.json', 'workspace']) assert.equal(existsSync(join(to, 'bot', name)), false, name)
+ })
+
+ test('copies every Session the team names into the same folder group, and only those', () => {
+ for (const [group, id] of [['--team--', 'session-a'], ['--team--', 'session-a2'], ['--team--', 'session-g'], ['--site--', 'session-b']]) {
+ assert.equal(readFileSync(join(to, 'sessions', group, id, 'session.v4.jsonl.zstd'), 'utf8'), id)
+ }
+ assert.equal(existsSync(join(to, 'sessions', '--team--', 'session-other')), false)
+ assert.deepEqual(summary.missingSessions, ['session-gone'])
+ assert.equal(summary.sessions, 4)
+ })
+
+ test('copies the attachments, the keys, and the model rows of the chosen profile', () => {
+ assert.equal(readFileSync(join(to, 'attachments', 'ab', 'cdef'), 'utf8'), 'file')
+ 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' } })
+ })
+
+ test('puts the old workspace files in the chosen folder without replacing one that is there', () => {
+ assert.equal(readFileSync(join(workspace, 'notes.txt'), 'utf8'), 'old notes')
+ assert.equal(readFileSync(join(workspace, 'kept.txt'), 'utf8'), 'new kept')
+ })
+
+ test('records the import, leaves nothing staged and changes nothing in the old home', () => {
+ 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: 4, missingSessions: ['session-gone'],
+ keys: ['.credentials.yaml', '.env'], modelSettings: 'desktop',
+ })
+ assert.deepEqual(readdirSync(to).filter(name => name.startsWith('.import-')), [])
+ assert.equal(treeHash(from), oldTree)
+ })
+
+ test('does not replace a team that is there', async () => {
+ await assert.rejects(importTeam({ from, to, workspace }), /already has a Bot team/u)
+ })
+})
+
+describe('finding the team', () => {
+ let root, from
+ before(() => {
+ root = mkdtempSync(join(tmpdir(), 'ds-bot-app-find-'))
+ from = oldHome(root)
+ })
+ after(() => { rmSync(root, { recursive: true, force: true }) })
+
+ test('counts the Bots and groups and lists only the profiles with model settings', () => {
+ const found = findTeam(from)
+ assert.equal(found.bots, 2)
+ assert.equal(found.rooms, 1)
+ assert.deepEqual(found.profiles.map(entry => [entry.name, entry.rows.map(row => row.id)]), [['desktop', ['llm-pi-ai', 'agent-default-model']]])
+ assert.equal(findTeam(join(root, 'none')), undefined)
+ })
+
+ test('names each Session of the team once', () => {
+ assert.deepEqual(sessionIdsOf(TEAM), ['session-a', 'session-a2', 'session-b', 'session-g', 'session-gone'])
+ })
+
+ test('finds Sessions written in a newer format than the pinned DSH reads', () => {
+ assert.deepEqual(newerSessions(from, TEAM), [])
+ write(join(from, 'sessions', '--site--', 'session-b', 'session.v99.jsonl.zstd'), 'newer')
+ assert.deepEqual(newerSessions(from, TEAM), ['session-b'])
+ })
+
+ test('takes the team for in use while a live process on this machine or a fresh lock elsewhere holds it', () => {
+ const lock = join(from, 'bot', 'state.lock')
+ write(lock, JSON.stringify({ pid: process.pid, host: 'here' }))
+ assert.equal(teamInUse(from, { host: 'here' }), true)
+ const ended = spawnSync(process.execPath, ['-e', '']).pid
+ write(lock, JSON.stringify({ pid: ended, host: 'here' }))
+ assert.equal(teamInUse(from, { host: 'here' }), false)
+ write(lock, JSON.stringify({ pid: 1, host: 'elsewhere' }))
+ assert.equal(teamInUse(from, { host: 'here' }), true)
+ const old = new Date(Date.now() - 120_000)
+ utimesSync(lock, old, old)
+ assert.equal(teamInUse(from, { host: 'here' }), false)
+ })
+
+ test('reads DSH_HOME as DSH does', () => {
+ assert.equal(userDshHome({}), join(homedir(), '.dsh'))
+ assert.equal(userDshHome({ DSH_HOME: ' ' }), join(homedir(), '.dsh'))
+ assert.equal(userDshHome({ DSH_HOME: '~/dsh-x' }), join(homedir(), 'dsh-x'))
+ })
+})
diff --git a/docs/plans/2026-10-16-desktop-app.md b/docs/plans/2026-10-16-desktop-app.md
index 84c88c58..62480adf 100644
--- a/docs/plans/2026-10-16-desktop-app.md
+++ b/docs/plans/2026-10-16-desktop-app.md
@@ -43,8 +43,12 @@
### 首次启动和导入
-- 首次启动分别选数据位置和 Bot 工作文件夹,以后能在设置里改。
-- 发现用户 DSH 里已有团队时,问要不要导入。导入复制 Bot、群、记忆、会话、附件、模型设置和密钥,旧位置一个字节都不改。导入以后两个团队各走各的,不同步。
+- 首次启动分别选数据位置(默认 `~/.ds-bot`)和 Bot 工作文件夹(默认 `~/DeepSeek Bot`),以后能在设置里改。两个位置不能一个在另一个里面,也不能在用户 DSH 的数据里。用的是系统对话框。
+- 发现用户 DSH 里已有团队时,问要不要导入,只在首次启动问一次。导入复制 Bot、群、记忆、会话、附件、模型设置和密钥,旧位置一个字节都不改。导入以后两个团队各走各的,不同步。
+ - DSH 正在用这个团队时,请用户先关掉。
+ - 引擎先在新数据位置启动一次再复制,这样 DSH 不会把旧团队的文件夹当成自己的项目。
+ - 旧团队工作文件夹里的文件复制到新的 Bot 工作文件夹,不覆盖已有的文件。
+ - 模型设置只取 profile 里模型的那几行(DeepSeek API 和账号、其他服务商、默认模型、预设)。几个 profile 都有时让用户选一份。DSH 里另外配的 MCP、技能和 DSH Agent 不导入。
- 导入后,每个 Bot 和群在下一个回合前换到新的一段(新工作文件夹),旧段只当历史读,照常能看、能搜。以后搬工作文件夹也一样。
- 用户 DSH 写的会话格式比锁定版新时,停下来请用户先更新 DeepSeek Bot。
@@ -77,7 +81,7 @@
## 已知限制
-- 还没有:首次启动和导入、更新。
+- 还没有:在设置里改数据位置和 Bot 工作文件夹;导入后逐个试读会话(同一格式版本里更新的 DSH 加了新事件时,锁定版打不开那段对话);更新。
- 不签名:Windows 第一次运行会弹出 SmartScreen 警告,macOS 要在系统设置里手动放行。
- 会话里记着工作文件夹的完整路径,不能改。所以导入和搬工作文件夹都要换段。
- 安装的 `@deepseek-ai/dsh` 包带着 Office 套件和语音包,所以安装包里仍有这些文件,只是不加载。
@@ -92,3 +96,4 @@
- 2026-10-18:应用标识定为 `io.github.fei2411.deepseekbot`;Windows 只给当前用户安装,更新下载完提示重启;安装包不按 profile 删减 DSH 的文件,PR #303。
- 2026-10-18:设置里加「模型」页,服务商和 key 存在 DSH 里,PR #319。
- 2026-10-18:自己的界面先停下,窗口换回 DSH 的网页前端和系统标题栏;引擎的 profile 换回 `dsh-base`、`dsh-web-app`、`ds-bot`,PR #323。
+- 2026-10-18:首次启动选两个位置、从用户 DSH 导入团队的细节。