hivedesk 1.0.0 → 1.0.2

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 (93) hide show
  1. package/CHANGELOG.md +143 -111
  2. package/README.md +307 -303
  3. package/desktop/controller.js +85 -7
  4. package/desktop/native.js +4 -1
  5. package/desktop/release-notes/1.0.1.json +12 -0
  6. package/desktop/release-notes/1.0.2.json +12 -0
  7. package/desktop/scripts/package.mjs +11 -0
  8. package/desktop/shell.html +5 -2
  9. package/desktop/workarea.js +440 -0
  10. package/i18n/README.pt-BR.md +308 -304
  11. package/i18n/de.json +247 -4
  12. package/i18n/en.json +247 -4
  13. package/i18n/es.json +247 -4
  14. package/i18n/fr.json +247 -4
  15. package/i18n/it.json +247 -4
  16. package/i18n/ja.json +247 -4
  17. package/i18n/ko.json +247 -4
  18. package/i18n/parts/downloads.de.json +29 -0
  19. package/i18n/parts/downloads.en.json +29 -0
  20. package/i18n/parts/downloads.es.json +29 -0
  21. package/i18n/parts/downloads.fr.json +29 -0
  22. package/i18n/parts/downloads.it.json +29 -0
  23. package/i18n/parts/downloads.ja.json +29 -0
  24. package/i18n/parts/downloads.ko.json +29 -0
  25. package/i18n/parts/downloads.pt-BR.json +29 -0
  26. package/i18n/parts/downloads.ru.json +29 -0
  27. package/i18n/parts/downloads.zh-CN.json +29 -0
  28. package/i18n/parts/office.de.json +184 -0
  29. package/i18n/parts/office.en.json +184 -0
  30. package/i18n/parts/office.es.json +184 -0
  31. package/i18n/parts/office.fr.json +184 -0
  32. package/i18n/parts/office.it.json +184 -0
  33. package/i18n/parts/office.ja.json +184 -0
  34. package/i18n/parts/office.ko.json +184 -0
  35. package/i18n/parts/office.pt-BR.json +184 -0
  36. package/i18n/parts/office.ru.json +184 -0
  37. package/i18n/parts/office.zh-CN.json +184 -0
  38. package/i18n/pt-BR.json +247 -4
  39. package/i18n/ru.json +247 -4
  40. package/i18n/zh-CN.json +247 -4
  41. package/package.json +3 -2
  42. package/src/brain/manager.js +23 -7
  43. package/src/brain/models.js +146 -30
  44. package/src/brain/runtime.js +61 -13
  45. package/src/crew/domains/flow.js +2 -1
  46. package/src/crew/engine.js +172 -22
  47. package/src/crew/legacy.js +72 -0
  48. package/src/crew/planner.js +14 -1
  49. package/src/crew/talk.js +110 -3
  50. package/src/crew/taskgraph.js +12 -2
  51. package/src/crew/worker.js +60 -2
  52. package/src/index.js +4 -1
  53. package/src/p2p/doctor.js +4 -1
  54. package/src/phone/hub.js +15 -3
  55. package/src/phone/port.js +1 -1
  56. package/src/replay/reduce.js +1 -0
  57. package/src/tools/check.js +2 -0
  58. package/src/voice/index.js +1 -1
  59. package/src/voice/piper.js +10 -4
  60. package/src/voice/store.js +2 -1
  61. package/src/voice/whisper.js +63 -25
  62. package/ui/city/activity.js +4 -1
  63. package/ui/city/city.js +5 -5
  64. package/ui/city/scene.js +2 -1
  65. package/ui/css/hive.css +20 -0
  66. package/ui/js/dock.js +2 -2
  67. package/ui/js/dom.js +23 -18
  68. package/ui/js/i18n.js +12 -0
  69. package/ui/js/main.js +43 -3
  70. package/ui/js/md.js +130 -0
  71. package/ui/js/net.js +6 -0
  72. package/ui/js/palette.js +2 -2
  73. package/ui/js/store.js +20 -2
  74. package/ui/js/topbar.js +2 -2
  75. package/ui/js/voice/index.js +3 -2
  76. package/ui/js/widgets/brief.js +28 -10
  77. package/ui/js/widgets/chat.js +16 -4
  78. package/ui/js/widgets/files.js +3 -3
  79. package/ui/js/widgets/memory.js +3 -3
  80. package/ui/js/widgets/replay.js +3 -3
  81. package/ui/js/widgets/settings.js +2 -2
  82. package/ui/js/widgets/timeline.js +2 -2
  83. package/ui/js/widgets/worker.js +17 -6
  84. package/ui/models/index.js +3 -2
  85. package/ui/models/window.js +2 -2
  86. package/ui/office/office.js +145 -106
  87. package/ui/office/popout.js +4 -3
  88. package/ui/office/scene.js +47 -28
  89. package/ui/phone/core/client.js +11 -5
  90. package/ui/phone/desktop.js +2 -1
  91. package/ui/widget.html +8 -8
  92. package/ui/widget.js +35 -20
  93. package/ui/workbench/searchview.js +3 -3
@@ -2,6 +2,7 @@
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import crypto from 'node:crypto';
5
+ import { once } from 'node:events';
5
6
  import { diskFree, formatBytes } from './hardware.js';
6
7
 
7
8
  const HF = 'https://huggingface.co';
@@ -141,11 +142,12 @@ export function isCached(home, model) {
141
142
  }
142
143
 
143
144
  export class DownloadError extends Error {
144
- /** @param {'no_disk'|'no_network'|'http'|'aborted'|'io'|'checksum'} code */
145
- constructor(code, message, hint) {
145
+ /** @param {'no_disk'|'no_network'|'not_found'|'forbidden'|'rate_limited'|'server'|'http'|'aborted'|'io'|'locked'|'checksum'|'too_big'} code */
146
+ constructor(code, message, hint, extra) {
146
147
  super(message);
147
148
  this.code = code;
148
149
  this.hint = hint;
150
+ if (extra) Object.assign(this, extra);
149
151
  }
150
152
  }
151
153
 
@@ -154,17 +156,29 @@ function networkCode(err) {
154
156
  return /ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ECONNRESET|ETIMEDOUT|ENETUNREACH|EHOSTUNREACH|UND_ERR/.test(c) || err?.name === 'TypeError';
155
157
  }
156
158
 
159
+ /** A file in use by another program (an antivirus scan, a second window): Windows says EBUSY or EPERM. */
160
+ const LOCKED = /^(EBUSY|EPERM|EACCES|EISDIR|ETXTBSY)$/;
161
+
157
162
  async function hashFile(file, hash) {
158
163
  await new Promise((resolve, reject) => {
159
164
  fs.createReadStream(file).on('data', (c) => hash.update(c)).on('end', resolve).on('error', reject);
160
165
  });
161
166
  }
162
167
 
168
+ const hostOf = (url) => { try { return new URL(url).host; } catch { return 'the download server'; } };
169
+ const sleep = (ms, signal) => new Promise((resolve) => {
170
+ const t = setTimeout(resolve, ms);
171
+ signal?.addEventListener('abort', () => { clearTimeout(t); resolve(); }, { once: true });
172
+ });
173
+
174
+ /** Downloads in progress, by target file: a second download of the same model waits for the first. */
175
+ const inflight = new Map();
176
+
163
177
  /**
164
178
  * Downloads a model into the cache with resume (`.part`) and SHA-256 verification of every file.
165
179
  * A split model (catalog picks of the biggest files) downloads its parts one after the other.
166
180
  * @param {{ name: string, bytes: number, file?: string, url?: string, sha256?: string | null, files?: { file?: string, path?: string, bytes: number, sha256: string, url: string }[] }} model
167
- * @param {{ home: string, dir?: string, onProgress?: (p: { received: number, total: number, bps: number, part?: number, parts?: number }) => void, signal?: AbortSignal, fetchImpl?: typeof fetch, freeBytes?: number | null }} opts
181
+ * @param {{ home: string, dir?: string, onProgress?: (p: { received: number, total: number, bps: number, part?: number, parts?: number }) => void, signal?: AbortSignal, fetchImpl?: typeof fetch, freeBytes?: number | null, retryDelayMs?: number }} opts
168
182
  * @returns {Promise<string>} the path to load (the first part)
169
183
  */
170
184
  export async function downloadModel(model, opts) {
@@ -176,7 +190,17 @@ export async function downloadModel(model, opts) {
176
190
  if (!Number.isSafeInteger(p.bytes) || p.bytes <= 0 || p.bytes > MAX_PART_BYTES) throw new DownloadError('too_big', `${model.name} has a part with no size or one over ${formatBytes(MAX_PART_BYTES)}.`, 'Pick a model from the catalog, or point --model at a GGUF file you already have.');
177
191
  if (typeof p.file !== 'string' || !p.file || p.file !== path.basename(p.file) || p.file.startsWith('.')) throw new DownloadError('io', `${model.name} has a part with a bad file name.`, 'Pick a model from the catalog.');
178
192
  }
179
- fs.mkdirSync(dir, { recursive: true });
193
+ const key = path.resolve(dir, parts[0].file).toLowerCase();
194
+ while (inflight.has(key)) { try { await inflight.get(key); } catch { /* this one tries for itself */ } }
195
+ const job = downloadParts(model, parts, dir, opts);
196
+ inflight.set(key, job);
197
+ try { return await job; } finally { inflight.delete(key); }
198
+ }
199
+
200
+ async function downloadParts(model, parts, dir, opts) {
201
+ try { fs.mkdirSync(dir, { recursive: true }); } catch (err) {
202
+ throw new DownloadError(LOCKED.test(err.code) ? 'locked' : 'io', `Could not create the folder ${dir} (${err.code || err.message}).`, 'Check that the folder can be written, then press Retry.');
203
+ }
180
204
  const total = parts.reduce((n, p) => n + p.bytes, 0);
181
205
  const sizeOf = (f) => { try { return fs.statSync(f).size; } catch { return 0; } };
182
206
  // Disk: what is still missing, plus room.
@@ -191,7 +215,7 @@ export async function downloadModel(model, opts) {
191
215
  const need = missing + 100e6;
192
216
  if (missing > 0 && free != null && free < need) {
193
217
  throw new DownloadError('no_disk', `Not enough disk space for ${model.name}: needs ${formatBytes(need)}, ${formatBytes(free)} free in ${dir}.`,
194
- 'Free some space, use a smaller model, point --model at a GGUF file you already have, or run Ollama or LM Studio.');
218
+ 'Free some space, use a smaller model, point --model at a GGUF file you already have, or run Ollama or LM Studio.', { need, free });
195
219
  }
196
220
  let done = 0;
197
221
  for (let i = 0; i < parts.length; i++) {
@@ -205,46 +229,132 @@ export async function downloadModel(model, opts) {
205
229
  return path.join(dir, parts[0].file);
206
230
  }
207
231
 
232
+ /** Retry-After in seconds (a number or an HTTP date), or null. */
233
+ function retryAfter(res) {
234
+ const v = res.headers?.get?.('retry-after');
235
+ if (!v) return null;
236
+ const n = Number(v);
237
+ if (Number.isFinite(n)) return Math.max(0, Math.ceil(n));
238
+ const t = Date.parse(v);
239
+ return Number.isFinite(t) ? Math.max(0, Math.ceil((t - Date.now()) / 1000)) : null;
240
+ }
241
+
242
+ /** The error for an HTTP status, with what to do. */
243
+ function httpError(res, name, url) {
244
+ const host = hostOf(url);
245
+ const st = res.status;
246
+ if (st === 404 || st === 410) return new DownloadError('not_found', `${name} is no longer at ${host} (HTTP ${st}).`, 'Use another model; updating hivedesk refreshes the catalog. Press Retry if the server was being updated.', { status: st });
247
+ if (st === 401 || st === 403) return new DownloadError('forbidden', `${host} refused the download of ${name} (HTTP ${st}).`, 'Press Retry later or use another model. A network filter or proxy can also block it.', { status: st });
248
+ if (st === 429) {
249
+ const after = retryAfter(res);
250
+ return new DownloadError('rate_limited', `${host} asks to wait before downloading again (HTTP 429)${after ? `, about ${after} seconds` : ''}.`, 'Wait a little and press Retry; the download continues where it stopped.', { status: st, retryAfter: after });
251
+ }
252
+ if (st >= 500) return new DownloadError('server', `${host} had a problem sending ${name} (HTTP ${st}).`, 'Press Retry in a few minutes; the download continues where it stopped.', { status: st });
253
+ return new DownloadError('http', `The download of ${name} failed with HTTP ${st}.`, 'Press Retry later, or use another model.', { status: st });
254
+ }
255
+
256
+ /** Moves the verified part into place, waiting out a short lock (an antivirus scanning the new file). */
257
+ async function moveIntoPlace(part, final, opts) {
258
+ const delay = opts.retryDelayMs ?? 500;
259
+ for (let i = 0; ; i++) {
260
+ try {
261
+ fs.renameSync(part, final);
262
+ return final;
263
+ } catch (err) {
264
+ if (!LOCKED.test(err?.code || '')) throw new DownloadError('io', `Could not save ${final} (${err.code || err.message}).`, 'Check that the folder can be written, then press Retry.');
265
+ if (i >= 5) {
266
+ throw new DownloadError('locked', `${final} is in use by another program (${err.code}), so the verified download could not be put in place.`,
267
+ 'An antivirus scan or another hivedesk window may hold it: wait a moment, or allow the hivedesk folder in the antivirus, then press Retry. The verified download is kept.');
268
+ }
269
+ await sleep(delay * (i + 1));
270
+ }
271
+ }
272
+ }
273
+
208
274
  async function downloadFile(p, final, opts) {
209
275
  const f = opts.fetchImpl || fetch;
210
276
  const part = final + '.part';
277
+ const host = hostOf(p.url);
211
278
  let have = 0;
212
- try { have = fs.statSync(part).size; } catch { /* fresh */ }
213
- if (have > p.bytes) { fs.rmSync(part, { force: true }); have = 0; }
279
+ let st = null;
280
+ try { st = fs.statSync(part); } catch { /* fresh */ }
281
+ // Something that is not a plain file sits where the part file goes (a folder, a device): never delete it.
282
+ if (st && !st.isFile()) {
283
+ throw new DownloadError('locked', `${part} is not a file, so the download cannot be written there.`, 'Move or remove it, then press Retry.');
284
+ }
285
+ if (st) have = st.size;
286
+ if (have > p.bytes) {
287
+ try { fs.rmSync(part, { force: true }); } catch (e) {
288
+ throw new DownloadError(LOCKED.test(e?.code || '') ? 'locked' : 'io', `${part} could not be removed (${e?.code || e?.message}).`, 'Close the program that uses it, then press Retry.');
289
+ }
290
+ have = 0;
291
+ }
214
292
  const hash = crypto.createHash('sha256');
215
293
  if (have > 0) await hashFile(part, hash);
294
+ if (have === p.bytes) {
295
+ // A complete part left by a crash or a lock: verify it, no request needed.
296
+ if (hash.digest('hex') === String(p.sha256).toLowerCase()) return moveIntoPlace(part, final, opts);
297
+ fs.rmSync(part, { force: true });
298
+ return downloadFile(p, final, opts);
299
+ }
216
300
  const report = (received, bps) => opts.onProgress?.({ received: opts.offset + received, total: opts.total, bps, ...(opts.count > 1 ? { part: opts.index + 1, parts: opts.count } : {}) });
301
+ const aborted = () => new DownloadError('aborted', 'The download was stopped.', 'Press Retry to continue where it stopped.');
217
302
  let res;
218
- try {
219
- res = await f(p.url, { headers: have ? { range: `bytes=${have}-` } : {}, redirect: 'follow', signal: opts.signal });
220
- } catch (err) {
221
- if (opts.signal?.aborted) throw new DownloadError('aborted', 'The download was stopped.', 'Press Retry to continue where it stopped.');
222
- if (networkCode(err)) {
223
- throw new DownloadError('no_network', `Could not reach huggingface.co to download ${opts.name}.`,
224
- 'Check the connection and press Retry, or use --model <file.gguf>, or --demo to look around.');
303
+ for (let tries = 0; ; tries++) {
304
+ try {
305
+ res = await f(p.url, { headers: have ? { range: `bytes=${have}-` } : {}, redirect: 'follow', signal: opts.signal });
306
+ } catch (err) {
307
+ if (opts.signal?.aborted) throw aborted();
308
+ if (networkCode(err)) {
309
+ throw new DownloadError('no_network', `Could not reach ${host} to download ${opts.name}.`,
310
+ 'Check the connection and press Retry, or use --model <file.gguf>, or --demo to look around.');
311
+ }
312
+ throw new DownloadError('io', String(err.message || err), 'Press Retry.');
313
+ }
314
+ // Too many requests with a short wait named by the server: wait and ask again, twice at most.
315
+ const wait = res.status === 429 ? retryAfter(res) : null;
316
+ if (wait != null && wait <= 30 && tries < 2) {
317
+ await res.body?.cancel?.().catch(() => {});
318
+ await sleep(wait * 1000, opts.signal);
319
+ if (opts.signal?.aborted) throw aborted();
320
+ continue;
225
321
  }
226
- throw new DownloadError('io', String(err.message || err), 'Press Retry.');
322
+ break;
227
323
  }
228
- if (have && res.status === 200) {
229
- // The server ignored the range: start over.
324
+ const restart = async () => {
325
+ await res.body?.cancel?.().catch(() => {});
230
326
  fs.rmSync(part, { force: true });
231
- hash.destroy?.();
232
327
  return downloadFile(p, final, opts);
328
+ };
329
+ // The server ignored the range, or could not serve it: start over.
330
+ if (have && (res.status === 200 || res.status === 416)) return restart();
331
+ if (have && res.status === 206) {
332
+ const m = /bytes (\d+)-/.exec(res.headers?.get?.('content-range') || '');
333
+ if (m && Number(m[1]) !== have) return restart();
334
+ }
335
+ if (!res.ok && res.status !== 206) {
336
+ await res.body?.cancel?.().catch(() => {});
337
+ throw httpError(res, opts.name, p.url);
233
338
  }
234
- if (!res.ok && res.status !== 206) throw new DownloadError('http', `The download failed with HTTP ${res.status}.`, 'Press Retry later, or use --model <file.gguf>.');
235
- const out = fs.createWriteStream(part, { flags: have ? 'a' : 'w' });
339
+ let out = null;
340
+ let wErr = null;
236
341
  let received = have;
237
342
  let lastTick = 0;
238
343
  let lastBytes = received;
239
344
  let lastTime = Date.now();
240
345
  let bps = 0;
241
346
  try {
347
+ if (!res.body) throw new Error('empty body');
348
+ out = fs.createWriteStream(part, { flags: have ? 'a' : 'w' });
349
+ // A write error (disk full, the file locked) must end the download, never crash or hang it.
350
+ out.on('error', (e) => { wErr ||= e; });
242
351
  for await (const chunk of res.body) {
352
+ if (wErr) throw wErr;
243
353
  hash.update(chunk);
244
354
  received += chunk.length;
245
355
  // Never more than the size the catalog names: a server sending more is cut off and the part is dropped.
246
- if (received > p.bytes) { out.destroy(); fs.rmSync(part, { force: true }); throw Object.assign(new Error('too big'), { tooBig: true }); }
247
- if (!out.write(chunk)) await new Promise((r) => out.once('drain', r));
356
+ if (received > p.bytes) throw Object.assign(new Error('too big'), { tooBig: true });
357
+ if (!out.write(chunk)) await once(out, 'drain');
248
358
  const now = Date.now();
249
359
  if (now - lastTick > 250) {
250
360
  const dt = (now - lastTime) / 1000;
@@ -253,24 +363,30 @@ async function downloadFile(p, final, opts) {
253
363
  report(received, bps);
254
364
  }
255
365
  }
366
+ await new Promise((resolve, reject) => out.end((err) => (err || wErr ? reject(err || wErr) : resolve())));
256
367
  } catch (err) {
257
- out.end();
368
+ const e = wErr || err;
369
+ await new Promise((resolve) => { if (!out || out.closed) return resolve(); out.once('close', resolve); out.destroy(); });
370
+ res.body?.cancel?.().catch(() => {});
258
371
  if (err?.tooBig) { fs.rmSync(part, { force: true }); throw new DownloadError('checksum', `The server sent more than the ${formatBytes(p.bytes)} of ${opts.name}.`, 'It was deleted; press Retry to download it again.'); }
259
- if (opts.signal?.aborted) throw new DownloadError('aborted', 'The download was stopped.', 'Press Retry to continue where it stopped.');
260
- if (err?.code === 'ENOSPC') throw new DownloadError('no_disk', 'The disk is full.', 'Free some space and press Retry; the download continues where it stopped.');
261
- throw new DownloadError('no_network', `The connection dropped at ${formatBytes(opts.offset + received)} of ${formatBytes(opts.total)}.`, 'Press Retry; the download continues where it stopped.');
372
+ if (opts.signal?.aborted) throw aborted();
373
+ if (e?.code === 'ENOSPC') throw new DownloadError('no_disk', 'The disk is full.', 'Free some space and press Retry; the download continues where it stopped.');
374
+ if (LOCKED.test(e?.code || '')) {
375
+ throw new DownloadError('locked', `${part} is in use by another program (${e.code}).`,
376
+ 'An antivirus scan or another hivedesk window may hold it: wait a moment, or allow the hivedesk folder in the antivirus, then press Retry.');
377
+ }
378
+ if (e?.syscall) throw new DownloadError('io', `Could not write ${part} (${e.code || e.message}).`, 'Check that the folder can be written and has free space, then press Retry.');
379
+ throw new DownloadError('no_network', `The connection dropped at ${formatBytes(opts.offset + received)} of ${formatBytes(opts.total)}.`, 'Check the connection and press Retry; the download continues where it stopped.');
262
380
  }
263
- await new Promise((resolve, reject) => out.end((err) => (err ? reject(err) : resolve())));
264
381
  report(received, bps);
265
382
  if (p.bytes && received < p.bytes) {
266
383
  // The body ended early without an error: keep the part, the next try resumes.
267
- throw new DownloadError('no_network', `The connection dropped at ${formatBytes(opts.offset + received)} of ${formatBytes(opts.total)}.`, 'Press Retry; the download continues where it stopped.');
384
+ throw new DownloadError('no_network', `The connection dropped at ${formatBytes(opts.offset + received)} of ${formatBytes(opts.total)}.`, 'Check the connection and press Retry; the download continues where it stopped.');
268
385
  }
269
386
  const digest = hash.digest('hex');
270
387
  if (digest !== String(p.sha256).toLowerCase()) {
271
388
  fs.rmSync(part, { force: true });
272
389
  throw new DownloadError('checksum', `The downloaded file for ${opts.name} is corrupt (checksum mismatch).`, 'It was deleted; press Retry to download it again.');
273
390
  }
274
- fs.renameSync(part, final);
275
- return final;
391
+ return moveIntoPlace(part, final, opts);
276
392
  }
@@ -40,12 +40,26 @@ export async function findRuntime(home) {
40
40
  return null;
41
41
  }
42
42
 
43
- function npmCli() {
44
- const guess = [
45
- path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js'),
46
- path.join(path.dirname(process.execPath), '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js')
47
- ];
48
- return guess.find((p) => fs.existsSync(p)) || null;
43
+ const nextToNode = (node) => [
44
+ path.join(path.dirname(node), 'node_modules', 'npm', 'bin', 'npm-cli.js'),
45
+ path.join(path.dirname(node), '..', 'lib', 'node_modules', 'npm', 'bin', 'npm-cli.js')
46
+ ];
47
+
48
+ /**
49
+ * npm to install the runtime with: { node, script }. First the npm that ships with the running Node.js (the
50
+ * desktop app bundles one), then the npm of a Node.js on the PATH, run by the running node.
51
+ */
52
+ export function npmCli(env = process.env, execPath = process.execPath) {
53
+ const own = nextToNode(execPath).find((p) => fs.existsSync(p));
54
+ if (own) return { node: execPath, script: own };
55
+ const exe = process.platform === 'win32' ? 'node.exe' : 'node';
56
+ for (const dir of String(env.PATH || env.Path || '').split(path.delimiter).filter(Boolean)) {
57
+ const node = path.join(dir, exe);
58
+ if (!fs.existsSync(node)) continue;
59
+ const script = nextToNode(node).find((p) => fs.existsSync(p));
60
+ if (script) return { node: execPath, script };
61
+ }
62
+ return null;
49
63
  }
50
64
 
51
65
  export class RuntimeError extends Error {
@@ -73,10 +87,35 @@ export async function installRuntime(home, opts = {}) {
73
87
  opts.onLine?.('retrying with a private npm cache');
74
88
  r = await npmInstall(dir, ['--cache', path.join(dir, '.npm-cache'), '--prefer-online'], opts);
75
89
  }
90
+ if (r.code !== 0 && !r.offline && !r.noNpm) {
91
+ // A runtime folder left broken by an earlier attempt: install into a fresh folder and swap it in.
92
+ opts.onLine?.('retrying in a fresh runtime folder');
93
+ const fresh = `${dir}.new`;
94
+ fs.rmSync(fresh, { recursive: true, force: true });
95
+ fs.mkdirSync(fresh, { recursive: true });
96
+ fs.writeFileSync(path.join(fresh, 'package.json'), JSON.stringify({ name: 'hivedesk-runtime', private: true, type: 'module' }, null, 2));
97
+ r = await npmInstall(fresh, ['--cache', path.join(fresh, '.npm-cache'), '--prefer-online'], opts);
98
+ if (r.code === 0) {
99
+ fs.rmSync(dir, { recursive: true, force: true });
100
+ fs.renameSync(fresh, dir);
101
+ } else {
102
+ fs.rmSync(fresh, { recursive: true, force: true });
103
+ }
104
+ }
76
105
  if (r.code !== 0) {
77
- throw new RuntimeError(r.offline ? 'no_network' : 'install_failed',
78
- r.offline ? 'Could not download the local runtime (node-llama-cpp): no network.' : `Installing the local runtime (node-llama-cpp) failed (exit code ${r.code}).`,
79
- r.offline ? 'Check the connection and press Retry, or use --brain ollama or --brain lmstudio.' : 'Run hivedesk --doctor, or use --brain ollama or --brain lmstudio.');
106
+ const why = r.reason ? ` ${r.reason}` : '';
107
+ if (r.noNpm) {
108
+ throw new RuntimeError('no_npm', 'Could not install the local runtime (node-llama-cpp): npm was not found.', 'Reinstall hivedesk from the site (the app brings its own npm), install Node.js 20 or newer, or use --brain ollama or --brain lmstudio.');
109
+ }
110
+ if (r.offline) throw new RuntimeError('no_network', `Could not download the local runtime (node-llama-cpp): no network.${why}`, 'Check the connection and press Retry, or use --brain ollama or --brain lmstudio.');
111
+ if (/EBUSY|EPERM|EACCES|resource busy|locked/i.test(r.reason || '')) {
112
+ throw new RuntimeError('locked', `Installing the local runtime (node-llama-cpp) failed: a file in the runtime folder is in use.${why}`, 'Close other hivedesk windows, wait for the antivirus scan or allow the hivedesk folder in it, then press Retry.');
113
+ }
114
+ if (/E404|404 Not Found/i.test(r.reason || '')) {
115
+ throw new RuntimeError('not_found', `Installing the local runtime (node-llama-cpp) failed: the npm registry does not have it (404).${why}`, 'Press Retry later or update hivedesk; meanwhile use --brain ollama or --brain lmstudio.');
116
+ }
117
+ throw new RuntimeError('install_failed', `Installing the local runtime (node-llama-cpp) failed:${why || ' npm stopped without saying why.'}`,
118
+ 'Press Retry, run hivedesk --doctor, or use --brain ollama or --brain lmstudio.');
80
119
  }
81
120
  const found = installedEntry(home);
82
121
  if (!found) throw new RuntimeError('install_failed', 'The runtime was installed but could not be found.', 'Delete the runtime folder in the cache and try again.');
@@ -89,9 +128,10 @@ async function npmInstall(dir, extra, opts) {
89
128
  // their own, and src/brain/local.js loads them with build: 'never', so the postinstall build step is never needed.
90
129
  const args = ['install', `${RUNTIME_PACKAGE}@${RUNTIME_VERSION}`, '--ignore-scripts', '--save-exact', '--no-audit', '--no-fund', '--omit=dev', '--loglevel=error', '--prefix', dir, ...extra];
91
130
  const sp = opts.spawnImpl || spawn;
92
- const child = cli
93
- ? sp(process.execPath, [cli, ...args], { cwd: dir, windowsHide: true })
94
- : sp(process.platform === 'win32' ? 'npm.cmd' : 'npm', args, { cwd: dir, windowsHide: true, shell: process.platform === 'win32' });
131
+ // Always npm-cli.js run by a node binary, never through a shell: a shell splits paths with spaces
132
+ // (C:\Users\First Last\.hivedesk\runtime) and npm then installs into the wrong place or fails.
133
+ if (!cli) return { code: -1, offline: false, noNpm: true, reason: 'npm was not found next to Node.js or on the PATH.' };
134
+ const child = sp(cli.node, [cli.script, ...args], { cwd: dir, windowsHide: true });
95
135
  let tail = '';
96
136
  const onData = (c) => {
97
137
  const text = String(c);
@@ -104,7 +144,15 @@ async function npmInstall(dir, extra, opts) {
104
144
  child.on('error', (err) => { tail += String(err.message); resolve(-1); });
105
145
  child.on('close', resolve);
106
146
  });
107
- return { code, offline: code !== 0 && /ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ETIMEDOUT|ECONNRESET|network/i.test(tail) };
147
+ return { code, offline: code !== 0 && /ENOTFOUND|EAI_AGAIN|ECONNREFUSED|ETIMEDOUT|ECONNRESET|network/i.test(tail), reason: code !== 0 ? npmReason(tail) : '' };
148
+ }
149
+
150
+ /** The useful part of a failed npm run: its error lines, without the log file noise, short enough for a dialog. */
151
+ export function npmReason(tail) {
152
+ const lines = String(tail).split(/\r?\n/).map((l) => l.trim()).filter(Boolean)
153
+ .filter((l) => !/complete log of this run|A complete log|npm error\s*$/i.test(l));
154
+ const errs = lines.filter((l) => /^npm (error|ERR!)/i.test(l)).map((l) => l.replace(/^npm (error|ERR!)\s*/i, ''));
155
+ return (errs.length ? errs : lines).slice(-3).join(' ').slice(0, 300);
108
156
  }
109
157
 
110
158
  /** Imports node-llama-cpp, installing it first when needed. */
@@ -165,7 +165,8 @@ export async function startDomain(hive, job, run) {
165
165
  if (signal.aborted) return { domain: cls.domain, specialist: null, seeded: [], notes: [], cancelled: true };
166
166
  // A job started on purpose (the top bar) with a question still builds, as before: on the web stack.
167
167
  if (cls.domain === 'chat') cls = { ...cls, domain: 'web', confidence: 'low', words: [], files: [], source: 'keywords' };
168
- const asks = job.refine !== false && !job.cityTaskId && hive.state.settings.questions !== false;
168
+ // A job revived from its waiting brief was asked before: no questions again.
169
+ const asks = job.refine !== false && !job.cityTaskId && !run.preDecision && hive.state.settings.questions !== false;
169
170
  if (asks) {
170
171
  const r = await ask(hive, job, run, cls);
171
172
  if (r.cancelled || signal.aborted) return { domain: cls.domain, specialist: null, seeded: [], notes: [], cancelled: true };