@ddtcorex/dsh-maestro-core 0.10.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.
Files changed (285) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +209 -0
  3. package/cordis.patch.yml +43 -0
  4. package/lib/bin.d.ts +2 -0
  5. package/lib/bin.js +3 -0
  6. package/lib/boot-guard.d.ts +33 -0
  7. package/lib/boot-guard.js +68 -0
  8. package/lib/boot-lock.d.ts +56 -0
  9. package/lib/boot-lock.js +155 -0
  10. package/lib/cli.d.ts +31 -0
  11. package/lib/cli.js +336 -0
  12. package/lib/client.js +2901 -0
  13. package/lib/config/index.d.ts +34 -0
  14. package/lib/config/index.js +62 -0
  15. package/lib/config/service.d.ts +18 -0
  16. package/lib/config/service.js +28 -0
  17. package/lib/config.d.ts +1 -0
  18. package/lib/config.js +19 -0
  19. package/lib/daemon-freshness.d.ts +48 -0
  20. package/lib/daemon-freshness.js +122 -0
  21. package/lib/debug-agent.d.ts +17 -0
  22. package/lib/debug-agent.js +144 -0
  23. package/lib/dsh-session.d.ts +26 -0
  24. package/lib/dsh-session.js +45 -0
  25. package/lib/guard/config.d.ts +82 -0
  26. package/lib/guard/config.js +211 -0
  27. package/lib/guard/decide.d.ts +30 -0
  28. package/lib/guard/decide.js +38 -0
  29. package/lib/guard/full-scan-tool.d.ts +6 -0
  30. package/lib/guard/full-scan-tool.js +65 -0
  31. package/lib/guard/index.d.ts +85 -0
  32. package/lib/guard/index.js +254 -0
  33. package/lib/guard/journal.d.ts +146 -0
  34. package/lib/guard/journal.js +398 -0
  35. package/lib/guard/migrate.d.ts +15 -0
  36. package/lib/guard/migrate.js +42 -0
  37. package/lib/guard/parse.d.ts +193 -0
  38. package/lib/guard/parse.js +1103 -0
  39. package/lib/guard/paths.d.ts +104 -0
  40. package/lib/guard/paths.js +254 -0
  41. package/lib/guard/permission-policy.d.ts +10 -0
  42. package/lib/guard/permission-policy.js +21 -0
  43. package/lib/guard/redact.d.ts +25 -0
  44. package/lib/guard/redact.js +52 -0
  45. package/lib/guard/rules.d.ts +65 -0
  46. package/lib/guard/rules.js +832 -0
  47. package/lib/guard/status-tool.d.ts +54 -0
  48. package/lib/guard/status-tool.js +195 -0
  49. package/lib/guard/tiers.d.ts +2 -0
  50. package/lib/guard/tiers.js +1 -0
  51. package/lib/guard/validators.d.ts +4 -0
  52. package/lib/guard/validators.js +45 -0
  53. package/lib/health-poller.d.ts +90 -0
  54. package/lib/health-poller.js +430 -0
  55. package/lib/index.d.ts +7 -0
  56. package/lib/index.js +7 -0
  57. package/lib/intents.d.ts +32 -0
  58. package/lib/intents.js +49 -0
  59. package/lib/notifier.d.ts +12 -0
  60. package/lib/notifier.js +62 -0
  61. package/lib/paths.d.ts +13 -0
  62. package/lib/paths.js +70 -0
  63. package/lib/plugin.d.ts +250 -0
  64. package/lib/plugin.js +1126 -0
  65. package/lib/preset.d.ts +73 -0
  66. package/lib/preset.js +158 -0
  67. package/lib/report.d.ts +11 -0
  68. package/lib/report.js +58 -0
  69. package/lib/restart-exec.d.ts +35 -0
  70. package/lib/restart-exec.js +60 -0
  71. package/lib/restart-guards.d.ts +39 -0
  72. package/lib/restart-guards.js +150 -0
  73. package/lib/restart-tool.d.ts +124 -0
  74. package/lib/restart-tool.js +539 -0
  75. package/lib/restart-web.d.ts +26 -0
  76. package/lib/restart-web.js +58 -0
  77. package/lib/resume-log.d.ts +24 -0
  78. package/lib/resume-log.js +18 -0
  79. package/lib/resume-tools.d.ts +131 -0
  80. package/lib/resume-tools.js +337 -0
  81. package/lib/resume.d.ts +33 -0
  82. package/lib/resume.js +221 -0
  83. package/lib/scan.d.ts +20 -0
  84. package/lib/scan.js +71 -0
  85. package/lib/self-kill-guard.d.ts +81 -0
  86. package/lib/self-kill-guard.js +208 -0
  87. package/lib/session-health.d.ts +89 -0
  88. package/lib/session-health.js +274 -0
  89. package/lib/session-log-file.d.ts +22 -0
  90. package/lib/session-log-file.js +74 -0
  91. package/lib/skill-provider.d.ts +6 -0
  92. package/lib/skill-provider.js +73 -0
  93. package/lib/snapshot.d.ts +59 -0
  94. package/lib/snapshot.js +358 -0
  95. package/lib/source.d.ts +19 -0
  96. package/lib/source.js +19 -0
  97. package/lib/store/index.d.ts +42 -0
  98. package/lib/store/index.js +340 -0
  99. package/lib/store/legacy.d.ts +17 -0
  100. package/lib/store/legacy.js +85 -0
  101. package/lib/supervisor.d.ts +119 -0
  102. package/lib/supervisor.js +741 -0
  103. package/lib/sync/backup-config.d.ts +55 -0
  104. package/lib/sync/backup-config.js +119 -0
  105. package/lib/sync/backup-service.d.ts +110 -0
  106. package/lib/sync/backup-service.js +440 -0
  107. package/lib/sync/bidirectional.d.ts +39 -0
  108. package/lib/sync/bidirectional.js +25 -0
  109. package/lib/sync/cli.d.ts +38 -0
  110. package/lib/sync/cli.js +536 -0
  111. package/lib/sync/config.d.ts +77 -0
  112. package/lib/sync/config.js +90 -0
  113. package/lib/sync/fingerprint.d.ts +29 -0
  114. package/lib/sync/fingerprint.js +65 -0
  115. package/lib/sync/hashing.d.ts +9 -0
  116. package/lib/sync/hashing.js +47 -0
  117. package/lib/sync/index.d.ts +6 -0
  118. package/lib/sync/index.js +634 -0
  119. package/lib/sync/machine-id.d.ts +29 -0
  120. package/lib/sync/machine-id.js +66 -0
  121. package/lib/sync/merge.d.ts +33 -0
  122. package/lib/sync/merge.js +88 -0
  123. package/lib/sync/peer-host.d.ts +22 -0
  124. package/lib/sync/peer-host.js +62 -0
  125. package/lib/sync/process-runner.d.ts +31 -0
  126. package/lib/sync/process-runner.js +161 -0
  127. package/lib/sync/remote-agent.d.ts +42 -0
  128. package/lib/sync/remote-agent.js +217 -0
  129. package/lib/sync/remote-cache.d.ts +18 -0
  130. package/lib/sync/remote-cache.js +60 -0
  131. package/lib/sync/remote-manifest.d.ts +8 -0
  132. package/lib/sync/remote-manifest.js +64 -0
  133. package/lib/sync/s3-object-store.d.ts +38 -0
  134. package/lib/sync/s3-object-store.js +126 -0
  135. package/lib/sync/session-merge.d.ts +18 -0
  136. package/lib/sync/session-merge.js +191 -0
  137. package/lib/sync/session-plan.d.ts +29 -0
  138. package/lib/sync/session-plan.js +213 -0
  139. package/lib/sync/sigv4.d.ts +20 -0
  140. package/lib/sync/sigv4.js +57 -0
  141. package/lib/sync/snapshot.d.ts +21 -0
  142. package/lib/sync/snapshot.js +176 -0
  143. package/lib/sync/ssh-mux.d.ts +12 -0
  144. package/lib/sync/ssh-mux.js +48 -0
  145. package/lib/sync/sync-plan.d.ts +24 -0
  146. package/lib/sync/sync-plan.js +366 -0
  147. package/lib/sync/sync-service.d.ts +177 -0
  148. package/lib/sync/sync-service.js +819 -0
  149. package/lib/sync/sync-types.d.ts +87 -0
  150. package/lib/sync/sync-types.js +1 -0
  151. package/lib/sync/transport.d.ts +75 -0
  152. package/lib/sync/transport.js +200 -0
  153. package/lib/sync/tunnel-restore.d.ts +77 -0
  154. package/lib/sync/tunnel-restore.js +142 -0
  155. package/lib/sync/validation.d.ts +10 -0
  156. package/lib/sync/validation.js +83 -0
  157. package/lib/tool-view.d.ts +62 -0
  158. package/lib/tool-view.js +70 -0
  159. package/lib/types/client/auto-reload.d.ts +8 -0
  160. package/lib/types/client/auto-reload.d.ts.map +1 -0
  161. package/lib/types/client/config/MaestroSettings.d.ts +25 -0
  162. package/lib/types/client/config/MaestroSettings.d.ts.map +1 -0
  163. package/lib/types/client/config/components/BrandMark.d.ts +50 -0
  164. package/lib/types/client/config/components/BrandMark.d.ts.map +1 -0
  165. package/lib/types/client/config/guard-view.d.ts +83 -0
  166. package/lib/types/client/config/guard-view.d.ts.map +1 -0
  167. package/lib/types/client/config/index.d.ts +20 -0
  168. package/lib/types/client/config/index.d.ts.map +1 -0
  169. package/lib/types/client/config/maestro-mark.d.ts +29 -0
  170. package/lib/types/client/config/maestro-mark.d.ts.map +1 -0
  171. package/lib/types/client/config/settings-nav-icon.d.ts +21 -0
  172. package/lib/types/client/config/settings-nav-icon.d.ts.map +1 -0
  173. package/lib/types/client/index.d.ts +16 -0
  174. package/lib/types/client/index.d.ts.map +1 -0
  175. package/lib/types/client/sync/R2SyncPanel.d.ts +6 -0
  176. package/lib/types/client/sync/R2SyncPanel.d.ts.map +1 -0
  177. package/lib/types/client/sync/SyncPanel.d.ts +12 -0
  178. package/lib/types/client/sync/SyncPanel.d.ts.map +1 -0
  179. package/lib/types/client/sync/confirm-dialog.d.ts +43 -0
  180. package/lib/types/client/sync/confirm-dialog.d.ts.map +1 -0
  181. package/lib/types/client/sync/index.d.ts +10 -0
  182. package/lib/types/client/sync/index.d.ts.map +1 -0
  183. package/lib/types/client/sync/ui.d.ts +79 -0
  184. package/lib/types/client/sync/ui.d.ts.map +1 -0
  185. package/lib/types/client/sync/use-backup.d.ts +50 -0
  186. package/lib/types/client/sync/use-backup.d.ts.map +1 -0
  187. package/lib/types/client/sync/use-sync.d.ts +88 -0
  188. package/lib/types/client/sync/use-sync.d.ts.map +1 -0
  189. package/package.json +89 -0
  190. package/skills/dsh-safe-restart/SKILL.md +206 -0
  191. package/skills/dsh-safe-restart/scripts/restart-dsh-web.sh +468 -0
  192. package/src/client/auto-reload.ts +104 -0
  193. package/src/client/config/MaestroSettings.tsx +892 -0
  194. package/src/client/config/components/BrandMark.tsx +94 -0
  195. package/src/client/config/guard-view.ts +187 -0
  196. package/src/client/config/index.tsx +109 -0
  197. package/src/client/config/maestro-mark.ts +37 -0
  198. package/src/client/config/settings-nav-icon.ts +68 -0
  199. package/src/client/index.tsx +33 -0
  200. package/src/client/sync/R2SyncPanel.tsx +260 -0
  201. package/src/client/sync/SyncPanel.tsx +422 -0
  202. package/src/client/sync/confirm-dialog.tsx +202 -0
  203. package/src/client/sync/index.tsx +336 -0
  204. package/src/client/sync/ui.tsx +313 -0
  205. package/src/client/sync/use-backup.ts +207 -0
  206. package/src/client/sync/use-sync.ts +502 -0
  207. package/src/host/bin.ts +3 -0
  208. package/src/host/boot-guard.ts +76 -0
  209. package/src/host/boot-lock.ts +155 -0
  210. package/src/host/cli.ts +288 -0
  211. package/src/host/config/index.ts +78 -0
  212. package/src/host/config/service.ts +40 -0
  213. package/src/host/config.ts +18 -0
  214. package/src/host/daemon-freshness.ts +143 -0
  215. package/src/host/debug-agent.ts +145 -0
  216. package/src/host/dsh-session.ts +56 -0
  217. package/src/host/dsh-skill.d.ts +44 -0
  218. package/src/host/guard/augment.d.ts +33 -0
  219. package/src/host/guard/config.ts +244 -0
  220. package/src/host/guard/decide.ts +40 -0
  221. package/src/host/guard/full-scan-tool.ts +61 -0
  222. package/src/host/guard/index.ts +281 -0
  223. package/src/host/guard/journal.ts +440 -0
  224. package/src/host/guard/migrate.ts +41 -0
  225. package/src/host/guard/parse.ts +1150 -0
  226. package/src/host/guard/paths.ts +239 -0
  227. package/src/host/guard/permission-policy.ts +15 -0
  228. package/src/host/guard/redact.ts +64 -0
  229. package/src/host/guard/rules.ts +891 -0
  230. package/src/host/guard/status-tool.ts +229 -0
  231. package/src/host/guard/tiers.ts +2 -0
  232. package/src/host/guard/validators.ts +29 -0
  233. package/src/host/health-poller.ts +446 -0
  234. package/src/host/index.ts +7 -0
  235. package/src/host/intents.ts +67 -0
  236. package/src/host/notifier.ts +71 -0
  237. package/src/host/paths.ts +70 -0
  238. package/src/host/plugin.ts +1097 -0
  239. package/src/host/preset.ts +170 -0
  240. package/src/host/report.ts +71 -0
  241. package/src/host/restart-exec.ts +81 -0
  242. package/src/host/restart-guards.ts +150 -0
  243. package/src/host/restart-tool.ts +483 -0
  244. package/src/host/restart-web.ts +72 -0
  245. package/src/host/resume-log.ts +39 -0
  246. package/src/host/resume-tools.ts +385 -0
  247. package/src/host/resume.ts +204 -0
  248. package/src/host/scan.ts +61 -0
  249. package/src/host/self-kill-guard.ts +216 -0
  250. package/src/host/session-health.ts +236 -0
  251. package/src/host/session-log-file.ts +77 -0
  252. package/src/host/skill-provider.ts +69 -0
  253. package/src/host/snapshot.ts +337 -0
  254. package/src/host/source.ts +19 -0
  255. package/src/host/store/index.ts +348 -0
  256. package/src/host/store/legacy.ts +96 -0
  257. package/src/host/supervisor.ts +720 -0
  258. package/src/host/sync/backup-config.ts +159 -0
  259. package/src/host/sync/backup-service.ts +453 -0
  260. package/src/host/sync/bidirectional.ts +66 -0
  261. package/src/host/sync/cli.ts +539 -0
  262. package/src/host/sync/config.ts +119 -0
  263. package/src/host/sync/fingerprint.ts +83 -0
  264. package/src/host/sync/hashing.ts +58 -0
  265. package/src/host/sync/index.ts +737 -0
  266. package/src/host/sync/machine-id.ts +81 -0
  267. package/src/host/sync/merge.ts +102 -0
  268. package/src/host/sync/peer-host.ts +65 -0
  269. package/src/host/sync/process-runner.ts +177 -0
  270. package/src/host/sync/remote-agent.ts +213 -0
  271. package/src/host/sync/remote-cache.ts +68 -0
  272. package/src/host/sync/remote-manifest.ts +70 -0
  273. package/src/host/sync/s3-object-store.ts +144 -0
  274. package/src/host/sync/session-merge.ts +220 -0
  275. package/src/host/sync/session-plan.ts +237 -0
  276. package/src/host/sync/sigv4.ts +81 -0
  277. package/src/host/sync/snapshot.ts +162 -0
  278. package/src/host/sync/ssh-mux.ts +56 -0
  279. package/src/host/sync/sync-plan.ts +366 -0
  280. package/src/host/sync/sync-service.ts +855 -0
  281. package/src/host/sync/sync-types.ts +102 -0
  282. package/src/host/sync/transport.ts +261 -0
  283. package/src/host/sync/tunnel-restore.ts +160 -0
  284. package/src/host/sync/validation.ts +91 -0
  285. package/src/host/tool-view.ts +98 -0
@@ -0,0 +1,207 @@
1
+ // src/client/use-backup.ts — R2 Sync tab controller (backup/restore/gc).
2
+ // Owns all R2-tab state: redacted status, backup preview job, restore modes,
3
+ // gc report, and the confirm dialog bound to a live preview id. Only shared
4
+ // presentation components are reused with the Remote tab — no shared state.
5
+ import * as React from 'react';
6
+ import { RPC_CHANNEL } from './ui.js';
7
+
8
+ export interface BackupStatusView {
9
+ configured: boolean;
10
+ source: 'env' | 'file' | 'none';
11
+ bucket: string;
12
+ prefix: string;
13
+ /** Non-secret snapshot for the config form (never secret material). */
14
+ r2?: { provider: string; endpoint: string; region: string; bucket: string; prefix: string };
15
+ lastManifest: string | null;
16
+ eligible: { md: number; sessions: number };
17
+ }
18
+
19
+ export function useBackupTarget(ctx: any) {
20
+ const [status, setStatus] = React.useState<BackupStatusView | null>(null);
21
+ const [checking, setChecking] = React.useState(true);
22
+ const [busy, setBusy] = React.useState(false);
23
+ const [error, setError] = React.useState('');
24
+ const [backupPreview, setBackupPreview] = React.useState<any>(null);
25
+ const [restorePreview, setRestorePreview] = React.useState<any>(null);
26
+ const [gcReport, setGcReport] = React.useState<any>(null);
27
+ const [confirmOpen, setConfirmOpen] = React.useState<'backup' | 'restore' | 'gc' | null>(null);
28
+
29
+ const call = React.useCallback(async (method: string, payload: any) => {
30
+ const conn = (ctx as any).connection ?? (ctx as any).get?.('connection');
31
+ const res: any = await conn.rpc.call(RPC_CHANNEL, method, payload);
32
+ if (res && typeof res === 'object' && 'ok' in res) return res;
33
+ return { ok: true, value: res };
34
+ }, [ctx]);
35
+
36
+ const loadStatus = React.useCallback(async () => {
37
+ setChecking(true);
38
+ setError('');
39
+ try {
40
+ const res = await call('backupStatus', {});
41
+ if (res.ok) setStatus(res.value);
42
+ else setError(res.error?.message ?? 'backup status failed');
43
+ } catch (e: any) {
44
+ setError(e?.message ?? String(e));
45
+ } finally {
46
+ setChecking(false);
47
+ }
48
+ }, [call]);
49
+
50
+ const previewBackup = React.useCallback(async () => {
51
+ setBusy(true);
52
+ setError('');
53
+ setBackupPreview(null);
54
+ try {
55
+ const res = await call('backupPreview', {});
56
+ if (res.ok) {
57
+ setBackupPreview(res.value);
58
+ setConfirmOpen('backup');
59
+ } else setError(res.error?.message ?? 'backup preview failed');
60
+ } catch (e: any) {
61
+ setError(e?.message ?? String(e));
62
+ } finally {
63
+ setBusy(false);
64
+ }
65
+ }, [call]);
66
+
67
+ const applyBackup = React.useCallback(async () => {
68
+ if (!backupPreview?.previewId) return;
69
+ setBusy(true);
70
+ try {
71
+ const res = await call('backupApply', { previewId: backupPreview.previewId, confirm: true });
72
+ setConfirmOpen(null);
73
+ setBackupPreview(null);
74
+ if (!res.ok) setError(res.error?.message ?? 'backup apply failed');
75
+ void loadStatus();
76
+ } catch (e: any) {
77
+ setError(e?.message ?? String(e));
78
+ } finally {
79
+ setBusy(false);
80
+ }
81
+ }, [backupPreview, call, loadStatus]);
82
+
83
+ const previewRestore = React.useCallback(
84
+ async (mode: 'new-dir' | 'in-place') => {
85
+ setBusy(true);
86
+ setError('');
87
+ try {
88
+ const res = await call('restorePreview', { mode });
89
+ if (res.ok) {
90
+ setRestorePreview(res.value);
91
+ setConfirmOpen('restore');
92
+ } else setError(res.error?.message ?? 'restore preview failed');
93
+ } catch (e: any) {
94
+ setError(e?.message ?? String(e));
95
+ } finally {
96
+ setBusy(false);
97
+ }
98
+ },
99
+ [call],
100
+ );
101
+
102
+ const applyRestore = React.useCallback(
103
+ async (mode: 'new-dir' | 'in-place', destDir?: string) => {
104
+ if (!restorePreview?.previewId) return;
105
+ setBusy(true);
106
+ try {
107
+ const res = await call('restoreApply', { previewId: restorePreview.previewId, mode, destDir, confirm: true });
108
+ setConfirmOpen(null);
109
+ setRestorePreview(null);
110
+ if (!res.ok) setError(res.error?.message ?? 'restore apply failed');
111
+ if (mode === 'in-place') void loadStatus();
112
+ } catch (e: any) {
113
+ setError(e?.message ?? String(e));
114
+ } finally {
115
+ setBusy(false);
116
+ }
117
+ },
118
+ [restorePreview, call, loadStatus],
119
+ );
120
+
121
+ const previewGc = React.useCallback(async () => {
122
+ setBusy(true);
123
+ setError('');
124
+ try {
125
+ const res = await call('backupGcPreview', {});
126
+ if (res.ok) {
127
+ setGcReport(res.value);
128
+ setConfirmOpen('gc');
129
+ } else setError(res.error?.message ?? 'gc preview failed');
130
+ } catch (e: any) {
131
+ setError(e?.message ?? String(e));
132
+ } finally {
133
+ setBusy(false);
134
+ }
135
+ }, [call]);
136
+
137
+ const applyGc = React.useCallback(async () => {
138
+ if (!gcReport?.previewId) return;
139
+ setBusy(true);
140
+ try {
141
+ const res = await call('backupGcApply', { previewId: gcReport.previewId, confirm: true });
142
+ setConfirmOpen(null);
143
+ setGcReport(null);
144
+ if (!res.ok) setError(res.error?.message ?? 'gc apply failed');
145
+ void loadStatus();
146
+ } catch (e: any) {
147
+ setError(e?.message ?? String(e));
148
+ } finally {
149
+ setBusy(false);
150
+ }
151
+ }, [gcReport, call, loadStatus]);
152
+
153
+ const cancelDialog = React.useCallback(() => {
154
+ setConfirmOpen(null);
155
+ setBackupPreview(null);
156
+ setRestorePreview(null);
157
+ setGcReport(null);
158
+ }, []);
159
+
160
+ /** Persist the non-secret backup target, then reload status. */
161
+ const saveR2Config = React.useCallback(
162
+ async (fields: { provider: string; accountId: string; endpoint: string; region: string; bucket: string; prefix: string }): Promise<{ ok: boolean; error?: string }> => {
163
+ setError('');
164
+ try {
165
+ const res = await call('saveR2Config', fields);
166
+ if (!res.ok) {
167
+ const msg = res.error?.message ?? 'save failed';
168
+ setError(msg);
169
+ return { ok: false, error: msg };
170
+ }
171
+ await loadStatus();
172
+ return { ok: true };
173
+ } catch (e: any) {
174
+ const msg = e?.message ?? String(e);
175
+ setError(msg);
176
+ return { ok: false, error: msg };
177
+ }
178
+ },
179
+ [call, loadStatus],
180
+ );
181
+
182
+ React.useEffect(() => {
183
+ void loadStatus();
184
+ }, [loadStatus]);
185
+
186
+ const configured = status?.configured === true;
187
+ return {
188
+ status,
189
+ checking,
190
+ busy,
191
+ error,
192
+ backupPreview,
193
+ restorePreview,
194
+ gcReport,
195
+ confirmOpen,
196
+ canBackup: configured && !checking && !busy,
197
+ loadStatus,
198
+ saveR2Config,
199
+ previewBackup,
200
+ applyBackup,
201
+ previewRestore,
202
+ applyRestore,
203
+ previewGc,
204
+ applyGc,
205
+ cancelDialog,
206
+ };
207
+ }
@@ -0,0 +1,502 @@
1
+ import * as React from 'react'
2
+ import { RPC_CHANNEL } from './ui.js'
3
+
4
+ /**
5
+ * Shared Sync state machine — confirmation-first Preview/Apply.
6
+ * - Preview is read-only; apply exists only inside a confirmation dialog bound
7
+ * to the live preview id, with {confirm:true}. Escape cancels; nothing applies
8
+ * without confirmation.
9
+ * - status pages two buckets (localOnly / remoteOnly) with cursors.
10
+ */
11
+
12
+ export interface SyncConnection {
13
+ ok: boolean
14
+ host: string
15
+ latencyMs?: number
16
+ error?: string
17
+ }
18
+
19
+ export interface PageState {
20
+ files: string[]
21
+ total: number
22
+ next: number | null
23
+ /** true once the first page has settled — separates "still loading" from "genuinely empty" */
24
+ loaded?: boolean
25
+ }
26
+
27
+ export type Bucket = 'localOnly' | 'remoteOnly'
28
+
29
+ export function useSync(ctx: any) {
30
+ const [remoteHost, setRemoteHost] = React.useState<string>('…')
31
+ // Where the SSH target came from: settings (saved) | env | default.
32
+ const [remoteSource, setRemoteSource] = React.useState<string>('default')
33
+ const [lastSync, setLastSync] = React.useState<string | null>(() => {
34
+ try {
35
+ return typeof localStorage !== 'undefined' ? localStorage.getItem('dsh-maestro-sync:lastSync') : null
36
+ } catch {
37
+ return null
38
+ }
39
+ })
40
+ const [status, setStatus] = React.useState<any>(null)
41
+ const [connection, setConnection] = React.useState<SyncConnection | null>(null)
42
+ // Machine identity (loaded alongside the connection check; null = not
43
+ // loaded yet — failures render inline with ok:false + reason, never null,
44
+ // so the line cannot vanish silently; the tab never blocks on it).
45
+ const [machines, setMachines] = React.useState<{ localId: string | null; remoteId: string | null; from?: string; to?: string; ok?: boolean; reason?: string } | null>(null)
46
+ // Idle until the user explicitly checks: entering the tab never probes SSH.
47
+ const [checking, setChecking] = React.useState<boolean>(false)
48
+ const [busy, setBusy] = React.useState<boolean>(false)
49
+ const [result, setResult] = React.useState<{ kind: string; ok: boolean; text: string } | null>(null)
50
+ const [error, setError] = React.useState<string>('')
51
+ const [preview, setPreview] = React.useState<any>(null)
52
+ const [previewDirection, setPreviewDirection] = React.useState<'pull' | 'push'>('pull')
53
+ const [confirmOpen, setConfirmOpen] = React.useState(false)
54
+ // Tunnel restore: read-only preview + its own confirmation dialog. The
55
+ // mutation rewrites domains.tunnel in the shared store, so it may never fire
56
+ // from the button itself.
57
+ const [tunnelPreview, setTunnelPreview] = React.useState<any>(null)
58
+ const [tunnelConfirmOpen, setTunnelConfirmOpen] = React.useState(false)
59
+ // Field-level error for the SSH target — the server validates, but the
60
+ // message must land under the field it belongs to, not in a generic banner.
61
+ const [hostFieldError, setHostFieldError] = React.useState<string | null>(null)
62
+ // Bidirectional round trip: one combined preview (exact push + projected
63
+ // pull), one confirmation, one server-side push-then-pull apply.
64
+ const [biPreview, setBiPreview] = React.useState<any>(null)
65
+ const [biConfirmOpen, setBiConfirmOpen] = React.useState(false)
66
+ const [actionLimit, setActionLimit] = React.useState(5)
67
+ const [progress, setProgress] = React.useState<{ phase: string; current: number; total: number; file?: string } | null>(null)
68
+ const cancelledRef = React.useRef(false)
69
+ const [pages, setPages] = React.useState<Record<Bucket, PageState>>({
70
+ localOnly: { files: [], total: 0, next: null, loaded: false },
71
+ remoteOnly: { files: [], total: 0, next: null, loaded: false },
72
+ })
73
+
74
+ // dsh-client-connection decodes every RPC response as the carrier shape
75
+ // { ok: true, value } | { ok: false, error: { code, message, details } }.
76
+ // Unwrap to the payload; normalize the failure error to a string.
77
+ const call = React.useCallback(async (method: string, payload: any): Promise<any> => {
78
+ const conn = (ctx as any).connection ?? (ctx as any).get?.('connection')
79
+ if (!conn?.rpc?.call) throw new Error('RPC not available')
80
+ const res: any = await conn.rpc.call(RPC_CHANNEL, method, payload)
81
+ if (res && typeof res === 'object' && 'ok' in res) {
82
+ if (res.ok) return res.value
83
+ const err = res.error
84
+ if (typeof err === 'string') return { ok: false, error: err }
85
+ return { ok: false, error: err?.message ?? 'RPC failed', code: typeof err?.code === 'string' ? err.code : undefined }
86
+ }
87
+ return res
88
+ }, [ctx])
89
+
90
+ const loadPage = React.useCallback(
91
+ async (bucket: Bucket, cursor: number) => {
92
+ try {
93
+ const res: any = await call('status', { bucket, cursor, limit: 10 })
94
+ if (!res) return
95
+ setPages((prev) => ({
96
+ ...prev,
97
+ [bucket]: {
98
+ files: cursor === 0 ? (res.files ?? []) : [...prev[bucket].files, ...(res.files ?? [])],
99
+ total: res.total ?? prev[bucket].total,
100
+ next: res.nextCursor ?? null,
101
+ loaded: true,
102
+ },
103
+ }))
104
+ } catch {
105
+ // page load failure is non-fatal
106
+ }
107
+ },
108
+ [call],
109
+ )
110
+
111
+ const loadStatus = React.useCallback(async () => {
112
+ // a refresh invalidates previous status/action state (the last announcement
113
+ // stays visible until the next user action)
114
+ setError('')
115
+ setChecking(true)
116
+ setStatus(null)
117
+ try {
118
+ const res: any = await call('status', {})
119
+ if (res?.ok === false) {
120
+ setError(res?.error ?? 'status failed')
121
+ return
122
+ }
123
+ setStatus(res)
124
+ const conn = (res as any)?.connection ?? null
125
+ if (conn) setConnection(conn)
126
+ else setConnection({ ok: true, host: (res as any)?.remoteHost ?? 'kai@ssh.ddtcorex.com' })
127
+ if (typeof (res as any)?.remoteHost === 'string' && (res as any).remoteHost) setRemoteHost((res as any).remoteHost)
128
+ } catch (e: any) {
129
+ setError(e?.message ?? String(e))
130
+ } finally {
131
+ setChecking(false)
132
+ }
133
+ await loadPage('localOnly', 0)
134
+ await loadPage('remoteOnly', 0)
135
+ }, [call, loadPage])
136
+
137
+ React.useEffect(() => {
138
+ // Load the saved SSH target only — never probe the connection on mount.
139
+ void (async () => {
140
+ try {
141
+ const v: any = await call('getRemoteConfig', {})
142
+ if (v?.remoteHost) setRemoteHost(String(v.remoteHost))
143
+ if (typeof v?.source === 'string') setRemoteSource(v.source)
144
+ } catch {
145
+ // leave the placeholder; the user can still type a host and check
146
+ }
147
+ })()
148
+ }, [call])
149
+
150
+ const persistLastSync = React.useCallback((ts: string) => {
151
+ setLastSync(ts)
152
+ try {
153
+ if (typeof localStorage !== 'undefined') localStorage.setItem('dsh-maestro-sync:lastSync', ts)
154
+ } catch {}
155
+ }, [])
156
+
157
+ const handlePreview = React.useCallback(
158
+ async (direction: 'pull' | 'push') => {
159
+ setBusy(true)
160
+ setError('')
161
+ setResult(null)
162
+ setActionLimit(5)
163
+ setProgress({ phase: 'listing', current: 0, total: 1 })
164
+ try {
165
+ // Asynchronous count-only preview: start the job, poll progress (the
166
+ // host hashes sessions over ssh, one progress tick per file) until the
167
+ // preview settles, then open the confirmation dialog.
168
+ const start: any = await call('previewStart', { direction })
169
+ const jobId = start?.jobId
170
+ if (!jobId) {
171
+ setError(start?.error ?? 'Preview failed to start')
172
+ setProgress(null)
173
+ return
174
+ }
175
+ let done = false
176
+ while (!done && !cancelledRef.current) {
177
+ const st: any = await call('previewStatus', { jobId })
178
+ if (st?.status === 'running' && st?.progress) {
179
+ setProgress({ phase: st.progress.phase, current: st.progress.current, total: st.progress.total, file: st.progress.file })
180
+ }
181
+ if (st?.status === 'done') {
182
+ if (st.preview) {
183
+ setPreview(st.preview)
184
+ setPreviewDirection(direction)
185
+ setConfirmOpen(true)
186
+ } else {
187
+ setError('Preview finished without a result')
188
+ }
189
+ done = true
190
+ } else if (st?.status === 'error') {
191
+ setError(st.error ?? 'Preview failed')
192
+ done = true
193
+ } else if (st?.ok === false) {
194
+ setError(st.error ?? 'Preview failed')
195
+ done = true
196
+ } else {
197
+ await new Promise((r) => setTimeout(r, 700))
198
+ }
199
+ }
200
+ } catch (e: any) {
201
+ setError(e?.message ?? String(e))
202
+ } finally {
203
+ setBusy(false)
204
+ setProgress(null)
205
+ }
206
+ },
207
+ [call],
208
+ )
209
+
210
+ const handleApply = React.useCallback(async () => {
211
+ if (!preview?.previewId) return
212
+ setBusy(true)
213
+ setError('')
214
+ const previewId = preview.previewId
215
+ const direction = previewDirection
216
+ try {
217
+ const res: any = await call('apply', { previewId, direction, confirm: true })
218
+ setConfirmOpen(false)
219
+ setPreview(null)
220
+ if (res?.ok === false) {
221
+ const label = typeof res.code === 'string' ? res.code : 'apply failed'
222
+ setError(`${label}: ${res?.error ?? 'apply failed'}`)
223
+ setResult({ kind: 'apply', ok: false, text: 'Apply failed' })
224
+ return
225
+ }
226
+ setResult({ kind: 'apply', ok: true, text: `Applied preview ${previewId.slice(0, 8)} — committed ${(res?.committed ?? []).length} file(s), +${res?.summary?.added ?? 0} entries` })
227
+ persistLastSync(new Date().toISOString())
228
+ void loadStatus()
229
+ } catch (e: any) {
230
+ setConfirmOpen(false)
231
+ setPreview(null)
232
+ setError(e?.message ?? String(e))
233
+ } finally {
234
+ setBusy(false)
235
+ }
236
+ }, [preview, previewDirection, call, loadStatus, persistLastSync])
237
+
238
+ const cancelDialog = React.useCallback(() => {
239
+ setConfirmOpen(false)
240
+ setPreview(null)
241
+ }, [])
242
+
243
+ const handleBidirectionalPreview = React.useCallback(async () => {
244
+ setBusy(true)
245
+ setError('')
246
+ setResult(null)
247
+ setActionLimit(5)
248
+ setProgress({ phase: 'planning', current: 0, total: 1 })
249
+ try {
250
+ const combined: any = await call('bidirectionalPreview', {})
251
+ if (combined?.ok === false) {
252
+ setError(combined?.error ?? 'Bidirectional preview failed')
253
+ return
254
+ }
255
+ if (!combined?.previewId) {
256
+ setError('Bidirectional preview finished without a result')
257
+ return
258
+ }
259
+ setBiPreview(combined)
260
+ setBiConfirmOpen(true)
261
+ } catch (e: any) {
262
+ setError(e?.message ?? String(e))
263
+ } finally {
264
+ setBusy(false)
265
+ setProgress(null)
266
+ }
267
+ }, [call])
268
+
269
+ const handleBidirectionalApply = React.useCallback(async () => {
270
+ if (!biPreview?.previewId) return
271
+ setBusy(true)
272
+ setError('')
273
+ const previewId = biPreview.previewId
274
+ try {
275
+ // One RPC runs push, then pull, then the convergence check server-side;
276
+ // the dialog busy state covers both phases ("Applying both ways…").
277
+ const res: any = await call('bidirectionalApply', { previewId, confirm: true })
278
+ setBiConfirmOpen(false)
279
+ setBiPreview(null)
280
+ if (res?.ok === false) {
281
+ const label = typeof res.code === 'string' ? res.code : 'apply failed'
282
+ setError(`${label}: ${res?.error ?? 'apply failed'}`)
283
+ setResult({ kind: 'bidirectional', ok: false, text: 'Both-ways apply failed' })
284
+ return
285
+ }
286
+ const pushAdded = res?.push?.summary?.added ?? 0
287
+ const pullAdded = res?.pull?.summary?.added ?? 0
288
+ const verification = res?.verification
289
+ const converged = verification && (verification.copied ?? 0) === 0 && (verification.merged ?? 0) === 0 && (verification.conflicts ?? 0) === 0
290
+ setResult({
291
+ kind: 'bidirectional',
292
+ ok: true,
293
+ text: `Both ways applied — push +${pushAdded}, pull +${pullAdded} entries · ${converged ? 'converged' : 'remaining delta, review and re-run'}`,
294
+ })
295
+ persistLastSync(new Date().toISOString())
296
+ void loadStatus()
297
+ } catch (e: any) {
298
+ setBiConfirmOpen(false)
299
+ setBiPreview(null)
300
+ setError(e?.message ?? String(e))
301
+ } finally {
302
+ setBusy(false)
303
+ }
304
+ }, [biPreview, call, loadStatus, persistLastSync])
305
+
306
+ const cancelBidirectionalDialog = React.useCallback(() => {
307
+ setBiConfirmOpen(false)
308
+ setBiPreview(null)
309
+ }, [])
310
+
311
+ /** Persist the SSH target to the settings store (no probing). */
312
+ const saveRemoteHost = React.useCallback(
313
+ async (host: string): Promise<{ ok: boolean; error?: string }> => {
314
+ setError('')
315
+ setHostFieldError(null)
316
+ try {
317
+ const res: any = await call('saveRemoteHost', { host })
318
+ if (res?.ok === false) {
319
+ const msg = res?.error ?? 'save failed'
320
+ // The failure is about the field the user just typed into: say it
321
+ // there (aria-describedby) rather than only in the panel banner.
322
+ setHostFieldError(msg)
323
+ return { ok: false, error: msg }
324
+ }
325
+ if (res?.remoteHost) {
326
+ setRemoteHost(String(res.remoteHost))
327
+ setRemoteSource('settings')
328
+ }
329
+ return { ok: true }
330
+ } catch (e: any) {
331
+ const msg = e?.message ?? String(e)
332
+ setHostFieldError(msg)
333
+ return { ok: false, error: msg }
334
+ }
335
+ },
336
+ [call],
337
+ )
338
+
339
+ /**
340
+ * Explicit connection check (the ONLY auto path is Apply's own refresh).
341
+ * On success the target is persisted and the status/pages load, unlocking
342
+ * Preview and the file lists; on failure everything stays gated.
343
+ * Machine ids load alongside (best-effort: a failure renders the line with
344
+ * "?" ids plus the reason inline, never blocking the tab and never
345
+ * vanishing silently — a vanished line is indistinguishable from stale UI).
346
+ */
347
+ const loadMachines = React.useCallback(async (): Promise<void> => {
348
+ try {
349
+ const res: any = await call('checkMachines', {})
350
+ if (res && typeof res === 'object' && (res.localId !== undefined || res.remoteId !== undefined)) {
351
+ setMachines({ localId: res.localId ?? null, remoteId: res.remoteId ?? null, from: res.from, to: res.to, ok: res.ok, reason: res.reason ?? res.error })
352
+ } else if (res && typeof res === 'object' && (res.ok === false || typeof res.reason === 'string' || typeof res.error === 'string')) {
353
+ setMachines({ localId: res.localId ?? null, remoteId: res.remoteId ?? null, from: res.from, to: res.to, ok: false, reason: typeof res.reason === 'string' ? res.reason : String(res.error ?? 'machines check failed') })
354
+ } else {
355
+ setMachines(null)
356
+ }
357
+ } catch (e: any) {
358
+ setMachines({ localId: null, remoteId: null, ok: false, reason: e?.message ?? String(e) })
359
+ }
360
+ }, [call])
361
+
362
+ const checkConnection = React.useCallback(async (): Promise<boolean> => {
363
+ setError('')
364
+ setResult(null)
365
+ setChecking(true)
366
+ try {
367
+ const res: any = await call('check', {})
368
+ const conn = res?.connection ?? null
369
+ if (!conn || conn.ok !== true) {
370
+ setConnection(conn ?? { ok: false, host: remoteHost, error: res?.error ?? 'connection failed' })
371
+ return false
372
+ }
373
+ setConnection(conn)
374
+ if (typeof res?.remoteHost === 'string' && res.remoteHost) setRemoteHost(res.remoteHost)
375
+ await loadStatus()
376
+ await loadMachines()
377
+ return true
378
+ } catch (e: any) {
379
+ setConnection({ ok: false, host: remoteHost, error: e?.message ?? String(e) })
380
+ return false
381
+ } finally {
382
+ setChecking(false)
383
+ }
384
+ }, [call, loadStatus, loadMachines, remoteHost])
385
+
386
+ /**
387
+ * Tunnel restore, step 1 — read-only preview.
388
+ *
389
+ * The restore rewrites `domains.tunnel` in the shared settings store; the
390
+ * host only performs it against a fresh, single-use preview id. So the button
391
+ * opens a dialog describing exactly what would change, and nothing is
392
+ * written until the operator confirms inside it.
393
+ */
394
+ const handleTunnelRestorePreview = React.useCallback(async (): Promise<void> => {
395
+ setError('')
396
+ setResult(null)
397
+ setBusy(true)
398
+ try {
399
+ const res: any = await call('tunnelRestorePreview', { side: 'local' })
400
+ if (res?.ok === false) {
401
+ setError(res?.error ?? 'tunnel restore preview failed')
402
+ return
403
+ }
404
+ if (!res?.previewId) {
405
+ setError('Tunnel restore preview finished without a result')
406
+ return
407
+ }
408
+ setTunnelPreview(res)
409
+ setTunnelConfirmOpen(true)
410
+ } catch (e: any) {
411
+ setError(e?.message ?? String(e))
412
+ } finally {
413
+ setBusy(false)
414
+ }
415
+ }, [call])
416
+
417
+ /** Tunnel restore, step 2 — the only call that writes, bound to the preview. */
418
+ const confirmTunnelRestore = React.useCallback(async (): Promise<void> => {
419
+ const previewId = tunnelPreview?.previewId
420
+ if (!previewId) return
421
+ setError('')
422
+ setBusy(true)
423
+ try {
424
+ const res: any = await call('tunnelRestore', { side: 'local', previewId, confirm: true })
425
+ setTunnelConfirmOpen(false)
426
+ setTunnelPreview(null)
427
+ if (res && res.ok) {
428
+ setResult({ kind: 'tunnel-restore', ok: true, text: `Tunnel restored from profile ${res.profile ?? 'auto'} (local)` })
429
+ } else {
430
+ setError(res?.error ?? 'tunnel restore failed')
431
+ }
432
+ } catch (e: any) {
433
+ setTunnelConfirmOpen(false)
434
+ setTunnelPreview(null)
435
+ setError(e?.message ?? String(e))
436
+ } finally {
437
+ setBusy(false)
438
+ }
439
+ }, [tunnelPreview, call])
440
+
441
+ const cancelTunnelRestore = React.useCallback(() => {
442
+ setTunnelConfirmOpen(false)
443
+ setTunnelPreview(null)
444
+ }, [])
445
+
446
+ React.useEffect(() => {
447
+ if (!confirmOpen && !biConfirmOpen && !tunnelConfirmOpen) return
448
+ const onKey = (e: KeyboardEvent) => {
449
+ if (e.key === 'Escape') {
450
+ cancelDialog()
451
+ cancelBidirectionalDialog()
452
+ cancelTunnelRestore()
453
+ }
454
+ }
455
+ window.addEventListener('keydown', onKey)
456
+ return () => window.removeEventListener('keydown', onKey)
457
+ }, [confirmOpen, biConfirmOpen, tunnelConfirmOpen, cancelDialog, cancelBidirectionalDialog, cancelTunnelRestore])
458
+
459
+ return {
460
+ remoteHost,
461
+ remoteSource,
462
+ lastSync,
463
+ status,
464
+ connection,
465
+ machines,
466
+ checking,
467
+ busy,
468
+ result,
469
+ error,
470
+ hostFieldError,
471
+ setHostFieldError,
472
+ preview,
473
+ previewDirection,
474
+ confirmOpen,
475
+ biPreview,
476
+ biConfirmOpen,
477
+ tunnelPreview,
478
+ tunnelConfirmOpen,
479
+ actionLimit,
480
+ progress,
481
+ pages,
482
+ setActionLimit,
483
+ setError,
484
+ setResult,
485
+ loadStatus,
486
+ loadPage,
487
+ saveRemoteHost,
488
+ checkConnection,
489
+ loadMachines,
490
+ handleTunnelRestorePreview,
491
+ confirmTunnelRestore,
492
+ cancelTunnelRestore,
493
+ handlePreview,
494
+ handleApply,
495
+ cancelDialog,
496
+ handleBidirectionalPreview,
497
+ handleBidirectionalApply,
498
+ cancelBidirectionalDialog,
499
+ }
500
+ }
501
+
502
+ export type SyncState = ReturnType<typeof useSync>