dsh-linked-workspace 0.34.0 → 0.34.1

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/CHANGELOG.md CHANGED
@@ -1,5 +1,21 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.34.1 — 2026-12-02
4
+
5
+ - **Word / Excel / PowerPoint 现在能直接看了**:文档面板不再把 .docx/.xlsx/.pptx 拆成段落、单元格、文字块来编辑,
6
+ 而是交给 LibreOffice 转成 PDF、再按页渲染成图片 —— 版式、表格、配色、公式位置都保持原样,只读。
7
+ 工具栏有 ‹ 页码 › 与「重新加载」;同一份文件第二次打开走缓存(首次约 8–11 秒,之后约 0.5 秒一页)。
8
+ - **网页(HTML)可以编辑了**:HTML 标签页多了「编辑 / 预览」切换,编辑用的是源码文本框,`Ctrl/⌘+S` 保存,
9
+ 预览仍在 `sandbox="allow-scripts"` 的 iframe 里跑,不碰 DSH 界面。保存走 `fs.write` / `local.write`,
10
+ 带 `expectedMtime` 冲突检查。
11
+ - **依赖说明**:Office 预览需要本机有 LibreOffice(`soffice`);没有时该标签页会明确说明「这台机器上没有
12
+ LibreOffice」,不再默默显示文字视图。可用 `DSH_LINKED_WORKSPACE_SOFFICE` 指定路径。
13
+ - **Host**:新增 `docs.officePage { path, page }`(转换 + 分页渲染,按内容哈希缓存 PDF),`apiRevision` 16 → 17。
14
+
15
+ - **Markdown 编辑模式也能批量替换了**:在文档面板点「编辑」后按 `Ctrl/⌘+F`,查找条里多了替换框、「替换」
16
+ 与「全部替换」。匹配规则与查找一致(不区分大小写的纯文本,不支持正则);「替换」只改当前命中并保持光标位置,
17
+ 「全部替换」从后往前改,避免偏移互相影响。改完仍是原来的保存路径(`Ctrl/⌘+S` 或「保存」)。
18
+
3
19
  ## 0.34.0 — 2026-12-01
4
20
 
5
21
  - **工作区外下载不会再点出两份**:下载期间按钮变成「下载中…」并禁用,结束后恢复;下载完成的页脚多一个
package/docs/API.md CHANGED
@@ -26,6 +26,7 @@ Codes: `BAD_REQUEST`, `NOT_FOUND`, `SSH_CONNECT`, `AUTH_FAILED`,
26
26
  | `docs.create` | `{ path, kind?, linkedId?, remoteId? }` | `{ kind, path, size, mtime }` |
27
27
  | `docs.mdPreview` | `{ path, text?, linkedId?, remoteId? }` | `{ kind: 'markdown-preview', html }` (rendered in-process; the fragment carries the KaTeX stylesheet and expects the plugin's `/dsh-linked-workspace/assets/katex/` fonts; the last 3 renders are cached by content hash) or `{ kind: 'markdown-preview-too-large', chars \| bytes, limit }` for a document above 512 Ki characters — the viewer must show the editor instead |
28
28
  | `docs.mdPdf` | `{ path, text?, linkedId?, remoteId? }` | `{ kind: "pdf", path, size, mtime }` |
29
+ | `docs.officePage` | `{ path, linkedId?/remoteId?, page }` | `{ kind, engine, pageCount, pages[{ index, png }] }` (docx/xlsx/pptx only: converts to PDF with LibreOffice, caches the PDF per content hash, renders the page as a PNG) |
29
30
 
30
31
  ## Records
31
32
 
package/docs/VERIFY.md CHANGED
@@ -1,5 +1,31 @@
1
1
  # Manual verification checklist
2
2
 
3
+ ## Office 渲染预览与 HTML 编辑(未发布)
4
+
5
+ 1. **准备**:本机需装 LibreOffice(`C:\Program Files\LibreOffice\program\soffice.exe`)。没有时打开 Office 文件应显示
6
+ 「这台机器上没有 LibreOffice,无法渲染 Office 文档」,而不是空白或文字视图。
7
+ 2. 在目录栏打开一个 `.pptx`(3 页、含标题/项目符号/表格):应直接看到**渲染后的第 1 页**,标题居中、表格带表头底色;
8
+ 工具栏右侧有 `‹ 1 / 3 ›` 与「重新加载」,**没有**「保存」按钮。
9
+ 3. 点 `›` 翻到第 2、3 页:每页约 0.5 秒(已转换过),版式与 PowerPoint 里一致。
10
+ 4. 打开一个 `.docx`:标题、正文、列表、表格都应正确渲染;打开 `.xlsx`:两个 sheet 各一页、列宽与换行正确。
11
+ 5. 关掉再打开同一个文件:不走重新转换(< 1 秒出图)。
12
+ 6. 打开一个 `.html`:默认预览(iframe),点「编辑」切到源码文本框,改一行后 `Ctrl/⌘+S`(或点「保存」),
13
+ 状态栏「未保存」消失、出现「已保存」;再点「预览」应看到改动。
14
+ 7. 让 `.html` 在别处被改动后再保存:应报冲突并要求重新加载(`expectedMtime` 生效)。
15
+ 8. Markdown 行为不变:默认预览、可切编辑、`Ctrl/⌘+F` 有查找与替换。
16
+
17
+
18
+ ## Markdown 编辑模式的替换(未发布)
19
+
20
+ 1. 在目录栏打开一个 `.md`,点工具栏「编辑」进入编辑模式,按 `Ctrl/⌘+F`:查找条里应有第二个输入框(替换)
21
+ 和「替换」「全部替换」两个按钮。
22
+ 2. 查找框输入 `alpha`:计数器显示命中数(不区分大小写,`ALPHA` 也算)。
23
+ 3. 替换框输入 `OMEGA`,点「全部替换」:正文里所有命中都变成 `OMEGA`,计数器变「无匹配」。
24
+ 4. 再查 `gamma`、替换为 `delta`,点「替换」(或在替换框按 Enter):只改当前这一处,光标落在 `delta` 之后。
25
+ 5. `Ctrl/⌘+S` 或点「保存」:重新打开该文件确认改动已写回远端。
26
+ 6. 预览模式下按 `Ctrl/⌘+F` 不应弹出查找条(替换只在编辑模式可用)。
27
+
28
+
3
29
  ## 工作区外:下载、图片与额外根目录搜索(未发布)
4
30
 
5
31
  1. 额外根目录里放一个 3 MB 以上的 `big.txt`,点击它的聊天链接,然后连点两次「下载到默认文件夹」:
package/lib/client.js CHANGED
@@ -2837,6 +2837,7 @@ function isInsideRoot(root, target) {
2837
2837
  docPdfAuthor: '作者',
2838
2838
  docPageOf: '第 {page} / {total} 页',
2839
2839
  docExportDone: '已导出 PDF:{path}',
2840
+ docRenderEmpty: '这一页没有渲染出内容,点「重新加载」再试一次。',
2840
2841
  docPreviewFailed: '预览失败',
2841
2842
  previewTooLarge: '这个文件太大({{chars}} 字符,上限 {{limit}}),没有生成预览;可以在编辑器里查看,或下载后用别的工具打开。',
2842
2843
  previewTooLargeBytes: '这个文件太大({{bytes}}),没有生成预览;可以在编辑器里查看,或下载后用别的工具打开。',
@@ -3461,6 +3462,7 @@ function isInsideRoot(root, target) {
3461
3462
  docPdfAuthor: 'Author',
3462
3463
  docPageOf: 'Page {page} / {total}',
3463
3464
  docExportDone: 'Exported PDF: {path}',
3465
+ docRenderEmpty: 'This page rendered empty; try reloading it.',
3464
3466
  docPreviewFailed: 'Preview failed',
3465
3467
  previewTooLarge: 'Too large to preview ({{chars}} characters, the ceiling is {{limit}}). Read it in the editor, or download it and open it elsewhere.',
3466
3468
  previewTooLargeBytes: 'Too large to preview ({{bytes}}). Read it in the editor, or download it and open it elsewhere.',
@@ -3868,7 +3870,7 @@ function isInsideRoot(root, target) {
3868
3870
  * Host methods the running DSH process does not have yet, the directory
3869
3871
  * pane says so instead of surfacing an unrelated error.
3870
3872
  */
3871
- var HOST_API_REVISION = 16;
3873
+ var HOST_API_REVISION = 17;
3872
3874
  var hostInfoProbe = null;
3873
3875
 
3874
3876
  function probeHostInfo() {
@@ -4480,6 +4482,8 @@ function isInsideRoot(root, target) {
4480
4482
  '.rw-doc-preview th,.rw-doc-preview td{border:1px solid var(--dsw-alias-border-l2);padding:5px 8px}',
4481
4483
  '.rw-doc-preview img{max-width:100%}',
4482
4484
  '.rw-doc-preview blockquote{border-left:3px solid var(--dsw-alias-border-l2);margin:0;padding-left:10px;color:var(--dsw-alias-label-secondary)}',
4485
+ '.rw-html-source{flex:1 1 auto;min-height:0;resize:none;border:0;border-radius:0;font-family:var(--dsw-alias-font-mono,ui-monospace,SFMono-Regular,Menlo,monospace);font-size:12px;line-height:1.55}',
4486
+ '.rw-doc-page{display:block;margin:0 auto;max-width:100%;background:#fff;box-shadow:0 1px 3px rgba(0,0,0,.18);border-radius:2px}',
4483
4487
  '.rw-doc-pdf-page{display:block;max-width:100%;margin:0 auto 10px;border:1px solid var(--dsw-alias-border-l2);box-shadow:0 2px 10px rgba(0,0,0,.08);background:#fff}',
4484
4488
  '.rw-doc-field{display:flex;align-items:center;gap:8px;margin:6px 0}',
4485
4489
  '.rw-doc-field label{font-size:11.5px;color:var(--dsw-alias-label-tertiary);min-width:38px}',
@@ -5922,39 +5926,62 @@ function isInsideRoot(root, target) {
5922
5926
  var scope = props.scope;
5923
5927
  var local = props.local === true;
5924
5928
  var filePath = props.path;
5925
- var state = useState({ loading: true, error: null, data: null });
5929
+ var state = useState({ loading: true, error: null, data: null, editing: false, draft: '', saving: false, notice: '', dirty: false });
5926
5930
  var view = state[0];
5927
5931
  var setView = state[1];
5928
5932
  var params = scopeParams(scope);
5929
5933
 
5934
+ function patch(next) { setView(function (previous) { return Object.assign({}, previous, next); }); }
5935
+
5930
5936
  var load = useCallback(function () {
5931
5937
  if (!filePath || (!local && !scope)) {
5932
- setView({ loading: false, error: new Error(t('noWorkspace')), data: null });
5938
+ setView({ loading: false, error: new Error(t('noWorkspace')), data: null, editing: false, draft: '', saving: false, notice: '', dirty: false });
5933
5939
  return;
5934
5940
  }
5935
- setView({ loading: true, error: null, data: null });
5941
+ setView(function (previous) { return Object.assign({}, previous, { loading: true, error: null }); });
5936
5942
  var request = local ? { path: filePath, preview: true } : Object.assign({ path: filePath, preview: true }, params);
5937
5943
  apiCall(local ? 'local.read' : 'fs.read', request).then(function (result) {
5938
5944
  if (result.tooLarge || result.truncated) {
5939
5945
  setView({
5940
5946
  loading: false,
5941
5947
  error: new Error(t('htmlPreviewTooLarge', { size: formatBytes(result.size), limit: formatBytes(PREVIEW_MAX_BYTES) })),
5942
- data: null,
5948
+ data: null, editing: false, draft: '', saving: false, notice: '', dirty: false,
5943
5949
  });
5944
5950
  return;
5945
5951
  }
5946
5952
  if (result.binary) {
5947
- setView({ loading: false, error: new Error(t('htmlPreviewBinary')), data: null });
5953
+ setView({ loading: false, error: new Error(t('htmlPreviewBinary')), data: null, editing: false, draft: '', saving: false, notice: '', dirty: false });
5948
5954
  return;
5949
5955
  }
5950
- setView({ loading: false, error: null, data: result });
5956
+ setView({
5957
+ loading: false, error: null, data: result,
5958
+ draft: typeof result.content === 'string' ? result.content : '',
5959
+ editing: false, saving: false, notice: '', dirty: false,
5960
+ });
5951
5961
  }).catch(function (error) {
5952
- setView({ loading: false, error: error, data: null });
5962
+ setView({ loading: false, error: error, data: null, editing: false, draft: '', saving: false, notice: '', dirty: false });
5953
5963
  });
5954
5964
  }, [scopeKeyOf(scope), filePath, local]);
5955
5965
 
5956
5966
  useEffect(function () { load(); }, [load]);
5957
5967
 
5968
+ function save() {
5969
+ if (view.saving || !view.dirty) return;
5970
+ patch({ saving: true, error: null, notice: '' });
5971
+ var request = local
5972
+ ? { path: filePath, content: view.draft, expectedMtime: view.data ? view.data.mtime : undefined }
5973
+ : Object.assign({ path: filePath, content: view.draft, expectedMtime: view.data ? view.data.mtime : undefined }, params);
5974
+ apiCall(local ? 'local.write' : 'fs.write', request).then(function (result) {
5975
+ patch({
5976
+ saving: false, dirty: false, notice: t('saved'),
5977
+ data: Object.assign({}, view.data, { content: view.draft, size: result.size, mtime: result.mtime }),
5978
+ });
5979
+ if (typeof props.onSaved === 'function') props.onSaved();
5980
+ }).catch(function (error) {
5981
+ patch({ saving: false, error: error });
5982
+ });
5983
+ }
5984
+
5958
5985
  var name = basename(filePath) || t('fileTabTitle');
5959
5986
  var header = h('div', { className: 'rw-image-head' },
5960
5987
  h(FileGlyph, { name: name, size: 15 }),
@@ -5962,35 +5989,61 @@ function isInsideRoot(root, target) {
5962
5989
  h('span', { className: 'rw-editor-name', title: name }, name),
5963
5990
  h('span', { className: 'rw-editor-path', title: filePath }, filePath)),
5964
5991
  h('div', { className: 'rw-actions' },
5992
+ h('button', {
5993
+ type: 'button',
5994
+ className: 'rw-btn rw-btn-sm',
5995
+ onClick: function () { patch({ editing: !view.editing, notice: '' }); },
5996
+ disabled: view.loading,
5997
+ }, view.editing ? t('docPreview') : t('docEdit')),
5998
+ view.editing
5999
+ ? h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-primary', onClick: save, disabled: view.saving || !view.dirty }, view.saving ? Spinner(12) : IconSave(12), view.saving ? t('saving') : t('save'))
6000
+ : null,
5965
6001
  h('button', { type: 'button', className: 'rw-btn rw-btn-sm', onClick: load, disabled: view.loading }, IconRefresh(12), t('reload'))));
5966
6002
 
5967
6003
  if (view.loading) {
5968
6004
  return h('div', { className: 'rw-html-preview' }, header,
5969
6005
  h('div', { className: 'rw-editor-message' }, Spinner(14), t('loading')));
5970
6006
  }
5971
- if (view.error) {
6007
+ if (view.error && !view.data) {
5972
6008
  return h('div', { className: 'rw-html-preview' }, header,
5973
6009
  h('div', { className: 'rw-editor-message' },
5974
6010
  h(Banner, { kind: 'error' }, t('htmlLoadError') + ':' + messageOf(view.error, t, locale)),
5975
6011
  h('button', { type: 'button', className: 'rw-btn', onClick: load }, IconRefresh(13), t('retry'))));
5976
6012
  }
5977
- var data = view.data;
6013
+ var data = view.data || {};
6014
+ var stage = view.editing
6015
+ ? h('textarea', {
6016
+ className: 'rw-doc-textarea rw-html-source',
6017
+ value: view.draft,
6018
+ spellCheck: false,
6019
+ onChange: function (event) { patch({ draft: event.currentTarget.value, dirty: true, notice: '' }); },
6020
+ onKeyDown: function (event) {
6021
+ if ((event.ctrlKey || event.metaKey) && (event.key === 's' || event.key === 'S')) {
6022
+ event.preventDefault();
6023
+ save();
6024
+ }
6025
+ },
6026
+ })
6027
+ : h('iframe', {
6028
+ className: 'rw-html-frame',
6029
+ title: name,
6030
+ // allow-scripts runs the page's own JS (charts need it) inside an
6031
+ // opaque origin: no access to the DSH UI, its storage or the tree.
6032
+ sandbox: 'allow-scripts',
6033
+ srcDoc: typeof view.draft === 'string' ? view.draft : (data.content || ''),
6034
+ });
6035
+
5978
6036
  return h('div', { className: 'rw-html-preview' },
5979
6037
  header,
5980
- h('div', { className: 'rw-html-stage' },
5981
- h('iframe', {
5982
- className: 'rw-html-frame',
5983
- title: name,
5984
- // allow-scripts runs the page's own JS (charts need it) inside an
5985
- // opaque origin: no access to the DSH UI, its storage or the tree.
5986
- sandbox: 'allow-scripts',
5987
- srcDoc: data.content || '',
5988
- })),
6038
+ view.notice ? h('div', { style: { padding: '6px 10px 0' } }, h(Banner, { kind: 'success' }, view.notice)) : null,
6039
+ view.error && view.data ? h('div', { style: { padding: '6px 10px 0' } }, h(Banner, { kind: 'error' }, messageOf(view.error, t, locale))) : null,
6040
+ h('div', { className: 'rw-html-stage' }, stage),
5989
6041
  h('div', { className: 'rw-editor-status' },
5990
6042
  h('span', { className: 'rw-status-chip' }, 'HTML'),
5991
- h('span', { className: 'rw-status-chip' }, formatBytes(data.size || 0)),
6043
+ h('span', { className: 'rw-status-chip' }, formatBytes(Buffer.byteLength(view.draft || '', 'utf8'))),
6044
+ view.dirty ? h('span', { className: 'rw-status-chip rw-status-warn' }, t('dirty')) : null,
5992
6045
  h('span', { className: 'rw-fill', style: { flex: '1 1 auto' } }),
5993
- h('span', { className: 'rw-status-chip' }, t('htmlSandboxed'))));
6046
+ h('span', { className: 'rw-status-chip' }, view.editing ? t('docEdit') : t('htmlSandboxed'))));
5994
6047
  }
5995
6048
 
5996
6049
  // ── editor ─────────────────────────────────────────────────────────────
@@ -8052,6 +8105,9 @@ function rememberShowHidden(value) {
8052
8105
  var onOpenLink = props.onOpenLink;
8053
8106
  var settings = useRuntimeSettings();
8054
8107
  var kind = documentKindOf(path);
8108
+ // Word/Excel/PowerPoint are rendered through a PDF: the preview keeps the real
8109
+ // layout and is read-only, because the PDF cannot be written back as .docx.
8110
+ var officeKind = kind === 'docx' || kind === 'xlsx' || kind === 'pptx';
8055
8111
  var viewKey = (local ? 'local' : ((scope && scope.kind ? scope.kind : 'remote') + ':' + ((scope && scope.id) || ''))) + '|' + path;
8056
8112
  var rememberedView = recallView(viewKey);
8057
8113
  var stateRef = useState({
@@ -8062,7 +8118,8 @@ function rememberShowHidden(value) {
8062
8118
  sheet: rememberedView ? Number(rememberedView.sheet) || 0 : 0,
8063
8119
  slide: rememberedView ? Number(rememberedView.slide) || 0 : 0,
8064
8120
  updates: {}, pptxUpdates: {}, rotations: {}, deleted: {}, pdfLoading: false, notice: '', warn: '',
8065
- findOpen: false, findQuery: '', findIndex: 0,
8121
+ findOpen: false, findQuery: '', findIndex: 0, findReplace: '',
8122
+ office: null,
8066
8123
  });
8067
8124
  var state = stateRef[0];
8068
8125
  var setState = stateRef[1];
@@ -8149,7 +8206,39 @@ function rememberShowHidden(value) {
8149
8206
  if (anchorOf(event)) event.preventDefault();
8150
8207
  }
8151
8208
 
8209
+ function loadOffice(index) {
8210
+ patch({ loading: true, error: '', notice: '', warn: '' });
8211
+ return apiCall('docs.officePage', params({ page: index })).then(function (result) {
8212
+ var rendered = (result.pages && result.pages[0]) || {};
8213
+ patch({
8214
+ loading: false,
8215
+ office: { png: rendered.png || '', page: Number(rendered.index) || 0, pageCount: Number(result.pageCount) || 0, engine: result.engine || '' },
8216
+ page: Number(rendered.index) || 0,
8217
+ });
8218
+ }).catch(function (error) {
8219
+ patch({ loading: false, error: messageOf(error, t, locale) });
8220
+ if (error && error.code === 'FS_NOT_FOUND' && typeof props.onMissing === 'function') props.onMissing(path);
8221
+ });
8222
+ }
8223
+
8224
+ function goOfficePage(index) {
8225
+ if (!state.office) return;
8226
+ if (index < 0 || index >= state.office.pageCount || index === state.office.page) return;
8227
+ patch({ pdfLoading: true });
8228
+ apiCall('docs.officePage', params({ page: index })).then(function (result) {
8229
+ var rendered = (result.pages && result.pages[0]) || {};
8230
+ patch({
8231
+ pdfLoading: false,
8232
+ page: Number(rendered.index) || 0,
8233
+ office: Object.assign({}, state.office, { png: rendered.png || state.office.png, page: Number(rendered.index) || 0 }),
8234
+ });
8235
+ }).catch(function (error) {
8236
+ patch({ pdfLoading: false, error: messageOf(error, t, locale) });
8237
+ });
8238
+ }
8239
+
8152
8240
  function load() {
8241
+ if (officeKind) return loadOffice(Number((recallView(viewKey) || {}).page) || 0);
8153
8242
  patch({ loading: true, error: '', notice: '', warn: '' });
8154
8243
  apiCall('docs.read', params()).then(function (result) {
8155
8244
  var remembered = recallView(viewKey);
@@ -8211,6 +8300,7 @@ function rememberShowHidden(value) {
8211
8300
  }, [state.dirty]);
8212
8301
 
8213
8302
  function save() {
8303
+ if (officeKind) return Promise.resolve(false);
8214
8304
  if (state.saving) return Promise.resolve(false);
8215
8305
  patch({ saving: true, error: '', notice: '' });
8216
8306
  var data = {};
@@ -8306,6 +8396,38 @@ function rememberShowHidden(value) {
8306
8396
  if (docTextareaRef.current) docTextareaRef.current.focus();
8307
8397
  }
8308
8398
 
8399
+ // Same matching rule as docMatches: plain case-insensitive text, no
8400
+ // regex, so the replacement stays predictable.
8401
+ function replaceRange(text, at, length) {
8402
+ return text.slice(0, at) + state.findReplace + text.slice(at + length);
8403
+ }
8404
+
8405
+ function replaceDocCurrent() {
8406
+ var matches = docMatches();
8407
+ if (matches.length === 0) return;
8408
+ var index = Math.min(Math.max(state.findIndex, 0), matches.length - 1);
8409
+ var at = matches[index];
8410
+ var nextText = replaceRange(state.text, at, state.findQuery.length);
8411
+ patch({ text: nextText, dirty: true, html: '', findIndex: index });
8412
+ var area = docTextareaRef.current;
8413
+ if (area) {
8414
+ area.focus();
8415
+ var caret = at + state.findReplace.length;
8416
+ area.setSelectionRange(caret, caret);
8417
+ }
8418
+ }
8419
+
8420
+ function replaceDocAll() {
8421
+ var matches = docMatches();
8422
+ if (matches.length === 0) return;
8423
+ var text = state.text;
8424
+ // Back to front: the earlier offsets stay valid while splicing.
8425
+ for (var cursor = matches.length - 1; cursor >= 0; cursor -= 1) {
8426
+ text = replaceRange(text, matches[cursor], state.findQuery.length);
8427
+ }
8428
+ patch({ text: text, dirty: true, html: '', findIndex: 0 });
8429
+ }
8430
+
8309
8431
  useEffect(function () {
8310
8432
  if (!settings.autoSave || !state.dirty || state.saving) return undefined;
8311
8433
  var timer = setTimeout(function () { saveRef.current(); }, 900);
@@ -8396,7 +8518,15 @@ function rememberShowHidden(value) {
8396
8518
  h('span', { className: 'rw-hint', style: { flex: '1 1 auto', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, title: path }, path),
8397
8519
  kind === 'markdown' ? h('button', { type: 'button', className: 'rw-btn rw-btn-sm', onClick: showPreview }, state.preview ? t('docEdit') : t('docPreview')) : null,
8398
8520
  kind === 'markdown' ? h('button', { type: 'button', className: 'rw-btn rw-btn-sm', onClick: exportPdf, disabled: state.saving }, IconDownload(12), t('exportPdf')) : null,
8399
- h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-primary', onClick: save, disabled: state.saving || !state.dirty }, state.saving ? Spinner(12) : IconSave(12), state.saving ? t('saving') : t('save')));
8521
+ officeKind && state.office
8522
+ ? h('div', { className: 'rw-inline' },
8523
+ h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: state.pdfLoading || state.office.page <= 0, onClick: function () { goOfficePage(state.office.page - 1); } }, '‹'),
8524
+ h('span', { className: 'rw-hint' }, (state.office.page + 1) + ' / ' + Math.max(state.office.pageCount, 1)),
8525
+ h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: state.pdfLoading || state.office.page >= state.office.pageCount - 1, onClick: function () { goOfficePage(state.office.page + 1); } }, '›'))
8526
+ : null,
8527
+ officeKind
8528
+ ? h('button', { type: 'button', className: 'rw-btn rw-btn-sm', onClick: function () { loadOffice(state.office ? state.office.page : 0); }, disabled: state.loading || state.pdfLoading }, IconRefresh(13), t('reload'))
8529
+ : h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-primary', onClick: save, disabled: state.saving || !state.dirty }, state.saving ? Spinner(12) : IconSave(12), state.saving ? t('saving') : t('save')));
8400
8530
 
8401
8531
  if (state.loading) {
8402
8532
  return h('div', { className: 'rw-doc' }, toolbar, h('div', { className: 'rw-editor-message' }, Spinner(14), t('loading')));
@@ -8438,6 +8568,20 @@ function rememberShowHidden(value) {
8438
8568
  })()),
8439
8569
  h('button', { type: 'button', className: 'rw-btn rw-btn-sm', title: t('findPrev'), onClick: function () { stepDocMatch(-1); } }, h('span', { style: { display: 'inline-flex', transform: 'rotate(180deg)' } }, IconChevron(12))),
8440
8570
  h('button', { type: 'button', className: 'rw-btn rw-btn-sm', title: t('findNext'), onClick: function () { stepDocMatch(1); } }, IconChevron(12)),
8571
+ h('input', {
8572
+ className: 'rw-input',
8573
+ value: state.findReplace,
8574
+ placeholder: t('replacePlaceholder'),
8575
+ 'aria-label': t('replacePlaceholder'),
8576
+ spellCheck: false,
8577
+ onChange: function (event) { patch({ findReplace: event.currentTarget.value }); },
8578
+ onKeyDown: function (event) {
8579
+ if (event.key === 'Enter') { event.preventDefault(); replaceDocCurrent(); }
8580
+ if (event.key === 'Escape') { event.preventDefault(); closeDocFind(); }
8581
+ },
8582
+ }),
8583
+ h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: docMatches().length === 0, onClick: replaceDocCurrent }, t('replaceOne')),
8584
+ h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: docMatches().length === 0, onClick: replaceDocAll }, t('replaceAll')),
8441
8585
  h('button', { type: 'button', className: 'rw-icon-btn', title: t('close'), onClick: closeDocFind }, IconClose(12)))
8442
8586
  : null,
8443
8587
  h('textarea', {
@@ -8464,70 +8608,14 @@ function rememberShowHidden(value) {
8464
8608
  h('button', { type: 'button', className: 'rw-btn rw-btn-sm rw-btn-danger', disabled: total <= 1, onClick: function () { var deleted = Object.assign({}, state.deleted); deleted[state.page] = true; var next = state.page + 1; while (next < total && deleted[next]) next += 1; if (next >= total) { next = state.page - 1; while (next >= 0 && deleted[next]) next -= 1; } var nextPage = next >= 0 ? next : state.page; patch({ deleted: deleted, dirty: true, page: nextPage }); if (next >= 0 && !((state.data.pages || []).some(function (page) { return page.index === next; }))) goPdfPage(next); } }, t('docDeletePage')))),
8465
8609
  state.pdfLoading ? h('div', { className: 'rw-editor-message' }, Spinner(14), t('loading')) : null,
8466
8610
  current ? h('img', { className: 'rw-doc-pdf-page', src: current.png, style: { transform: 'rotate(' + ((state.rotations[current.index] || current.rotation || 0) % 360) + 'deg)' } }) : null);
8467
- } else if (kind === 'docx' && state.data) {
8468
- var paragraphs = state.data.paragraphs || [];
8469
- var tables = state.data.tables || [];
8470
- body = h('div', { className: 'rw-doc-body' },
8471
- paragraphs.map(function (paragraph, index) {
8472
- return h('div', { key: 'p' + index, className: 'rw-doc-block' },
8473
- h('div', { className: 'rw-doc-block-label' }, (paragraph.style || t('docParagraph')) + ' · ' + (index + 1)),
8474
- h('textarea', { value: paragraph.text || '', onChange: function (event) { updateParagraph(index, event.currentTarget.value); } }));
8475
- }),
8476
- tables.map(function (rows, tableIndex) {
8477
- return h('div', { key: 't' + tableIndex },
8478
- h('div', { className: 'rw-doc-block-label' }, t('docTable') + ' ' + (tableIndex + 1)),
8479
- h('table', { className: 'rw-doc-table' }, h('tbody', null,
8480
- rows.map(function (row, rowIndex) {
8481
- return h('tr', { key: rowIndex }, row.map(function (cell, cellIndex) {
8482
- return h('td', { key: cellIndex }, h('input', { value: cell || '', onChange: function (event) { updateTableCell(tableIndex, rowIndex, cellIndex, event.currentTarget.value); } }));
8483
- }));
8484
- }))));
8485
- }));
8486
- } else if (kind === 'xlsx' && state.data) {
8487
- var sheets = state.data.sheets || [];
8488
- var active = sheets[Math.min(state.sheet, Math.max(sheets.length - 1, 0))] || { name: '', rows: [] };
8489
- var columns = Math.max(active.maxCol || 0, 8);
8490
- var header = h('tr', null, h('th', null, ''), Array.from({ length: columns }, function (_, index) { return h('th', { key: index }, String.fromCharCode(65 + index)); }));
8491
- var gridRows = (active.rows || []).map(function (row, rowIndex) {
8492
- return h('tr', { key: rowIndex },
8493
- h('th', null, String(rowIndex + 1)),
8494
- Array.from({ length: columns }, function (_, colIndex) {
8495
- var cell = String.fromCharCode(65 + colIndex) + (rowIndex + 1);
8496
- var value = row[colIndex];
8497
- return h('td', { key: colIndex }, h('input', {
8498
- value: value === null || value === undefined ? '' : String(value),
8499
- onChange: function (event) { updateCell(active.name, cell, event.currentTarget.value); },
8500
- }));
8501
- }));
8502
- });
8503
- body = h('div', { className: 'rw-doc-body', style: { padding: 0, overflow: 'hidden' } },
8504
- h('div', { className: 'rw-doc-tabs' }, sheets.map(function (sheet, index) {
8505
- return h('button', { key: sheet.name, type: 'button', className: 'rw-doc-tab' + (index === state.sheet ? ' is-on' : ''), onClick: function () { patch({ sheet: index }); } }, sheet.name);
8506
- })),
8507
- active.truncated
8508
- ? h('div', { className: 'rw-doc-note' }, t('sheetTruncated', { rows: active.maxRow || 0, cols: active.maxCol || 0 }))
8509
- : null,
8510
- (state.data.sheetCount || sheets.length) > sheets.length
8511
- ? h('div', { className: 'rw-doc-note' }, t('sheetMore'))
8512
- : null,
8513
- h('div', { style: { flex: '1 1 auto', overflow: 'auto', padding: 8 } },
8514
- h('table', { className: 'rw-doc-grid' },
8515
- h('thead', null, header),
8516
- h('tbody', null, gridRows))));
8517
- } else if (kind === 'pptx' && state.data) {
8518
- var slides = state.data.slides || [];
8519
- var slide = slides[Math.min(state.slide, Math.max(slides.length - 1, 0))] || { texts: [] };
8520
- body = h('div', { className: 'rw-doc-body' },
8521
- h('div', { className: 'rw-inline', style: { justifyContent: 'space-between', marginBottom: 6 } },
8522
- h('div', { className: 'rw-inline' },
8523
- h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: state.slide <= 0, onClick: function () { patch({ slide: state.slide - 1 }); } }, '‹'),
8524
- h('span', { className: 'rw-hint' }, (state.slide + 1) + ' / ' + slides.length),
8525
- h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: state.slide >= slides.length - 1, onClick: function () { patch({ slide: state.slide + 1 }); } }, '›'))),
8526
- (slide.texts || []).map(function (item) {
8527
- return h('div', { key: item.shape, className: 'rw-doc-block' },
8528
- h('div', { className: 'rw-doc-block-label' }, (item.name || t('docSlide')) + ' · ' + item.shape),
8529
- h('textarea', { value: (state.pptxUpdates[state.slide + ':' + item.shape] || item).text || '', onChange: function (event) { updateSlideText(state.slide, item.shape, event.currentTarget.value); } }));
8530
- }));
8611
+ } else if (officeKind && state.office) {
8612
+ // A rendered page is the whole point: the layout came out of LibreOffice,
8613
+ // so nothing here re-flows the document.
8614
+ body = h('div', { className: 'rw-doc-body', ref: docBodyRef, onScroll: rememberScroll },
8615
+ state.pdfLoading ? h('div', { className: 'rw-editor-message' }, Spinner(14), t('loading')) : null,
8616
+ state.office.png
8617
+ ? h('img', { className: 'rw-doc-page', alt: basename(path), src: state.office.png })
8618
+ : h('div', { className: 'rw-editor-message' }, t('docRenderEmpty')));
8531
8619
  }
8532
8620
 
8533
8621
  return h('div', { className: 'rw-doc' }, toolbar,
package/lib/index.js CHANGED
@@ -26,6 +26,7 @@ import { fileURLToPath } from 'node:url'
26
26
  import { createRequire } from 'node:module'
27
27
  import { forgetKnownHost, listHosts, listKnownHosts, RemoteHost, SshError, writeLocalCredential } from './ssh.js'
28
28
  import { renderMarkdownFragment } from './markdown.js'
29
+ import { convertOfficeToPdf, sofficePath } from './office.js'
29
30
  import * as linkedFs from './linked.js'
30
31
  import * as git from './git.js'
31
32
 
@@ -41,7 +42,7 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'workingDirectory']
41
42
  * is still running an older copy of the Host — refreshing the page only swaps
42
43
  * the browser bundle, so the two halves can drift by one restart.
43
44
  */
44
- const API_REVISION = 16
45
+ const API_REVISION = 17
45
46
 
46
47
  /** When this copy of the Host was loaded; shown by `meta.info`. */
47
48
  const STARTED_AT = new Date().toISOString()
@@ -2842,7 +2843,50 @@ export function apply(ctx) {
2842
2843
  return kind
2843
2844
  }
2844
2845
 
2845
- async function docStat(target) {
2846
+ // Office previews: one PDF per (content) hash, kept next to the plugin data so a
2847
+ // second open of the same document renders instantly.
2848
+ const officePdfCache = new Map()
2849
+
2850
+ function officeRenderDir() {
2851
+ const directory = join(tmpdir(), 'dsh-linked-workspace-office')
2852
+ mkdirSync(directory, { recursive: true })
2853
+ return directory
2854
+ }
2855
+
2856
+ async function officePdfFor(bytes, ext) {
2857
+ const key = createHash('sha1').update(bytes).digest('hex')
2858
+ const known = officePdfCache.get(key)
2859
+ if (known && existsSync(known)) return known
2860
+ const file = join(officeRenderDir(), key + '.pdf')
2861
+ if (existsSync(file)) {
2862
+ officePdfCache.set(key, file)
2863
+ return file
2864
+ }
2865
+ const pending = officePdfPending.get(key)
2866
+ if (pending) return await pending
2867
+ const job = (async () => {
2868
+ const converted = await convertOfficeToPdf(bytes, ext)
2869
+ writeFileSync(file, converted.pdf)
2870
+ officePdfCache.set(key, file)
2871
+ if (officePdfCache.size > 12) {
2872
+ const oldest = officePdfCache.keys().next().value
2873
+ const oldestFile = officePdfCache.get(oldest)
2874
+ officePdfCache.delete(oldest)
2875
+ try { rmSync(oldestFile, { force: true }) } catch { /* best effort */ }
2876
+ }
2877
+ return file
2878
+ })()
2879
+ officePdfPending.set(key, job)
2880
+ try {
2881
+ return await job
2882
+ } finally {
2883
+ officePdfPending.delete(key)
2884
+ }
2885
+ }
2886
+
2887
+ const officePdfPending = new Map()
2888
+
2889
+ async function docStat(target) {
2846
2890
  if (!target.remote) {
2847
2891
  try { const info = await fsStat(target.path); return info } catch { return null }
2848
2892
  }
@@ -3888,6 +3932,29 @@ const GREP_MAX_QUERY = 200
3888
3932
  }
3889
3933
  },
3890
3934
 
3935
+ /**
3936
+ * Render one page of a Word/Excel/PowerPoint document. The preview is
3937
+ * read-only on purpose: a converted PDF is the only way to keep the layout
3938
+ * intact, and it cannot be written back into the original file.
3939
+ */
3940
+ async 'docs.officePage'(params = {}) {
3941
+ const target = await docTarget(params)
3942
+ const kind = assertDocKind(target.path)
3943
+ if (kind !== 'docx' && kind !== 'xlsx' && kind !== 'pptx') {
3944
+ throw new ApiError('BAD_REQUEST', '只有 Word、Excel 与 PowerPoint 需要这种渲染')
3945
+ }
3946
+ const page = Number(params.page)
3947
+ if (!Number.isInteger(page) || page < 0) throw new ApiError('BAD_REQUEST', '页码无效')
3948
+ const engine = sofficePath() === '' ? '' : 'libreoffice'
3949
+ if (engine === '') {
3950
+ throw new ApiError('NO_RENDERER', '这台机器上没有 LibreOffice,无法渲染 Office 文档')
3951
+ }
3952
+ const current = await readDocBytes(target, target)
3953
+ const pdf = await officePdfFor(current.data, kind)
3954
+ const rendered = await runDocTool(['read', '--kind', 'pdf', '--file', pdf, '--page', String(page)])
3955
+ return { kind, engine, path: target.path, mtime: current.mtime, ...rendered }
3956
+ },
3957
+
3891
3958
  async 'docs.pdfPage'(params = {}) {
3892
3959
  const target = await docTarget(params)
3893
3960
  assertDocKind(target.path, 'pdf')
package/lib/office.js ADDED
@@ -0,0 +1,118 @@
1
+ // Convert Office documents to PDF with a headless LibreOffice.
2
+ //
3
+ // Why a subprocess: the PDF is only a stepping stone — PyMuPDF renders its pages
4
+ // for the read-only preview, and a real office engine is the only way to keep
5
+ // Word/Excel/PowerPoint layout intact. LibreOffice is started per conversion
6
+ // with its own profile directory, because two instances sharing one profile
7
+ // block each other and the first one wins.
8
+
9
+ import { spawn } from 'node:child_process'
10
+ import { existsSync } from 'node:fs'
11
+ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
12
+ import { tmpdir } from 'node:os'
13
+ import { join } from 'node:path'
14
+
15
+ const WINDOWS_PATHS = [
16
+ 'C:\\Program Files\\LibreOffice\\program\\soffice.exe',
17
+ 'C:\\Program Files (x86)\\LibreOffice\\program\\soffice.exe',
18
+ ]
19
+
20
+ let cachedPath
21
+
22
+ /** The LibreOffice binary, or '' when this machine has none. */
23
+ export function sofficePath() {
24
+ if (cachedPath !== undefined) return cachedPath
25
+ const fromEnv = typeof process.env.DSH_LINKED_WORKSPACE_SOFFICE === 'string'
26
+ ? process.env.DSH_LINKED_WORKSPACE_SOFFICE.trim()
27
+ : ''
28
+ if (fromEnv !== '' && existsSync(fromEnv)) {
29
+ cachedPath = fromEnv
30
+ return cachedPath
31
+ }
32
+ if (process.platform === 'win32') {
33
+ cachedPath = WINDOWS_PATHS.find((item) => existsSync(item)) || ''
34
+ return cachedPath
35
+ }
36
+ const names = process.platform === 'darwin'
37
+ ? ['/Applications/LibreOffice.app/Contents/MacOS/soffice', '/usr/local/bin/soffice']
38
+ : ['/usr/bin/soffice', '/usr/local/bin/soffice', '/snap/bin/libreoffice']
39
+ cachedPath = names.find((item) => existsSync(item)) || ''
40
+ return cachedPath
41
+ }
42
+
43
+ function run(command, args, timeoutMs) {
44
+ return new Promise((resolve, reject) => {
45
+ let child
46
+ try {
47
+ child = spawn(command, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
48
+ } catch (error) {
49
+ reject(error)
50
+ return
51
+ }
52
+ let stderr = ''
53
+ const timer = setTimeout(() => {
54
+ // LibreOffice ignores SIGTERM on Windows; the tree kill is the only way out.
55
+ try {
56
+ if (process.platform === 'win32') {
57
+ spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' })
58
+ } else {
59
+ child.kill('SIGKILL')
60
+ }
61
+ } catch (error) {
62
+ /* already gone */
63
+ }
64
+ reject(new Error(`soffice timed out after ${timeoutMs} ms`))
65
+ }, timeoutMs)
66
+ child.stderr.on('data', (chunk) => {
67
+ if (stderr.length < 4000) stderr += chunk.toString('utf8')
68
+ })
69
+ child.on('error', (error) => {
70
+ clearTimeout(timer)
71
+ reject(error)
72
+ })
73
+ child.on('close', (code) => {
74
+ clearTimeout(timer)
75
+ if (code === 0) resolve(stderr)
76
+ else reject(new Error(`soffice exited ${code}: ${stderr.trim().slice(-400)}`))
77
+ })
78
+ })
79
+ }
80
+
81
+ /**
82
+ * Convert one Office document (given as bytes) to PDF.
83
+ * Returns { pdf: Buffer, engine: 'libreoffice' }; throws when nothing can render.
84
+ */
85
+ export async function convertOfficeToPdf(bytes, ext, options = {}) {
86
+ const binary = sofficePath()
87
+ if (binary === '') {
88
+ const error = new Error('这台机器上没有 LibreOffice,无法渲染 Office 文档')
89
+ error.code = 'NO_RENDERER'
90
+ throw error
91
+ }
92
+ const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : 120_000
93
+ const work = await mkdtemp(join(tmpdir(), 'dsh-office-'))
94
+ try {
95
+ const source = join(work, `source.${ext}`)
96
+ const profile = join(work, 'profile')
97
+ await writeFile(source, bytes)
98
+ await run(binary, [
99
+ `-env:UserInstallation=file:///${profile.replace(/\\/g, '/')}`,
100
+ '--headless',
101
+ '--norestore',
102
+ '--nologo',
103
+ '--nolockcheck',
104
+ '--nodefault',
105
+ '--convert-to',
106
+ 'pdf',
107
+ '--outdir',
108
+ work,
109
+ source,
110
+ ], timeoutMs)
111
+ const pdfPath = join(work, 'source.pdf')
112
+ if (!existsSync(pdfPath)) throw new Error('LibreOffice 没有产出 PDF')
113
+ const pdf = await readFile(pdfPath)
114
+ return { pdf, engine: 'libreoffice' }
115
+ } finally {
116
+ await rm(work, { recursive: true, force: true }).catch(() => {})
117
+ }
118
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-linked-workspace",
3
- "version": "0.34.0",
3
+ "version": "0.34.1",
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",