dsh-linked-workspace 0.18.0 → 0.19.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/CHANGELOG.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  English · [简体中文](CHANGELOG.zh.md)
4
4
 
5
+ ## 0.19.0 — 2026-11-19
6
+
7
+ - **Push local edits back.** `linked.plan` compares the local directory with the remote one file by file against the hash remembered from the last push, and classifies each file as added / changed / conflict / gone-upstream; the tree toolbar gained a sync button with a diff preview, and the row menu gained "push this to the remote side".
8
+ - `linked.push` writes the planned files back with a temporary file + rename per file, a `dryRun` switch, and `conflict: 'skip' | 'overwrite' | 'newer'`; a file that moved on both sides is never clobbered unless you ask for it. `linked.pushCancel { jobId }` stops a running push after the current file.
9
+ - **Opt-in autoPush**: `autoPushEnabled` (off by default, first enable asks for confirmation in place), `autoPushDebounceMs` (default 1500, 300–60000), plus `autoPushInclude`/`autoPushExclude` globs. It always pushes with `conflict: 'skip'`, so a formatter on this side never overwrites a remote edit.
10
+ - `fs.transfer` accepts `paths: string[]`, so a multi-selection becomes one request instead of N.
11
+ - `transfer.history` returns the last 50 transfers and pushes (`transfer-history.json`).
12
+ - `apiRevision` 4 → 5.
13
+
5
14
  ## 0.18.0 — 2026-11-19
6
15
 
7
16
  - New `fs.references` and a `references` action on `linked_workspace`: case-insensitive path completion with the **best match first** (exact name → prefix → substring) and directories flagged `dir`; it stops after 20000 entries or 3 s and reports `truncated`. The model can now resolve a remote path you mention by name.
package/README.en.md CHANGED
@@ -148,6 +148,12 @@ Every attempt — including refused ones — appends a line to `$DSH_HOME/linked
148
148
  .remote/ # optional: mirrored remote files (written on read/save, full sync on demand)
149
149
  ```
150
150
 
151
+ ### Push local edits back (0.19.0)
152
+
153
+ The sync button in the tree toolbar compares the local directory with the remote one and lists what is added, changed, in conflict, or gone upstream. "Push (skip conflicts)" writes back only the files you changed locally while the remote side left them alone; a file that moved on both sides stays under conflict until you explicitly choose "Push and overwrite conflicts".
154
+
155
+ To let it happen on its own, enable Settings → "Linked workspaces" → "Push back automatically": the switch asks for confirmation first, and once on, saving locally writes back after about 1.5 s while always skipping conflicts.
156
+
151
157
  ## Screenshots
152
158
 
153
159
  Settings → “Linked workspaces”: the upper half lists **linked workspaces** (local folder ⇄ remote folder), the lower half lists **remote workspaces** (the session runs inside the remote folder). Each card shows the connection state; linked workspaces also have the mirror switch and the sync button. The host name and the local placeholder path are blurred in this shot.
package/README.md CHANGED
@@ -148,6 +148,12 @@
148
148
  .remote/ # 可选:远端文件镜像存档(读取/保存时自动归档,可手动全量同步)
149
149
  ```
150
150
 
151
+ ### 把本地改动推回远端(0.19.0)
152
+
153
+ 目录栏的同步按钮会比较本地与远端:新增、修改、冲突、远端已删四类都会列出来。点「推送(跳过冲突)」只写回本地改过、远端没动过的文件;两边都改过的会留在「冲突」里,只有明确选「推送并覆盖冲突」才会用本地版本覆盖。
154
+
155
+ 想让它自动发生,可以在设置 →「联动工作区」→「自动推回远端」里开启:开关会先弹一段说明要你确认,开启后本地保存约 1.5 秒就会写回远端,而且始终跳过冲突。
156
+
151
157
  ## 界面
152
158
 
153
159
  设置 →「联动工作区」:上半部分是**联动工作区**(本地目录 ⇄ 远端目录),下半部分是**远程工作区**(会话直接运行在远端目录)。卡片里能看到连接状态,联动工作区还有镜像开关和同步按钮。图中的主机名与本地占位目录做了模糊处理。
package/docs/API.md CHANGED
@@ -98,11 +98,15 @@ scope root, or absolute inside it.
98
98
  | `fs.search` | `{ linkedId?/remoteId?, side, query, maxResults? }` | `{ ok, query, entries, truncated }` (matches **file names**, not contents; use `fs.grep` for contents) |
99
99
  | `fs.grep` | `{ linkedId?/remoteId?, side, query, maxResults?, path?, ignoreCase?, regex?, includeIgnored?, resultMode?, maxFiles?, maxFileBytes?, timeoutMs?, jobId? }` | `{ ok, query, entries: [{ path, relative, size, line, preview, matches }], truncated, truncatedReason, scannedFiles, scannedBytes, skippedFiles }` (searches file **contents**; `path` narrows the scan to a sub-folder; `ignoreCase` defaults to `true`; `regex` treats `query` as a regular expression; `includeIgnored: true` also walks usually ignored folders such as `node_modules`/`.venv`/`dist` (`.git`/`.hg`/`.svn` always stay out); `resultMode: 'files'` lists file names only (`line: 0`, empty `preview`, `matches` = hit count); `maxFiles` (default 2000), `maxFileBytes` (default 1 MB) and `timeoutMs` (default 5 s, max 10 s) raise or lower the sweep; limits are 1 MB per file, 2000 files, 8 MB and 5 s for both sides, and `truncatedReason` is one of `files`, `bytes`, `deadline`, `results`, `cancelled`; max 1000 rows) |
100
100
  | `fs.grepCancel` | `{ jobId }` | `{ cancelled }` (marks the job started by `fs.grep`'s `jobId`; the Host checks it between files and answers `truncatedReason: 'cancelled'`) |
101
+ | `linked.plan` | `{ id, maxFiles? }` | `{ linkedId, localPath, remotePath, added, changed, conflict, removed, unchanged, pending, truncated, skipped, maxFiles }` (each entry carries `relative`, `size`, `localHash`, `remoteHash`; a file that moved on both sides since the last push lands in `conflict`) |
102
+ | `linked.push` | `{ id, paths?, dryRun?, conflict?, jobId? }` | `{ linkedId, dryRun, conflict, files, pushed, skipped, conflictsLeft, bytes, cancelled }` (`conflict` is `skip` by default; every file is written as a temporary file and renamed into place) |
103
+ | `linked.pushCancel` | `{ jobId }` | `{ cancelled }` (stops after the file being written) |
104
+ | `transfer.history` | `{}` | `{ entries: [{ kind: "transfer" \| "push", direction?, linkedId?, files, bytes, skipped, truncated?, at }] }` (newest first, at most 50) |
101
105
  | `fs.references` | `{ linkedId?/remoteId?, query, limit?, includeIgnored?, side? }` | `{ ok, query, candidates: [{ path, relative, name, kind }], total, truncated, scannedEntries }` (path completion for `@`-style references: matches the **path**, case-insensitive, best match first — exact name, then prefix, then substring; `limit` defaults to 50 and caps at 200; walking stops after 20000 entries or 3 s; `side: 'local'` searches the local tree of a linked workspace) |
102
106
  | `fs.compare` | `{ linkedId?, path? }` | `{ path, relative, localPath, localMissing, counts: { onlyLocal, onlyRemote, changed, same }, onlyLocal, onlyRemote, changed, truncated, remoteTruncated, localTruncated, skippedLinks }` (linked workspaces only; excludes `.git`, `node_modules`, `.local`, `.remote`; 4000 files and depth 12 **per side**, 200 rows per group; `skippedLinks` counts symlinks and non-regular files) |
103
107
  | `fs.pullToLocal` | `{ linkedId?, path, targetDir?, conflict? }` | `{ path, relative, size, mtime }` (linked workspaces only; single file, ≤64 MB; `targetDir` must stay inside the local root; `conflict` is `error` (default), `overwrite` or `unique`) |
104
108
  | `fs.upload` | `{ linkedId?/remoteId?, path, paths, conflict? }` | `{ side: 'remote', target, files, bytes, skipped }` (≤50 local files, 64 MB each; `conflict` is `error` (default), `overwrite` or `unique`; a missing target directory is created) |
105
- | `fs.transfer` | `{ linkedId?/remoteId?, path, jobId? }` | `{ files, bytes, skipped, truncated, dest }` (with `jobId` the run is tracked and can be polled/cancelled) |
109
+ | `fs.transfer` | `{ linkedId?/remoteId?, path, paths?, jobId? }` | `{ files, bytes, skipped, truncated, dest }` (with `jobId` the run is tracked and can be polled/cancelled) |
106
110
  | `fs.transferProgress` | `{ jobId }` | `{ job: { id, files, bytes, skipped, state, cancelled, reason } \| null }` (`state` is `running`, `done`, `cancelled` or `failed`; jobs are dropped after 5 minutes) |
107
111
  | `fs.transferCancel` | `{ jobId }` | `{ cancelled }` (asks the running transfer to stop; it finishes the file in flight, then reports `CANCELLED`) |
108
112
  | `fs.download` | `{ linkedId?/remoteId?, path }` | `{ path, files, bytes, skipped, truncated }` |
package/docs/VERIFY.md CHANGED
@@ -2,6 +2,15 @@
2
2
 
3
3
  Host code (lib/) reloads live with `plugin_manager set_plugin include:linked-workspace-ui`; client changes load with **应用 → 重新加载界面** (a full restart is only needed after re-installing the package). Then verify:
4
4
 
5
+ ## 本地改动推回远端(0.19.0)
6
+
7
+ 1. 在联动工作区的**本地**目录里改一个文件、新建一个文件,然后点目录栏的同步按钮:差异预览里能看到「新增 1 · 修改 1」,并列出这两个文件。
8
+ 2. 点「推送(跳过冲突)」后提示「已推送 N 个文件」,远端目录刷新后能看到新内容(`ssh … cat` 核对)。
9
+ 3. 在**远端**改同一个文件、本地再改一次,重新打开差异预览:该文件出现在「冲突」里;点「推送(跳过冲突)」后远端内容保持不变,提示里带「1 个冲突未处理」;点「推送并覆盖冲突」才会用本地版本覆盖。
10
+ 4. 在行菜单上对某个远端文件点「把这个推送到远端」:差异预览只包含该文件。
11
+ 5. 设置 → 联动工作区 → 「自动推回远端」:打开开关会先出现黄色说明与「我明白,开启自动推送」,未确认前不会开启;确认后本地保存文件约 1.5 秒后自动出现在远端,同一文件远端也改过时保留远端版本。
12
+ 6. 断网或 SSH 断开时推送会失败并显示原因,本地文件不受影响。
13
+
5
14
  ## @ 引用与搜索增强(0.18.0)
6
15
 
7
16
  1. 内容搜索栏在「内容」模式下有五枚 chip(`Aa`、`.*`、目录范围、`.*/`、文件图标)与一个「停止」按钮(仅在搜索中、且有 jobId 时出现)。
package/lib/client.js CHANGED
@@ -2501,6 +2501,32 @@ function attributeViolation(name, value, tagName) {
2501
2501
  autoSaveHint: '编辑停顿约 1 秒后自动保存;关闭后请按 Ctrl+S 手动保存。',
2502
2502
  autoSaveLabel: '开启自动保存',
2503
2503
  autoSaveSaved: '自动保存设置已保存',
2504
+ syncTitle: '把本地改动推回远端',
2505
+ syncNeedsLinked: '只有联动工作区有本地目录可以推送',
2506
+ syncSummary: '新增 {{added}} · 修改 {{changed}} · 冲突 {{conflict}} · 远端已删 {{removed}}',
2507
+ syncNothing: '本地与远端一致,没有需要推送的文件。',
2508
+ syncTruncated: '文件太多,只比较了前 {{max}} 个;请先清理或分批推送。',
2509
+ syncSkipped: '跳过了 {{count}} 个(过大或无法读取)。',
2510
+ syncAdded: '新增',
2511
+ syncChanged: '修改',
2512
+ syncConflict: '冲突',
2513
+ syncRemoved: '远端已删',
2514
+ syncMore: '还有 {{count}} 个未列出…',
2515
+ syncPushSkip: '推送(跳过冲突)',
2516
+ syncPushOverwrite: '推送并覆盖冲突',
2517
+ syncPushing: '正在推送…',
2518
+ syncPushed: '已推送 {{pushed}} 个文件',
2519
+ syncConflictLeft: '{{count}} 个冲突未处理',
2520
+ ctxPushThis: '把这个推送到远端',
2521
+ autoPushTitle: '自动推回远端',
2522
+ autoPushLabel: '开启自动推送',
2523
+ autoPushWarn: '开启后,本地目录里保存的文件会在停止编辑约 1.5 秒后自动写回远端;如果同一文件在远端也被改过,会保留远端版本(不覆盖)。',
2524
+ autoPushConfirm: '我明白,开启自动推送',
2525
+ autoPushCancel: '先不开',
2526
+ autoPushIncludeLabel: '只推送这些路径(每行一个,支持 *)',
2527
+ autoPushExcludeLabel: '不要推送这些路径(每行一个,支持 *)',
2528
+ autoPushDebounceLabel: '停止编辑后等待(毫秒)',
2529
+ autoPushSaved: '自动推送设置已保存',
2504
2530
  execTitle: '远端命令执行',
2505
2531
  execHint: '默认关闭。开启后,会话里的模型可以通过 linked_workspace 的 exec 动作在远端跑命令;只对下面勾选的主机/工作区生效,每次尝试(含被拒)都记进审计日志。',
2506
2532
  execEnabledLabel: '允许在远端执行命令',
@@ -2999,6 +3025,32 @@ function attributeViolation(name, value, tagName) {
2999
3025
  autoSaveHint: 'Saves about one second after you stop typing. When off, press Ctrl+S to save.',
3000
3026
  autoSaveLabel: 'Enable auto save',
3001
3027
  autoSaveSaved: 'Auto-save setting saved',
3028
+ syncTitle: 'Push local changes back to the remote side',
3029
+ syncNeedsLinked: 'Only a linked workspace has a local directory to push',
3030
+ syncSummary: 'added {{added}} · changed {{changed}} · conflict {{conflict}} · gone upstream {{removed}}',
3031
+ syncNothing: 'Local and remote agree; nothing to push.',
3032
+ syncTruncated: 'Too many files; only the first {{max}} were compared. Tidy up or push in batches.',
3033
+ syncSkipped: '{{count}} skipped (too large or unreadable).',
3034
+ syncAdded: 'added',
3035
+ syncChanged: 'changed',
3036
+ syncConflict: 'conflict',
3037
+ syncRemoved: 'gone upstream',
3038
+ syncMore: '{{count}} more not listed…',
3039
+ syncPushSkip: 'Push (skip conflicts)',
3040
+ syncPushOverwrite: 'Push and overwrite conflicts',
3041
+ syncPushing: 'Pushing…',
3042
+ syncPushed: 'Pushed {{pushed}} file(s)',
3043
+ syncConflictLeft: '{{count}} conflict(s) left',
3044
+ ctxPushThis: 'Push this to the remote side',
3045
+ autoPushTitle: 'Push back automatically',
3046
+ autoPushLabel: 'Enable automatic push',
3047
+ autoPushWarn: 'Once enabled, files saved locally are written back about 1.5 s after you stop editing. If the same file also changed on the remote side, the remote version is kept (never overwritten).',
3048
+ autoPushConfirm: 'I understand, enable it',
3049
+ autoPushCancel: 'Not now',
3050
+ autoPushIncludeLabel: 'Only push these paths (one per line, * allowed)',
3051
+ autoPushExcludeLabel: 'Never push these paths (one per line, * allowed)',
3052
+ autoPushDebounceLabel: 'Wait after editing stops (ms)',
3053
+ autoPushSaved: 'Automatic push settings saved',
3002
3054
  execTitle: 'Remote command execution',
3003
3055
  execHint: 'Off by default. When on, the model can run commands on the remote host through the linked_workspace "exec" action — only for the hosts and workspaces ticked below, and every attempt (refusals included) is audited.',
3004
3056
  execEnabledLabel: 'Allow running commands remotely',
@@ -3203,7 +3255,7 @@ function attributeViolation(name, value, tagName) {
3203
3255
  * Host methods the running DSH process does not have yet, the directory
3204
3256
  * pane says so instead of surfacing an unrelated error.
3205
3257
  */
3206
- var HOST_API_REVISION = 4;
3258
+ var HOST_API_REVISION = 5;
3207
3259
  var hostInfoProbe = null;
3208
3260
 
3209
3261
  function probeHostInfo() {
@@ -3682,6 +3734,11 @@ function attributeViolation(name, value, tagName) {
3682
3734
  '.rw-warn-box{padding:8px 10px;border-radius:8px;border:1px solid color-mix(in srgb,var(--dsw-alias-state-warn-primary) 45%,transparent);background:color-mix(in srgb,var(--dsw-alias-state-warn-primary) 8%,var(--dsw-alias-bg-layer-1));font-size:12px;line-height:18px}',
3683
3735
  '.rw-setting-row{display:flex;align-items:center;gap:10px;padding:10px 12px;border:1px solid var(--dsw-alias-border-l1);border-radius:9px;background:var(--dsw-alias-bg-layer-1)}',
3684
3736
  '.rw-exec-list{display:flex;flex-direction:column;gap:4px;margin-top:8px}',
3737
+ '.rw-sync-list{display:flex;flex-direction:column;gap:2px;max-height:260px;overflow:auto;margin:8px 0;padding:6px 8px;border-radius:10px;background:var(--dsw-alias-bg-base)}',
3738
+ '.rw-sync-row{display:flex;align-items:center;gap:8px;font-size:12px;line-height:20px}',
3739
+ '.rw-sync-tag{flex:none;min-width:52px;color:rgb(150,150,152)}',
3740
+ '.rw-sync-path{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-family:var(--dsw-font-mono,monospace)}',
3741
+ '.rw-autopush-list{width:100%;resize:vertical;font-family:var(--dsw-font-mono,monospace);font-size:12px}',
3685
3742
  '.rw-exec-item{display:flex;align-items:center;gap:8px;padding:7px 10px;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-layer-1);cursor:pointer;font-size:13px}',
3686
3743
  '.rw-exec-item input[type=checkbox]{margin:0;flex:none}',
3687
3744
  '.rw-exec-name{flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
@@ -6080,6 +6137,14 @@ function attributeViolation(name, value, tagName) {
6080
6137
  style: props.transferEnabled ? undefined : { opacity: 0.42, cursor: 'default' },
6081
6138
  onClick: props.transferSelected,
6082
6139
  }, IconDownload(14)),
6140
+ h('button', {
6141
+ type: 'button',
6142
+ className: 'rw-icon-btn' + (props.syncBusy ? ' is-on' : ''),
6143
+ title: props.syncTitle || t('syncTitle'),
6144
+ disabled: !props.syncEnabled,
6145
+ style: props.syncEnabled ? undefined : { opacity: 0.42, cursor: 'default' },
6146
+ onClick: props.onSync,
6147
+ }, IconSync(14)),
6083
6148
  h('button', {
6084
6149
  type: 'button',
6085
6150
  className: 'rw-icon-btn',
@@ -6763,6 +6828,50 @@ function rememberShowHidden(value) {
6763
6828
  h('button', { type: 'button', className: 'rw-btn rw-btn-sm', onClick: props.onClose }, props.t('cancel'))));
6764
6829
  }
6765
6830
 
6831
+ function SyncPlanDialog(props) {
6832
+ var t = props.t;
6833
+ var plan = props.plan;
6834
+ var rows = []
6835
+ .concat((plan.added || []).map(function (item) { return { tag: t('syncAdded'), item: item }; }))
6836
+ .concat((plan.changed || []).map(function (item) { return { tag: t('syncChanged'), item: item }; }))
6837
+ .concat((plan.conflict || []).map(function (item) { return { tag: t('syncConflict'), item: item }; }))
6838
+ .concat((plan.removed || []).map(function (item) { return { tag: t('syncRemoved'), item: item }; }));
6839
+ var busy = Boolean(props.busy);
6840
+ return h(DialogShell, { title: t('syncTitle'), onClose: busy ? function () {} : props.onClose },
6841
+ h('div', { className: 'rw-dialog-message' },
6842
+ t('syncSummary', {
6843
+ added: (plan.added || []).length,
6844
+ changed: (plan.changed || []).length,
6845
+ conflict: (plan.conflict || []).length,
6846
+ removed: (plan.removed || []).length,
6847
+ })),
6848
+ plan.truncated ? h('div', { className: 'rw-dialog-message rw-warn-text' }, t('syncTruncated', { max: plan.maxFiles })) : null,
6849
+ plan.skipped ? h('div', { className: 'rw-dialog-message' }, t('syncSkipped', { count: plan.skipped })) : null,
6850
+ rows.length === 0
6851
+ ? h('div', { className: 'rw-dialog-message' }, t('syncNothing'))
6852
+ : h('div', { className: 'rw-sync-list' }, rows.slice(0, 40).map(function (row) {
6853
+ return h('div', { key: row.tag + row.item.relative, className: 'rw-sync-row' },
6854
+ h('span', { className: 'rw-sync-tag' }, row.tag),
6855
+ h('span', { className: 'rw-sync-path', title: row.item.relative }, row.item.relative));
6856
+ })),
6857
+ rows.length > 40 ? h('div', { className: 'rw-dialog-message' }, t('syncMore', { count: rows.length - 40 })) : null,
6858
+ props.message ? h('div', { className: 'rw-dialog-message' }, props.message) : null,
6859
+ h('div', { className: 'rw-dialog-actions' },
6860
+ h('button', { type: 'button', className: 'rw-btn rw-btn-sm', disabled: busy, onClick: props.onClose }, t('cancel')),
6861
+ h('button', {
6862
+ type: 'button',
6863
+ className: 'rw-btn rw-btn-sm',
6864
+ disabled: busy || plan.pending === 0,
6865
+ onClick: function () { props.onPush('skip'); },
6866
+ }, t('syncPushSkip')),
6867
+ h('button', {
6868
+ type: 'button',
6869
+ className: 'rw-btn rw-btn-sm rw-btn-primary',
6870
+ disabled: busy,
6871
+ onClick: function () { props.onPush('overwrite'); },
6872
+ }, t('syncPushOverwrite'))));
6873
+ }
6874
+
6766
6875
  function QueueDialog(props) {
6767
6876
  var history = props.history && props.history.length > 0 ? props.history : null;
6768
6877
  return h(DialogShell, { title: props.title, onClose: props.onClose },
@@ -7931,6 +8040,40 @@ function rememberShowHidden(value) {
7931
8040
  });
7932
8041
  }
7933
8042
 
8043
+ /** Open the diff preview for the whole workspace (or the given paths). */
8044
+ function openSyncPlan(paths) {
8045
+ var scope = sourceScopeOf(selected);
8046
+ if (!scope || scope.kind !== 'linked') return;
8047
+ apiCall('linked.plan', { id: scope.id, maxFiles: 2000 }).then(function (plan) {
8048
+ setDialog({
8049
+ kind: 'syncPlan',
8050
+ plan: plan,
8051
+ paths: Array.isArray(paths) && paths.length > 0 ? paths : null,
8052
+ busy: false,
8053
+ message: '',
8054
+ });
8055
+ }).catch(noticeError);
8056
+ }
8057
+
8058
+ /** Push the planned files back to the remote directory. */
8059
+ function pushPlan(plan, conflict, paths) {
8060
+ var scope = sourceScopeOf(selected);
8061
+ if (!scope || scope.kind !== 'linked') return;
8062
+ setDialog({ kind: 'syncPlan', plan: plan, paths: paths || null, busy: true, message: t('syncPushing') });
8063
+ var jobId = 'push-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8);
8064
+ var params = { id: scope.id, conflict: conflict, jobId: jobId };
8065
+ if (Array.isArray(paths) && paths.length > 0) params.paths = paths;
8066
+ apiCall('linked.push', params).then(function (result) {
8067
+ setDialog(null);
8068
+ var text = t('syncPushed', { pushed: result.pushed, skipped: result.skipped });
8069
+ if (result.conflictsLeft > 0) text += ' · ' + t('syncConflictLeft', { count: result.conflictsLeft });
8070
+ showNotice(result.pushed > 0 ? 'success' : 'warn', text);
8071
+ refreshTree();
8072
+ }).catch(function (error) {
8073
+ setDialog({ kind: 'syncPlan', plan: plan, paths: paths || null, busy: false, message: messageOf(error, t, locale) });
8074
+ });
8075
+ }
8076
+
7934
8077
  function editNotepad(side, filePath) {
7935
8078
  var method = side === 'remote' ? 'fs.edit' : 'local.edit';
7936
8079
  var params = side === 'remote'
@@ -8366,6 +8509,15 @@ function rememberShowHidden(value) {
8366
8509
  if (menu.side === 'remote' && menu.isDir) {
8367
8510
  items.push({ label: t('ctxCopySsh'), onSelect: function () { copySshCommand(menu.path); } });
8368
8511
  }
8512
+ if (selected.kind === 'linked' && menu.side === 'remote') {
8513
+ var remoteRoot = selected.remotePath;
8514
+ var relativePath = menu.path.indexOf(remoteRoot) === 0
8515
+ ? menu.path.slice(remoteRoot.length).replace(/^\/+/, '')
8516
+ : '';
8517
+ if (relativePath !== '') {
8518
+ items.push({ label: t('ctxPushThis'), onSelect: function () { openSyncPlan([relativePath]); } });
8519
+ }
8520
+ }
8369
8521
  items.push({ separator: true });
8370
8522
  var rootPath = menu.side === 'remote' ? selected.remotePath : selected.localPath;
8371
8523
  if (menu.path !== rootPath) {
@@ -8511,6 +8663,16 @@ function rememberShowHidden(value) {
8511
8663
  onPick: function (targetDir) { moveEntries(dialog.side, moveTargets, targetDir); },
8512
8664
  });
8513
8665
  }
8666
+ if (dialog.kind === 'syncPlan') {
8667
+ return h(SyncPlanDialog, {
8668
+ t: t,
8669
+ plan: dialog.plan,
8670
+ busy: Boolean(dialog.busy),
8671
+ message: dialog.message,
8672
+ onClose: function () { if (!dialog.busy) setDialog(null); },
8673
+ onPush: function (conflict) { return pushPlan(dialog.plan, conflict, dialog.paths); },
8674
+ });
8675
+ }
8514
8676
  if (dialog.kind === 'renameMany') {
8515
8677
  return h(BatchRenameDialog, {
8516
8678
  t: t,
@@ -8840,6 +9002,9 @@ function rememberShowHidden(value) {
8840
9002
  onToggleSearch: function () { setSearchOpen(!searchOpen); },
8841
9003
  onOpenMode: updateOpenMode,
8842
9004
  onRefresh: refreshAll,
9005
+ syncEnabled: selected.kind === 'linked',
9006
+ syncTitle: selected.kind === 'linked' ? t('syncTitle') : t('syncNeedsLinked'),
9007
+ onSync: function () { openSyncPlan(null); },
8843
9008
  }),
8844
9009
  searchOpen
8845
9010
  ? h('div', { className: 'rw-searchbar' },
@@ -10772,6 +10937,163 @@ function rememberShowHidden(value) {
10772
10937
  return h('div', { className: 'rw-group' }, children);
10773
10938
  }
10774
10939
 
10940
+ function AutoPushSettingsGroup(props) {
10941
+ var t = props.t;
10942
+ var locale = props.locale;
10943
+ var localState = useState({ loading: true, saving: false, message: null, asking: false });
10944
+ var local = localState[0];
10945
+ var setLocal = localState[1];
10946
+ var valuesState = useState({
10947
+ autoPushEnabled: false,
10948
+ autoPushDebounceMs: 1500,
10949
+ autoPushInclude: '',
10950
+ autoPushExclude: '',
10951
+ });
10952
+ var values = valuesState[0];
10953
+ var setValues = valuesState[1];
10954
+
10955
+ useEffect(function () {
10956
+ var alive = true;
10957
+ apiCall('settings.get', {}).then(function (settings) {
10958
+ if (!alive) return;
10959
+ setValues({
10960
+ autoPushEnabled: settings.autoPushEnabled === true,
10961
+ autoPushDebounceMs: Number(settings.autoPushDebounceMs) || 1500,
10962
+ autoPushInclude: (settings.autoPushInclude || []).join('\n'),
10963
+ autoPushExclude: (settings.autoPushExclude || []).join('\n'),
10964
+ });
10965
+ setLocal(function (previous) { return Object.assign({}, previous, { loading: false }); });
10966
+ }).catch(function () {
10967
+ if (alive) setLocal(function (previous) { return Object.assign({}, previous, { loading: false }); });
10968
+ });
10969
+ return function () { alive = false; };
10970
+ }, []);
10971
+
10972
+ function save(patch, okText) {
10973
+ setLocal(function (previous) { return Object.assign({}, previous, { saving: true, message: null }); });
10974
+ apiCall('settings.update', patch).then(function (settings) {
10975
+ setValues({
10976
+ autoPushEnabled: settings.autoPushEnabled === true,
10977
+ autoPushDebounceMs: Number(settings.autoPushDebounceMs) || 1500,
10978
+ autoPushInclude: (settings.autoPushInclude || []).join('\n'),
10979
+ autoPushExclude: (settings.autoPushExclude || []).join('\n'),
10980
+ });
10981
+ setLocal({ loading: false, saving: false, asking: false, message: { kind: 'success', text: okText } });
10982
+ }).catch(function (error) {
10983
+ setLocal({
10984
+ loading: false,
10985
+ saving: false,
10986
+ asking: false,
10987
+ message: { kind: 'error', text: messageOf(error, t, locale) },
10988
+ });
10989
+ });
10990
+ }
10991
+
10992
+ function toggle(next) {
10993
+ if (next === true && values.autoPushEnabled === false) {
10994
+ // Turning it on writes files behind the user's back: ask once, in
10995
+ // place, before the switch actually flips.
10996
+ setLocal(function (previous) { return Object.assign({}, previous, { asking: true, message: null }); });
10997
+ return;
10998
+ }
10999
+ save({ autoPushEnabled: Boolean(next) }, t('autoPushSaved'));
11000
+ }
11001
+
11002
+ function commitList(field, key) {
11003
+ var lines = String(values[field] || '').split('\n').map(function (line) { return line.trim(); }).filter(function (line) { return line !== ''; });
11004
+ var patch = {};
11005
+ patch[key] = lines;
11006
+ save(patch, t('autoPushSaved'));
11007
+ }
11008
+
11009
+ var children = [
11010
+ h('div', { className: 'rw-group-head' },
11011
+ h('span', { className: 'rw-group-title' }, t('autoPushTitle'))),
11012
+ h('div', { className: 'rw-setting-row' },
11013
+ h(Switch, {
11014
+ checked: values.autoPushEnabled,
11015
+ onChange: toggle,
11016
+ label: t('autoPushLabel'),
11017
+ text: t('autoPushLabel'),
11018
+ }),
11019
+ local.saving ? Spinner(12) : null),
11020
+ ];
11021
+
11022
+ if (local.asking && !values.autoPushEnabled) {
11023
+ children.push(h('div', { className: 'rw-group-hint', style: { marginTop: 8, color: 'rgb(210,153,34)' } }, t('autoPushWarn')));
11024
+ children.push(h('div', { className: 'rw-dialog-actions', style: { marginTop: 10 } },
11025
+ h('button', {
11026
+ type: 'button',
11027
+ className: 'rw-btn rw-btn-sm',
11028
+ onClick: function () { setLocal(function (previous) { return Object.assign({}, previous, { asking: false }); }); },
11029
+ }, t('autoPushCancel')),
11030
+ h('button', {
11031
+ type: 'button',
11032
+ className: 'rw-btn rw-btn-sm rw-btn-primary',
11033
+ onClick: function () { save({ autoPushEnabled: true }, t('autoPushSaved')); },
11034
+ }, t('autoPushConfirm'))));
11035
+ }
11036
+
11037
+ if (values.autoPushEnabled) {
11038
+ children.push(h('div', { className: 'rw-group-hint', style: { marginTop: 8 } }, t('autoPushWarn')));
11039
+ children.push(h('div', { className: 'rw-group-head', style: { marginTop: 12 } },
11040
+ h('span', { className: 'rw-group-title' }, t('autoPushIncludeLabel'))));
11041
+ children.push(h('textarea', {
11042
+ className: 'rw-input rw-input-mono rw-autopush-list',
11043
+ rows: 3,
11044
+ value: values.autoPushInclude,
11045
+ placeholder: 'src/**\ndocs/*.md',
11046
+ onChange: function (event) {
11047
+ var value = event.currentTarget.value;
11048
+ setValues(function (previous) { return Object.assign({}, previous, { autoPushInclude: value }); });
11049
+ },
11050
+ onBlur: function () { commitList('autoPushInclude', 'autoPushInclude'); },
11051
+ }));
11052
+ children.push(h('div', { className: 'rw-group-head', style: { marginTop: 12 } },
11053
+ h('span', { className: 'rw-group-title' }, t('autoPushExcludeLabel'))));
11054
+ children.push(h('textarea', {
11055
+ className: 'rw-input rw-input-mono rw-autopush-list',
11056
+ rows: 3,
11057
+ value: values.autoPushExclude,
11058
+ placeholder: '*.log\n.remote/**',
11059
+ onChange: function (event) {
11060
+ var value = event.currentTarget.value;
11061
+ setValues(function (previous) { return Object.assign({}, previous, { autoPushExclude: value }); });
11062
+ },
11063
+ onBlur: function () { commitList('autoPushExclude', 'autoPushExclude'); },
11064
+ }));
11065
+ children.push(h('div', { className: 'rw-inline', style: { marginTop: 12, flexWrap: 'wrap', gap: 12 } },
11066
+ h('span', { className: 'rw-setting-label' }, t('autoPushDebounceLabel')),
11067
+ h('input', {
11068
+ className: 'rw-input rw-input-num',
11069
+ type: 'number',
11070
+ min: 300,
11071
+ max: 60000,
11072
+ step: 100,
11073
+ value: values.autoPushDebounceMs,
11074
+ onChange: function (event) {
11075
+ var value = event.currentTarget.value;
11076
+ setValues(function (previous) { return Object.assign({}, previous, { autoPushDebounceMs: value }); });
11077
+ },
11078
+ onBlur: function () {
11079
+ var ms = Math.round(Number(values.autoPushDebounceMs) || 1500);
11080
+ save({ autoPushDebounceMs: ms }, t('autoPushSaved'));
11081
+ },
11082
+ })));
11083
+ }
11084
+
11085
+ if (local.message) {
11086
+ children.push(h(Banner, {
11087
+ kind: local.message.kind === 'success' ? 'success' : 'error',
11088
+ onClose: function () {
11089
+ setLocal(function (previous) { return Object.assign({}, previous, { message: null }); });
11090
+ },
11091
+ }, local.message.text));
11092
+ }
11093
+
11094
+ return h('div', { className: 'rw-group' }, children);
11095
+ }
11096
+
10775
11097
  function ConnectionsPage(props) {
10776
11098
  var ctx = props.ctx;
10777
11099
  var locale = useLocale(ctx);
@@ -10838,6 +11160,7 @@ function rememberShowHidden(value) {
10838
11160
  hosts: remote.data.hosts || [],
10839
11161
  workspaces: links.concat(remotes),
10840
11162
  }),
11163
+ h(AutoPushSettingsGroup, { t: t, locale: locale }),
10841
11164
  adding === 'linked'
10842
11165
  ? h(AddWorkspaceFlow, {
10843
11166
  ctx: ctx, t: t, locale: locale,
package/lib/index.js CHANGED
@@ -15,8 +15,8 @@
15
15
  * Credentials never leave this process: the client only sees host names,
16
16
  * addresses and workspace paths.
17
17
  */
18
- import { randomUUID } from 'node:crypto'
19
- import { chmodSync, closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
18
+ import { createHash, randomUUID } from 'node:crypto'
19
+ import { chmodSync, closeSync, cpSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, readdirSync, renameSync, rmSync, statSync, watch, writeFileSync } from 'node:fs'
20
20
  import { spawn } from 'node:child_process'
21
21
  import { appendFile, mkdir, readdir, rename, rm, stat as fsStat } from 'node:fs/promises'
22
22
  import { homedir, tmpdir } from 'node:os'
@@ -38,7 +38,7 @@ export const inject = ['webServer', 'tools', 'systemPrompt', 'workingDirectory']
38
38
  * is still running an older copy of the Host — refreshing the page only swaps
39
39
  * the browser bundle, so the two halves can drift by one restart.
40
40
  */
41
- const API_REVISION = 4
41
+ const API_REVISION = 5
42
42
 
43
43
  /** When this copy of the Host was loaded; shown by `meta.info`. */
44
44
  const STARTED_AT = new Date().toISOString()
@@ -55,7 +55,9 @@ const PACKAGE_VERSION = (() => {
55
55
 
56
56
  const DATA_VERSION = 1
57
57
  const SETTINGS_VERSION = 1
58
- const SETTINGS_DEFAULTS = Object.freeze({ editorTheme: 'github-light', editorThemeFamily: 'github', editorThemeMode: 'system', fileOpenMode: 'editor', autoSave: false, execEnabled: false, execTimeoutMs: 60000, execMaxOutputChars: 200000, execShell: '' })
58
+ 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 })
59
+ const AUTO_PUSH_DEBOUNCE_MIN = 300
60
+ const AUTO_PUSH_DEBOUNCE_MAX = 60000
59
61
  /** Exec allow-lists travel as arrays, so they are not part of the frozen defaults. */
60
62
  const EMPTY_ID_LIST = Object.freeze([])
61
63
  const EDITOR_THEME_FAMILIES = new Set(['github', 'solarized', 'one', 'dracula', 'monokai', 'nord', 'vscode', 'xcode', 'catppuccin'])
@@ -94,8 +96,7 @@ const PEEK_LIMIT = 512 * 1024
94
96
  const READ_CAP = 8 * 1024 * 1024
95
97
  const MAX_WRITE_BYTES = 8 * 1024 * 1024
96
98
  const MAX_MEDIA_BYTES = 24 * 1024 * 1024
97
- // ── remote command execution (0.17.0) ───────────────────────────────────────
98
- /** Longest command line accepted; anything longer is almost always a paste error. */
99
+ // ── remote command execution (0.17.0) ───────────────────────────────────────/** Longest command line accepted; anything longer is almost always a paste error. */
99
100
  const EXEC_MAX_COMMAND = 8000
100
101
  const EXEC_TIMEOUT_DEFAULT = 60_000
101
102
  const EXEC_TIMEOUT_MAX = 600_000
@@ -449,10 +450,26 @@ function clampInt(value, min, max, fallback) {
449
450
  return Math.min(max, Math.max(min, Math.round(number)))
450
451
  }
451
452
 
453
+ /** Same idea as normalizeIdList, for the auto-push include/exclude patterns. */
454
+ function normalizeStringList(value) {
455
+ if (!Array.isArray(value)) return []
456
+ const seen = new Set()
457
+ const out = []
458
+ for (const item of value) {
459
+ if (typeof item !== 'string') continue
460
+ const pattern = item.trim()
461
+ if (pattern === '' || seen.has(pattern)) continue
462
+ seen.add(pattern)
463
+ out.push(pattern)
464
+ if (out.length >= 100) break
465
+ }
466
+ return out
467
+ }
468
+
452
469
  class SettingsStore {
453
470
  constructor(file) {
454
471
  this.file = file
455
- this.value = { ...SETTINGS_DEFAULTS, execHostIds: [], execWorkspaceIds: [] }
472
+ this.value = { ...SETTINGS_DEFAULTS, execHostIds: [], execWorkspaceIds: [], autoPushInclude: [], autoPushExclude: [] }
456
473
  const raw = readJsonFile(file, { version: SETTINGS_VERSION, settings: {} })
457
474
  const settings = raw && typeof raw === 'object' && raw.settings && typeof raw.settings === 'object'
458
475
  ? raw.settings
@@ -482,6 +499,16 @@ class SettingsStore {
482
499
  if (settings && typeof settings === 'object' && typeof settings.autoSave === 'boolean') {
483
500
  this.value.autoSave = settings.autoSave
484
501
  }
502
+ if (settings && typeof settings === 'object' && typeof settings.autoPushEnabled === 'boolean') {
503
+ this.value.autoPushEnabled = settings.autoPushEnabled
504
+ }
505
+ if (settings && typeof settings === 'object') {
506
+ if (settings.autoPushDebounceMs !== undefined) {
507
+ this.value.autoPushDebounceMs = clampInt(settings.autoPushDebounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, SETTINGS_DEFAULTS.autoPushDebounceMs)
508
+ }
509
+ this.value.autoPushInclude = normalizeStringList(settings.autoPushInclude)
510
+ this.value.autoPushExclude = normalizeStringList(settings.autoPushExclude)
511
+ }
485
512
  if (settings && typeof settings === 'object' && settings.themeExplicit === true) {
486
513
  this.themeExplicit = true
487
514
  }
@@ -514,6 +541,8 @@ class SettingsStore {
514
541
  ...this.value,
515
542
  execHostIds: this.value.execHostIds ? this.value.execHostIds.slice() : [],
516
543
  execWorkspaceIds: this.value.execWorkspaceIds ? this.value.execWorkspaceIds.slice() : [],
544
+ autoPushInclude: this.value.autoPushInclude ? this.value.autoPushInclude.slice() : [],
545
+ autoPushExclude: this.value.autoPushExclude ? this.value.autoPushExclude.slice() : [],
517
546
  }
518
547
  }
519
548
 
@@ -566,6 +595,21 @@ class SettingsStore {
566
595
  }
567
596
  this.value.execShell = patch.execShell
568
597
  }
598
+ if (patch && typeof patch === 'object' && patch.autoPushEnabled !== undefined) {
599
+ if (typeof patch.autoPushEnabled !== 'boolean') throw new ApiError('BAD_REQUEST', '自动推送设置无效')
600
+ this.value.autoPushEnabled = patch.autoPushEnabled
601
+ }
602
+ if (patch && typeof patch === 'object' && patch.autoPushDebounceMs !== undefined) {
603
+ this.value.autoPushDebounceMs = clampInt(patch.autoPushDebounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, SETTINGS_DEFAULTS.autoPushDebounceMs)
604
+ }
605
+ if (patch && typeof patch === 'object' && patch.autoPushInclude !== undefined) {
606
+ if (!Array.isArray(patch.autoPushInclude)) throw new ApiError('BAD_REQUEST', '自动推送包含列表必须是字符串数组')
607
+ this.value.autoPushInclude = normalizeStringList(patch.autoPushInclude)
608
+ }
609
+ if (patch && typeof patch === 'object' && patch.autoPushExclude !== undefined) {
610
+ if (!Array.isArray(patch.autoPushExclude)) throw new ApiError('BAD_REQUEST', '自动推送排除列表必须是字符串数组')
611
+ this.value.autoPushExclude = normalizeStringList(patch.autoPushExclude)
612
+ }
569
613
  writeJsonAtomic(this.file, { version: SETTINGS_VERSION, settings: { ...this.value, themeExplicit: this.themeExplicit === true } })
570
614
  return this.get()
571
615
  }
@@ -1814,6 +1858,375 @@ export function apply(ctx) {
1814
1858
  job.updatedAt = Date.now()
1815
1859
  }
1816
1860
 
1861
+ // ── local → remote push (0.19.0) ────────────────────────────────────────
1862
+ //
1863
+ // The local directory is the place people edit, and it is also where tools
1864
+ // (formatters, codegen, notebooks) write. `linked.plan` compares the two
1865
+ // sides file by file against the hash recorded at the last successful push,
1866
+ // so "changed here, untouched there" can be pushed safely while a file that
1867
+ // moved on *both* sides is reported as a conflict instead of being clobbered.
1868
+ // The state file is the only new data structure: without a baseline a two
1869
+ // sided hash comparison cannot tell "I edited this" from "they edited this".
1870
+
1871
+ const PUSH_STATE_NAME = 'push-state.json'
1872
+ const PUSH_MAX_FILES = 2000
1873
+ const PUSH_FILES_CONFLICT = new Set(['skip', 'overwrite', 'newer'])
1874
+
1875
+ const pushStateFile = () => join(dir, PUSH_STATE_NAME)
1876
+
1877
+ const readPushState = () => {
1878
+ const raw = readJsonFile(pushStateFile(), { version: 1, byWorkspace: {} })
1879
+ const byWorkspace = raw && typeof raw.byWorkspace === 'object' && raw.byWorkspace ? raw.byWorkspace : {}
1880
+ return { version: 1, byWorkspace }
1881
+ }
1882
+
1883
+ const writePushState = (state) => {
1884
+ writeJsonAtomic(pushStateFile(), state)
1885
+ }
1886
+
1887
+ const hashBytes = (buffer) => createHash('sha256').update(buffer).digest('hex')
1888
+
1889
+ /** Every regular file under the local directory, mirror/excludes skipped. */
1890
+ const walkLocalTree = async (record, limit = PUSH_MAX_FILES) => {
1891
+ const root = resolve(record.localPath)
1892
+ const files = []
1893
+ let truncated = false
1894
+ let skipped = 0
1895
+ const visit = async (current, prefix, depth) => {
1896
+ if (truncated) return
1897
+ if (depth > LINKED_SYNC_MAX_DEPTH) { skipped += 1; return }
1898
+ let entries
1899
+ try {
1900
+ entries = await readdir(current, { withFileTypes: true })
1901
+ } catch {
1902
+ skipped += 1
1903
+ return
1904
+ }
1905
+ for (const entry of entries) {
1906
+ if (files.length >= limit) { truncated = true; return }
1907
+ const name = entry.name
1908
+ if (entry.isDirectory()) {
1909
+ if (name === linkedFs.MIRROR_DIR || LINKED_SYNC_EXCLUDES.has(name) || name === '.remote') continue
1910
+ await visit(join(current, name), prefix === '' ? name : `${prefix}/${name}`, depth + 1)
1911
+ continue
1912
+ }
1913
+ if (!entry.isFile()) { skipped += 1; continue }
1914
+ let info
1915
+ try {
1916
+ info = await fsStat(join(current, name))
1917
+ } catch {
1918
+ skipped += 1
1919
+ continue
1920
+ }
1921
+ files.push({
1922
+ relative: prefix === '' ? name : `${prefix}/${name}`,
1923
+ absolute: join(current, name),
1924
+ size: info.size,
1925
+ mtimeMs: info.mtimeMs,
1926
+ })
1927
+ }
1928
+ }
1929
+ await visit(root, '', 0)
1930
+ return { files, truncated, skipped }
1931
+ }
1932
+
1933
+ const readLocalHash = async (file) => {
1934
+ if (file.size > LINKED_SYNC_FILE) return null
1935
+ try {
1936
+ return hashBytes(readFileSync(file.absolute))
1937
+ } catch {
1938
+ return null
1939
+ }
1940
+ }
1941
+
1942
+ const readRemoteHash = async (remote, remotePath, size) => {
1943
+ if (size > LINKED_SYNC_FILE) return null
1944
+ try {
1945
+ const read = await withTimeout(remote.readFile(remotePath, { maxBytes: LINKED_SYNC_FILE }), LINKED_SYNC_TIMEOUT_MS, 'push plan')
1946
+ return hashBytes(read.data)
1947
+ } catch {
1948
+ return null
1949
+ }
1950
+ }
1951
+
1952
+ /**
1953
+ * Classify every local file against the remote side and the last push:
1954
+ * added — remote has no such file (or it changed and the baseline agrees),
1955
+ * changed — both sides differ from the baseline but remote is untouched,
1956
+ * conflict— remote moved away from the baseline too,
1957
+ * removed — the baseline knows a file that is gone locally (never pushed).
1958
+ */
1959
+ const buildPlan = async (record, remote, options = {}) => {
1960
+ const limit = clampInt(options.maxFiles, 1, 5000, PUSH_MAX_FILES)
1961
+ const walk = await walkLocalTree(record, limit)
1962
+ const state = readPushState()
1963
+ const baseline = state.byWorkspace[record.id] && typeof state.byWorkspace[record.id] === 'object'
1964
+ ? state.byWorkspace[record.id]
1965
+ : {}
1966
+ const buckets = { added: [], changed: [], conflict: [], removed: [] }
1967
+ let unchanged = 0
1968
+ let skipped = walk.skipped
1969
+ for (const file of walk.files) {
1970
+ const localHash = await readLocalHash(file)
1971
+ if (localHash === null) { skipped += 1; continue }
1972
+ const remotePath = posix.join(record.remotePath, file.relative)
1973
+ const known = baseline[file.relative]
1974
+ let remoteStat = null
1975
+ try {
1976
+ remoteStat = await remote.stat(remotePath)
1977
+ } catch {
1978
+ remoteStat = null
1979
+ }
1980
+ if (!remoteStat || remoteStat.type !== 'file') {
1981
+ buckets.added.push({ relative: file.relative, size: file.size, localHash, remoteHash: null })
1982
+ continue
1983
+ }
1984
+ const remoteHash = await readRemoteHash(remote, remotePath, remoteStat.size)
1985
+ if (remoteHash !== null && remoteHash === localHash) {
1986
+ unchanged += 1
1987
+ continue
1988
+ }
1989
+ const baselineHash = known && typeof known.hash === 'string' ? known.hash : ''
1990
+ const entry = { relative: file.relative, size: file.size, localHash, remoteHash }
1991
+ if (baselineHash === '' || baselineHash === remoteHash) buckets.changed.push(entry)
1992
+ else buckets.conflict.push(entry)
1993
+ }
1994
+ for (const relative of Object.keys(baseline)) {
1995
+ if (walk.files.some((file) => file.relative === relative)) continue
1996
+ buckets.removed.push({ relative })
1997
+ }
1998
+ return {
1999
+ linkedId: record.id,
2000
+ localPath: record.localPath,
2001
+ remotePath: record.remotePath,
2002
+ maxFiles: limit,
2003
+ truncated: walk.truncated,
2004
+ skipped,
2005
+ unchanged,
2006
+ added: buckets.added,
2007
+ changed: buckets.changed,
2008
+ conflict: buckets.conflict,
2009
+ removed: buckets.removed,
2010
+ pending: buckets.added.length + buckets.changed.length,
2011
+ }
2012
+ }
2013
+
2014
+ const pushOneFile = async (record, remote, file, baseline) => {
2015
+ const data = readFileSync(file.absolute)
2016
+ const target = posix.join(record.remotePath, file.relative)
2017
+ await remote.mkdirp(posix.dirname(target))
2018
+ await withTimeout(remote.writeFileAtomic(target, data), LINKED_SYNC_TIMEOUT_MS, `push ${file.relative}`)
2019
+ baseline[file.relative] = { hash: hashBytes(data), size: data.length, pushedAt: Date.now() }
2020
+ return data.length
2021
+ }
2022
+
2023
+ const applyPlan = async (record, remote, plan, options = {}, job = null) => {
2024
+ const mode = PUSH_FILES_CONFLICT.has(options.conflict) ? options.conflict : 'skip'
2025
+ const only = Array.isArray(options.paths) && options.paths.length > 0
2026
+ ? new Set(options.paths.map((item) => String(item).replace(/^\/+/, '')))
2027
+ : null
2028
+ const state = readPushState()
2029
+ const baseline = state.byWorkspace[record.id] && typeof state.byWorkspace[record.id] === 'object'
2030
+ ? state.byWorkspace[record.id]
2031
+ : {}
2032
+ const queue = [...plan.added, ...plan.changed].filter((item) => !only || only.has(item.relative))
2033
+ const conflicted = plan.conflict.filter((item) => !only || only.has(item.relative))
2034
+ const pushed = []
2035
+ let bytes = 0
2036
+ let skipped = 0
2037
+ const dryRun = options.dryRun === true
2038
+ for (const item of queue) {
2039
+ if (job && job.cancelled) break
2040
+ if (dryRun) {
2041
+ pushed.push({ relative: item.relative, size: item.size, dryRun: true })
2042
+ continue
2043
+ }
2044
+ try {
2045
+ const written = await pushOneFile(record, remote, {
2046
+ relative: item.relative,
2047
+ absolute: join(record.localPath, item.relative),
2048
+ }, baseline)
2049
+ bytes += written
2050
+ pushed.push({ relative: item.relative, size: written })
2051
+ countTransferred(job, written)
2052
+ } catch (error) {
2053
+ skipped += 1
2054
+ pushed.push({ relative: item.relative, error: error && error.message ? error.message : String(error) })
2055
+ }
2056
+ }
2057
+ let resolvedConflicts = 0
2058
+ if (mode !== 'skip' && !dryRun) {
2059
+ for (const item of conflicted) {
2060
+ if (job && job.cancelled) break
2061
+ const remoteStat = await remote.stat(posix.join(record.remotePath, item.relative)).catch(() => null)
2062
+ const takeLocal = mode === 'overwrite'
2063
+ || (mode === 'newer' && (!remoteStat || Date.now() >= remoteStat.mtime))
2064
+ if (!takeLocal) { skipped += 1; continue }
2065
+ try {
2066
+ const written = await pushOneFile(record, remote, {
2067
+ relative: item.relative,
2068
+ absolute: join(record.localPath, item.relative),
2069
+ }, baseline)
2070
+ bytes += written
2071
+ resolvedConflicts += 1
2072
+ pushed.push({ relative: item.relative, size: written, resolved: 'conflict' })
2073
+ countTransferred(job, written)
2074
+ } catch (error) {
2075
+ skipped += 1
2076
+ pushed.push({ relative: item.relative, error: error && error.message ? error.message : String(error) })
2077
+ }
2078
+ }
2079
+ }
2080
+ if (!dryRun && pushed.some((item) => !item.error)) {
2081
+ state.byWorkspace[record.id] = baseline
2082
+ writePushState(state)
2083
+ appendTransferHistory({
2084
+ kind: 'push',
2085
+ linkedId: record.id,
2086
+ localPath: record.localPath,
2087
+ remotePath: record.remotePath,
2088
+ files: pushed.filter((item) => !item.error).length,
2089
+ bytes,
2090
+ skipped,
2091
+ at: Date.now(),
2092
+ })
2093
+ }
2094
+ return {
2095
+ linkedId: record.id,
2096
+ dryRun,
2097
+ conflict: mode,
2098
+ files: pushed,
2099
+ pushed: pushed.filter((item) => !item.error).length,
2100
+ skipped,
2101
+ conflictsLeft: conflicted.length - resolvedConflicts,
2102
+ bytes,
2103
+ cancelled: Boolean(job && job.cancelled),
2104
+ }
2105
+ }
2106
+
2107
+ // ── transfer history ────────────────────────────────────────────────────
2108
+ //
2109
+ // The queue dialog forgets everything when it closes, so the last few
2110
+ // transfers are persisted: it is the only place to answer "did that upload
2111
+ // actually finish?" after the fact.
2112
+
2113
+ const HISTORY_NAME = 'transfer-history.json'
2114
+ const HISTORY_LIMIT = 50
2115
+
2116
+ const appendTransferHistory = (entry) => {
2117
+ try {
2118
+ const raw = readJsonFile(join(dir, HISTORY_NAME), { version: 1, entries: [] })
2119
+ const entries = Array.isArray(raw && raw.entries) ? raw.entries.slice() : []
2120
+ entries.unshift(entry)
2121
+ writeJsonAtomic(join(dir, HISTORY_NAME), { version: 1, entries: entries.slice(0, HISTORY_LIMIT) })
2122
+ } catch (error) {
2123
+ console.error('[dsh-linked-workspace] transfer history write failed:', error && error.message ? error.message : error)
2124
+ }
2125
+ }
2126
+
2127
+ // ── autoPush ────────────────────────────────────────────────────────────
2128
+ //
2129
+ // Opt-in watcher on the local directory: after a quiet period the changed
2130
+ // files are pushed with `conflict: 'skip'`, so a file that moved on the
2131
+ // remote side is never overwritten by a formatter saving on this side.
2132
+ // `include`/`exclude` are simple globs (`*` only) matched against the
2133
+ // workspace-relative path.
2134
+
2135
+ const AUTO_PUSH_RETRY_MS = 2000
2136
+ const autoPushWatchers = new Map()
2137
+
2138
+ const globToRegExp = (pattern) => {
2139
+ const escaped = String(pattern).replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*').replace(/\?/g, '.')
2140
+ return new RegExp(`^${escaped}$`, 'i')
2141
+ }
2142
+
2143
+ const autoPushMatches = (patterns, relative) => {
2144
+ if (!Array.isArray(patterns) || patterns.length === 0) return null
2145
+ for (const pattern of patterns) {
2146
+ if (typeof pattern === 'string' && globToRegExp(pattern).test(relative)) return true
2147
+ }
2148
+ return false
2149
+ }
2150
+
2151
+ const autoPushFilter = (settings, plan) => {
2152
+ const include = autoPushMatches(settings.autoPushInclude, '')
2153
+ const keep = (item) => {
2154
+ const included = autoPushMatches(settings.autoPushInclude, item.relative)
2155
+ if (included === false) return false
2156
+ const excluded = autoPushMatches(settings.autoPushExclude, item.relative)
2157
+ if (excluded === true) return false
2158
+ return true
2159
+ }
2160
+ void include
2161
+ return { ...plan, added: plan.added.filter(keep), changed: plan.changed.filter(keep) }
2162
+ }
2163
+
2164
+ const stopAutoPush = (id) => {
2165
+ const entry = autoPushWatchers.get(id)
2166
+ if (!entry) return
2167
+ if (entry.timer) clearTimeout(entry.timer)
2168
+ try { entry.watcher.close() } catch { /* already closed */ }
2169
+ autoPushWatchers.delete(id)
2170
+ }
2171
+
2172
+ const runAutoPush = async (record, entry) => {
2173
+ if (entry.running) return
2174
+ entry.running = true
2175
+ try {
2176
+ const settings = settingsStore.get()
2177
+ if (!settings.autoPushEnabled) return
2178
+ const host = await findHost(record.hostId)
2179
+ const remote = await connectHost(host)
2180
+ const plan = autoPushFilter(settings, await buildPlan(record, remote, {}))
2181
+ if (plan.added.length === 0 && plan.changed.length === 0) return
2182
+ const result = await applyPlan(record, remote, plan, { conflict: 'skip' })
2183
+ forgetListings()
2184
+ log('info', `autoPush ${record.name}: ${result.pushed} file(s), ${result.skipped} skipped`)
2185
+ } catch (error) {
2186
+ log('warn', `autoPush ${record.name} failed: ${error && error.message ? error.message : error}`)
2187
+ entry.timer = setTimeout(() => { entry.timer = null; void runAutoPush(record, entry) }, AUTO_PUSH_RETRY_MS)
2188
+ } finally {
2189
+ entry.running = false
2190
+ }
2191
+ }
2192
+
2193
+ const scheduleAutoPush = (record, entry) => {
2194
+ if (entry.timer) clearTimeout(entry.timer)
2195
+ const settings = settingsStore.get()
2196
+ const delay = clampInt(settings.autoPushDebounceMs, AUTO_PUSH_DEBOUNCE_MIN, AUTO_PUSH_DEBOUNCE_MAX, 1500)
2197
+ entry.timer = setTimeout(() => {
2198
+ entry.timer = null
2199
+ void runAutoPush(record, entry)
2200
+ }, delay)
2201
+ if (entry.timer && typeof entry.timer.unref === 'function') entry.timer.unref()
2202
+ }
2203
+
2204
+ /** Start/stop watchers so they match the current settings; safe to call often. */
2205
+ const syncAutoPush = () => {
2206
+ const settings = settingsStore.get()
2207
+ const wanted = settings.autoPushEnabled === true
2208
+ for (const id of [...autoPushWatchers.keys()]) {
2209
+ const record = linkedStore.get(id)
2210
+ if (!wanted || !record) stopAutoPush(id)
2211
+ }
2212
+ if (!wanted) return
2213
+ for (const record of linkedStore.list()) {
2214
+ if (autoPushWatchers.has(record.id)) continue
2215
+ let watcher
2216
+ try {
2217
+ watcher = watch(record.localPath, { recursive: true, persistent: false }, () => {
2218
+ const entry = autoPushWatchers.get(record.id)
2219
+ if (entry) scheduleAutoPush(record, entry)
2220
+ })
2221
+ } catch (error) {
2222
+ log('warn', `autoPush watcher for ${record.name} failed: ${error && error.message ? error.message : error}`)
2223
+ continue
2224
+ }
2225
+ watcher.on('error', () => stopAutoPush(record.id))
2226
+ autoPushWatchers.set(record.id, { watcher, timer: null, running: false })
2227
+ }
2228
+ }
2229
+
1817
2230
  // A content search can run for seconds; the client can stop it by job id the
1818
2231
  // same way it stops a transfer. The flag is checked between files.
1819
2232
  const GREP_JOB_TTL_MS = 60 * 1000
@@ -3114,17 +3527,60 @@ export function apply(ctx) {
3114
3527
  const scope = await requireScope(params)
3115
3528
  if (scope.kind !== 'linked') throw new ApiError('BAD_REQUEST', '只有联动工作区支持文件传输')
3116
3529
  const job = beginTransferJob(params.jobId)
3530
+ // 0.19.0: a batch carries several paths, so a multi-selection no longer
3531
+ // turns into N round trips that each rebuild the queue entry.
3532
+ const batch = Array.isArray(params.paths) && params.paths.length > 0
3533
+ ? params.paths.filter((item) => typeof item === 'string' && item.trim() !== '')
3534
+ : null
3117
3535
  try {
3118
3536
  if (params.side === 'local') {
3119
- const result = await transferLocalToRemote(scope.record, scope.remote, params.path, job)
3537
+ const list = batch || [params.path]
3538
+ const total = { side: 'local', files: 0, bytes: 0, skipped: 0, truncated: false, targets: [] }
3539
+ for (const item of list) {
3540
+ const result = await transferLocalToRemote(scope.record, scope.remote, item, job)
3541
+ total.files += result.files
3542
+ total.bytes += result.bytes
3543
+ total.skipped += result.skipped
3544
+ total.truncated = total.truncated || result.truncated
3545
+ total.targets.push(result.target)
3546
+ }
3120
3547
  forgetListings()
3121
3548
  finishTransferJob(job, 'done')
3122
- return result
3549
+ appendTransferHistory({
3550
+ kind: 'transfer',
3551
+ direction: 'local-to-remote',
3552
+ linkedId: scope.record.id,
3553
+ files: total.files,
3554
+ bytes: total.bytes,
3555
+ skipped: total.skipped,
3556
+ truncated: total.truncated,
3557
+ at: Date.now(),
3558
+ })
3559
+ return total
3560
+ }
3561
+ const list = batch || [params.path]
3562
+ const total = { side: 'remote', files: 0, bytes: 0, skipped: 0, truncated: false, targets: [] }
3563
+ for (const item of list) {
3564
+ const target = scopeTarget(scope, item)
3565
+ const result = await transferToMirror(scope.record, scope.remote, target, job)
3566
+ total.files += result.files
3567
+ total.bytes += result.bytes
3568
+ total.skipped += result.skipped
3569
+ total.truncated = total.truncated || result.truncated
3570
+ total.targets.push(result.dest)
3123
3571
  }
3124
- const target = scopeTarget(scope, params.path)
3125
- const result = await transferToMirror(scope.record, scope.remote, target, job)
3126
3572
  finishTransferJob(job, 'done')
3127
- return result
3573
+ appendTransferHistory({
3574
+ kind: 'transfer',
3575
+ direction: 'remote-to-mirror',
3576
+ linkedId: scope.record.id,
3577
+ files: total.files,
3578
+ bytes: total.bytes,
3579
+ skipped: total.skipped,
3580
+ truncated: total.truncated,
3581
+ at: Date.now(),
3582
+ })
3583
+ return total
3128
3584
  } catch (error) {
3129
3585
  finishTransferJob(job, error && error.code === 'CANCELLED' ? 'cancelled' : 'failed', error && error.message ? error.message : '')
3130
3586
  throw error
@@ -3237,7 +3693,11 @@ export function apply(ctx) {
3237
3693
  },
3238
3694
 
3239
3695
  async 'settings.update'(params = {}) {
3240
- return settingsStore.update(params)
3696
+ const next = settingsStore.update(params)
3697
+ // Toggling autoPush (or editing its filters) has to start/stop watchers
3698
+ // without a restart; the call is cheap and idempotent.
3699
+ syncAutoPush()
3700
+ return next
3241
3701
  },
3242
3702
 
3243
3703
  // ── local directories (workspace pickers) ──────────────────────────────
@@ -4156,6 +4616,49 @@ export function apply(ctx) {
4156
4616
  return { cancelled: true }
4157
4617
  },
4158
4618
 
4619
+ /** What the local directory has that the remote side does not (and vice versa). */
4620
+ async 'linked.plan'(params = {}) {
4621
+ const record = requireLinked(params.id)
4622
+ const host = await findHost(record.hostId)
4623
+ const remote = await connectHost(host)
4624
+ return await buildPlan(record, remote, params)
4625
+ },
4626
+
4627
+ /** Write local files back to the remote directory, atomically per file. */
4628
+ async 'linked.push'(params = {}) {
4629
+ const record = requireLinked(params.id)
4630
+ const host = await findHost(record.hostId)
4631
+ const remote = await connectHost(host)
4632
+ const job = beginTransferJob(params.jobId)
4633
+ try {
4634
+ const plan = await buildPlan(record, remote, params)
4635
+ const result = await applyPlan(record, remote, plan, params, job)
4636
+ forgetListings()
4637
+ finishTransferJob(job, result.cancelled ? 'cancelled' : 'done')
4638
+ return result
4639
+ } catch (error) {
4640
+ finishTransferJob(job, error && error.code === 'CANCELLED' ? 'cancelled' : 'failed', error && error.message ? error.message : '')
4641
+ throw error
4642
+ }
4643
+ },
4644
+
4645
+ /** Ask a running push to stop after the file it is writing. */
4646
+ async 'linked.pushCancel'(params = {}) {
4647
+ const id = typeof params.jobId === 'string' ? params.jobId : ''
4648
+ const job = transferJobs.get(id)
4649
+ if (!job) return { cancelled: false }
4650
+ job.cancelled = true
4651
+ job.updatedAt = Date.now()
4652
+ return { cancelled: true }
4653
+ },
4654
+
4655
+ /** The last few transfers and pushes, newest first. */
4656
+ async 'transfer.history'() {
4657
+ const raw = readJsonFile(join(dir, HISTORY_NAME), { version: 1, entries: [] })
4658
+ const entries = Array.isArray(raw && raw.entries) ? raw.entries : []
4659
+ return { entries: entries.slice(0, HISTORY_LIMIT) }
4660
+ },
4661
+
4159
4662
  // ── remote_workspaces methods ───────────────────────────────────────────────
4160
4663
 
4161
4664
  async 'remote_workspaces.list'() {
@@ -4843,6 +5346,17 @@ export function apply(ctx) {
4843
5346
  })
4844
5347
  }, 900)
4845
5348
  if (titleMigrationTimer && typeof titleMigrationTimer.unref === 'function') titleMigrationTimer.unref()
5349
+
5350
+ // autoPush may already be enabled from a previous run: start its watchers and
5351
+ // make sure they are closed when this plugin instance goes away.
5352
+ try {
5353
+ syncAutoPush()
5354
+ } catch (error) {
5355
+ log('warn', `autoPush start failed: ${error && error.message ? error.message : error}`)
5356
+ }
5357
+ ctx.effect(() => () => {
5358
+ for (const id of [...autoPushWatchers.keys()]) stopAutoPush(id)
5359
+ }, 'dsh-linked-workspace: auto push watchers')
4846
5360
  }
4847
5361
 
4848
5362
  // ── response helpers ────────────────────────────────────────────────────────
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-linked-workspace",
3
- "version": "0.18.0",
3
+ "version": "0.19.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",