dsh-linked-workspace 0.26.1 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js CHANGED
@@ -23,7 +23,9 @@ import { appendFile, mkdir, readdir, rename, rm, stat as fsStat } from 'node:fs/
23
23
  import { homedir, tmpdir } from 'node:os'
24
24
  import { basename, dirname, extname, isAbsolute, join, posix, resolve, sep } from 'node:path'
25
25
  import { fileURLToPath } from 'node:url'
26
+ import { createRequire } from 'node:module'
26
27
  import { forgetKnownHost, listHosts, listKnownHosts, RemoteHost, SshError, writeLocalCredential } from './ssh.js'
28
+ import { renderMarkdownFragment } from './markdown.js'
27
29
  import * as linkedFs from './linked.js'
28
30
  import * as git from './git.js'
29
31
 
@@ -39,7 +41,7 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'workingDirectory']
39
41
  * is still running an older copy of the Host — refreshing the page only swaps
40
42
  * the browser bundle, so the two halves can drift by one restart.
41
43
  */
42
- const API_REVISION = 11
44
+ const API_REVISION = 14
43
45
 
44
46
  /** When this copy of the Host was loaded; shown by `meta.info`. */
45
47
  const STARTED_AT = new Date().toISOString()
@@ -56,10 +58,51 @@ const PACKAGE_VERSION = (() => {
56
58
 
57
59
  const DATA_VERSION = 1
58
60
  const SETTINGS_VERSION = 1
59
- const SETTINGS_DEFAULTS = Object.freeze({ editorTheme: 'github-light', editorThemeFamily: 'github', editorThemeMode: 'system', fileOpenMode: 'editor', autoSave: false, execEnabled: false, execTimeoutMs: 60000, execMaxOutputChars: 200000, execShell: '', autoPushEnabled: false, autoPushDebounceMs: 1500, hostKeyPolicy: 'tofu', outputEncoding: 'utf8' })
61
+ // The chat's `present` tool records the files it showed; the newest one per
62
+ // session is what the directory panel's locate button jumps to.
63
+ const lastArtifacts = new Map()
64
+
65
+ function artifactPathsOf(value, depth, out) {
66
+ if (!value || depth > 5) return out
67
+ if (Array.isArray(value)) {
68
+ for (const item of value) artifactPathsOf(item, depth + 1, out)
69
+ return out
70
+ }
71
+ if (typeof value !== 'object') return out
72
+ for (const [key, item] of Object.entries(value)) {
73
+ if (/^(path|paths|file|files|filePath|filePaths|target|targets)$/i.test(key)) {
74
+ if (typeof item === 'string' && item.trim() !== '') out.push(item.trim())
75
+ else if (Array.isArray(item)) artifactPathsOf(item, depth + 1, out)
76
+ } else {
77
+ artifactPathsOf(item, depth + 1, out)
78
+ }
79
+ }
80
+ return out
81
+ }
82
+
83
+ function artifactToolName(event) {
84
+ const candidates = [event && event.name, event && event.tool, event && event.toolName,
85
+ event && event.data && event.data.name, event && event.data && event.data.tool]
86
+ for (const candidate of candidates) {
87
+ if (typeof candidate === 'string' && candidate !== '') return candidate
88
+ }
89
+ return ''
90
+ }
91
+
92
+ function rememberArtifact(sessionId, event) {
93
+ if (typeof sessionId !== 'string' || sessionId === '') return
94
+ if (artifactToolName(event) !== 'present') return
95
+ const payload = (event && event.data) || (event && event.payload) || event
96
+ const paths = artifactPathsOf(payload, 0, [])
97
+ if (paths.length === 0) return
98
+ lastArtifacts.set(sessionId, { path: paths[paths.length - 1], at: Date.now() })
99
+ }
100
+
101
+ const SETTINGS_DEFAULTS = Object.freeze({ editorTheme: 'github-light', editorThemeFamily: 'github', editorThemeMode: 'system', fileOpenMode: 'editor', autoSave: false, execEnabled: false, execTimeoutMs: 60000, execMaxOutputChars: 200000, execShell: '', autoPushEnabled: false, autoPushDebounceMs: 1500, revealSide: 'remote', hostKeyPolicy: 'tofu', outputEncoding: 'utf8' })
60
102
  const AUTO_PUSH_DEBOUNCE_MIN = 300
61
103
  const AUTO_PUSH_DEBOUNCE_MAX = 60000
62
104
  /** `tofu` trusts a new host key once; `strict` refuses one it has never seen. */
105
+ const REVEAL_SIDES = new Set(['remote', 'local'])
63
106
  const HOST_KEY_POLICIES = new Set(['tofu', 'strict'])
64
107
  /** Command output encoding: `utf8` for POSIX hosts, `gbk` for Chinese Windows. */
65
108
  const OUTPUT_ENCODINGS = new Set(['utf8', 'gbk'])
@@ -519,6 +562,9 @@ class SettingsStore {
519
562
  this.value.autoPushExclude = normalizeStringList(settings.autoPushExclude)
520
563
  this.value.extraRoots = normalizeStringList(settings.extraRoots)
521
564
  }
565
+ if (settings && typeof settings === 'object' && REVEAL_SIDES.has(settings.revealSide)) {
566
+ this.value.revealSide = settings.revealSide
567
+ }
522
568
  if (settings && typeof settings === 'object' && HOST_KEY_POLICIES.has(settings.hostKeyPolicy)) {
523
569
  this.value.hostKeyPolicy = settings.hostKeyPolicy
524
570
  }
@@ -635,6 +681,10 @@ class SettingsStore {
635
681
  if (!Array.isArray(patch.autoPushExclude)) throw new ApiError('BAD_REQUEST', '自动推送排除列表必须是字符串数组')
636
682
  this.value.autoPushExclude = normalizeStringList(patch.autoPushExclude)
637
683
  }
684
+ if (patch && typeof patch === 'object' && patch.revealSide !== undefined) {
685
+ if (!REVEAL_SIDES.has(patch.revealSide)) throw new ApiError('BAD_REQUEST', '产物默认打开位置无效')
686
+ this.value.revealSide = patch.revealSide
687
+ }
638
688
  if (patch && typeof patch === 'object' && patch.extraRoots !== undefined) {
639
689
  if (!Array.isArray(patch.extraRoots)) throw new ApiError('BAD_REQUEST', '额外根目录必须是字符串数组')
640
690
  this.value.extraRoots = normalizeStringList(patch.extraRoots)
@@ -1339,6 +1389,8 @@ export function apply(ctx) {
1339
1389
 
1340
1390
  const describeLink = (record, runningKeys) => {
1341
1391
  const host = pool.host(record.hostId)
1392
+ // Skip workspaces whose host is gone from SSH config to avoid blocking
1393
+ if (!host) return null
1342
1394
  const snapshot = record.hostSnapshot || {}
1343
1395
  const workspace = findWorkspaceByPath(linkedRegistry(), record.localPath)
1344
1396
  return {
@@ -1366,6 +1418,8 @@ export function apply(ctx) {
1366
1418
 
1367
1419
  const describeRemote = (record) => {
1368
1420
  const host = pool.host(record.hostId)
1421
+ // Skip workspaces whose host is gone from SSH config
1422
+ if (!host) return null
1369
1423
  const snapshot = record.hostSnapshot || {}
1370
1424
  return {
1371
1425
  id: record.id,
@@ -3866,15 +3920,11 @@ export function apply(ctx) {
3866
3920
  const current = await readDocBytes(target, target)
3867
3921
  text = decodeUtf8(current.data)
3868
3922
  }
3869
- const temp = await makeDocTemp()
3870
- try {
3871
- const input = temp.file('preview.md')
3872
- writeFileSync(input, text, 'utf8')
3873
- const data = await runDocTool(['md-preview', '--file', input])
3874
- return data
3875
- } finally {
3876
- temp.cleanup()
3877
- }
3923
+ // Rendered in-process on purpose: the previous implementation shelled out
3924
+ // to `node scripts/md-to-html.mjs`, and a DSH process without `node` on its
3925
+ // PATH silently fell back to a plain renderer — every formula came out as
3926
+ // raw `$$…$$` text.
3927
+ return { kind: 'markdown-preview', html: renderMarkdownFragment(text) }
3878
3928
  },
3879
3929
 
3880
3930
  async 'docs.mdPdf'(params = {}) {
@@ -4730,6 +4780,14 @@ export function apply(ctx) {
4730
4780
  * The client half has no way to read a session's cwd, so the '@' reference
4731
4781
  * source asks for it here instead of guessing.
4732
4782
  */
4783
+ async 'linked.lastArtifact'(params = {}) {
4784
+ const sessionId = typeof params.sessionId === 'string' ? params.sessionId : ''
4785
+ if (sessionId === '') throw new ApiError('BAD_REQUEST', 'sessionId 不能为空')
4786
+ const record = lastArtifacts.get(sessionId)
4787
+ if (!record) return { artifact: null }
4788
+ return { artifact: { path: record.path, at: record.at } }
4789
+ },
4790
+
4733
4791
  async 'linked.sessionScope'(params = {}) {
4734
4792
  const sessionId = typeof params.sessionId === 'string' ? params.sessionId.trim() : ''
4735
4793
  if (sessionId === '') throw new ApiError('BAD_REQUEST', '缺少 sessionId')
@@ -5043,7 +5101,7 @@ export function apply(ctx) {
5043
5101
  async 'linked.list'() {
5044
5102
  await refreshHosts()
5045
5103
  const running = await runningLocalKeys()
5046
- return { links: linkedStore.list().map((record) => describeLink(record, running)) }
5104
+ return { links: linkedStore.list().map((record) => describeLink(record, running)).filter(Boolean) }
5047
5105
  },
5048
5106
 
5049
5107
  async 'localWorkspace.create'(params = {}) {
@@ -5256,7 +5314,7 @@ export function apply(ctx) {
5256
5314
 
5257
5315
  async 'remote_workspaces.list'() {
5258
5316
  await refreshHosts()
5259
- return { workspaces: remoteStore.list().map((record) => describeRemote(record)) }
5317
+ return { workspaces: remoteStore.list().map((record) => describeRemote(record)).filter(Boolean) }
5260
5318
  },
5261
5319
 
5262
5320
  async 'remote_workspaces.create'(params = {}) {
@@ -5937,6 +5995,19 @@ export function apply(ctx) {
5937
5995
  },
5938
5996
  }
5939
5997
 
5998
+ ctx.effect(
5999
+ () =>
6000
+ ctx.on('session/event', (session, event) => {
6001
+ try {
6002
+ const sessionId = (session && session.id) || (event && event.sessionId)
6003
+ rememberArtifact(sessionId, event)
6004
+ } catch (error) {
6005
+ log('artifact tracking failed: ' + (error && error.message ? error.message : error))
6006
+ }
6007
+ }),
6008
+ 'dsh-linked-workspace: artifact tracking',
6009
+ )
6010
+
5940
6011
  ctx.effect(() => ctx.tools.register(linkedTool), 'dsh-linked-workspace: linked tool')
5941
6012
  ctx.effect(() => ctx.tools.register(localSkillsTool), 'dsh-linked-workspace: local skills tool')
5942
6013
  ctx.effect(
@@ -6010,6 +6081,19 @@ export function apply(ctx) {
6010
6081
  'dsh-linked-workspace: api',
6011
6082
  )
6012
6083
 
6084
+ // The markdown preview is injected into the host page, so it cannot use a CDN
6085
+ // for KaTeX's stylesheet or fonts. KaTeX CSS travels inside the preview HTML;
6086
+ // the font files it points at are served from the installed katex package.
6087
+ ctx.effect(
6088
+ () =>
6089
+ ctx.webServer.register({
6090
+ kind: 'prefix',
6091
+ path: KATEX_ASSET_PREFIX,
6092
+ handler: katexAssetHandler,
6093
+ }),
6094
+ 'dsh-linked-workspace: katex assets',
6095
+ )
6096
+
6013
6097
  ctx.effect(
6014
6098
  () => () => {
6015
6099
  pool.disposeAll().catch(() => {})
@@ -6078,6 +6162,67 @@ export function apply(ctx) {
6078
6162
 
6079
6163
  // ── response helpers ────────────────────────────────────────────────────────
6080
6164
 
6165
+ const KATEX_ASSET_PREFIX = '/dsh-linked-workspace/assets'
6166
+ const KATEX_ASSET_TYPES = {
6167
+ '.css': 'text/css; charset=utf-8',
6168
+ '.woff2': 'font/woff2',
6169
+ '.woff': 'font/woff',
6170
+ '.ttf': 'font/ttf',
6171
+ }
6172
+ const katexAssetRequire = createRequire(import.meta.url)
6173
+ // Only these names are reachable: katex.min.css plus the font files it declares.
6174
+ const KATEX_FONT_FILE = /^fonts\/[A-Za-z0-9_-]+\.(?:woff2|woff|ttf)$/
6175
+
6176
+ function katexDistDir() {
6177
+ try {
6178
+ return join(dirname(katexAssetRequire.resolve('katex/package.json')), 'dist')
6179
+ } catch {
6180
+ return null
6181
+ }
6182
+ }
6183
+
6184
+ function katexAssetHandler(req, res) {
6185
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
6186
+ res.writeHead(405, { allow: 'GET, HEAD', 'content-type': 'text/plain; charset=utf-8' })
6187
+ res.end('method not allowed')
6188
+ return
6189
+ }
6190
+ const root = katexDistDir()
6191
+ const rawUrl = String(req.url || '')
6192
+ const queryAt = rawUrl.indexOf('?')
6193
+ const pathPart = queryAt === -1 ? rawUrl : rawUrl.slice(0, queryAt)
6194
+ let rest = ''
6195
+ try {
6196
+ rest = decodeURIComponent(pathPart.slice(KATEX_ASSET_PREFIX.length)).replace(/^\/+/, '')
6197
+ } catch {
6198
+ rest = ''
6199
+ }
6200
+ const relative = rest === 'katex.min.css' || KATEX_FONT_FILE.test(rest) ? rest : ''
6201
+ if (!root || relative === '') {
6202
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
6203
+ res.end('not found')
6204
+ return
6205
+ }
6206
+ let body
6207
+ try {
6208
+ body = readFileSync(join(root, relative))
6209
+ } catch {
6210
+ res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
6211
+ res.end('not found')
6212
+ return
6213
+ }
6214
+ res.writeHead(200, {
6215
+ 'content-type': KATEX_ASSET_TYPES[extname(relative)] || 'application/octet-stream',
6216
+ 'content-length': String(body.length),
6217
+ 'cache-control': 'public, max-age=31536000, immutable',
6218
+ })
6219
+ if (req.method === 'HEAD') {
6220
+ res.end()
6221
+ return
6222
+ }
6223
+ res.end(body)
6224
+ }
6225
+
6081
6226
  function errorEnvelope(error) {
6082
6227
  return { ok: false, error: { code: error.code || 'INTERNAL', message: error.message || String(error) } }
6083
6228
  }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Markdown → HTML fragment, matching DSH's native pipeline
3
+ * (micromark + GFM + math, math rendered by KaTeX).
4
+ *
5
+ * The preview is injected into the host page with dangerouslySetInnerHTML, so
6
+ * this module returns a **fragment** (no doctype/head/body) that carries the
7
+ * KaTeX stylesheet with it — the host page does not ship KaTeX rules, and a
8
+ * CDN <link> is unreachable offline. Font files are served by the plugin
9
+ * itself under /dsh-linked-workspace/assets/katex/fonts/.
10
+ *
11
+ * Rendering happens in-process: shelling out to `node` would depend on a
12
+ * `node` that the DSH process may not have on its PATH (the plugin only needs
13
+ * to run inside DSH), and a missing one silently degraded every formula to
14
+ * raw `$$…$$` text.
15
+ */
16
+
17
+ import { readFileSync } from 'node:fs';
18
+ import { createRequire } from 'node:module';
19
+ import { dirname, join } from 'node:path';
20
+ import { micromark } from 'micromark';
21
+ import { gfm, gfmHtml } from 'micromark-extension-gfm';
22
+ import { math, mathHtml } from 'micromark-extension-math';
23
+ import katex from 'katex';
24
+
25
+ export const FONT_BASE = '/dsh-linked-workspace/assets/katex/fonts/';
26
+
27
+ function escapeHtml(str) {
28
+ return String(str).replace(/[&<>"']/g, (ch) => {
29
+ const map = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
30
+ return map[ch];
31
+ });
32
+ }
33
+
34
+ let cachedCss = '';
35
+
36
+ export function katexCss() {
37
+ if (cachedCss) return cachedCss;
38
+ const require = createRequire(import.meta.url);
39
+ const pkg = require.resolve('katex/package.json');
40
+ const cssPath = join(dirname(pkg), 'dist', 'katex.min.css');
41
+ let css = readFileSync(cssPath, 'utf8');
42
+ // KaTeX's stylesheet points at fonts/<name>.woff2; the plugin serves those.
43
+ css = css.replace(/url\((['"]?)fonts\//g, (match, quote) => `url(${quote}${FONT_BASE}`);
44
+ cachedCss = css;
45
+ return css;
46
+ }
47
+
48
+ /**
49
+ * Render markdown text to an HTML fragment that already contains everything it
50
+ * needs to look right (KaTeX rules + preview-scoped layout tweaks).
51
+ */
52
+ export function renderMarkdownFragment(markdown) {
53
+ let body = '';
54
+ try {
55
+ body = micromark(markdown, {
56
+ extensions: [gfm(), math()],
57
+ htmlExtensions: [
58
+ gfmHtml(),
59
+ // mathHtml() forwards these straight to katex.renderToString(), so they
60
+ // are KaTeX options — not renderer callbacks.
61
+ mathHtml({ throwOnError: false, errorColor: '#d73a49', strict: 'ignore', trust: false, output: 'html' }),
62
+ ],
63
+ });
64
+ } catch (error) {
65
+ // Never fail the preview: fall back to a plain <pre> of the source.
66
+ const message = error && error.message ? error.message : String(error);
67
+ body = `<pre class="rw-md-fallback">${escapeHtml(markdown)}</pre><!-- ${escapeHtml(message)} -->`;
68
+ }
69
+
70
+ // Only KaTeX rules live in the fragment: they are namespaced under .katex*,
71
+ // so inserting them into the host page cannot restyle the app itself. The
72
+ // handful of layout tweaks below are scoped to the preview container.
73
+ const html = [
74
+ '<style data-rw-katex="1">',
75
+ katexCss(),
76
+ '.rw-doc-preview .katex{font-size:1.05em}',
77
+ '.rw-doc-preview .katex-display{overflow-x:auto;overflow-y:hidden;margin:1.1em 0;padding:2px 0}',
78
+ // Keep KaTeX's own block layout: the equation number (`\tag`) is absolutely
79
+ // positioned at the right edge of the block, so shrinking the block to the
80
+ // formula's width (inline-block) parks the number on top of the formula.
81
+ // `min-width:max-content` is what still lets an over-wide formula scroll.
82
+ '.rw-doc-preview .katex-display>.katex{display:block;min-width:max-content;text-align:center}',
83
+ // KaTeX pins the equation number with `position:absolute; right:0`, which
84
+ // lands on top of the formula whenever the formula is (nearly) as wide as
85
+ // the column. Lay the number out after the formula instead, so it can never
86
+ // collide; `min-width:max-content` above keeps over-wide lines scrollable.
87
+ '.rw-doc-preview .katex-display>.katex:has(>.katex-html>.tag)>.katex-html{white-space:nowrap}',
88
+ '.rw-doc-preview .katex-display>.katex:has(>.katex-html>.tag)>.katex-html>.tag{position:static;right:auto;margin:0 0 0 1.6em;vertical-align:middle;white-space:nowrap}',
89
+ '.rw-doc-preview .katex-error{color:var(--dsw-alias-state-error-primary,#d73a49);font-family:ui-monospace,Consolas,monospace;font-size:.9em}',
90
+ '.rw-doc-preview .rw-md-fallback{white-space:pre-wrap}',
91
+ '</style>',
92
+ body,
93
+ ].join('\n');
94
+
95
+ return html;
96
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-linked-workspace",
3
- "version": "0.26.1",
3
+ "version": "0.27.0",
4
4
  "description": "Linked local ⇄ remote workspaces and remote workspaces for DeepSeek Harness: theme-aware split editor, file-type icons, and agent tools that edit remote files directly.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -23,7 +23,8 @@
23
23
  "README.en.md",
24
24
  "docs/API.md",
25
25
  "docs/VERIFY.md",
26
- "scripts/doc_tool.py"
26
+ "scripts/doc_tool.py",
27
+ "scripts/md-to-html.mjs"
27
28
  ],
28
29
  "keywords": [
29
30
  "deepseek-harness",
@@ -67,11 +68,15 @@
67
68
  }
68
69
  },
69
70
  "dependencies": {
71
+ "katex": "^0.16.47",
72
+ "micromark": "^4.0.3",
73
+ "micromark-extension-gfm": "^3.0.0",
74
+ "micromark-extension-math": "^3.1.0",
70
75
  "ssh2": "^1.17.0"
71
76
  },
72
77
  "scripts": {
73
78
  "build": "node scripts/build-client.mjs",
74
- "test": "node --test test/linked.test.mjs test/parts.test.mjs test/git.test.mjs test/file-creation.test.mjs && node test/ssh-credentials.test.mjs && node test/client-smoke.mjs",
79
+ "test": "node --test test/linked.test.mjs test/parts.test.mjs test/git.test.mjs test/file-creation.test.mjs test/md-preview.test.mjs && node test/ssh-credentials.test.mjs && node test/client-smoke.mjs",
75
80
  "prepack": "node scripts/build-client.mjs"
76
81
  },
77
82
  "repository": {
@@ -405,6 +405,33 @@ img{max-width:100%} a{color:#0969da} hr{border:0;border-top:1px solid #d0d7de;ma
405
405
 
406
406
 
407
407
  def markdown_preview(path):
408
+ # Use the Node.js renderer (micromark + GFM + KaTeX) so the preview matches
409
+ # DSH's native markdown pipeline. The renderer returns a body fragment that
410
+ # carries the KaTeX stylesheet; the client injects it with innerHTML.
411
+ import subprocess
412
+ import json
413
+ from pathlib import Path
414
+
415
+ renderer = Path(__file__).parent / "md-to-html.mjs"
416
+
417
+ if renderer.exists():
418
+ try:
419
+ result = subprocess.run(
420
+ ["node", str(renderer), path],
421
+ capture_output=True,
422
+ text=True,
423
+ timeout=30,
424
+ check=True
425
+ )
426
+ # The renderer outputs JSON with { kind, html }
427
+ data = json.loads(result.stdout)
428
+ emit(data)
429
+ return
430
+ except Exception:
431
+ # Fall back to the Python renderer when Node or the modules are missing.
432
+ pass
433
+
434
+ # Fallback: use Python markdown
408
435
  html = markdown_to_html(path)
409
436
  emit({"kind": "markdown-preview", "html": html})
410
437
 
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * CLI wrapper around lib/markdown.js, kept for standalone rendering and tests.
4
+ *
5
+ * usage: node md-to-html.mjs <markdown-file>
6
+ * output: {"kind":"markdown-preview","html":"..."}
7
+ */
8
+
9
+ import { readFileSync } from 'node:fs';
10
+ import { renderMarkdownFragment } from '../lib/markdown.js';
11
+
12
+ const args = process.argv.slice(2);
13
+ if (args.length === 0) {
14
+ console.error('usage: md-to-html.mjs <markdown-file>');
15
+ process.exit(1);
16
+ }
17
+
18
+ const markdown = readFileSync(args[0], 'utf8');
19
+ console.log(JSON.stringify({ kind: 'markdown-preview', html: renderMarkdownFragment(markdown) }));