Deleting a Session: DeepSeek Harness Plugin

Preface

In DeepSeek Harness (DSH), once you accumulate a large number of sessions, deleting them one by one from the workspace list is both time-consuming and prone to accidental deletions. The built-in “Archive” feature merely hides sessions while their files remain on disk, making it unsuitable for reclaiming disk space. Below is an introduction to a two-phase deletion plugin: first, sessions are moved to a trash bin (fully restorable), and after confirmation, their logs, caches, registrations, and accounting records are permanently purged.

Plugin Overview

  • Name: dsh-session-purge
  • Maintainer: jh0oo
  • Category: Memory
  • Core value: Adds a “Delete Sessions” entry above the “Workspaces” section in the sidebar, lists all sessions in a workspace, and after multi-selection, moves them to trash first, then permanently deletes them.

Installation

The plugin is installed as a tarball. It must be packaged from within the plugin directory with a package/ prefix:

tar -czf dsh-session-purge-0.1.10.tgz --transform 's,^,package/,' \
  index.js client.js lib locale cordis.patch.yml icon.svg README.md CHANGELOG.md LICENSE package.json test tools

After packaging, point the plugin manager’s install_bundle to the tgz file, or select the local package via “Settings → Plugins” on the desktop client.

UI & Interaction

The sidebar adds a new row (icon + “Delete Sessions”) after all built-in panels, directly above the “Workspaces” heading. Clicking it opens the management page in the main area, which has two tabs: “Sessions” and “Trash”.

  • Sessions tab: Lists all sessions in the workspace. Single-clicking a row toggles selection. The “Select All” button in the upper-right corner selects all deletable sessions at once. The “Delete” button in the lower-right corner is grayed out when nothing is selected.
  • Confirmation dialog: Clicking Delete pops up a confirmation dialog with the fixed title “Are you sure you want to delete these sessions?” The body lists the scope of records to be moved and the session titles. More than 6 titles are collapsed into “…and N more sessions”. The dialog captures focus, Tab navigation is restricted to within the dialog, and pressing Esc closes it and returns focus to its original position.
  • Trash tab: Shows deleted sessions. Each row displays the title, deletion time, size, and expiry time. You can click “Restore” to return the session to its original location (bytes, title, and workspace position are all restored) or “Delete Permanently” (irreversible). The “Empty Trash” button in the upper-right corner permanently deletes all sessions in the trash at once.

Trash Behavior

  • Directory: ~/.dsh/storages/dsh-session-purge/trash/, with index file index.json.
  • Retention period: Defaults to 30 days (config item config.trashRetentionDays, clamped between 1 and 3650 days). Expired entries are automatically purged the next time the trash is opened.
  • Restore: Moves the session log directory, projection cache, and session policy back to their original locations, re-registers the session in the workspace, and restores its original archive/pin status. Bytes are identical — this is a restoration, not a regeneration.
  • Effective timing: The moment a session is moved to trash, its workspace registration and accounting records are cleaned up. Therefore, sessions in the trash will not appear in the sidebar, will not participate in cost statistics, and will no longer be targeted by scheduled tasks.
  • Unreadable expiry time: Entries with unreadable expiry times are never automatically purged — it is better to keep them than to risk deleting valid data.

What Permanent Deletion Removes

Each selected session is processed in the following sequence:

  1. Host release: Instructs the Harness itself to remove the agent/session from its in-memory registry (agents.detachEntered / sessions.detachEntered).
  2. Workspace registration: Removes the session from storages/workspace.json → tables.workspaces[*].sessionIds, and from global.archivedSessionIds / global.pinnedSessionIds.
  3. Session log directory: Deletes ~/.dsh/sessions/<slug>/<sessionId>/ (including session.v4.jsonl.zstd). If the parent slug directory becomes empty, it is also cleaned up (up to 3 levels, stopping at ~/.dsh, sessions, and storages).
  4. Projection cache: Deletes storages/session_projcache/sessions/<id>.json.
  5. Session policy: Deletes storages/vision_router_session_policy/policies/<id>.json.
  6. Workspace ledger: Covered in step 2.
  7. Cost accounting: Removes the session’s accounting entries from storages/cost-meter/ledger.json → days[*].sessions[], and deletes its cursors from usageCursors.
  8. Context overview cache: Removes the entry by id from storages/dsh-context/overview-cache.v1.json → sessions[].
  9. Scheduled task references: Removes the session from storages/schedule.json → involvedSessionIds. If a task’s target.sessionId points to the deleted session, it is re-pointed to the task’s built-in fallback target (session-schedule-<sha256>), and the task itself is preserved.
  10. Orphaned attachments: Only deletes attachments that are “referenced by the selected session and no longer referenced by any live session” (tracked by sha256 reference counting).

Intentionally left untouched:
- Documents created within the workspace (the session’s cwd is the user’s directory).
- Daily-aggregated cost statistics (account-level history).
- Scheduled tasks themselves (see step 9).

Safety Design

The plugin enforces deletion safety through multiple layers of guards:

  • Batch pre-check: If even one session is non-deletable (running / current session / path out of bounds / actively being written), the entire batch is aborted.
  • Activity detection: If an agent is in the running state, or the in-memory store still holds the session, deletion is refused.
  • Current session: The session you are actively conversing in can never be deleted.
  • Quiescence check: Reads the log file’s size+mtime twice (240 ms apart); if still changing, the file is considered actively being written and deletion is refused.
  • Path fencing: The target must be located under sessions/ or storages/, and must not point to the plugin’s own storage directory.
  • Single entry point: Only one POST route is registered; all non-POST requests receive 405. Only requests from the loopback address are accepted.
  • Explicit confirmation: Destructive methods must include confirm: true, otherwise a 400 is returned.
  • No tool registration: No deletion tool is exposed to the model, no CLI commands exist. The only entry point is the UI.
  • Idempotency: If a session directory no longer exists, it is treated as “already cleaned” rather than an error.
  • Deletion order: Deregister first, then delete bytes. Leaving the registry entry while deleting the log would cause a fatal error on the host’s next startup; the reverse merely leaves orphaned logs.
  • Abort on deregistration failure: When deregistering via the host API, if the registry still references the session, the deletion is abandoned and a failure is reported.
  • Restore must not mis-attach: When calling async methods like attachSession, await is mandatory. IDs unknown to the host are never passed to attachSession.

Write Robustness

To prevent fatal errors caused by rename hitting EPERM/-4048 on Windows, ledger writes use four layers of protection:

  1. Atomic temp file: Uses .${randomUUID()}.tmp, writes the full content, then performs rename.
  2. Backoff retry: For EPERM/EACCES/EBUSY/EAGAIN/EMFILE/ENOENT, exponential backoff starting at 60 ms, up to 6 attempts.
  3. Snapshot comparison: Records mtimeMs+size at read time; if modified by another process before writing, the current write is abandoned and retried.
  4. Post-write verification: After writing, re-reads the file to confirm the target id has truly disappeared; if verification fails, another round is executed.

Directory deletion also uses 4 rounds of backoff, and on failure prompts the user to disable antivirus real-time scanning.

Rescue Script for a Broken Application

The plugin itself loads only after the host has fully started, so it cannot repair a system that is “already broken”. The repository provides a standalone rescue script tools/repair-ledger.mjs that does not depend on the plugin being active:

node tools/repair-ledger.mjs              # Dry-run only; exits with code 1 if issues found
node tools/repair-ledger.mjs --apply      # Actually apply fixes
node tools/repair-ledger.mjs --apply --home "D:\other\.dsh"

It performs three actions, all of which are “remove references to sessions that no longer exist”:
1. Remove dangling members: Deletes ids from workspace.json → tables.workspaces[*].sessionIds, global.archivedSessionIds, and global.pinnedSessionIds whose logs no longer exist.
2. Clean orphaned indexes: Removes records pointing to non-existent sessions from storages/session_projcache/sessions/ and storages/vision_router_session_policy/policies/ (including .bak.<stamp> variants).
3. Tidy up directories: Deletes empty session directories and empty slug directories.

Exit codes: 0 clean or repaired, 1 issues found but --apply not specified, 2 invalid path (no storages/ directory), 3 unexpected error.

Tests

npm test     # atomic(26) + schedule(21) + trash(59) + order(18) + e2e(47) + guard(17) + restore-unknown(23)
#   = 211 assertions

All tests run on a temporary DSH_HOME. The test harness asserts at the start that the temp directory is not inside the real profile, and at the end verifies that no test session ids have leaked into the real profile.

Use Cases & Caveats

Suitable for DSH users who need batch session management, want trash-bin protection, and clearly understand which files permanent deletion will clean up.

Caveats:
- The plugin runs with the current DSH process privileges. Review the source code and license before installation.
- Permanent deletion is irreversible. Proceed with caution.
- If the host fails to start due to an incorrect deletion order, use tools/repair-ledger.mjs to clean up dangling references.

Summary

The session deletion plugin provides DSH with a safe two-phase deletion capability: first moving sessions to a restorable trash bin, then permanently purging logs, caches, registrations, and accounting records. Through batch pre-checks, path fencing, explicit confirmation, and strict deletion ordering, it prevents accidental deletions or host startup breakage. It also provides a rescue script and robust write mechanisms to reduce the risk of disk corruption.

  • Directory page: https://www.skillhub.cn/plugins/jh0oo/dsh-session-purge
  • GitHub: https://github.com/jh0oo/dsh-session-purge
羽毛球分组比赛记分
小程序二维码

欢迎使用《羽毛球分组比赛记分》微信小程序

Xiaoye