@openchambery/web 1.18.1 → 1.18.2-beta.10

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 (126) hide show
  1. package/dist/assets/{AgentAvatar-B2kZjgaf.js → AgentAvatar-BzRb9sP6.js} +1 -1
  2. package/dist/assets/{AssistantView-f5eK9QED.js → AssistantView-Bcx9ER-E.js} +1 -1
  3. package/dist/assets/{ChatContainer-BvJoxcjJ.js → ChatContainer-DaBnpayh.js} +38 -38
  4. package/dist/assets/{DiagramView-Vu2JnmC-.js → DiagramView-DaZSw3PM.js} +1 -1
  5. package/dist/assets/{FadeInOnReveal-aeWlaqVB.js → FadeInOnReveal-oeyB_nIi.js} +1 -1
  6. package/dist/assets/{Icon-AXqa-fYB.js → Icon-DHaR0peD.js} +1 -1
  7. package/dist/assets/{MarkdownRendererImpl-CSxVZ_eA.js → MarkdownRendererImpl-CoMjP1t6.js} +1 -1
  8. package/dist/assets/{MobileDetailNavigation-3NIRdxpt.js → MobileDetailNavigation-Bsi54FsV.js} +1 -1
  9. package/dist/assets/{MobileShareBridge-B7jqfJ-S.js → MobileShareBridge-BQd5tCJN.js} +1 -1
  10. package/dist/assets/MobileSurface-C0bqzAcb.js +2 -0
  11. package/dist/assets/{MultiRunWindow-DkYTqcPq.js → MultiRunWindow-CJLa67M0.js} +1 -1
  12. package/dist/assets/{OnboardingScreen-CCfdEtW6.js → OnboardingScreen-BZHN7C2r.js} +1 -1
  13. package/dist/assets/{OverlayScrollbar-DeL1aO59.js → OverlayScrollbar-BLbgO_QF.js} +1 -1
  14. package/dist/assets/SettingsView-pHa9Y38q.js +25 -0
  15. package/dist/assets/{SettingsWindow--nLXOo-L.js → SettingsWindow-q6zT03-N.js} +1 -1
  16. package/dist/assets/{TerminalView-B80SmYHn.js → TerminalView-BFb17E29.js} +1 -1
  17. package/dist/assets/{ToolOutputDialog-CtbnU35x.js → ToolOutputDialog-sVkggrhW.js} +1 -1
  18. package/dist/assets/appThemeRegistry-Bh6gmBoH.js +2 -0
  19. package/dist/assets/{button-CDvMVaiO.js → button-DCUMIXDC.js} +1 -1
  20. package/dist/assets/{clipboard-Jdqe05db.js → clipboard-DF5tFLDb.js} +1 -1
  21. package/dist/assets/{collapsible-C2aamDvD.js → collapsible-DNg5bLKV.js} +1 -1
  22. package/dist/assets/{context-menu-D16ocNrk.js → context-menu-VD4qvZ6C.js} +1 -1
  23. package/dist/assets/{desktopHosts-CBoBpJ1Z.js → desktopHosts-DSgGxDpI.js} +1 -1
  24. package/dist/assets/{desktopRelayRestore-l2R9muux.js → desktopRelayRestore-DVIx7jsz.js} +1 -1
  25. package/dist/assets/{diagram-CEon0BQs.js → diagram-cjvFqVa8.js} +1 -1
  26. package/dist/assets/{dialog-BzZ3cKxG.js → dialog-DaSIYgrj.js} +1 -1
  27. package/dist/assets/{es-C25PRSjo.js → es-DCoGZljP.js} +1 -1
  28. package/dist/assets/{fileQueries-CE_DaZWQ.js → fileQueries-DXvhIL_U.js} +1 -1
  29. package/dist/assets/{fr-Cv8ZWQdW.js → fr-dkEoZpPz.js} +2 -2
  30. package/dist/assets/{gitApi-B1CIqazO.js → gitApi-cPhxx3NZ.js} +1 -1
  31. package/dist/assets/gitApiHttp-SLrnr8a5.js +2 -0
  32. package/dist/assets/{input-k9DGGyZ6.js → input-QS3IWgY5.js} +1 -1
  33. package/dist/assets/{insertionBoundaries-B9cwRNac.js → insertionBoundaries-XUyczmFs.js} +1 -1
  34. package/dist/assets/{ja-Ue9m9eSe.js → ja-bQwSsvRr.js} +1 -1
  35. package/dist/assets/{ko-DWBUCCV6.js → ko-Kq5C3hsv.js} +1 -1
  36. package/dist/assets/{main-BSVnX01h.js → main-D4CTy7xa.js} +2 -2
  37. package/dist/assets/{main-DzZumJ48.js → main-Mkx9wBnO.js} +23 -23
  38. package/dist/assets/{markdown-worker-DkeWiER6.js → markdown-worker-D-OR2e_G.js} +1 -1
  39. package/dist/assets/{markdownTheme-DNT93i5L.js → markdownTheme-y_Rf6mLa.js} +1 -1
  40. package/dist/assets/{miniChat-CrEtOV4u.js → miniChat-Bq6uelzq.js} +2 -2
  41. package/dist/assets/mobile-C1L9OCdh.js +2 -0
  42. package/dist/assets/{multirun-G-ZwKVUq.js → multirun-9OIhLOWP.js} +1 -1
  43. package/dist/assets/{persistence-DPNMIbF5.js → persistence-oSFWyKgV.js} +1 -1
  44. package/dist/assets/{pl-DaBaPCyE.js → pl-CYpMAgVn.js} +2 -2
  45. package/dist/assets/projectMeta-BXPWMXjv.js +3 -0
  46. package/dist/assets/{pt-BR-C2cJZ43o.js → pt-BR-MSPTLfTm.js} +1 -1
  47. package/dist/assets/{radio-BtilB34p.js → radio-CqpSp0pL.js} +1 -1
  48. package/dist/assets/{renderElectronMiniChatApp-D1HWiWMn.js → renderElectronMiniChatApp-B8cSB7U4.js} +2 -2
  49. package/dist/assets/renderMobileApp-DmBjzy65.js +23 -0
  50. package/dist/assets/{runtimeConfig-BtWi74Pm.js → runtimeConfig-n4QAk1lU.js} +1 -1
  51. package/dist/assets/runtimeEndpointReset-Bw-RBy5a.js +145 -0
  52. package/dist/assets/{sortable-tabs-strip-BpvOof2G.js → sortable-tabs-strip-B4wI7VAP.js} +1 -1
  53. package/dist/assets/src-BhvNwAr-.css +2 -0
  54. package/dist/assets/{store-SqV3zfE8.js → store-OURVnLSN.js} +2 -2
  55. package/dist/assets/{terminalApi-tB3qLcfa.js → terminalApi-_NnfkxgP.js} +1 -1
  56. package/dist/assets/{tooltip-DMNR5rN0.js → tooltip-xEnco9xY.js} +1 -1
  57. package/dist/assets/{uk-DJz_P8OZ.js → uk-cSkRAYFY.js} +1 -1
  58. package/dist/assets/{url-7MqoLs9X.js → url-DIZgk80M.js} +1 -1
  59. package/dist/assets/{useAppFontEffects-BBxqFIta.js → useAppFontEffects-BHoHqFhx.js} +3 -3
  60. package/dist/assets/{useDesktopWindowControlsLayout-D8fjPyqI.js → useDesktopWindowControlsLayout-DwmEdp3O.js} +1 -1
  61. package/dist/assets/{useEffectiveDirectory-C5OxWqUH.js → useEffectiveDirectory-Bjo9xE9q.js} +1 -1
  62. package/dist/assets/{useFontPreferences-CIurCeNv.js → useFontPreferences-B-QHyR3C.js} +1 -1
  63. package/dist/assets/useMobileNavigationStore-SCw9NohC.js +476 -0
  64. package/dist/assets/useSessionAutoCleanup-KwCKRF_d.js +1 -0
  65. package/dist/assets/{useWorkerHighlightedLines-CJozblYF.js → useWorkerHighlightedLines-Cm3UQxhi.js} +1 -1
  66. package/dist/assets/{utils-Co19EJEL.js → utils-Dxsi3J3l.js} +1 -1
  67. package/dist/assets/{zh-CN-DLAKDOM9.js → zh-CN-BKqeT_uz.js} +1 -1
  68. package/dist/assets/{zh-TW-s3Jjx1_n.js → zh-TW-BaNjJ8Y4.js} +1 -1
  69. package/dist/index.html +8 -8
  70. package/dist/mini-chat.html +8 -8
  71. package/dist/mobile.html +8 -8
  72. package/package.json +1 -1
  73. package/server/index.d.ts +6 -0
  74. package/server/index.js +6 -0
  75. package/server/lib/config-sync/DOCUMENTATION.md +70 -0
  76. package/server/lib/config-sync/config-sync.test.js +197 -0
  77. package/server/lib/config-sync/constants.js +39 -0
  78. package/server/lib/config-sync/contract.js +130 -0
  79. package/server/lib/config-sync/credential-auth.js +39 -0
  80. package/server/lib/config-sync/engine.js +108 -0
  81. package/server/lib/config-sync/index.js +67 -0
  82. package/server/lib/config-sync/local-backup.js +171 -0
  83. package/server/lib/config-sync/plan.js +318 -0
  84. package/server/lib/config-sync/receiver.js +330 -0
  85. package/server/lib/config-sync/routes.js +141 -0
  86. package/server/lib/config-sync/routes.test.js +154 -0
  87. package/server/lib/config-sync/scripts.js +264 -0
  88. package/server/lib/config-sync/selections.js +112 -0
  89. package/server/lib/config-sync/tar.js +35 -0
  90. package/server/lib/config-sync/target-id.js +24 -0
  91. package/server/lib/event-stream/DOCUMENTATION.md +2 -2
  92. package/server/lib/event-stream/diff-summary.js +35 -16
  93. package/server/lib/event-stream/diff-summary.test.js +46 -6
  94. package/server/lib/event-stream/protocol.test.js +7 -7
  95. package/server/lib/git/DOCUMENTATION.md +2 -1
  96. package/server/lib/git/service.js +24 -5
  97. package/server/lib/git/service.test.js +51 -0
  98. package/server/lib/opencode/DOCUMENTATION.md +4 -1
  99. package/server/lib/opencode/bootstrap-runtime.js +2 -0
  100. package/server/lib/opencode/core-routes.js +1 -0
  101. package/server/lib/opencode/feature-routes-runtime.test.js +10 -1
  102. package/server/lib/opencode/openchamber-routes.js +7 -0
  103. package/server/lib/opencode/settings-runtime.js +82 -51
  104. package/server/lib/opencode/settings-runtime.test.js +42 -0
  105. package/server/lib/relay/DOCUMENTATION.md +1 -1
  106. package/server/lib/session-turn-pages/DOCUMENTATION.md +26 -6
  107. package/server/lib/session-turn-pages/changes.service.js +156 -0
  108. package/server/lib/session-turn-pages/changes.service.test.js +188 -0
  109. package/server/lib/session-turn-pages/reconcile.routes.test.js +48 -0
  110. package/server/lib/session-turn-pages/reconcile.service.js +3 -1
  111. package/server/lib/session-turn-pages/reconcile.service.test.js +40 -0
  112. package/server/lib/session-turn-pages/routes.js +273 -12
  113. package/server/lib/session-turn-pages/routes.test.js +359 -0
  114. package/server/lib/session-turn-pages/service.js +29 -7
  115. package/server/lib/session-turn-pages/service.test.js +30 -0
  116. package/dist/assets/MobileSurface-BL3hired.js +0 -2
  117. package/dist/assets/SettingsView-CyrIDyDl.js +0 -25
  118. package/dist/assets/appThemeRegistry-D2ZUcQmr.js +0 -2
  119. package/dist/assets/gitApiHttp-D8j1qRH4.js +0 -2
  120. package/dist/assets/mobile-DMjO-f5u.js +0 -2
  121. package/dist/assets/projectMeta-owiDYjF9.js +0 -3
  122. package/dist/assets/renderMobileApp-Cqxwb3Ub.js +0 -23
  123. package/dist/assets/runtimeEndpointReset-C0oDuy2R.js +0 -145
  124. package/dist/assets/src-oHrYIqHF.css +0 -2
  125. package/dist/assets/useMobileNavigationStore-U3b_hG4m.js +0 -475
  126. package/dist/assets/useSessionAutoCleanup-CDYDm76L.js +0 -1
@@ -0,0 +1,264 @@
1
+ import path from 'node:path';
2
+
3
+ import {
4
+ OPENCODE_AGENTS_ROOT_PROBE_MARKER,
5
+ OPENCODE_AGENTS_SYNC_BACKUP_DIR,
6
+ OPENCODE_AUTH_FILE_PROBE_MARKER,
7
+ OPENCODE_AUTH_SYNC_BACKUP_DIR,
8
+ OPENCODE_CONFIG_SYNC_ALLOWLIST,
9
+ OPENCODE_CONFIG_SYNC_BACKUP_DIR,
10
+ OPENCODE_CONFIG_SYNC_BACKUP_GENERATIONS,
11
+ } from './constants.js';
12
+
13
+ const shellQuote = (value) => `'${String(value).replace(/'/g, `'\\''`)}'`;
14
+
15
+ /**
16
+ * Sanitize syncRunId for use as a single path segment under backup roots.
17
+ * @param {string} syncRunId
18
+ */
19
+ export const sanitizeSyncRunIdForPath = (syncRunId) => {
20
+ const trimmed = String(syncRunId || '').trim();
21
+ if (!trimmed) throw new Error('syncRunId is required for generational backup');
22
+ if (!/^[A-Za-z0-9._-]+$/.test(trimmed)) {
23
+ throw new Error('syncRunId contains unsupported characters for backup paths');
24
+ }
25
+ return trimmed;
26
+ };
27
+
28
+ /**
29
+ * Emit POSIX lines that create `<$backupVar>/<syncRunId>` as `$runVar` and prune older generations.
30
+ * Does not wipe the entire backup root — only replaces the current run dir and
31
+ * deletes generations beyond the retention limit (failed runs keep their scene).
32
+ *
33
+ * @param {{ backupVar: string, runVar: string, quotedRunId: string, generations: number }} args
34
+ * @returns {string[]}
35
+ */
36
+ const generationalBackupSetupLines = ({ backupVar, runVar, quotedRunId, generations }) => [
37
+ `mkdir -p "$${backupVar}"`,
38
+ `${runVar}="$${backupVar}"/${quotedRunId}`,
39
+ `rm -rf -- "$${runVar}"`,
40
+ `mkdir -p "$${runVar}"`,
41
+ `(cd "$${backupVar}" && ls -1t 2>/dev/null | awk 'NR>${generations} {print}' | while IFS= read -r old; do`,
42
+ ' [ -n "$old" ] || continue',
43
+ ` [ "$old" = ${quotedRunId} ] && continue`,
44
+ ` rm -rf -- "$${backupVar}/$old"`,
45
+ 'done) || true',
46
+ ];
47
+
48
+ /**
49
+ * Build the remote POSIX prepare script: generational backup, delete stale counterparts, print SYNC_READY.
50
+ * Backups land under `<backupRoot>/<syncRunId>/…`. Older generations beyond
51
+ * {@link OPENCODE_CONFIG_SYNC_BACKUP_GENERATIONS} are pruned; prepare no longer
52
+ * `rm -rf`s the entire backup root at start.
53
+ *
54
+ * @param {{ files: { path: string }[], directories: { path: string }[], deletes: string[], agentsRoot?: { fileCount: number, bytes: number } | null, authFile?: { bytes: number } | null }} plan
55
+ * @param {{ syncRunId: string, generations?: number }} options
56
+ * @returns {string}
57
+ */
58
+ export const buildRemoteSyncPrepareScript = (plan, options) => {
59
+ const syncRunId = sanitizeSyncRunIdForPath(options?.syncRunId);
60
+ const generations = Number.isFinite(options?.generations) && Number(options.generations) > 0
61
+ ? Math.trunc(Number(options.generations))
62
+ : OPENCODE_CONFIG_SYNC_BACKUP_GENERATIONS;
63
+ const backupDir = OPENCODE_CONFIG_SYNC_BACKUP_DIR;
64
+ const directoryDeleteNames = new Set();
65
+ for (const dirSpec of OPENCODE_CONFIG_SYNC_ALLOWLIST.directories) {
66
+ directoryDeleteNames.add(dirSpec.path);
67
+ if (typeof dirSpec.legacy === 'string' && dirSpec.legacy) {
68
+ directoryDeleteNames.add(dirSpec.legacy);
69
+ }
70
+ }
71
+
72
+ const quotedRunId = shellQuote(syncRunId);
73
+ const lines = [
74
+ 'set -e',
75
+ 'CFG="$HOME/.config/opencode"',
76
+ 'mkdir -p "$CFG"',
77
+ `BK="$CFG/${backupDir}"`,
78
+ ...generationalBackupSetupLines({
79
+ backupVar: 'BK',
80
+ runVar: 'RUN_BK',
81
+ quotedRunId,
82
+ generations,
83
+ }),
84
+ ];
85
+
86
+ const backupPaths = [
87
+ ...(Array.isArray(plan?.files) ? plan.files.map((entry) => entry.path) : []),
88
+ ...(Array.isArray(plan?.directories) ? plan.directories.map((entry) => entry.path) : []),
89
+ ];
90
+
91
+ for (const rel of backupPaths) {
92
+ const quoted = shellQuote(rel);
93
+ const dirname = path.posix.dirname(rel);
94
+ const quotedDir = shellQuote(dirname === '.' ? '' : dirname);
95
+ lines.push(`if [ -e "$CFG"/${quoted} ]; then`);
96
+ if (dirname === '.' || dirname === '') {
97
+ lines.push(' mkdir -p "$RUN_BK"');
98
+ } else {
99
+ lines.push(` mkdir -p "$RUN_BK"/${quotedDir}`);
100
+ }
101
+ lines.push(` cp -a "$CFG"/${quoted} "$RUN_BK"/${quoted}`);
102
+ lines.push('fi');
103
+ }
104
+
105
+ for (const rel of Array.isArray(plan?.deletes) ? plan.deletes : []) {
106
+ const quoted = shellQuote(rel);
107
+ if (directoryDeleteNames.has(rel)) {
108
+ lines.push(`rm -rf -- "$CFG"/${quoted}`);
109
+ } else {
110
+ lines.push(`rm -f -- "$CFG"/${quoted}`);
111
+ }
112
+ }
113
+
114
+ if (plan?.agentsRoot) {
115
+ lines.push(`AGENTS_BK="$HOME/${OPENCODE_AGENTS_SYNC_BACKUP_DIR}"`);
116
+ lines.push(...generationalBackupSetupLines({
117
+ backupVar: 'AGENTS_BK',
118
+ runVar: 'AGENTS_RUN_BK',
119
+ quotedRunId,
120
+ generations,
121
+ }));
122
+ lines.push('if [ -e "$HOME/.agents" ]; then');
123
+ lines.push(' cp -a "$HOME/.agents" "$AGENTS_RUN_BK/agents"');
124
+ lines.push('fi');
125
+ lines.push('rm -rf -- "$HOME/.agents"');
126
+ }
127
+
128
+ if (plan?.authFile) {
129
+ lines.push(`AUTH_BK="$HOME/${OPENCODE_AUTH_SYNC_BACKUP_DIR}"`);
130
+ lines.push(...generationalBackupSetupLines({
131
+ backupVar: 'AUTH_BK',
132
+ runVar: 'AUTH_RUN_BK',
133
+ quotedRunId,
134
+ generations,
135
+ }));
136
+ lines.push('if [ -e "$HOME/.local/share/opencode/auth.json" ]; then');
137
+ lines.push(' cp -a "$HOME/.local/share/opencode/auth.json" "$AUTH_RUN_BK/auth.json"');
138
+ lines.push('fi');
139
+ }
140
+
141
+ lines.push("printf 'SYNC_READY\\n'");
142
+ return lines.join('\n');
143
+ };
144
+
145
+ /**
146
+ * Build the remote existence probe script for the sync preview.
147
+ * @param {string[]} uniqueProbePaths
148
+ * @returns {string}
149
+ */
150
+ export const buildRemoteSyncProbeScript = (uniqueProbePaths) => {
151
+ const lines = (Array.isArray(uniqueProbePaths) ? uniqueProbePaths : []).map((rel) => {
152
+ const quoted = shellQuote(rel);
153
+ return `[ -e "$HOME/.config/opencode"/${quoted} ] && printf '%s\\n' ${quoted}`;
154
+ });
155
+ lines.push(
156
+ `[ -e "$HOME/.agents" ] && printf '%s\\n' ${shellQuote(OPENCODE_AGENTS_ROOT_PROBE_MARKER)}`,
157
+ );
158
+ lines.push(
159
+ `[ -e "$HOME/.local/share/opencode/auth.json" ] && printf '%s\\n' ${shellQuote(OPENCODE_AUTH_FILE_PROBE_MARKER)}`,
160
+ );
161
+ lines.push('exit 0');
162
+ return lines.join('\n');
163
+ };
164
+
165
+ /**
166
+ * Finalize script: confirm generational backup dir exists for this syncRunId and print SYNC_DONE.
167
+ * @param {{ syncRunId: string }} options
168
+ */
169
+ export const buildRemoteSyncFinalizeScript = (options) => {
170
+ const syncRunId = sanitizeSyncRunIdForPath(options?.syncRunId);
171
+ const quotedRunId = shellQuote(syncRunId);
172
+ return [
173
+ 'set -e',
174
+ `BK="$HOME/.config/opencode/${OPENCODE_CONFIG_SYNC_BACKUP_DIR}"/${quotedRunId}`,
175
+ 'if [ ! -d "$BK" ]; then',
176
+ " printf 'SYNC_FINALIZE_MISSING_BACKUP\\n' >&2",
177
+ ' exit 1',
178
+ 'fi',
179
+ "printf 'SYNC_DONE\\n'",
180
+ ].join('\n');
181
+ };
182
+
183
+ /**
184
+ * Build a remote inventory script that prints a JSON object describing which
185
+ * allowlist paths exist on the remote (for pull planning). Uses only POSIX sh.
186
+ * Output is a single JSON line prefixed by SYNC_INVENTORY=.
187
+ * @returns {string}
188
+ */
189
+ export const buildRemoteSyncInventoryScript = () => {
190
+ const filePaths = [
191
+ ...OPENCODE_CONFIG_SYNC_ALLOWLIST.fileGroups.flat(),
192
+ ...OPENCODE_CONFIG_SYNC_ALLOWLIST.singleFiles,
193
+ ];
194
+ const dirPaths = OPENCODE_CONFIG_SYNC_ALLOWLIST.directories.map((entry) => entry.path);
195
+ const lines = [
196
+ 'set -e',
197
+ 'CFG="$HOME/.config/opencode"',
198
+ 'FILES=""',
199
+ 'DIRS=""',
200
+ ];
201
+ for (const rel of filePaths) {
202
+ const quoted = shellQuote(rel);
203
+ lines.push(`if [ -f "$CFG"/${quoted} ]; then`);
204
+ lines.push(` BYTES="$(wc -c < "$CFG"/${quoted} | tr -d ' ')"`);
205
+ lines.push(` FILES="$FILES{\\"path\\":${JSON.stringify(rel)},\\"bytes\\":$BYTES},"`);
206
+ lines.push('fi');
207
+ }
208
+ for (const rel of dirPaths) {
209
+ const quoted = shellQuote(rel);
210
+ lines.push(`if [ -d "$CFG"/${quoted} ]; then`);
211
+ lines.push(` COUNT="$(find "$CFG"/${quoted} -type f ! -path '*/node_modules/*' ! -name '*.backup' 2>/dev/null | wc -l | tr -d ' ')"`);
212
+ lines.push(` BYTES="$(find "$CFG"/${quoted} -type f ! -path '*/node_modules/*' ! -name '*.backup' -exec wc -c {} + 2>/dev/null | awk 'END{print $1+0}')"`);
213
+ lines.push(` DIRS="$DIRS{\\"path\\":${JSON.stringify(rel)},\\"fileCount\\":$COUNT,\\"bytes\\":$BYTES},"`);
214
+ lines.push('fi');
215
+ }
216
+ lines.push('AGENTS="null"');
217
+ lines.push('if [ -d "$HOME/.agents" ]; then');
218
+ lines.push(" ACOUNT=\"$(find \"$HOME/.agents\" -type f ! -path '*/node_modules/*' ! -name '*.backup' 2>/dev/null | wc -l | tr -d ' ')\"");
219
+ lines.push(" ABYTES=\"$(find \"$HOME/.agents\" -type f ! -path '*/node_modules/*' ! -name '*.backup' -exec wc -c {} + 2>/dev/null | awk 'END{print $1+0}')\"");
220
+ lines.push(' AGENTS="{\\"fileCount\\":$ACOUNT,\\"bytes\\":$ABYTES}"');
221
+ lines.push('fi');
222
+ lines.push('AUTH="null"');
223
+ lines.push('if [ -f "$HOME/.local/share/opencode/auth.json" ]; then');
224
+ lines.push(' AUBYTES="$(wc -c < "$HOME/.local/share/opencode/auth.json" | tr -d \' \')"');
225
+ lines.push(' AUTH="{\\"bytes\\":$AUBYTES}"');
226
+ lines.push('fi');
227
+ lines.push('FILES="${FILES%,}"');
228
+ lines.push('DIRS="${DIRS%,}"');
229
+ lines.push('printf \'SYNC_INVENTORY={"files":[%s],"directories":[%s],"agentsRoot":%s,"authFile":%s}\\n\' "$FILES" "$DIRS" "$AGENTS" "$AUTH"');
230
+ lines.push('exit 0');
231
+ return lines.join('\n');
232
+ };
233
+
234
+ /**
235
+ * Stream a remote tar.gz of selected config paths to stdout.
236
+ * @param {{ files?: { path: string }[], directories?: { path: string }[] }} plan
237
+ */
238
+ export const buildRemoteConfigTarScript = (plan) => {
239
+ const entries = [
240
+ ...(Array.isArray(plan?.files) ? plan.files.map((entry) => entry.path) : []),
241
+ ...(Array.isArray(plan?.directories) ? plan.directories.map((entry) => entry.path) : []),
242
+ ];
243
+ if (entries.length === 0) {
244
+ return "printf '' ; exit 0";
245
+ }
246
+ const quotedEntries = entries.map((rel) => shellQuote(rel)).join(' ');
247
+ return [
248
+ 'set -e',
249
+ 'CFG="$HOME/.config/opencode"',
250
+ `cd "$CFG" && tar -h -czf - ${quotedEntries}`,
251
+ ].join('\n');
252
+ };
253
+
254
+ export const buildRemoteAgentsTarScript = () => [
255
+ 'set -e',
256
+ 'cd "$HOME" && tar -h -czf - .agents',
257
+ ].join('\n');
258
+
259
+ export const buildRemoteAuthTarScript = () => [
260
+ 'set -e',
261
+ 'cd "$HOME/.local/share/opencode" && tar -h -czf - auth.json',
262
+ ].join('\n');
263
+
264
+ export { shellQuote };
@@ -0,0 +1,112 @@
1
+ import { OPENCODE_CONFIG_SYNC_ALLOWLIST } from './constants.js';
2
+
3
+ /**
4
+ * @typedef {{
5
+ * fileGroups: boolean[],
6
+ * singleFiles: boolean[],
7
+ * directories: boolean[],
8
+ * agentsRoot: boolean,
9
+ * authFile: boolean,
10
+ * }} SyncSelections
11
+ */
12
+
13
+ /**
14
+ * Default: everything selected except authFile (credentials stay opt-in).
15
+ * @param {{ includeAuthFile?: boolean }} [options]
16
+ * @returns {SyncSelections}
17
+ */
18
+ export const buildDefaultSyncSelections = (options = {}) => ({
19
+ fileGroups: OPENCODE_CONFIG_SYNC_ALLOWLIST.fileGroups.map(() => true),
20
+ singleFiles: OPENCODE_CONFIG_SYNC_ALLOWLIST.singleFiles.map(() => true),
21
+ directories: OPENCODE_CONFIG_SYNC_ALLOWLIST.directories.map(() => true),
22
+ agentsRoot: true,
23
+ authFile: options.includeAuthFile === true,
24
+ });
25
+
26
+ /**
27
+ * Normalize a partial selections object against the allowlist shape.
28
+ * @param {Partial<SyncSelections> | null | undefined} raw
29
+ * @param {{ includeAuthFile?: boolean }} [options]
30
+ * @returns {SyncSelections}
31
+ */
32
+ export const normalizeSyncSelections = (raw, options = {}) => {
33
+ const defaults = buildDefaultSyncSelections(options);
34
+ if (!raw || typeof raw !== 'object') return defaults;
35
+
36
+ const fileGroups = OPENCODE_CONFIG_SYNC_ALLOWLIST.fileGroups.map((_, index) => (
37
+ Array.isArray(raw.fileGroups) ? raw.fileGroups[index] !== false : defaults.fileGroups[index]
38
+ ));
39
+ const singleFiles = OPENCODE_CONFIG_SYNC_ALLOWLIST.singleFiles.map((_, index) => (
40
+ Array.isArray(raw.singleFiles) ? raw.singleFiles[index] !== false : defaults.singleFiles[index]
41
+ ));
42
+ const directories = OPENCODE_CONFIG_SYNC_ALLOWLIST.directories.map((_, index) => (
43
+ Array.isArray(raw.directories) ? raw.directories[index] !== false : defaults.directories[index]
44
+ ));
45
+
46
+ return {
47
+ fileGroups,
48
+ singleFiles,
49
+ directories,
50
+ agentsRoot: raw.agentsRoot !== false,
51
+ authFile: raw.authFile === true,
52
+ };
53
+ };
54
+
55
+ /**
56
+ * Filter a full plan down to the selected allowlist groups.
57
+ * Mutual-exclusion within a fileGroup is preserved (plan already picked a winner).
58
+ * @param {object} plan
59
+ * @param {SyncSelections} selections
60
+ */
61
+ export const filterPlanBySelections = (plan, selections) => {
62
+ const selected = normalizeSyncSelections(selections, { includeAuthFile: selections?.authFile === true });
63
+ const selectedFileNames = new Set();
64
+ const selectedDeleteNames = new Set();
65
+
66
+ OPENCODE_CONFIG_SYNC_ALLOWLIST.fileGroups.forEach((group, index) => {
67
+ if (!selected.fileGroups[index]) return;
68
+ for (const name of group) {
69
+ selectedFileNames.add(name);
70
+ selectedDeleteNames.add(name);
71
+ }
72
+ });
73
+ OPENCODE_CONFIG_SYNC_ALLOWLIST.singleFiles.forEach((name, index) => {
74
+ if (!selected.singleFiles[index]) return;
75
+ selectedFileNames.add(name);
76
+ });
77
+
78
+ const selectedDirNames = new Set();
79
+ const selectedDirLegacy = new Set();
80
+ OPENCODE_CONFIG_SYNC_ALLOWLIST.directories.forEach((dirSpec, index) => {
81
+ if (!selected.directories[index]) return;
82
+ selectedDirNames.add(dirSpec.path);
83
+ selectedDeleteNames.add(dirSpec.path);
84
+ if (typeof dirSpec.legacy === 'string' && dirSpec.legacy) {
85
+ selectedDirLegacy.add(dirSpec.legacy);
86
+ selectedDeleteNames.add(dirSpec.legacy);
87
+ }
88
+ });
89
+
90
+ const files = (Array.isArray(plan?.files) ? plan.files : []).filter((entry) => selectedFileNames.has(entry.path));
91
+ const directories = (Array.isArray(plan?.directories) ? plan.directories : []).filter((entry) => selectedDirNames.has(entry.path));
92
+ const deletes = (Array.isArray(plan?.deletes) ? plan.deletes : []).filter((name) => selectedDeleteNames.has(name) || selectedDirLegacy.has(name));
93
+ const agentsRoot = selected.agentsRoot ? (plan?.agentsRoot ?? null) : null;
94
+ const authFile = selected.authFile ? (plan?.authFile ?? null) : null;
95
+
96
+ let totalBytes = 0;
97
+ for (const entry of files) totalBytes += Number(entry.bytes) || 0;
98
+ for (const entry of directories) totalBytes += Number(entry.bytes) || 0;
99
+ if (agentsRoot) totalBytes += Number(agentsRoot.bytes) || 0;
100
+ if (authFile) totalBytes += Number(authFile.bytes) || 0;
101
+
102
+ return {
103
+ ...plan,
104
+ files,
105
+ directories,
106
+ deletes,
107
+ agentsRoot,
108
+ authFile,
109
+ totalBytes,
110
+ selections: selected,
111
+ };
112
+ };
@@ -0,0 +1,35 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ /**
4
+ * Collect stdout from a local `tar …` into a Buffer.
5
+ *
6
+ * Callers buffer the entire archive in memory; TargetExecutor.putTar accepts
7
+ * Buffer | Uint8Array only.
8
+ *
9
+ * @param {string[]} tarArgs
10
+ * @param {{ windowsHide?: boolean }} [spawnOptions]
11
+ * @returns {Promise<Buffer>}
12
+ */
13
+ export const collectLocalTarBuffer = (tarArgs, spawnOptions = {}) => new Promise((resolve, reject) => {
14
+ const child = spawn('tar', tarArgs, {
15
+ stdio: ['ignore', 'pipe', 'pipe'],
16
+ ...(spawnOptions.windowsHide ? { windowsHide: true } : {}),
17
+ });
18
+ /** @type {Buffer[]} */
19
+ const chunks = [];
20
+ let stderr = '';
21
+ child.stdout?.on('data', (chunk) => {
22
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
23
+ });
24
+ child.stderr?.on('data', (chunk) => {
25
+ stderr += chunk.toString();
26
+ });
27
+ child.on('error', reject);
28
+ child.on('close', (code) => {
29
+ if (code !== 0) {
30
+ reject(new Error((stderr || 'Local tar failed').trim()));
31
+ return;
32
+ }
33
+ resolve(Buffer.concat(chunks));
34
+ });
35
+ });
@@ -0,0 +1,24 @@
1
+ /** @param {string} instanceId */
2
+ export const syncTargetIdForSshInstance = (instanceId) => {
3
+ const id = String(instanceId || '').trim();
4
+ if (!id) throw new Error('SSH instance id is required');
5
+ return `ssh:${id}`;
6
+ };
7
+
8
+ /** @param {string} hostId */
9
+ export const syncTargetIdForDirectHost = (hostId) => {
10
+ const id = String(hostId || '').trim();
11
+ if (!id) throw new Error('Desktop host id is required');
12
+ return `host:${id}`;
13
+ };
14
+
15
+ /**
16
+ * @param {string} serverId relay host signing-key fingerprint
17
+ * Mirrored in packages/ui/src/lib/relay/relay-config-sync.ts (browser bundle cannot
18
+ * import this server module); keep both sides in sync when changing the prefix.
19
+ */
20
+ export const syncTargetIdForRelayServer = (serverId) => {
21
+ const id = String(serverId || '').trim();
22
+ if (!id) throw new Error('Relay serverId is required');
23
+ return `relay:${id}`;
24
+ };
@@ -9,7 +9,7 @@ This module contains the OpenChamber message-stream WebSocket protocol and runti
9
9
  - `packages/web/server/lib/event-stream/global-ws-bridge.js`: browser-facing global WS bridge that subscribes clients to the shared global hub.
10
10
  - `packages/web/server/lib/event-stream/directory-ws-bridge.js`: browser-facing per-directory WS bridge that owns one scoped upstream reader per connection.
11
11
  - `packages/web/server/lib/event-stream/protocol.js`: path constants, SSE envelope parsing, and WebSocket frame serialization helpers.
12
- - `packages/web/server/lib/event-stream/diff-summary.js`: pure outbound FileDiff summarization (drops patch/before/after/from/to; keeps file/status/additions/deletions).
12
+ - `packages/web/server/lib/event-stream/diff-summary.js`: pure outbound FileDiff helpers. L1 message/session `summary.diffs` project to `diffCount`/`hasDiffs` (array removed). `session.diff` event frames still keep file/status/additions/deletions and drop patch bodies. `summarizeFileDiff(s)` remains for explicit L2-style file lists.
13
13
  - `packages/web/server/lib/event-stream/upstream-reader.js`: reusable upstream SSE reader with event-id tracking, stall recovery, and reconnect handling.
14
14
  - `packages/web/server/lib/event-stream/runtime.js`: thin WebSocket server runtime for upgrade handling and path dispatch to the global/directory bridges.
15
15
  - `packages/web/server/lib/event-stream/protocol.test.js`: unit tests for protocol helpers.
@@ -26,7 +26,7 @@ The following APIs are exported by their owning modules. `event-stream/index.js`
26
26
  - `MESSAGE_STREAM_WS_HEARTBEAT_INTERVAL_MS`: heartbeat interval for browser-facing WS connections.
27
27
  - `parseSseEventEnvelope(block)`: parses an SSE block into `{ eventId, directory, payload }`.
28
28
  - `sendMessageStreamWsFrame(socket, payload)`: serializes and sends a JSON WS frame.
29
- - `sendMessageStreamWsEvent(socket, payload, options)`: sends an event frame with optional `eventId` and `directory`. Outbound `session.diff` and message/session `summary.diffs` are summarized to file/status/additions/deletions only (no full patch bodies).
29
+ - `sendMessageStreamWsEvent(socket, payload, options)`: sends an event frame with optional `eventId` and `directory`. Outbound `session.diff` keeps file/status/additions/deletions only (no full patch bodies). Message/session `summary.diffs` are L1-projected to `diffCount`/`hasDiffs` (file array removed).
30
30
 
31
31
  ### Runtime helpers
32
32
  - `createGlobalMessageStreamHub(...)`: creates a shared `/global/event` upstream SSE hub with event/status subscribers and bounded event-id replay.
@@ -1,9 +1,12 @@
1
1
  // ---------------------------------------------------------------------------
2
- // Outbound FileDiff summarization for message-stream fan-out.
2
+ // Outbound FileDiff summarization for message-stream fan-out and Host L1.
3
3
  //
4
- // Mirrors packages/ui/src/sync/sanitize.ts summarizeFileDiff(s) so Host never
5
- // pushes full patch/before/after/from/to blobs over Relay/WS (>64KB frames).
6
- // Pure JS do not import UI TypeScript from the server package.
4
+ // L1 (ordinary first-packet / SSE / exact message GET):
5
+ // project `info.summary.diffs` arrays to `{ diffCount, hasDiffs }` and remove
6
+ // the file array entirely. Never ship patch bodies on these paths.
7
+ //
8
+ // Explicit L2/L3 APIs may still use summarizeFileDiff(s) for file-list / patch
9
+ // responses. Pure JS — do not import UI TypeScript from the server package.
7
10
  // ---------------------------------------------------------------------------
8
11
 
9
12
  /** Lightweight FileDiff fields safe for outbound event frames (preview only). */
@@ -25,6 +28,9 @@ const hasHeavyDiffBody = (diff) => {
25
28
  * Reduce a FileDiff / SnapshotFileDiff to preview-safe scalars only.
26
29
  * Drops patch / before / after / from / to and any other large body fields.
27
30
  * Already-summary objects keep identity.
31
+ *
32
+ * Retained for explicit L2 file-list APIs; L1 message paths must use
33
+ * `projectMessageSummaryDiffCounts` instead and never keep a file array.
28
34
  */
29
35
  export function summarizeFileDiff(diff) {
30
36
  if (!diff || typeof diff !== 'object' || Array.isArray(diff)) {
@@ -62,7 +68,14 @@ export function summarizeFileDiffs(diffs) {
62
68
  return changed ? next : diffs;
63
69
  }
64
70
 
65
- const summarizeSummaryDiffs = (owner) => {
71
+ /**
72
+ * L1 projection: replace `summary.diffs` with count/marker scalars.
73
+ * Keeps every other lightweight summary field. Identity when unchanged.
74
+ *
75
+ * @param {unknown} owner message info / session info / summary-bearing object
76
+ * @returns {unknown}
77
+ */
78
+ export const projectMessageSummaryDiffCounts = (owner) => {
66
79
  if (!owner || typeof owner !== 'object' || Array.isArray(owner)) {
67
80
  return owner;
68
81
  }
@@ -72,30 +85,36 @@ const summarizeSummaryDiffs = (owner) => {
72
85
  return owner;
73
86
  }
74
87
 
75
- if (!Array.isArray(summary.diffs)) {
88
+ if (!Object.prototype.hasOwnProperty.call(summary, 'diffs')) {
76
89
  return owner;
77
90
  }
78
91
 
79
- const stripped = summarizeFileDiffs(summary.diffs);
80
- if (stripped === summary.diffs) {
81
- return owner;
82
- }
92
+ const diffs = summary.diffs;
93
+ const diffCount = Array.isArray(diffs) ? diffs.length : 0;
94
+ const hasDiffs = diffCount > 0;
95
+
96
+ const nextSummary = { ...summary };
97
+ delete nextSummary.diffs;
98
+ nextSummary.diffCount = diffCount;
99
+ nextSummary.hasDiffs = hasDiffs;
83
100
 
84
101
  return {
85
102
  ...owner,
86
- summary: {
87
- ...summary,
88
- diffs: stripped,
89
- },
103
+ summary: nextSummary,
90
104
  };
91
105
  };
92
106
 
107
+ /** @deprecated Prefer projectMessageSummaryDiffCounts — L1 removes the file array. */
108
+ export const summarizeMessageDiffSnapshots = projectMessageSummaryDiffCounts;
109
+
93
110
  /**
94
111
  * Summarize FileDiff bodies on outbound event payloads.
95
112
  *
96
113
  * Handles:
97
114
  * - `session.diff` with legacy `properties.diff` or current `data.diff`
115
+ * (keeps file/status/additions/deletions; drops patch bodies)
98
116
  * - message/session objects carrying `summary.diffs` under properties/data info
117
+ * (L1: projects to diffCount/hasDiffs and removes the array)
99
118
  *
100
119
  * Non-diff events keep identity.
101
120
  */
@@ -154,7 +173,7 @@ export function summarizeOutboundEventPayload(payload) {
154
173
 
155
174
  // Common shape: properties.info.summary.diffs
156
175
  if (body.info && typeof body.info === 'object' && !Array.isArray(body.info)) {
157
- const nextInfo = summarizeSummaryDiffs(body.info);
176
+ const nextInfo = projectMessageSummaryDiffCounts(body.info);
158
177
  if (nextInfo !== body.info) {
159
178
  next = {
160
179
  ...next,
@@ -169,7 +188,7 @@ export function summarizeOutboundEventPayload(payload) {
169
188
  }
170
189
 
171
190
  // Rare: properties.summary.diffs directly on the properties/data body
172
- const nextBody = summarizeSummaryDiffs(body);
191
+ const nextBody = projectMessageSummaryDiffCounts(body);
173
192
  if (nextBody !== body) {
174
193
  next = {
175
194
  ...next,
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, it } from 'vitest';
2
2
 
3
3
  import {
4
+ projectMessageSummaryDiffCounts,
4
5
  summarizeFileDiff,
5
6
  summarizeFileDiffs,
6
7
  summarizeOutboundEventPayload,
@@ -48,6 +49,45 @@ describe('summarizeFileDiffs', () => {
48
49
  });
49
50
  });
50
51
 
52
+ describe('projectMessageSummaryDiffCounts', () => {
53
+ it('replaces summary.diffs with diffCount/hasDiffs and drops the array', () => {
54
+ const owner = {
55
+ id: 'msg_1',
56
+ summary: {
57
+ title: 'turn',
58
+ diffs: [
59
+ { file: 'a.ts', additions: 1, deletions: 0, patch: '@@' },
60
+ { file: 'b.ts', additions: 2, deletions: 1 },
61
+ ],
62
+ },
63
+ };
64
+
65
+ const next = projectMessageSummaryDiffCounts(owner);
66
+ expect(next).not.toBe(owner);
67
+ expect(next.summary).toEqual({
68
+ title: 'turn',
69
+ diffCount: 2,
70
+ hasDiffs: true,
71
+ });
72
+ expect(next.summary.diffs).toBeUndefined();
73
+ });
74
+
75
+ it('projects empty arrays to diffCount 0 / hasDiffs false', () => {
76
+ const owner = {
77
+ summary: { diffs: [] },
78
+ };
79
+ expect(projectMessageSummaryDiffCounts(owner).summary).toEqual({
80
+ diffCount: 0,
81
+ hasDiffs: false,
82
+ });
83
+ });
84
+
85
+ it('keeps identity when summary has no diffs key', () => {
86
+ const owner = { summary: { title: 'x', diffCount: 3, hasDiffs: true } };
87
+ expect(projectMessageSummaryDiffCounts(owner)).toBe(owner);
88
+ });
89
+ });
90
+
51
91
  describe('summarizeOutboundEventPayload', () => {
52
92
  it('summarizes session.diff properties.diff', () => {
53
93
  const payload = {
@@ -97,7 +137,7 @@ describe('summarizeOutboundEventPayload', () => {
97
137
  }]);
98
138
  });
99
139
 
100
- it('summarizes message.updated info.summary.diffs', () => {
140
+ it('projects message.updated info.summary.diffs to L1 count/marker', () => {
101
141
  const payload = {
102
142
  type: 'message.updated',
103
143
  properties: {
@@ -116,11 +156,11 @@ describe('summarizeOutboundEventPayload', () => {
116
156
  };
117
157
 
118
158
  const next = summarizeOutboundEventPayload(payload);
119
- expect(next.properties.info.summary.diffs).toEqual([{
120
- file: 'a.ts',
121
- additions: 1,
122
- deletions: 0,
123
- }]);
159
+ expect(next.properties.info.summary).toEqual({
160
+ diffCount: 1,
161
+ hasDiffs: true,
162
+ });
163
+ expect(next.properties.info.summary.diffs).toBeUndefined();
124
164
  });
125
165
 
126
166
  it('returns identity for session.status', () => {
@@ -223,7 +223,7 @@ describe('event stream protocol helpers', () => {
223
223
  expect(rawPayload.length).toBeLessThan(64 * 1024);
224
224
  });
225
225
 
226
- it('summarizes message.updated summary.diffs patches on outbound frames', () => {
226
+ it('projects message.updated summary.diffs to L1 count/marker on outbound frames', () => {
227
227
  let rawPayload = null;
228
228
  const socket = {
229
229
  readyState: 1,
@@ -254,13 +254,13 @@ describe('event stream protocol helpers', () => {
254
254
 
255
255
  expect(sent).toBe(true);
256
256
  const frame = JSON.parse(rawPayload);
257
- expect(frame.payload.properties.info.summary.diffs).toEqual([{
258
- file: 'a.ts',
259
- status: 'modified',
260
- additions: 2,
261
- deletions: 1,
262
- }]);
257
+ expect(frame.payload.properties.info.summary).toEqual({
258
+ diffCount: 1,
259
+ hasDiffs: true,
260
+ });
261
+ expect(frame.payload.properties.info.summary.diffs).toBeUndefined();
263
262
  expect(JSON.stringify(frame)).not.toContain('patch');
263
+ expect(JSON.stringify(frame)).not.toContain('a.ts');
264
264
  });
265
265
 
266
266
  it('leaves ordinary session.status events unchanged', () => {