# bgjobs — standalone background jobs for DSH

**English** · [中文](README.md)

[![npm version](https://img.shields.io/npm/v/bgjobs)](https://www.npmjs.com/package/bgjobs)
[![GitHub tag](https://img.shields.io/github/v/tag/bitsmug/dsh-bgjobs)](https://github.com/bitsmug/dsh-bgjobs/tags)
[![publish](https://github.com/bitsmug/dsh-bgjobs/actions/workflows/publish.yml/badge.svg)](https://github.com/bitsmug/dsh-bgjobs/actions/workflows/publish.yml)
[![License](https://img.shields.io/npm/l/bgjobs)](LICENSE)
[![Listed on dsh-plugin.org](https://dsh-plugin.org/badges/listed.svg)](https://dsh-plugin.org/plugins/bitsmug/dsh-bgjobs)
[![Awesome DSH Plugin](https://awesome-dsh-plugin.com/badge.svg)](https://github.com/awesome-dsh-plugin/awesome-dsh-plugin)

**Run commands outside the DSH process**: jobs are handed to the Windows Task Scheduler service, so closing the DSH process or the web page does not stop them; a floating panel in the web UI shows live output; and when DSH is offline you can still manage jobs with the standalone CLI/GUI.

Built for long-running work — large downloads, batch scripts, compilation, data sync/export — **a DSH crash (usually OOM) does not affect running jobs either**.

---

⚠️ **Upgrade notice:** MCP tasks are now provided by the `bgjob-mcp` plugin. Upgrading this plugin without installing `bgjob-mcp` will disable MCP tasks. History of MCP tasks will remain, but they will fail on restart.

---

## Quick install

1. Open the official DSH desktop client or the web page, click the "Plugins" entry in the left navigation bar, go to the plugin page and click "Add plugin" in the top-right corner;
2. Enter `bgjobs` in the plugin install box (or the latest from GitHub: `github:bitsmug/dsh-bgjobs`) and confirm; on the first install it asks you to allow `pnpm approve build` — click allow and install again.

## Table of contents

- [Quick install](#quick-install)
- [Feature overview](#feature-overview)
- [Prerequisites & compatibility](#prerequisites--compatibility)
- [Install / uninstall](#install--uninstall)
- [Web panel](#web-panel)
- [Offline CLI (works without DSH)](#offline-cli-works-without-dsh)
- [GUI](#gui)
- [Configuration & data](#configuration--data)
- [Notes & limits](#notes--limits)
- [Development](#development)
- [Contributing](#contributing)
- [Recent updates](#recent-updates)
- [License](#license)

## Feature overview

| Capability | Description |
|---|---|
| Runs outside DSH | Jobs are hosted via `schtasks`; a DSH crash/shutdown doesn't matter |
| Live output panel | Floating panel (bottom-right) refreshes every second: draggable, minimizable to a bubble, collapsible to a job list, theme-aware; grouped by workspace, resizable; the sidebar-bottom entry hides/shows it in one click. Rows show a live **Runtime** (growing while running, total time once done), and each field can be placed in the list / detail view / hidden |
| Manual cleanup | 🧹 click the cleanup icon to open the trash bar: drag a single finished job to delete, or bulk-clean (>24h only / all; follows the view filter). Jobs whose process state **cannot be determined** (the probe/lookup itself failed) first show a **warning confirmation box** (it spells out that continuing may leave an invisible orphan process and shows the original reason) — only 「confirm cleanup」 sends `force`; cancelling deletes nothing |
| Completion notice | Toast on exit (does not interrupt the session); optionally notify the creating agent (`notify` param) |
| In-session waiting | `bgjob_wait` lets the agent wait for results **without hogging the conversation**: unlimited by default (configurable via "Default wait timeout" in Settings), released immediately when a new inbound message yields or the user stops it; supports any-race and all-conjunctive (fail fast) modes |
| Reconnect & track | Auto-recovers after a DSH restart; old job ids can still be queried from disk |
| Offline management | CLI / GUI that don't need DSH: list / status / log / submit / kill (terminate processes) / delete (remove records) / cleanup |
| Optional sandbox | `bgjob_submit_pwsh` can pass `sandbox` to constrain job file permissions (never wider than the current session mode). With the **Sandbox selection** switch on (experimental, off by default) it can also pass `sandbox_backend: 'dsh'` to reuse the current session's dsh sandbox provider (`ctx.sandbox.confine`) instead, with support for the [dsh-sandbox-mxc](https://github.com/bitsmug/dsh-sandbox-mxc) backend (file and network constraints). Switch = panel "Sandbox selection" |
| MCP tool calls (optional plugin) | Moved to the separate `bgjob-mcp` plugin: it registers the `mcp` engine and provides `bgjob_submit_mcp` / `mcp_list_tools` plus the "MCP jobs" settings page. This package only exposes the engine registry (`ctx.bgjobEngines`); without that plugin `engine: 'mcp'` fails with `engine "mcp" not registered` (no fallback). MCP jobs created by older releases are no longer supported: they stay visible/cleanable but fail immediately with exit code `2` on re-run — re-submit them |
| No residue | A finished job removes its own scheduled task; done jobs stay visible until you clean them up |

## Prerequisites & compatibility

| Prerequisite | Compatible | Recommended |
|---|---|---|
| Windows | `10`-`11` | `11` (build `>=26300`) |
| PowerShell 7+ | `>=7.6.5` (sandbox features need the [zip build of PowerShell](https://learn.microsoft.com/zh-cn/powershell/scripting/install/install-powershell-on-windows?view=powershell-7.6#install-the-zip-package)) | [`>=7.7.0`](https://github.com/PowerShell/PowerShell/releases#release-v7.7.0-preview.5) |
| DSH | `0.1.2-rc.1` ~ `0.2.1-rc.3` (rc builds) ([official desktop build](https://www.deepseek.com/harness/) / run [npx @deepseek-ai/dsh web](https://github.com/deepseek-ai/deepseek-harness#run-from-npm) via Win+R) | `0.2.1-rc.3` |
| Node.js | `^22.19.0 \|\| >=24.0.0` (or automatically use the Node bundled with the official desktop build) | [`>=24.22.1`](https://nodejs.org/zh-cn/download) |

| Optional plugin | Compatible |
|---|---|
| [dsh-sandbox-mxc](https://github.com/bitsmug/dsh-sandbox-mxc) | `0.1.2` (latest version) |
| [dsh-multi-folder](https://github.com/AngelosZou/dsh-multi-folder) | `0.3.4` |
| bgjob-mcp | `0.1.0` (requires bgjobs `>=0.4.1-beta <0.5.0`) |

## Install / uninstall

**Method A (easiest: plugin manager (the GUI plugin entry); DSH >=0.2.0-rc.2)**`

1. Open the official DSH desktop client or the web page, click the "Plugins" entry in the left navigation bar, go to the plugin page and click "Add plugin" in the top-right corner;
2. Enter `bgjobs` in the plugin install box (or the latest from GitHub: `github:bitsmug/dsh-bgjobs`) and confirm; on the first install it asks you to allow `pnpm approve build` — click allow and install again.

**Method B (fast, npm release)**

```powershell
$pf="web"; dsh plugin --profile $pf add bgjobs || dsh plugin --profile $pf approve-builds koffi; dsh plugin --profile $pf add bgjobs && Write-Host "✓ bgjobs installed successfully!" -ForegroundColor Green
```

> Replace `web` with your own profile name and paste the whole line into PowerShell (pwsh). The first `add` raises `ERR_PNPM_IGNORED_BUILDS` (koffi build script not approved); `||` then automatically runs `approve-builds` to approve and build koffi, the second `add` succeeds, and "bgjobs installed" is printed.

**Method C (always latest, from GitHub)**

```powershell
$pf="web"; dsh plugin --profile $pf add github:bitsmug/dsh-bgjobs || dsh plugin --profile $pf approve-builds koffi; dsh plugin --profile $pf add github:bitsmug/dsh-bgjobs && Write-Host "✓ bgjobs installed successfully!" -ForegroundColor Green
```

> Pulls the default branch directly from the GitHub repo — **always the newest code** (published and unpublished alike), no registry-lag. All methods above install under the name `bgjobs`, so the uninstall command is the same.

**From dsh-market install fails with `ERR_PNPM_IGNORED_BUILDS`?**

The plugin depends on the native library `koffi`; installing it triggers a build script, and pnpm ≥10 blocks dependency build scripts by default (a GitHub install also runs `prepare`). The error looks like:

```
[ERR_PNPM_IGNORED_BUILDS] Ignored build scripts: koffi@3.2.1
dsh: pnpm failed in profile directory <your DSH home>\profiles\<profile>
```

Fix (replace `web` with your own `<profile>` name and paste the whole line into PowerShell (pwsh)):

```powershell
$pf="web"; dsh plugin --profile $pf approve-builds koffi; dsh plugin --profile $pf add bgjobs
```

The first command approves and runs koffi's build script; the second `add` then succeeds.

If your DSH version has no `approve-builds` subcommand, edit `pnpm-workspace.yaml` (the error prints its full path) manually: the failed `add` left a placeholder `set this to true or false` — change it to `true`, then re-run `add`:

```yaml
allowBuilds:
  koffi: true
```

Only the first install needs this — once koffi is compiled it stays compiled, and upgrades/reinstalls don't repeat the step.

Restart DSH afterwards (that means **fully quit and relaunch** — both the desktop client and the web version): the "Background Jobs Monitor" panel appears bottom-right of the web page and the agent gains `bgjob_submit` / `bgjob_config` / `bgjob_status` / `bgjob_wait` / `bgjob_list` / `bgjob_pending_list` / `bgjob_kill` / `bgjob_delete` tools (MCP tools and their settings page live in the optional bgjob-mcp plugin).

**Method D (local source)**

1. Put the repo in a local plugin directory (avoid non-ASCII in the path), e.g. `D:\dsh\plugins\bgjobs`;
2. Make DSH's module resolver find it (junction the plugin dir to DSH's `node_modules\bgjobs`, or add the dir to DSH's plugin scan paths); for local dev also run `pnpm install` once inside the plugin dir (sandbox runner deps, below);
3. Append the mount to `<DSH_HOME>\profiles\<profile>\cordis.patch.yml`:

```yaml
- insert:
    - id: bgjobs
      name: bgjobs
```

**Uninstall:** `dsh plugin --profile <profile> remove bgjobs`

> Methods B / C / D all need a **DSH restart** (fully quit and relaunch) to take effect.

## Web panel

Top bar, left to right: cleanup (opens the bottom trash bar: drag a finished job to delete, or bulk-clean >24h / all), collapse (to a compact job list), minimize (floating bubble anchored at the button). Toolbar **scope** is a three-way switch (persisted by the host, so it survives reloads and is shared across tabs): "Session" (only jobs submitted by the current session; legacy jobs without a creator are kept), "Workspace" (the current session's workspace, incl. subdirectories), and "All" (no filtering). If the active session cannot be resolved it degrades automatically (session → workspace → all) and the echo shows what is actually in effect; hiding this control in Settings disables filtering. There is also a "Full access" toggle (pre-approve full-access jobs; off by default). Click a job row to expand its live log. Rows show a live "Runtime" by default (growing while running, total time once done); move it to the detail view or hide it under Settings → Background Jobs → Field display. Panel copy follows the DSH UI language (Chinese DSH → Chinese panel, otherwise English).

**Sidebar entry**: the left sidebar (chat-list column) has a bgjobs entry at the bottom — at full width it shows "Background Jobs", collapsed to a narrow rail it is the icon only. Click it to hide/show the whole floating panel; while the panel is hidden, jobs keep running and completion toasts still pop. The entry can be toggled under **DSH Settings → Background Jobs** (**hidden by default**).

**The bgjobs page in DSH Settings** (gear at the bottom-left): one page — "Background Jobs" — and the panel's title bar ⚙ opens it (hide it under Settings → Background Jobs → UI elements). With the optional bgjob-mcp plugin installed, it adds a "MCP jobs" page and a data-gear shortcut of its own.

- "Background Jobs" (shows the current plugin version): ① sidebar-entry toggle (off by default; turning it on adds an entry at the bottom of the sidebar — click it to hide/show the floating panel); ② monitor-panel toggle (show/hide the floating panel and bubble, independent of the entry); ③ **"Default wait timeout"** (number input + Save): the default `timeoutSeconds` for `bgjob_wait` when the agent omits it — `0`/empty means unlimited; ④ Open the offline GUI in its own window (the row shows the GUI script path); ⑤ Open the tools folder in File Explorer (find `dsh-bgjobs-gui.bat` there if the GUI won't open); ⑥ **Field display**: place each job field in the list / detail view / hidden (includes the "Runtime" field); ⑦ the **"Hide task window (experimental)"** toggle (off by default).

## Offline CLI (works without DSH)

```powershell
# run from the tools/ directory
.\dsh-bgjobs.ps1 list
.\dsh-bgjobs.ps1 status -Id <id>
.\dsh-bgjobs.ps1 log -Id <id> [-Tail 100]
.\dsh-bgjobs.ps1 submit -Name <n> -Command <c> -Workdir <dir> [-Pwsh]
.\dsh-bgjobs.ps1 kill -Id <id> [-Force]                    # terminate processes only (records kept; writes the non-zero exit code 1 = the value taskkill records)
.\dsh-bgjobs.ps1 delete -Id <id> [-NoDeleteDir] [-Force]   # remove records only (refused while a live process remains — kill first)
.\dsh-bgjobs.ps1 cleanup [-OlderThanHours 24]   # 0 = clean all
.\dsh-bgjobs.ps1 index -Workdir <dir>
```

When the process state **cannot be determined** (the probe/lookup itself failed) nothing is done by default: the CLI
prints a warning and exits with code `3`; add `-Force` to go ahead (the GUI's equivalent is the "cannot determine
process state" confirmation box).

## GUI

Double-click `tools\dsh-bgjobs-gui.bat` to open a standalone window (no DSH needed): job list/log, submit (bat or pwsh), kill processes (records kept), delete records (finished / no-process jobs only), cleanup (custom age cutoff or all), rebuild index. The toolbar's **"📌 Desktop shortcut"** button creates a shortcut to this GUI on the current user's desktop in one click (double-click to open, no console window flash). GUI and Toast copy follow the Windows UI language (zh* → Simplified Chinese, otherwise English); the CLI prints English. **Can't find the GUI?** DSH Settings → Background Jobs → "Open the offline GUI" / "Open the tools folder" launches it or locates the script.

## Configuration & data

### Environment variables

All of the following are **optional** (usually nothing to set):

- `BGJOBS_SANDBOX_RUNNER` — explicit path to the sandbox runner (auto-detected by default; a sandbox submission fails loudly when none is found).
- `BGJOBS_DSH_HOME` — the "portable-first" home for the offline GUI/CLI; set it explicitly when you need to pin it down (v0.1.89).
- `DSH_HOME` — source of the global state directory (state lives under `$DSH_HOME\bgjobs\`); usually provided by DSH.
- `DSH_DESKTOP_NODE_EXECUTABLE` — where the desktop build's runtime node comes from (the "real node" a sandboxed job needs is preferred from there).
- `BGJOBS_PWSH`  explicit path to the PowerShell interpreter.

### Data & storage

- Job data: `<workdir>\.dsh\bgjobs\<jobId>\` (`job.json` metadata, `stdout.log` output, `exitcode.txt` exit code; MCP jobs also have `mcp.json` for the call spec and `result.json` for the outcome);
- Global state: `$DSH_HOME\bgjobs\` (`index.json` job "map", `fullaccess.json` full-access switch, `ui-prefs.json` web UI prefs, `mcp-*.json` MCP switch/registry/cache; 
- `done` jobs persist by default until you clean them (panel 🧹 / CLI cleanup / GUI).

## Notes & limits

- `workdir` must be an absolute path inside a DSH workspace;
- Jobs run by default "only while the user is logged in": closing DSH/the terminal is fine, but **logging out of Windows terminates jobs**;
- Don't put `> log`-style redirects in your command (the plugin already redirects all output and guarantees UTF-8);
- **Sandbox**: `sandbox` only constrains file effects (writes outside the workspace/temp area are denied), network is unrestricted; it is "best effort", not a mathematical boundary — it fails if the workdir sits in an Everyone-writable location; sandboxed job dirs are readable by local users (the script text is visible); bat-engine jobs are always full-access, so restricted sessions must enable "Full access" to submit them;
- In a restricted session, requesting more than the session mode triggers an approval prompt — put the reason in `justification`. The panel's **"Full access" switch does not change the session access mode** (it does not touch DSH's mode): it only decides whether such a wider request is approved via that prompt (off) or let through directly (on), and the job is still persisted with its resolved mode.

## Development

Architecture, mechanism details, testing and release flow: see [docs/developer.md](docs/developer.md).

## Contributing

Issues and PRs are welcome: bug reports, panel / CLI experience, docs and translations (the Chinese and English mirrors must be kept in sync) are all good to file.

- Repository: <https://github.com/bitsmug/dsh-bgjobs>
- Issues and suggestions: <https://github.com/bitsmug/dsh-bgjobs/issues>

## Recent updates

**v0.4.2**

- **⚠️Upgrade notice:** MCP tasks are now provided by the `bgjob-mcp` plugin. Upgrading this plugin without installing `bgjob-mcp` will disable MCP tasks. History of MCP tasks will remain, but they will fail on restart.

**v0.4.1-beta**

- **New: three-state panel scope (current session / current workspace / all)**: upgrades the previous "current session only" boolean into a three-way selector; the choice is **persisted to the host** in `ui-prefs.json` (the `scope` key, shared across panels and tabs). It also fixes the long-standing bug where the setting had no effect on DSH 0.2.x — the old implementation read `SessionListState.current` (a field that no longer exists and was always `undefined`); it now determines the active session via the session's `retainedBy.mainView > 0` (0.1.x has no `retainedBy`, so it automatically falls back to `current`). "Session" filters by the job's creator session (older records without a creator are kept, so nothing disappears), and "workspace" keeps the path-prefix semantics. When no active session can be resolved it degrades automatically, and when the control is hidden on the settings page nothing is filtered. **Note**: because of that old bug the setting was effectively "no filtering", so after upgrading the default "session" mode really will start filtering — the first frame may show fewer jobs, which is expected.
- **New panel switch "Hide job windows (experimental)"**: when Win11 delegates the console to Windows Terminal, the `pwsh`/`node` processes started by the scheduled task pop up a visible terminal window; with the switch on, launching goes through the bundled static asset `launch.vbs` (`wscript.exe`, GUI subsystem) instead, hiding the window without affecting the exit code, process tree, or the sandbox chain. **Off by default** (off is byte-for-byte identical to the old behavior); if WSH is disabled by policy it automatically falls back to the original path and shows a notice; it only affects jobs submitted after the switch is turned on.
- **New engine registry**: built-in `bat` / `pwsh`; third-party plugins can register their own engines (`supportsSandbox` decides whether sandboxing is allowed). Unregistered engines always fail closed (they error out rather than falling back to another engine).

## License

MIT — see [LICENSE](LICENSE).
