droidsembly 0.5.0-beta.1 → 0.5.0-beta.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.
package/README.it.md CHANGED
@@ -12,7 +12,7 @@ Uno spazio visuale per lo sviluppo software assistito dall'AI: collega i tuoi re
12
12
 
13
13
  [Sito](https://droidsembly.com) · [npm](https://www.npmjs.com/package/droidsembly) · [Release](https://github.com/rosariomoscato/droidsembly/releases) · [Segnala un problema](https://github.com/rosariomoscato/droidsembly/issues) · [Contribuire](CONTRIBUTING.it.md) · [Documentazione](#documentazione) · [Sostieni il progetto](#sostieni-il-progetto)
14
14
 
15
- **Beta pubblica: 0.5.0-beta.1.** Il canale previsto è npm `latest`, per permettere ai tester di usare `npx droidsembly` senza selezionare un canale. Verifica su [npm](https://www.npmjs.com/package/droidsembly) e nella [release](https://github.com/rosariomoscato/droidsembly/releases/tag/droidsembly-v0.5.0-beta.1) lo stato della pubblicazione. Include profili cloud manuali di review/deploy e notifiche di accesso cloud, oltre alla pianificazione di app con il CEO e alla ripresa delle issue interrotte. Vedi [note di rilascio e limiti di validazione](https://github.com/rosariomoscato/droidsembly/blob/main/docs/RELEASE_NOTES_0.5.0-beta.1.md). Visita [droidsembly.com](https://droidsembly.com) per la presentazione.
15
+ **Beta pubblicata: 0.5.0-beta.1**, disponibile su npm **`latest` e `next`**. Avvia con `npx droidsembly` senza selezionare un canale. Vedi [npm](https://www.npmjs.com/package/droidsembly) e la [release](https://github.com/rosariomoscato/droidsembly/releases/tag/droidsembly-v0.5.0-beta.1). Include profili cloud manuali di review/deploy e notifiche di accesso cloud, oltre alla pianificazione di app con il CEO e alla ripresa delle issue interrotte. Vedi [note di rilascio e limiti di validazione](https://github.com/rosariomoscato/droidsembly/blob/main/docs/RELEASE_NOTES_0.5.0-beta.1.md). Visita [droidsembly.com](https://droidsembly.com) per la presentazione.
16
16
 
17
17
  **Gratuito e open source, con licenza MIT.** Nessuna attivazione a pagamento o sblocco commerciale degli agenti. Il sostegno volontario aiuta lo sviluppo; abbonamenti AI, consumi API e servizi cloud opzionali hanno costi e limiti propri.
18
18
 
@@ -54,9 +54,9 @@ Catture reali della **0.4.0-beta.6 pubblicata**, acquisite il 21 novembre 2026 i
54
54
 
55
55
  ## Installa questo fork
56
56
 
57
- **Pacchetto:** [droidsembly su npm](https://www.npmjs.com/package/droidsembly). Dopo la pubblicazione della 0.5 avvia con `npx droidsembly` (`npx.cmd droidsembly` in PowerShell), oppure scegli la versione esatta con `npx droidsembly@0.5.0-beta.1`. Compilare un checkout usa la sua versione, non necessariamente i byte pubblicati. Queste sono istruzioni di avvio, non un aggiornamento automatico dell'ufficio esistente: segui prima la [procedura di aggiornamento controllato](docs/QUICKSTART_PC.md). Non è ancora disponibile un installer desktop. `npx cubefarm` installa il pacchetto originale, non Droidsembly.
57
+ **Pacchetto:** [droidsembly su npm](https://www.npmjs.com/package/droidsembly). Avvia con `npx droidsembly` (`npx.cmd droidsembly` in PowerShell), oppure scegli la versione esatta con `npx droidsembly@0.5.0-beta.1`. Compilare un checkout usa la sua versione, non necessariamente i byte pubblicati. Queste sono istruzioni di avvio, non un aggiornamento automatico dell'ufficio esistente: segui prima la [procedura di aggiornamento controllato](docs/QUICKSTART_PC.md). Non è ancora disponibile un installer desktop. `npx cubefarm` installa il pacchetto originale, non Droidsembly.
58
58
 
59
- **È una beta, non una versione stabile, anche su `latest`.** Il maintainer ha scelto `latest` per questo collaudo pubblico; la 0.5.0-beta.1 cerca gli aggiornamenti su quel canale. Le precedenti beta 0.4 continuano a controllare `next`, il cui allineamento viene verificato separatamente dopo la pubblicazione. Il pacchetto non espone un alias globale `cubefarm`. Il file interno `bin/cubefarm.js` e i launcher dei checkout esistenti restano compatibili. Le home legacy esistenti sono adottate; `DROIDSEMBLY_HOME` prevale su `SWARM_HOME` e una doppia home ambigua richiede scelta esplicita. Per l'uso affiancato scegli una home separata e porte libere come descritto sotto.
59
+ **È una beta, non una versione stabile, anche su `latest`.** Il maintainer ha scelto `latest` per questo collaudo pubblico; la 0.5.0-beta.1 cerca gli aggiornamenti su quel canale. Le precedenti beta 0.4 continuano a controllare `next`, ora allineato allo stesso pacchetto 0.5.0-beta.1. Il pacchetto non espone un alias globale `cubefarm`. Il file interno `bin/cubefarm.js` e i launcher dei checkout esistenti restano compatibili. Le home legacy esistenti sono adottate; `DROIDSEMBLY_HOME` prevale su `SWARM_HOME` e una doppia home ambigua richiede scelta esplicita. Per l'uso affiancato scegli una home separata e porte libere come descritto sotto.
60
60
 
61
61
  ### Requisiti
62
62
 
@@ -171,7 +171,7 @@ Le impostazioni comprendono sottotitoli, comfort di movimento, scala UI, contras
171
171
 
172
172
  Per un'installazione dai sorgenti, ferma l'ufficio quando gli agenti sono inattivi, salva un backup dello `SWARM_HOME` scelto e consulta il [changelog del fork](https://github.com/rosariomoscato/droidsembly/blob/main/docs/FORK_CHANGELOG.md). In un checkout pulito su `main`, esegui `git pull --ff-only`, poi `npm.cmd ci` e `npm.cmd run build` su Windows (`npm ci` e `npm run build` su macOS/Linux). Riavvia con la stessa cartella dati e le stesse porte. Preserva eventuali modifiche locali prima di aggiornare.
173
173
 
174
- Non usare `npx cubefarm@latest` per aggiornare questo fork: punta al pacchetto npm originale. La CLI preparata verifica soltanto `droidsembly`, su `next` per le prerelease e `latest` per le stabili; una voce del registry non disponibile viene ignorata. I comandi diretti del server qui indicati non usano il launcher autoaggiornante del checkout; vedi [come funzionano gli aggiornamenti](https://github.com/rosariomoscato/droidsembly/blob/main/docs/how-it-works.md#updating-the-office) per quel flusso distinto. Gli aggiornamenti del pacchetto sono manuali; installare un nuovo nome npm non migra un'installazione esistente o i suoi dati.
174
+ Non usare `npx cubefarm@latest` per aggiornare questo fork: punta al pacchetto npm originale. La CLI verifica soltanto `droidsembly`: questa beta pubblica 0.5.0-beta.1 e le versioni stabili usano `latest`; le altre prerelease usano `next`. Una voce del registry non disponibile viene ignorata. I comandi diretti del server qui indicati non usano il launcher autoaggiornante del checkout; vedi [come funzionano gli aggiornamenti](https://github.com/rosariomoscato/droidsembly/blob/main/docs/how-it-works.md#updating-the-office) per quel flusso distinto. Gli aggiornamenti del pacchetto sono manuali; installare un nuovo nome npm non migra un'installazione esistente o i suoi dati.
175
175
 
176
176
  ## Sostieni il progetto
177
177
 
package/README.md CHANGED
@@ -12,7 +12,7 @@ A visual workspace for AI-assisted software development: connect your GitHub rep
12
12
 
13
13
  [Website](https://droidsembly.com) · [npm](https://www.npmjs.com/package/droidsembly) · [Releases](https://github.com/rosariomoscato/droidsembly/releases) · [Report an issue](https://github.com/rosariomoscato/droidsembly/issues) · [Contributing](CONTRIBUTING.md) · [Documentation](#documentation) · [Support the project](#support-the-project)
14
14
 
15
- **Public beta release: 0.5.0-beta.1.** The release target is npm `latest`, so testers can run `npx droidsembly` without choosing a channel. Check [npm](https://www.npmjs.com/package/droidsembly) and the [release](https://github.com/rosariomoscato/droidsembly/releases/tag/droidsembly-v0.5.0-beta.1) for publication status. Includes manual cloud review/deployment profiles and cloud sign-in notifications, alongside CEO-guided app planning and interrupted-issue recovery. See [release notes and validation limits](https://github.com/rosariomoscato/droidsembly/blob/main/docs/RELEASE_NOTES_0.5.0-beta.1.md). Visit [droidsembly.com](https://droidsembly.com) for an introduction.
15
+ **Published public beta: 0.5.0-beta.1**, available on npm **`latest` and `next`**. Run `npx droidsembly` without choosing a channel. See [npm](https://www.npmjs.com/package/droidsembly) and the [release](https://github.com/rosariomoscato/droidsembly/releases/tag/droidsembly-v0.5.0-beta.1). Includes manual cloud review/deployment profiles and cloud sign-in notifications, alongside CEO-guided app planning and interrupted-issue recovery. See [release notes and validation limits](https://github.com/rosariomoscato/droidsembly/blob/main/docs/RELEASE_NOTES_0.5.0-beta.1.md). Visit [droidsembly.com](https://droidsembly.com) for an introduction.
16
16
 
17
17
  **Free and open source, under the MIT license.** No paid activation or commercial agent unlocks. Voluntary support helps development; your AI subscriptions, API usage and optional cloud services have their own costs and limits.
18
18
 
@@ -54,9 +54,9 @@ Actual captures of the published **0.4.0-beta.6**, taken on 21 November 2026 in
54
54
 
55
55
  ## Install this fork
56
56
 
57
- **Package:** [droidsembly on npm](https://www.npmjs.com/package/droidsembly). After the 0.5 release is published, run `npx droidsembly` (`npx.cmd droidsembly` in PowerShell), or pin it with `npx droidsembly@0.5.0-beta.1`. Building a checkout uses that checkout's version, not necessarily the published bytes. These are launch instructions, not an automatic update of an existing office: first follow the [controlled update guidance](docs/QUICKSTART_PC.md). There is no desktop installer yet. `npx cubefarm` installs the original package, not Droidsembly.
57
+ **Package:** [droidsembly on npm](https://www.npmjs.com/package/droidsembly). Run `npx droidsembly` (`npx.cmd droidsembly` in PowerShell), or pin it with `npx droidsembly@0.5.0-beta.1`. Building a checkout uses that checkout's version, not necessarily the published bytes. These are launch instructions, not an automatic update of an existing office: first follow the [controlled update guidance](docs/QUICKSTART_PC.md). There is no desktop installer yet. `npx cubefarm` installs the original package, not Droidsembly.
58
58
 
59
- **This is a beta, not a stable release, even on `latest`.** The maintainer selected `latest` for this public test release; 0.5.0-beta.1 checks that channel for updates. Earlier 0.4 betas continue checking `next`; its alignment is verified separately after publication. The package exposes no global `cubefarm` alias. The internal entry file `bin/cubefarm.js` and existing checkout launchers remain compatible. Existing legacy homes are adopted; `DROIDSEMBLY_HOME` takes precedence over `SWARM_HOME`, and ambiguous dual homes require an explicit choice. For side-by-side use, select a separate home and free ports as described below.
59
+ **This is a beta, not a stable release, even on `latest`.** The maintainer selected `latest` for this public test release; 0.5.0-beta.1 checks that channel for updates. Earlier 0.4 betas continue checking `next`, now aligned to the same 0.5.0-beta.1 package. The package exposes no global `cubefarm` alias. The internal entry file `bin/cubefarm.js` and existing checkout launchers remain compatible. Existing legacy homes are adopted; `DROIDSEMBLY_HOME` takes precedence over `SWARM_HOME`, and ambiguous dual homes require an explicit choice. For side-by-side use, select a separate home and free ports as described below.
60
60
 
61
61
  ### Requirements
62
62
 
@@ -171,7 +171,7 @@ Settings include captions, motion comfort, UI scaling, contrast and list views.
171
171
 
172
172
  For a source installation, stop the office when agents are idle, back up your chosen `SWARM_HOME`, and review the [fork changelog](https://github.com/rosariomoscato/droidsembly/blob/main/docs/FORK_CHANGELOG.md). In a clean checkout on `main`, use `git pull --ff-only`, then `npm.cmd ci` and `npm.cmd run build` on Windows (`npm ci` and `npm run build` on macOS/Linux). Restart using the same data folder and ports. Preserve local changes before updating.
173
173
 
174
- Do not use `npx cubefarm@latest` to update this fork: it targets the original npm package. This prepared CLI checks only `droidsembly`, using `next` for prereleases and `latest` for stable versions; an unavailable registry entry is ignored. The direct server commands above do not use the checkout's self-updating launcher; see [how updating works](https://github.com/rosariomoscato/droidsembly/blob/main/docs/how-it-works.md#updating-the-office) for that separate workflow. Package updates are manual; installing a new package name does not migrate an existing installation or its data.
174
+ Do not use `npx cubefarm@latest` to update this fork: it targets the original npm package. The CLI checks only `droidsembly`: this approved 0.5.0-beta.1 public beta and stable versions use `latest`; other prereleases use `next`. An unavailable registry entry is ignored. The direct server commands above do not use the checkout's self-updating launcher; see [how updating works](https://github.com/rosariomoscato/droidsembly/blob/main/docs/how-it-works.md#updating-the-office) for that separate workflow. Package updates are manual; installing a new package name does not migrate an existing installation or its data.
175
175
 
176
176
  ## Support the project
177
177
 
@@ -258,10 +258,11 @@ async function resumeDesk(main, desk, branch, defaultRef) {
258
258
  return desk;
259
259
  }
260
260
  if (entries.length) throw new Error("The desk folder contains files but is not a worktree; its files were left untouched.");
261
- await g(main, ["fetch", "origin", "--prune"]);
262
261
  const exists2 = (ref) => g(main, ["show-ref", "--verify", "--quiet", ref]).then(() => true, () => false);
262
+ const local = await exists2(`refs/heads/${branch}`);
263
+ if (!local) await g(main, ["fetch", "origin", "--prune"]);
263
264
  await fs3.mkdir(path3.dirname(desk), { recursive: true });
264
- if (await exists2(`refs/heads/${branch}`)) await g(main, ["worktree", "add", desk, branch]);
265
+ if (local) await g(main, ["worktree", "add", desk, branch]);
265
266
  else {
266
267
  const ref = await exists2(`refs/remotes/origin/${branch}`) ? `origin/${branch}` : defaultRef;
267
268
  await g(main, ["worktree", "add", "-b", branch, desk, ref]);
@@ -8292,12 +8293,20 @@ var WeatherService = class {
8292
8293
  this.saving = this.saving.then(() => this.save());
8293
8294
  }
8294
8295
  saving = Promise.resolve();
8296
+ savedCache = null;
8297
+ cacheText() {
8298
+ return JSON.stringify({ city: this.city, place: this.view.place, reading: this.view.reading }, null, 2);
8299
+ }
8295
8300
  async save() {
8296
8301
  const tmp = `${this.o.file}.tmp`;
8297
8302
  try {
8303
+ if (this.cacheText() === this.savedCache) return;
8298
8304
  await fs17.mkdir(path17.dirname(this.o.file), { recursive: true });
8299
- await fs17.writeFile(tmp, JSON.stringify({ city: this.city, place: this.view.place, reading: this.view.reading }, null, 2));
8305
+ const data = this.cacheText();
8306
+ if (data === this.savedCache) return;
8307
+ await fs17.writeFile(tmp, data);
8300
8308
  await fs17.rename(tmp, this.o.file);
8309
+ this.savedCache = data;
8301
8310
  } catch (err) {
8302
8311
  this.o.log(`weather: couldn't save the cache: ${err.message}`);
8303
8312
  }
@@ -9162,6 +9171,7 @@ async function fakeTrim(stillIdle) {
9162
9171
  return { freed: Math.round((300 + Math.random() * 600) * 2 ** 20), removed: ["node_modules", "dist"], skipped: [] };
9163
9172
  }
9164
9173
  function createDemoBackend(scale = null) {
9174
+ const sessions = /* @__PURE__ */ new Set();
9165
9175
  const planIssues = /* @__PURE__ */ new Map();
9166
9176
  const planningDir = path18.join(HOME_DIR, "demo-planning-github");
9167
9177
  const planningRepos = /* @__PURE__ */ new Set();
@@ -9414,7 +9424,18 @@ Closes #${pr.closesIssues[0] ?? "?"}`,
9414
9424
  releaseDesk: async () => void 0,
9415
9425
  startSession: (opts, cb) => {
9416
9426
  if (++sessionsStarted === USAGE_WARNING_AT && !scale) fakeUsageWarning(cb);
9417
- return inTerminal(opts, cb, (c) => opts.role === "ceo" ? ceoSession(opts, c) : fakeSession(opts, c, deskRepo.get(opts.cwd) ?? boxDeskRepo(opts.cwd) ?? [...repos.keys()][0]));
9427
+ let session;
9428
+ let finished = false;
9429
+ session = inTerminal(opts, {
9430
+ ...cb,
9431
+ finished: (result) => {
9432
+ finished = true;
9433
+ if (session) sessions.delete(session);
9434
+ cb.finished(result);
9435
+ }
9436
+ }, (c) => opts.role === "ceo" ? ceoSession(opts, c) : fakeSession(opts, c, deskRepo.get(opts.cwd) ?? boxDeskRepo(opts.cwd) ?? [...repos.keys()][0]));
9437
+ if (!finished) sessions.add(session);
9438
+ return session;
9418
9439
  },
9419
9440
  terminals: true,
9420
9441
  openCodeModels: async (directory) => ({ directory, defaultModel: "openai/demo-model", models: [
@@ -9424,7 +9445,10 @@ Closes #${pr.closesIssues[0] ?? "?"}`,
9424
9445
  reconnectClis: async () => [],
9425
9446
  // fake sessions end with the office
9426
9447
  hooksReady: () => void 0,
9427
- releaseClis: async () => void 0,
9448
+ releaseClis: async () => {
9449
+ for (const session of [...sessions]) session.stop();
9450
+ sessions.clear();
9451
+ },
9428
9452
  detectClis: async () => CLIS.map((c) => ({ id: c.id, label: c.label, installed: true, version: "demo", integrated: c.integrated })),
9429
9453
  previews: demoPreviews,
9430
9454
  office: demoOffice,
@@ -10448,32 +10472,6 @@ function recorded(last, e) {
10448
10472
  if (e.type === "repo") return repoPatch(JSON.parse(prev).repo, e.repo);
10449
10473
  return e;
10450
10474
  }
10451
- function remember2(last, e) {
10452
- const key = `${e.type === "agentPatch" ? "agent" : "repo"}:${e.id}`;
10453
- const prev = last.get(key);
10454
- if (!prev) return;
10455
- if (e.type === "agentPatch") last.set(key, JSON.stringify({ type: "agent", agent: { ...JSON.parse(prev).agent, ...e.set } }));
10456
- else last.set(key, JSON.stringify({ type: "repo", repo: applyRepoPatch(JSON.parse(prev).repo, e) }));
10457
- }
10458
- function compress(lines) {
10459
- let last = /* @__PURE__ */ new Map();
10460
- const out = [];
10461
- for (const l of lines) {
10462
- if (isFrame(l)) {
10463
- last = frameKeys(l.k);
10464
- out.push(l);
10465
- continue;
10466
- }
10467
- if (l.e.type === "agentPatch" || l.e.type === "repoPatch") {
10468
- remember2(last, l.e);
10469
- out.push(l);
10470
- continue;
10471
- }
10472
- const e = recorded(last, l.e);
10473
- if (e) out.push({ t: l.t, e });
10474
- }
10475
- return out;
10476
- }
10477
10475
  var LAB_DESK = 12;
10478
10476
  var LAB_STATIONS = 3;
10479
10477
  function legacyAgent(a) {
@@ -14371,6 +14369,7 @@ function activityOf(a) {
14371
14369
  }
14372
14370
  function sampleDay(base, midnight, rand = seeded(7)) {
14373
14371
  const lines = [];
14372
+ let last = /* @__PURE__ */ new Map();
14374
14373
  const clone = (x) => structuredClone(x);
14375
14374
  const between = (lo, hi) => lo + Math.floor(rand() * (hi - lo + 1));
14376
14375
  const pick2 = (xs) => xs[Math.floor(rand() * xs.length)];
@@ -14396,7 +14395,10 @@ function sampleDay(base, midnight, rand = seeded(7)) {
14396
14395
  let msgId = 9e5;
14397
14396
  let t = midnight + SAMPLE_FROM_MIN * MIN;
14398
14397
  const end = midnight + SAMPLE_TO_MIN * MIN;
14399
- const ev = (e) => lines.push({ t, e: clone(e) });
14398
+ const ev = (e) => {
14399
+ const change = recorded(last, e);
14400
+ if (change) lines.push({ t, e: clone(change) });
14401
+ };
14400
14402
  const repoById = (id) => repos2.find((r) => r.id === id);
14401
14403
  const emitAgent = (a) => {
14402
14404
  a.activity = activityOf(a);
@@ -14528,7 +14530,11 @@ function sampleDay(base, midnight, rand = seeded(7)) {
14528
14530
  ev({ type: "ceo", ceo });
14529
14531
  }
14530
14532
  for (; t < end; t += MIN) {
14531
- if ((t - (midnight + SAMPLE_FROM_MIN * MIN)) % KEYFRAME_MS === 0) lines.push(lines.length ? { t, k: frame() } : { t, k: frame(), boot: true });
14533
+ if ((t - (midnight + SAMPLE_FROM_MIN * MIN)) % KEYFRAME_MS === 0) {
14534
+ const k = frame();
14535
+ last = frameKeys(k);
14536
+ lines.push(lines.length ? { t, k } : { t, k, boot: true });
14537
+ }
14532
14538
  const minute = Math.round((t - midnight) / MIN);
14533
14539
  if (minute === SAMPLE_FROM_MIN + 5) say("ceo", `\u2600\uFE0F Good morning! ${repos2.reduce((n, r) => n + r.issues.length, 0)} issues on the board today. I'll keep the backlog topped up.`);
14534
14540
  if ([600, 690, 780, 870, 960].includes(minute)) {
@@ -14626,7 +14632,7 @@ function sampleDay(base, midnight, rand = seeded(7)) {
14626
14632
  });
14627
14633
  }
14628
14634
  }
14629
- return compress(lines);
14635
+ return lines;
14630
14636
  }
14631
14637
 
14632
14638
  // shared/careers.ts
@@ -15162,10 +15168,15 @@ var AgentTerminal = class {
15162
15168
  save(file) {
15163
15169
  const next = this.saving.then(async () => {
15164
15170
  this.dirty = false;
15165
- await this.flush();
15166
- await fs22.mkdir(path22.dirname(file), { recursive: true });
15167
- await fs22.writeFile(`${file}.tmp`, this.snapshot());
15168
- await fs22.rename(`${file}.tmp`, file);
15171
+ try {
15172
+ await this.flush();
15173
+ await fs22.mkdir(path22.dirname(file), { recursive: true });
15174
+ await fs22.writeFile(`${file}.tmp`, this.snapshot());
15175
+ await fs22.rename(`${file}.tmp`, file);
15176
+ } catch (error) {
15177
+ this.dirty = true;
15178
+ throw error;
15179
+ }
15169
15180
  });
15170
15181
  this.saving = next.catch(() => void 0);
15171
15182
  return next;
@@ -16413,8 +16424,12 @@ var Swarm = class {
16413
16424
  saveTimer = null;
16414
16425
  shutdownTask = null;
16415
16426
  stopping = false;
16427
+ backgroundIntervals = /* @__PURE__ */ new Set();
16428
+ backgroundTimeouts = /* @__PURE__ */ new Set();
16416
16429
  writing = Promise.resolve();
16417
16430
  // state file writes, one at a time: they share its temp file
16431
+ periodicStateWrite = null;
16432
+ stateChangedDuringWrite = false;
16418
16433
  terminalSaving = null;
16419
16434
  logSeq = 1;
16420
16435
  previews;
@@ -16454,6 +16469,21 @@ var Swarm = class {
16454
16469
  signIns = /* @__PURE__ */ new Map();
16455
16470
  toldStuck = /* @__PURE__ */ new Set();
16456
16471
  // ---------- lifecycle ----------
16472
+ backgroundInterval(run2, ms) {
16473
+ if (this.stopping) return;
16474
+ const timer = setInterval(() => {
16475
+ if (!this.stopping) run2();
16476
+ }, ms);
16477
+ this.backgroundIntervals.add(timer);
16478
+ }
16479
+ backgroundTimeout(run2, ms) {
16480
+ if (this.stopping) return;
16481
+ const timer = setTimeout(() => {
16482
+ this.backgroundTimeouts.delete(timer);
16483
+ if (!this.stopping) run2();
16484
+ }, ms);
16485
+ this.backgroundTimeouts.add(timer);
16486
+ }
16457
16487
  async init() {
16458
16488
  let legacyDefaults = false;
16459
16489
  try {
@@ -16646,25 +16676,25 @@ var Swarm = class {
16646
16676
  this.officeHead = await this.backend.office.head();
16647
16677
  const updated = await this.backend.office.takeLastUpdate().catch(() => null);
16648
16678
  if (updated) await this.reportUpdate(updated);
16649
- setInterval(() => this.state.repos.forEach((r, i) => setTimeout(() => void this.syncRepo(r.id), i * 1500)), SYNC_INTERVAL_MS);
16650
- setInterval(() => this.schedule(), SCHEDULER_INTERVAL_MS);
16651
- setInterval(() => this.previews.sweepPrs(), 15e3);
16652
- setInterval(() => void this.saveTerminals(), TERMINAL_SAVE_MS);
16653
- setInterval(() => {
16679
+ this.backgroundInterval(() => this.state.repos.forEach((r, i) => this.backgroundTimeout(() => void this.syncRepo(r.id), i * 1500)), SYNC_INTERVAL_MS);
16680
+ this.backgroundInterval(() => this.schedule(), SCHEDULER_INTERVAL_MS);
16681
+ this.backgroundInterval(() => this.previews.sweepPrs(), 15e3);
16682
+ this.backgroundInterval(() => void this.saveTerminals(), TERMINAL_SAVE_MS);
16683
+ this.backgroundInterval(() => {
16654
16684
  void this.trimIdleDesks();
16655
16685
  void this.voice.prune();
16656
16686
  void this.journal.prune().catch((err) => console.warn("could not prune the journal", err));
16657
16687
  }, this.backend.demo ? 6e4 : TRIM_SWEEP_MS);
16658
- setInterval(() => {
16659
- this.state.repos.forEach((r, i) => setTimeout(() => void this.sweepFloor(r.id), i * 1500));
16688
+ this.backgroundInterval(() => {
16689
+ this.state.repos.forEach((r, i) => this.backgroundTimeout(() => void this.sweepFloor(r.id), i * 1500));
16660
16690
  void this.sweepMachines();
16661
16691
  }, DESK_SWEEP_INTERVAL_MS);
16662
16692
  void this.sweepMachines();
16663
- setInterval(() => this.greet(), 6e4);
16664
- setTimeout(() => this.greet(), 5e3);
16665
- setInterval(() => this.emitOps(), OPS_TICK_MS);
16666
- setInterval(() => this.notifyStuck(), 6e4);
16667
- setInterval(() => this.watchdogTick(), WATCHDOG_MS);
16693
+ this.backgroundInterval(() => this.greet(), 6e4);
16694
+ this.backgroundTimeout(() => this.greet(), 5e3);
16695
+ this.backgroundInterval(() => this.emitOps(), OPS_TICK_MS);
16696
+ this.backgroundInterval(() => this.notifyStuck(), 6e4);
16697
+ this.backgroundInterval(() => this.watchdogTick(), WATCHDOG_MS);
16668
16698
  void this.backend.detectClis().then((clis) => {
16669
16699
  this.clis = clis;
16670
16700
  this.broadcast({ type: "clis", clis });
@@ -16679,7 +16709,7 @@ var Swarm = class {
16679
16709
  }),
16680
16710
  this.state.repos.map((r) => this.repoView(r))
16681
16711
  );
16682
- setTimeout(() => this.schedule(), 1e3);
16712
+ this.backgroundTimeout(() => this.schedule(), 1e3);
16683
16713
  }
16684
16714
  /**
16685
16715
  * Startup reconciliation (reconcile.ts), before anything is reattached or scheduled: GitHub is asked about every task
@@ -17025,8 +17055,27 @@ var Swarm = class {
17025
17055
  }
17026
17056
  // ---------- persistence ----------
17027
17057
  save() {
17028
- if (this.stopping || this.saveTimer) return;
17029
- this.saveTimer = setTimeout(() => void this.writeState().catch((err) => console.warn("could not save the state", err)), 1500);
17058
+ if (this.stopping) return;
17059
+ if (this.periodicStateWrite) {
17060
+ this.stateChangedDuringWrite = true;
17061
+ return;
17062
+ }
17063
+ if (this.saveTimer) return;
17064
+ this.saveTimer = setTimeout(() => {
17065
+ const pending2 = this.writeState();
17066
+ this.periodicStateWrite = pending2;
17067
+ const settled = () => {
17068
+ this.periodicStateWrite = null;
17069
+ if (this.stateChangedDuringWrite) {
17070
+ this.stateChangedDuringWrite = false;
17071
+ this.save();
17072
+ }
17073
+ };
17074
+ void pending2.then(settled, (err) => {
17075
+ console.warn("could not save the state", err);
17076
+ settled();
17077
+ });
17078
+ }, 1500);
17030
17079
  }
17031
17080
  /** Write the state file now, e.g. before the office stops or hands itself to the launcher. Waits for a write in progress. */
17032
17081
  writeState() {
@@ -17748,6 +17797,10 @@ var Swarm = class {
17748
17797
  shutdown(restart = false) {
17749
17798
  if (this.shutdownTask) return this.shutdownTask;
17750
17799
  this.stopping = true;
17800
+ for (const timer of this.backgroundIntervals) clearInterval(timer);
17801
+ for (const timer of this.backgroundTimeouts) clearTimeout(timer);
17802
+ this.backgroundIntervals.clear();
17803
+ this.backgroundTimeouts.clear();
17751
17804
  this.shutdownTask = this.finishShutdown(restart);
17752
17805
  return this.shutdownTask;
17753
17806
  }
@@ -18855,6 +18908,7 @@ var Swarm = class {
18855
18908
  let next = 0;
18856
18909
  await Promise.all(Array.from({ length: Math.min(8, pending2.length) }, async () => {
18857
18910
  while (next < pending2.length) {
18911
+ if (!all && this.stopping) break;
18858
18912
  const { id, terminal } = pending2[next++];
18859
18913
  await terminal.save(terminalFile(id)).catch((err) => console.warn("could not save a terminal", err));
18860
18914
  }