Skip to content

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

Serve the desktop window from the Host's loopback address

Fei2411a8cfb775d668
diff --git a/NOTICE b/NOTICE
index afb29d66..58ee2855 100644
--- a/NOTICE
+++ b/NOTICE
@@ -14,16 +14,13 @@ MIT License, Copyright (c) 2026 DeepSeek
apps/desktop/scripts/dev.ts in DeepSeek Harness and reuses a few of its
lines (the release record and the Electron launch arguments). It is a
developer script for screenshots on Linux and is not in the npm package.
- - app/src/web.mjs adapts apps/desktop/src/web-document.ts: the launch-token
- cookie exchange and the request forwarding.
- app/src/host.mjs and app/src/profile.mjs follow
apps/desktop-host/src/index.ts: the profile boot and the ready, fatal and
shutdown messages.
- app/src/host-process.mjs follows apps/desktop/src/host-process.ts: the
Host in Electron's Node mode and the shutdown escalation.
- - app/src/main.mjs follows apps/desktop/src/main.ts for the dsh-app scheme,
- the request routing, and the Windows window options (the caption-button
- overlay, its colors and the native theme). app/src/preload.cjs adapts
+ - app/src/main.mjs follows apps/desktop/src/main.ts for the Windows window
+ options (the caption-button overlay, its colors and the native theme). app/src/preload.cjs adapts
apps/desktop/src/preload-windows.ts, apps/desktop/src/preload-platform.ts
and apps/desktop/src/preload-theme.ts: the caption-band marks, the
fullscreen mark, the caption-color measure and the theme sync.
diff --git a/app/README.md b/app/README.md
index 7dded765..8f74f270 100644
--- a/app/README.md
+++ b/app/README.md
@@ -108,8 +108,9 @@ The script serves a releases list with one release of that version that has this
| File | What it does |
|---|---|
-| `src/main.mjs` | Main process: one instance, the `dsh-app://app` scheme (DSH's Web front end, and everything else forwarded to the Host), the window and its boot data |
-| `src/preload.cjs` | Hands the window the boot data that DSH's Web front end needs, and DS Bot's settings the data location and its move. On Windows it marks the page for the frameless window and sends the caption buttons the colors of the surface under them |
+| `src/main.mjs` | Main process: one instance, the window, which loads the Host's loopback address as DSH Web does, and the sign-in page DSH opens, which goes to the system browser |
+| `src/host-port.mjs` | The Host's port, kept between starts, since the page keeps its storage per address |
+| `src/preload.cjs` | Hands DS Bot's settings the data location and its move. On Windows it marks the page for the frameless window and sends the caption buttons the colors of the surface under them |
| `src/window-frame.mjs`, `src/mica.css` | The frameless Windows window: the caption band, when Mica is available (Windows 11 22H2 and later), and the stylesheet that lets Mica through the sidebar |
| `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 |
@@ -121,7 +122,6 @@ The script serves a releases list with one release of that version that has this
| `src/updates.mjs` | The Windows installer updates and macOS release-page checks |
| `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 |
| `ui/` | On hold, not built or packaged: the app's own window. React, built with Vite (`vite.config.js`) into `ui/dist`. It draws the plugin's own Bot views from `../ds-bot/src/client/` (sidebar, chat rows, docks, dialogs and their stylesheets) and puts its own Markdown in place of DSH's. It uses ds-bot's `api/bot` channel and its live feed `api/bot/feed` |
| `assets/` | The app icon: `icon.svg`, `icon.png` (1024 px) and `icon.ico` (Windows, 16 to 256 px). `npm run icon` (`scripts/icon.mjs`) draws them again from the Main Bot's whale in `../ds-bot` |
| `electron-builder.yml`, `build/` | The package and the installer: app identity, files, icons, the Windows installer and the macOS disk image |
diff --git a/app/scripts/check-packed.mjs b/app/scripts/check-packed.mjs
index b690ea0d..96f96d78 100644
--- a/app/scripts/check-packed.mjs
+++ b/app/scripts/check-packed.mjs
@@ -79,7 +79,7 @@ async function appPage(port, deadline) {
while (Date.now() < deadline) {
try {
const targets = await (await fetch(`http://127.0.0.1:${String(port)}/json/list`)).json()
- const page = targets.find(target => target.type === 'page' && target.url.startsWith('dsh-app://app'))
+ const page = targets.find(target => target.type === 'page' && /^http:\/\/127\.0\.0\.1:\d+\//u.test(target.url))
if (page) return page
} catch {
// The debugging port is not listening yet.
diff --git a/app/scripts/check-update.mjs b/app/scripts/check-update.mjs
index f66b0f8f..034219eb 100644
--- a/app/scripts/check-update.mjs
+++ b/app/scripts/check-update.mjs
@@ -51,7 +51,7 @@ const feed = `http://127.0.0.1:${String(server.address().port)}/`
// when a user closes it. The page goes away with the window, so the call gets no answer.
async function closeWindow(port, waitForReady = false) {
const targets = await (await fetch(`http://127.0.0.1:${String(port)}/json/list`)).json()
- const page = targets.find(target => target.type === 'page' && target.url.startsWith('dsh-app://app'))
+ const page = targets.find(target => target.type === 'page' && /^http:\/\/127\.0\.0\.1:\d+\//u.test(target.url))
if (!page) throw new Error('the app window is not there')
const socket = new WebSocket(page.webSocketDebuggerUrl)
await new Promise((done, reject) => {
diff --git a/app/scripts/shot.mjs b/app/scripts/shot.mjs
index 9307c801..6b3c7615 100644
--- a/app/scripts/shot.mjs
+++ b/app/scripts/shot.mjs
@@ -27,7 +27,7 @@ async function appPage(deadline) {
while (Date.now() < deadline) {
try {
const targets = await (await fetch(`http://127.0.0.1:${String(port)}/json/list`)).json()
- const page = targets.find((target) => target.type === 'page' && target.url.startsWith('dsh-app://app'))
+ const page = targets.find((target) => target.type === 'page' && /^http:\/\/127\.0\.0\.1:\d+\//u.test(target.url))
if (page) return page
} catch {
// The debugging port is not listening yet.
diff --git a/app/src/first-run.mjs b/app/src/first-run.mjs
index cc8c60f0..4a604954 100644
--- a/app/src/first-run.mjs
+++ b/app/src/first-run.mjs
@@ -26,6 +26,7 @@ const TEXT = {
moveDetail: from => `DeepSeek Bot copies its data there and starts again. ${from} stays as it is; you can delete it once everything works.`,
move: 'Move and restart', cancel: 'Cancel',
moving: 'Copying DeepSeek Bot\'s data…',
+ starting: 'Starting DeepSeek Bot…',
moveInUse: 'Another DeepSeek Harness is using this data, so it was not moved. Close it, then try again.',
moveFailed: message => `The data could not be copied: ${message}\n\nDeepSeek Bot goes on with its data where it was.`,
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?`,
@@ -56,6 +57,7 @@ const TEXT = {
moveDetail: from => `DeepSeek Bot 会把数据复制过去,然后重新启动。${from} 会原样保留,确认一切正常后可以自己删掉。`,
move: '移动并重启', cancel: '取消',
moving: '正在复制 DeepSeek Bot 的数据…',
+ starting: '正在启动 DeepSeek Bot…',
moveInUse: '另一个 DeepSeek Harness 正在使用这份数据,所以没有移动。请先关掉它,再重试。',
moveFailed: message => `数据没有复制成功:${message}\n\nDeepSeek Bot 会继续使用原来位置的数据。`,
found: (bots, rooms) => `DeepSeek Harness 里有一个 Bot 团队:${bots} 个 Bot${rooms > 0 ? `、${rooms} 个群` : ''}。要复制到 DeepSeek Bot 吗?`,
diff --git a/app/src/host-port.mjs b/app/src/host-port.mjs
new file mode 100644
index 00000000..25fcdb33
--- /dev/null
+++ b/app/src/host-port.mjs
@@ -0,0 +1,39 @@
+// The window's origin is the Host's loopback address, and the page keeps its storage (unread
+// marks, layout, preferences) per origin, so the Host listens on the same port at every start.
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { createServer } from 'node:net'
+import { dirname } from 'node:path'
+
+const free = port => new Promise((resolve) => {
+ const server = createServer()
+ server.once('error', () => { resolve(undefined) })
+ server.listen(port, '127.0.0.1', () => {
+ const { port: bound } = server.address()
+ server.close(() => { resolve(bound) })
+ })
+})
+
+const saved = (file) => {
+ try {
+ const { port } = JSON.parse(readFileSync(file, 'utf8'))
+ return Number.isInteger(port) && port > 0 && port < 65536 ? port : undefined
+ } catch {
+ return undefined
+ }
+}
+
+/**
+ * The port saved in `file` while it is free, otherwise a new free one, which is saved.
+ * @param {string} file
+ * @returns {Promise<number>}
+ */
+export async function hostPort(file) {
+ const kept = saved(file)
+ const port = (kept === undefined ? undefined : await free(kept)) ?? await free(0)
+ if (port === undefined) throw new Error('DeepSeek Bot: no free port on 127.0.0.1')
+ if (port !== kept) {
+ mkdirSync(dirname(file), { recursive: true })
+ writeFileSync(file, `${JSON.stringify({ port })}\n`)
+ }
+ return port
+}
diff --git a/app/src/host.mjs b/app/src/host.mjs
index 9d5bd0ea..ce2c8e58 100644
--- a/app/src/host.mjs
+++ b/app/src/host.mjs
@@ -26,7 +26,7 @@ async function main() {
profile: check === undefined ? PROFILE : CHECK_PROFILE,
resolvedProfile: { profile, installAnchor: INSTALL_ANCHOR },
patchFiles: [],
- args: ['--no-open', '--port', '0'],
+ 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/main.mjs b/app/src/main.mjs
index ecd74255..b08aff3f 100644
--- a/app/src/main.mjs
+++ b/app/src/main.mjs
@@ -1,10 +1,9 @@
// Electron main process: one window for the Bot team, served by the app's own DSH Host.
-// The dsh-app scheme, the request forwarding and the WebSocket header rewrite follow
-// DeepSeek Harness apps/desktop/src/main.ts (MIT); see NOTICE.
-import { app, BrowserWindow, dialog, ipcMain, Menu, nativeTheme, protocol, session, shell } from 'electron'
+// The window loads the Host's loopback address as DSH Web does: DSH's sign-in sends the page's
+// origin as the address the browser comes back to, and accepts only a loopback one.
+import { app, BrowserWindow, dialog, ipcMain, Menu, nativeTheme, shell } from 'electron'
import { mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
import { rm } from 'node:fs/promises'
-import { createRequire } from 'node:module'
import { release } from 'node:os'
import { dirname, isAbsolute, join, resolve } from 'node:path'
import { setTimeout as sleep } from 'node:timers/promises'
@@ -12,42 +11,33 @@ import { fileURLToPath } from 'node:url'
import { getDshRuntimeVersion } from '@deepseek-ai/dsh-app-boot'
import electronUpdater from 'electron-updater'
import { chooseLocations, localeText, programFolder, saveLocations, text } from './first-run.mjs'
+import { hostPort } from './host-port.mjs'
import { HostProcess } from './host-process.mjs'
import { copySessions, findTeam, importTeam, teamInUse, userDshHome } from './import.mjs'
import { copyData, moveProblem } from './move-data.mjs'
import { CHECK_PROFILE, PROFILE } from './profile.mjs'
import { UPDATE_TEXT, watchReleases, watchUpdates } from './updates.mjs'
-import { APP_ORIGIN, authenticateWebHost, forwardWebRequest, serveWebDocument } from './web.mjs'
import { CAPTION_HEIGHT, cssColor, micaAvailable, nativeThemeSource } from './window-frame.mjs'
-// DSH writes dsh-app://app/ into workspace file URLs and Markdown file links, so the window keeps that scheme.
-const SCHEME = 'dsh-app'
const IPC = {
- boot: 'ds-bot:boot', bootFailed: 'ds-bot:boot-failed',
caption: 'ds-bot:caption-colors', nativeTheme: 'ds-bot:native-theme', fullscreen: 'ds-bot:fullscreen',
dataLocation: 'ds-bot:data-location', moveData: 'ds-bot:move-data', teamWorkspace: 'ds-bot:team-workspace',
}
const MOVE_PROBLEMS = { drive: 'moveDrive', nested: 'moveNested', workspace: 'moveWorkspace', program: 'inProgram', notEmpty: 'moveNotEmpty' }
-const STATIC_PATHS = new Set(['/', '/index.html', '/manifest.webmanifest'])
const UPDATE_CHECK_WAIT_MS = 15_000
const UPDATE_DOWNLOAD_WAIT_MS = 15 * 60_000
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')
// Windows 11 draws Mica behind the page; mica.css lets it through the sidebar.
const mica = micaAvailable(process.platform, release())
if (process.env.DS_BOT_SHELL_DATA) app.setPath('userData', process.env.DS_BOT_SHELL_DATA)
-protocol.registerSchemesAsPrivileged([{
- scheme: SCHEME,
- privileges: { standard: true, secure: true, supportFetchAPI: true, corsEnabled: true, stream: true, codeCache: true },
-}])
-
let mainWindow
let host
-let hostState
+// The Host's loopback origin, which the window loads.
+let origin
let hostStop
let updates
let stopping = false
@@ -98,13 +88,15 @@ async function start() {
const where = await chooseLocations(choosing.signal).finally(() => { choosing = undefined })
if (where.quit) { app.exit(0); return }
places = { dataDir: where.dataDir, workspace: where.workspace }
+ const port = await hostPort(join(app.getPath('userData'), 'host-port.json'))
+ origin = `http://127.0.0.1:${String(port)}`
const pnpm = join(app.getAppPath(), 'node_modules', 'pnpm', 'bin', 'pnpm.mjs')
const profileDir = join(where.dataDir, 'profiles', PROFILE)
mkdirSync(profileDir, { recursive: true })
const newHost = () => new HostProcess({
entry: join(here, 'host.mjs'),
cwd: profileDir,
- env: { ...process.env, DSH_HOME: where.dataDir, DS_BOT_APP: '1', DS_BOT_USER_DSH_HOME: userDshHome(), ...(where.workspace ? { DS_BOT_WORKSPACE: where.workspace } : {}) },
+ env: { ...process.env, DSH_HOME: where.dataDir, DS_BOT_PORT: String(port), DS_BOT_APP: '1', DS_BOT_USER_DSH_HOME: userDshHome(), ...(where.workspace ? { DS_BOT_WORKSPACE: where.workspace } : {}) },
pnpm,
onFailure: fail,
})
@@ -128,29 +120,9 @@ async function start() {
// update can still come when this version's Host does not start.
updates = startUpdates()
host = newHost()
- const started = await host.start()
- hostState = { ...started, cookie: await authenticateWebHost(started.url) }
- return hostState
+ return host.start()
})()
ready.catch(fail)
-
- protocol.handle(SCHEME, (request) => {
- const url = new URL(request.url)
- if (url.hostname !== 'app') return new Response(null, { status: 404 })
- if (STATIC_PATHS.has(url.pathname) || url.pathname.startsWith('/assets/')) return serveWebDocument(request, webDist)
- if (hostState === undefined) return new Response(null, { status: 503 })
- return forwardWebRequest(request, hostState.url, hostState.cookie)
- })
-
- ipcMain.handle(IPC.boot, async (event) => {
- assertWindow(event)
- const { url, injections } = await ready
- return { injections, streamBaseUrl: new URL(url).origin }
- })
- ipcMain.handle(IPC.bootFailed, (event, message) => {
- assertWindow(event)
- fail(new Error(String(message)))
- })
// A throwaway run (DS_BOT_HOME) keeps its folders where it was told.
const fixed = Boolean(process.env.DS_BOT_HOME)
ipcMain.handle(IPC.dataLocation, (event) => {
@@ -180,20 +152,12 @@ async function start() {
})
}
- // The stream connects to the Host directly; the Host accepts only its own origin and cookie.
- session.defaultSession.webRequest.onBeforeSendHeaders({ urls: ['ws://127.0.0.1/*'] }, (details, callback) => {
- if (hostState === undefined || details.webContentsId !== mainWindow?.webContents.id) { callback({}); return }
- const target = new URL(hostState.url)
- if (new URL(details.url).host !== target.host) { callback({}); return }
- const headers = Object.fromEntries(Object.entries(details.requestHeaders).map(([name, value]) => [name.toLowerCase(), value]))
- if (headers.origin !== APP_ORIGIN) { callback({ cancel: true }); return }
- callback({ requestHeaders: { ...headers, origin: target.origin, cookie: hostState.cookie, 'sec-fetch-site': 'same-origin' } })
- })
-
setMenu()
// A packaged app has the icon in its bundle; Electron's own run shows Electron's.
if (process.platform === 'darwin' && !app.isPackaged) app.dock?.setIcon(iconFile)
createWindow()
+ // The launch URL trades its token for the Host's cookie and goes on to the page.
+ void ready.then(({ url }) => mainWindow?.loadURL(url)).catch(() => {})
}
// The Host starts once on the new data location first: DSH then sets up its project list
@@ -299,7 +263,7 @@ async function moveData(workspace) {
const signal = copyAbort.signal
copying = (async () => {
// The settings go away first, so that nothing moves the team workspace from here on.
- void mainWindow?.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(movingPage(t.moving))}`)
+ void mainWindow?.loadURL(notePage(t.moving))
await stopHost()
// The app may have heard of a team workspace change while the Host stopped.
if (await refused()) {
@@ -337,8 +301,8 @@ async function moveData(workspace) {
return true
}
-const movingPage = message => `<!doctype html><meta charset="utf-8"><meta name="color-scheme" content="light dark">
-<body style="margin:0;height:100vh;display:grid;place-items:center;font:14px system-ui,sans-serif;background:Canvas;color:CanvasText">${message.replace(/[&<>]/gu, char => `&#${String(char.charCodeAt(0))};`)}</body>`
+const notePage = message => `data:text/html;charset=utf-8,${encodeURIComponent(`<!doctype html><meta charset="utf-8"><meta name="color-scheme" content="light dark">
+<body style="margin:0;height:100vh;display:grid;place-items:center;font:14px system-ui,sans-serif;background:Canvas;color:CanvasText">${message.replace(/[&<>]/gu, char => `&#${String(char.charCodeAt(0))};`)}</body>`)}`
// Windows updates itself; macOS asks to download the new version. Throwaway runs check only a
// given feed and never ask.
@@ -390,7 +354,7 @@ function createWindow() {
} : {}),
webPreferences: {
preload: join(here, 'preload.cjs'), contextIsolation: true, sandbox: true,
- additionalArguments: win32 ? [`--ds-bot-caption=${String(CAPTION_HEIGHT)}`, ...(mica ? ['--ds-bot-mica'] : [])] : [],
+ additionalArguments: [`--ds-bot-origin=${origin}`, ...(win32 ? [`--ds-bot-caption=${String(CAPTION_HEIGHT)}`, ...(mica ? ['--ds-bot-mica'] : [])] : [])],
},
})
mainWindow.once('ready-to-show', () => { mainWindow?.show() })
@@ -409,9 +373,24 @@ function createWindow() {
const css = readFileSync(join(here, 'mica.css'), 'utf8')
contents.on('dom-ready', () => { void contents.insertCSS(css) })
}
- contents.setWindowOpenHandler(({ url }) => { openOutside(url); return { action: 'deny' } })
+ contents.setWindowOpenHandler(({ url }) => {
+ // DSH's sign-in opens a blank window during the click and sends it to the sign-in page later.
+ if (url === 'about:blank') return { action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { sandbox: true } } }
+ openOutside(url)
+ return { action: 'deny' }
+ })
+ contents.on('did-create-window', (child) => {
+ const away = (event, url) => {
+ if (url === 'about:blank') return
+ event.preventDefault()
+ openOutside(url)
+ child.destroy()
+ }
+ child.webContents.on('will-navigate', away)
+ child.webContents.on('will-redirect', away)
+ })
contents.on('will-navigate', (event, url) => {
- if (url.startsWith(`${APP_ORIGIN}/`)) return
+ if (url.startsWith(`${origin}/`)) return
event.preventDefault()
openOutside(url)
})
@@ -420,7 +399,7 @@ function createWindow() {
if (input.type === 'keyDown' && (input.key === 'F12' || (input.control && input.shift && input.key.toLowerCase() === 'i'))) contents.toggleDevTools()
})
}
- void mainWindow.loadURL(`${APP_ORIGIN}/`)
+ void mainWindow.loadURL(notePage(text().starting))
}
function setMenu() {
@@ -438,7 +417,7 @@ function focusWindow() {
function assertWindow(event) {
const contents = mainWindow?.webContents
if (contents === undefined || event.sender !== contents || event.senderFrame !== contents.mainFrame
- || !event.senderFrame.url.startsWith(`${APP_ORIGIN}/`)) throw new Error('DeepSeek Bot: rejected IPC from an unknown page')
+ || !event.senderFrame.url.startsWith(`${origin}/`)) throw new Error('DeepSeek Bot: rejected IPC from an unknown page')
}
function fromWindow(event) {
diff --git a/app/src/preload.cjs b/app/src/preload.cjs
index 22790459..348388d6 100644
--- a/app/src/preload.cjs
+++ b/app/src/preload.cjs
@@ -1,15 +1,12 @@
-// Gives the DSH Web entry the boot handshake it uses inside an app window. On Windows it also
-// marks the page for the frameless window the way DSH Desktop's preload does
+// Gives the page that the app's Host serves the app's own bridge. On Windows it also marks the
+// page for the frameless window the way DSH Desktop's preload does
// (apps/desktop/src/preload-windows.ts, preload-platform.ts and preload-theme.ts; see NOTICE),
// but without data-platform: that puts DSH's shortcuts on native menu input, which this
// window does not have.
const { contextBridge, ipcRenderer } = require('electron')
-if (location.protocol === 'dsh-app:' && location.hostname === 'app') {
- contextBridge.exposeInMainWorld('dshDesktopBoot', {
- ready: () => ipcRenderer.invoke('ds-bot:boot'),
- failed: (message) => ipcRenderer.invoke('ds-bot:boot-failed', String(message)),
- })
+const host = process.argv.find(value => value.startsWith('--ds-bot-origin='))?.slice('--ds-bot-origin='.length)
+if (host !== undefined && location.origin === host) {
// DS Bot's settings show and move the app's data location through this.
contextBridge.exposeInMainWorld('dsBotApp', {
dataLocation: () => ipcRenderer.invoke('ds-bot:data-location'),
diff --git a/app/src/web.mjs b/app/src/web.mjs
deleted file mode 100644
index 24b77b4c..00000000
--- a/app/src/web.mjs
+++ /dev/null
@@ -1,89 +0,0 @@
-// The local Web document and the authenticated request forwarding for the app window.
-// Adapted from DeepSeek Harness apps/desktop/src/web-document.ts (MIT); see NOTICE.
-import { readFile } from 'node:fs/promises'
-import { extname, resolve, sep } from 'node:path'
-
-export const APP_ORIGIN = 'dsh-app://app'
-
-const MIME = {
- '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
- '.css': 'text/css; charset=utf-8', '.svg': 'image/svg+xml', '.json': 'application/json',
- '.woff2': 'font/woff2', '.png': 'image/png', '.ico': 'image/x-icon',
-}
-// The Web entry waits on this gate until the shell hands over the Host's index injections.
-const BOOT = '<script>globalThis.__DSH_BOOT_READY__ = Promise.withResolvers()</script>'
-
-/**
- * Serve a file of the DSH Web build; the index gets the boot gate.
- * @param {Request} request - request from the app origin
- * @param {string} root - the Web build's `dist` directory
- * @returns {Promise<Response>}
- */
-export async function serveWebDocument(request, root) {
- if (!['GET', 'HEAD'].includes(request.method)) return new Response(null, { status: 405 })
- const url = new URL(request.url)
- let pathname
- try { pathname = decodeURIComponent(url.pathname) } catch { return new Response(null, { status: 400 }) }
- const target = resolve(root, '.' + (pathname === '/' ? '/index.html' : pathname))
- if (!target.startsWith(resolve(root) + sep)) return new Response(null, { status: 403 })
- let body
- try { body = await readFile(target) } catch (error) {
- if (error.code === 'ENOENT') return new Response(null, { status: 404 })
- throw error
- }
- const content = pathname === '/' || pathname === '/index.html'
- ? body.toString().replace('<head>', '<head>' + BOOT) : new Uint8Array(body)
- return new Response(request.method === 'HEAD' ? null : content, {
- headers: { 'content-type': MIME[extname(target)] ?? 'application/octet-stream' },
- })
-}
-
-/**
- * Exchange the Host's launch URL for its authority-bound cookie.
- * @param {string} url - authenticated URL reported by the Host
- * @returns {Promise<string>} the `name=value` cookie pair
- */
-export async function authenticateWebHost(url) {
- const response = await fetch(url, { redirect: 'manual' })
- const cookie = response.headers.get('set-cookie')
- await response.body?.cancel()
- if (response.status !== 303 || cookie === null) throw new Error('DeepSeek Bot: the DSH Host refused the launch token')
- const end = cookie.indexOf(';')
- return end < 0 ? cookie : cookie.slice(0, end)
-}
-
-// `set-cookie` would put the Host cookie into the page's cookie jar, which the shell owns instead;
-// the rest describe Node's own connection, which Chromium never sees.
-const WITHHELD_RESPONSE_HEADERS = [
- 'set-cookie',
- 'content-encoding', 'content-length',
- 'transfer-encoding', 'connection', 'keep-alive', 'te', 'trailer', 'upgrade', 'proxy-authenticate', 'proxy-authorization',
-]
-// The Host marks plugin bundles immutable under a revision that changes every launch.
-const PLUGIN_BUNDLE_PATH = /^\/plugins\//u
-
-/**
- * Forward a request from the app origin to the Host as a same-origin request with the Host cookie.
- * @param {Request} request - request from the app origin
- * @param {string} host - Host URL
- * @param {string} cookie - Host cookie pair
- * @returns {Promise<Response>}
- */
-export async function forwardWebRequest(request, host, cookie) {
- const source = new URL(request.url)
- const origin = request.headers.get('origin')
- if (origin !== null && origin !== APP_ORIGIN) return new Response(null, { status: 403 })
- const target = new URL(host)
- target.pathname = source.pathname
- target.search = source.search
- const headers = new Headers(request.headers)
- for (const name of ['host', 'origin', 'cookie', 'sec-fetch-site']) headers.delete(name)
- headers.set('cookie', cookie)
- const response = await fetch(target, {
- method: request.method, headers, body: request.body, signal: request.signal, duplex: 'half', redirect: 'manual',
- })
- const outgoing = new Headers(response.headers)
- for (const name of WITHHELD_RESPONSE_HEADERS) outgoing.delete(name)
- if (PLUGIN_BUNDLE_PATH.test(source.pathname)) outgoing.set('cache-control', 'no-store')
- return new Response(response.body, { status: response.status, headers: outgoing })
-}
diff --git a/app/test/host-port.test.mjs b/app/test/host-port.test.mjs
new file mode 100644
index 00000000..5fbd0049
--- /dev/null
+++ b/app/test/host-port.test.mjs
@@ -0,0 +1,38 @@
+import assert from 'node:assert/strict'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { createServer } from 'node:net'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { after, test } from 'node:test'
+import { hostPort } from '../src/host-port.mjs'
+
+const root = mkdtempSync(join(tmpdir(), 'ds-bot-app-port-'))
+after(() => { rmSync(root, { recursive: true, force: true }) })
+
+test('picks a free port once and keeps it', async () => {
+ const file = join(root, 'keep', 'host-port.json')
+ const port = await hostPort(file)
+ assert.ok(port > 0)
+ assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), { port })
+ assert.equal(await hostPort(file), port)
+})
+
+test('moves to another port when the saved one is taken', async (t) => {
+ const server = createServer()
+ await new Promise((resolve) => { server.listen(0, '127.0.0.1', resolve) })
+ t.after(() => { server.close() })
+ const taken = server.address().port
+ const file = join(root, 'taken.json')
+ writeFileSync(file, JSON.stringify({ port: taken }))
+ const port = await hostPort(file)
+ assert.notEqual(port, taken)
+ assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), { port })
+})
+
+test('takes a new port for a file it cannot read', async () => {
+ const file = join(root, 'broken.json')
+ writeFileSync(file, '{"port": "x"')
+ const port = await hostPort(file)
+ assert.ok(port > 0)
+ assert.deepEqual(JSON.parse(readFileSync(file, 'utf8')), { port })
+})
diff --git a/docs/plans/2026-10-16-desktop-app.md b/docs/plans/2026-10-16-desktop-app.md
index 67eff8a4..238b2245 100644
--- a/docs/plans/2026-10-16-desktop-app.md
+++ b/docs/plans/2026-10-16-desktop-app.md
@@ -18,8 +18,8 @@
| 部分 | 做什么 |
|---|---|
-| 壳 | Electron 主进程。只开一个实例;窗口用 `dsh-app://app` 加载 DSH 的网页前端,把请求转发给引擎;管引擎进程的启动和退出。窗口见下面「窗口」一节 |
-| 引擎 | 子进程,用 Electron 自带的 Node 运行。通过 `@deepseek-ai/dsh/profile-boot` 的 `runProfile()` 启动 profile `ds-bot`,只监听 `127.0.0.1` 上系统分配的端口。环境变量 `DS_BOT_APP=1` 告诉 ds-bot 它跑在桌面应用里 |
+| 壳 | Electron 主进程。只开一个实例;窗口加载引擎自己的本机地址(`http://127.0.0.1:端口`),和 DSH Web 一样由引擎提供网页前端;管引擎进程的启动和退出。窗口见下面「窗口」一节 |
+| 引擎 | 子进程,用 Electron 自带的 Node 运行。通过 `@deepseek-ai/dsh/profile-boot` 的 `runProfile()` 启动 profile `ds-bot`,只监听 `127.0.0.1`。端口第一次启动时选一个空闲的,之后一直用它:页面的本地存储(未读标记、布局、偏好)跟着地址走。端口被占用时换一个新的。环境变量 `DS_BOT_APP=1` 告诉 ds-bot 它跑在桌面应用里 |
| 界面 | DSH 的网页前端加上 `ds-bot` 插件,和插件版一样 |
- 插件版和桌面应用用同一份 `ds-bot`,插件版不变。
@@ -130,3 +130,4 @@
- 2026-10-20:Windows 上窗口无边框,Windows 11 上侧栏用 Mica;macOS 仍用系统标题栏,Issue #362。
- 2026-10-20:macOS 改发 zip,不再发 dmg:macOS 26 上用 Safari 下载的未签名 dmg(arm64、x64,本机和 CI 打的都一样)显示「已损坏」,打不开;dmg 做 ad-hoc 签名也不行;zip 只被 Gatekeeper 拦下,可以「仍要打开」,Issue #351。
- 2026-10-20:设置里能换总工作区和数据位置;中文界面里「团队工作区」改叫「总工作区」,Issue #364。
+- 2026-10-20:窗口改为加载引擎的本机地址,不再用 `dsh-app://app`:DSH 的账号登录把页面地址当作浏览器登录完回来的地址,只接受本机 http 地址。DSH 打开的登录窗口交给系统浏览器,Issue #376。