home-hosted 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -4,7 +4,7 @@ import { defineCommand, runCommand } from "citty";
4
4
  import path from "node:path";
5
5
  import readline from "node:readline";
6
6
  import fs, { createReadStream } from "node:fs";
7
- import { exec, execFile, execFileSync, spawn, spawnSync } from "node:child_process";
7
+ import cp, { exec, execFile, execFileSync, spawn, spawnSync } from "node:child_process";
8
8
  import { Buffer as Buffer$1 } from "node:buffer";
9
9
  import os from "node:os";
10
10
  import { describeRoute, openAPIRouteHandler, resolver, validator } from "hono-openapi";
@@ -217,11 +217,17 @@ function findArg(argsDef, name) {
217
217
  * with the wrong policy. This keeps the refusal the command line always had, from
218
218
  * citty's own definitions rather than a second list.
219
219
  *
220
- * A command that declares no arguments parses its own argv (and rejects its own
221
- * unknown flags), so it is left alone. Returns the message to print, or null.
220
+ * `undefined` means the command parses its own argv — `ui-switch` calls `node:util`'s
221
+ * `parseArgs` with its own options, which is strict already — so it is left alone. An
222
+ * **empty** definition is different: it declares that this command takes nothing, so
223
+ * every flag and every bare word is refused here. Reading `{}` as "parses its own argv"
224
+ * is what let `ui-revert`, which has no parser at all, accept and discard anything:
225
+ * `ui-revert --dry-run` deleted the installed UI and exited 0.
226
+ *
227
+ * Returns the message to print, or null.
222
228
  */
223
229
  function rejectUnknownFlags(argv, argsDef) {
224
- if (argsDef === void 0 || Object.keys(argsDef).length === 0) return null;
230
+ if (argsDef === void 0) return null;
225
231
  let positionals = Object.values(argsDef).filter((def) => def?.type === "positional").length;
226
232
  for (let index = 0; index < argv.length; index++) {
227
233
  const token = argv[index];
@@ -742,6 +748,100 @@ function secureCookieFor(mode, protocol) {
742
748
  }
743
749
  var init_cookies = __esmMin((() => {}));
744
750
  //#endregion
751
+ //#region src/shared/host-readings.ts
752
+ /** A number the frame carries, or null when it carries none. */
753
+ function present(value) {
754
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
755
+ }
756
+ /**
757
+ * How a per-cpu load sits against the threshold the panel notifies on.
758
+ *
759
+ * The ratio is what a person configures: `host.loadPerCpu` is the count the alert fires at, so
760
+ * `danger` is that number itself and `warn` is the approach to it. `0` disables the alert in
761
+ * `sampleHost`, so nothing can breach it and the band is `ok` — painting a box red for a
762
+ * notification that will never arrive is the same defect as inventing a reading. It lives here
763
+ * rather than in a component so both UIs share one band, the mistake that produced two hardcoded
764
+ * copies of the default.
765
+ */
766
+ function loadBand(loadPerCpu, alertPerCpu) {
767
+ return thresholdBand(loadPerCpu, alertPerCpu, 2);
768
+ }
769
+ /**
770
+ * How a reading sits against the threshold the panel notifies on.
771
+ *
772
+ * `danger` at the threshold is the whole point: the alert fires there, so a bar that stays `warn`
773
+ * while a notification goes out disagrees with the panel's own verdict. `0` disables that alert in
774
+ * `sampleHost`, so nothing can breach it and the band is `ok`. One rule for the per-cpu load, the
775
+ * three percentages and each disk — they differ only in what the number means, and the mistake this
776
+ * replaced was four surfaces each deciding a band for itself.
777
+ */
778
+ function percentageBand(value, alertAt, fallback) {
779
+ return thresholdBand(value, alertAt, fallback);
780
+ }
781
+ function thresholdBand(value, alertAt, fallback) {
782
+ if (value === null || !Number.isFinite(value)) return null;
783
+ const threshold = alertAt === void 0 || !Number.isFinite(alertAt) ? fallback : alertAt;
784
+ if (threshold <= 0) return "ok";
785
+ if (value >= threshold) return "danger";
786
+ if (value >= threshold * .7) return "warn";
787
+ return "ok";
788
+ }
789
+ /** The readings of one host frame; a missing frame is the same as an unsampled one. */
790
+ function hostReadings(host) {
791
+ if (host === null || host === void 0) return NOTHING_SAMPLED;
792
+ if (!(host.sampledAt !== null)) return {
793
+ ...NOTHING_SAMPLED,
794
+ disks: []
795
+ };
796
+ const load1m = present(host.loadAvg[0]);
797
+ const cpus = present(host.cpus);
798
+ const loadPerCpu = load1m === null ? null : load1m / Math.max(1, cpus ?? 1);
799
+ return {
800
+ sampled: true,
801
+ cpuUsedPercent: present(host.cpuUsedPercent),
802
+ memoryUsedPercent: present(host.memoryUsedPercent),
803
+ swapUsedPercent: present(host.swapUsedPercent),
804
+ load1m,
805
+ load5m: present(host.loadAvg[1]),
806
+ load15m: present(host.loadAvg[2]),
807
+ loadPerCpu,
808
+ loadBand: loadBand(loadPerCpu, host.loadAlertPerCpu),
809
+ memoryBand: percentageBand(present(host.memoryUsedPercent), host.memoryUsedPercentAlert, HOST_ALERT_DEFAULTS.memoryUsedPercent),
810
+ swapBand: percentageBand(present(host.swapUsedPercent), host.swapUsedPercentAlert, HOST_ALERT_DEFAULTS.swapUsedPercent),
811
+ tempBand: percentageBand(present(host.tempCelsius), host.tempCelsiusAlert, HOST_ALERT_DEFAULTS.tempCelsius),
812
+ tempCelsius: present(host.tempCelsius),
813
+ disks: host.disks.map((disk) => ({
814
+ ...disk,
815
+ band: percentageBand(present(disk.usedPercent), host.diskUsedPercentAlert, HOST_ALERT_DEFAULTS.diskUsedPercent)
816
+ }))
817
+ };
818
+ }
819
+ var HOST_ALERT_DEFAULTS, NOTHING_SAMPLED;
820
+ var init_host_readings = __esmMin((() => {
821
+ HOST_ALERT_DEFAULTS = {
822
+ diskUsedPercent: 90,
823
+ memoryUsedPercent: 90,
824
+ swapUsedPercent: 50,
825
+ tempCelsius: 85
826
+ };
827
+ NOTHING_SAMPLED = {
828
+ sampled: false,
829
+ cpuUsedPercent: null,
830
+ memoryUsedPercent: null,
831
+ swapUsedPercent: null,
832
+ load1m: null,
833
+ load5m: null,
834
+ load15m: null,
835
+ loadPerCpu: null,
836
+ tempCelsius: null,
837
+ disks: [],
838
+ loadBand: null,
839
+ memoryBand: null,
840
+ swapBand: null,
841
+ tempBand: null
842
+ };
843
+ }));
844
+ //#endregion
745
845
  //#region src/shared/contracts.ts
746
846
  var contracts_exports = /* @__PURE__ */ __exportAll({
747
847
  actionResultSchema: () => actionResultSchema,
@@ -755,15 +855,21 @@ var contracts_exports = /* @__PURE__ */ __exportAll({
755
855
  backupFileSchema: () => backupFileSchema,
756
856
  backupFilesResponseSchema: () => backupFilesResponseSchema,
757
857
  backupHookOrNullSchema: () => backupHookOrNullSchema,
858
+ backupHookPatchOrNullSchema: () => backupHookPatchOrNullSchema,
859
+ backupHookPatchSchema: () => backupHookPatchSchema,
758
860
  backupHookSchema: () => backupHookSchema,
759
861
  backupScheduleSchema: () => backupScheduleSchema,
760
862
  backupScheduleViewSchema: () => backupScheduleViewSchema,
761
863
  backupScopeSchema: () => backupScopeSchema,
864
+ backupSelectionSchema: () => backupSelectionSchema,
762
865
  backupsSchema: () => backupsSchema,
763
866
  backupsViewSchema: () => backupsViewSchema,
764
867
  bindSchema: () => bindSchema,
765
868
  bootstrapOrNullSchema: () => bootstrapOrNullSchema,
869
+ bootstrapPatchOrNullSchema: () => bootstrapPatchOrNullSchema,
870
+ bootstrapPatchSchema: () => bootstrapPatchSchema,
766
871
  bootstrapSchema: () => bootstrapSchema,
872
+ bufferedLogsResponseSchema: () => bufferedLogsResponseSchema,
767
873
  controlSchema: () => controlSchema,
768
874
  controlViewSchema: () => controlViewSchema,
769
875
  ddnsAccountSchema: () => ddnsAccountSchema,
@@ -910,8 +1016,9 @@ function duplicateWebhookIds(targets) {
910
1016
  }
911
1017
  return [...duplicates];
912
1018
  }
913
- var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, backupHookSchema, backupHookOrNullSchema, labelOrNullSchema, logBufferLinesSchema, serverSchema, authSchema, notificationPolicyShape, notificationDefaultsSchema, notificationDefaultsViewSchema, useOwnSettingsSchema, telegramDestinationSchema, webhookTargetSchema, notificationTargetSchema, destinationListSchema, notificationsSchema, logsSchema, tlsSchema, hostSchema, ddnsRecordTypeSchema, ddnsAccountSchema, ddnsDomainSchema, ddnsIpv4Schema, ddnsIpv6Schema, ddnsConfigSchema, ddnsRecordStateSchema, ddnsRecordViewSchema, ddnsStatusSchema, ddnsProviderFieldSchema, ddnsProviderInfoSchema, ddnsViewSchema, ddnsCredentialsSchema, ddnsPatchSchema, backupScopeSchema, backupScheduleSchema, backupsSchema, controlSchema, defaultsSchema, restartPatchSchema, httpCheckPatchSchema, resourcesPatchSchema, healthPatchSchema, stopPatchSchema, authPatchSchema, notificationPolicyPatchShape, destinationPatchSchema, notificationsPatchSchema, hostPatchSchema, backupSchedulePatchSchema, backupsPatchSchema, logsPatchSchema, tlsPatchSchema, controlPatchSchema, defaultsPatchSchema, editableFields, serverPatchSchema, serverCreateSchema, nannySpecSchema, nannyExitSchema, nannyStateSchema, entryStateSchema, settingsPatchSchema, workspaceSettingsPatchSchema, authStatusSchema, tlsStatusSchema, proxyEngineSchema, proxyTargetSchema, proxyTlsModeSchema, proxyRouteSchema, proxyCertificateSchema, proxyCertificateStateSchema, proxyDns01Schema, proxyConfigSchema, proxyEngineSourceSchema, proxyEngineStatusSchema, proxyEngineInfoSchema, proxyRouteStatusSchema, proxyRouteViewSchema, proxyRunStateSchema, proxyStatusSchema, proxyCertificateViewSchema, proxyDnsAccountViewSchema, proxyViewSchema, proxyRoutePatchSchema, proxyPatchSchema, proxyCertificateUploadSchema, proxyEngineInstallSchema, notificationPolicyStatusShape, destinationStatusSchema, telegramChatsSchema, notificationViewSchema, sessionViewSchema, loginSchema, passwordValueSchema, passwordSchema, serverStatusSchema, healthStateSchema, portStateSchema, logStreamSchema, logLineSchema, historyActorSchema, historyEventSchema, serverHistorySchema, processResourcesSchema, hostDiskSchema, hostViewSchema, wslTemperatureSchema, backupFileSchema, backupEntrySchema, backupScheduleViewSchema, backupsViewSchema, restoreItemSchema, restoreSkipSchema, restorePlanSchema, backupCreateSchema, restoreRequestSchema, serverViewSchema, healthResponseSchema, controlViewSchema, uiMetaSchema, uiStatusSchema, serverOrphanSchema, workspaceViewSchema, appStateSchema, sseMessageSchema, logQuerySchema, actionResultSchema, deliveryResultSchema, passwordSetResponseSchema, tlsReviewResponseSchema, okResponseSchema, backupFilesResponseSchema, uiInstallResponseSchema, backupCreatedResponseSchema, logLinesResponseSchema, freePortResultSchema, logHistoryQuerySchema, logFileInfoSchema, logServerViewSchema, logServersViewSchema, logHistoryViewSchema, notificationActionSchema, destinationIdParamSchema, destinationTestSchema, telegramTokenSchema, apiErrorSchema, tlsUploadSchema, settingsViewSchema, settingsSavedSchema, workspaceSettingsViewSchema, workspaceSettingsSavedSchema;
1019
+ var bindSchema, workspaceIdSchema, workspaceSchema, workspaceCreateSchema, workspaceRenameSchema, portSchema, onPortConflictSchema, onPortConflictDefaultSchema, restartSchema, httpCheckSchema, resourcesSchema, healthSchema, stopSchema, bootstrapSchema, bootstrapOrNullSchema, bootstrapPatchSchema, bootstrapPatchOrNullSchema, backupHookSchema, backupHookOrNullSchema, backupHookPatchSchema, backupHookPatchOrNullSchema, labelOrNullSchema, logBufferLinesSchema, serverSchema, authSchema, notificationPolicyShape, notificationDefaultsSchema, notificationDefaultsViewSchema, useOwnSettingsSchema, telegramDestinationSchema, webhookTargetSchema, notificationTargetSchema, destinationListSchema, notificationsSchema, logsSchema, tlsSchema, hostSchema, ddnsRecordTypeSchema, ddnsAccountSchema, ddnsDomainSchema, ddnsIpv4Schema, ddnsIpv6Schema, ddnsConfigSchema, ddnsRecordStateSchema, ddnsRecordViewSchema, ddnsStatusSchema, ddnsProviderFieldSchema, ddnsProviderInfoSchema, ddnsViewSchema, ddnsCredentialsSchema, ddnsPatchSchema, backupScopeSchema, backupScheduleSchema, backupsSchema, controlSchema, defaultsSchema, restartPatchSchema, httpCheckPatchSchema, resourcesPatchSchema, healthPatchSchema, stopPatchSchema, authPatchSchema, notificationPolicyPatchShape, destinationPatchSchema, notificationsPatchSchema, hostPatchSchema, backupSchedulePatchSchema, backupsPatchSchema, logsPatchSchema, tlsPatchSchema, controlPatchSchema, defaultsPatchSchema, editableFields, serverPatchSchema, serverCreateSchema, nannySpecSchema, nannyExitSchema, nannyStateSchema, entryStateSchema, settingsPatchSchema, workspaceSettingsPatchSchema, authStatusSchema, tlsStatusSchema, proxyEngineSchema, proxyTargetSchema, proxyTlsModeSchema, proxyRouteSchema, proxyCertificateSchema, proxyCertificateStateSchema, proxyDns01Schema, proxyConfigSchema, proxyEngineSourceSchema, proxyEngineStatusSchema, proxyEngineInfoSchema, proxyRouteStatusSchema, proxyRouteViewSchema, proxyRunStateSchema, proxyStatusSchema, proxyCertificateViewSchema, proxyDnsAccountViewSchema, proxyViewSchema, proxyRoutePatchSchema, proxyPatchSchema, proxyCertificateUploadSchema, proxyEngineInstallSchema, notificationPolicyStatusShape, destinationStatusSchema, telegramChatsSchema, notificationViewSchema, sessionViewSchema, loginSchema, passwordValueSchema, passwordSchema, serverStatusSchema, healthStateSchema, portStateSchema, logStreamSchema, logLineSchema, historyActorSchema, historyEventSchema, serverHistorySchema, processResourcesSchema, hostDiskSchema, hostViewSchema, wslTemperatureSchema, backupFileSchema, backupEntrySchema, backupScheduleViewSchema, backupsViewSchema, backupSelectionSchema, restoreItemSchema, restoreSkipSchema, restorePlanSchema, backupCreateSchema, restoreRequestSchema, serverViewSchema, healthResponseSchema, controlViewSchema, uiMetaSchema, uiStatusSchema, serverOrphanSchema, workspaceViewSchema, appStateSchema, sseMessageSchema, logQuerySchema, actionResultSchema, deliveryResultSchema, passwordSetResponseSchema, tlsReviewResponseSchema, okResponseSchema, backupFilesResponseSchema, uiInstallResponseSchema, backupCreatedResponseSchema, bufferedLogsResponseSchema, logLinesResponseSchema, freePortResultSchema, logHistoryQuerySchema, logFileInfoSchema, logServerViewSchema, logServersViewSchema, logHistoryViewSchema, notificationActionSchema, destinationIdParamSchema, destinationTestSchema, telegramTokenSchema, apiErrorSchema, tlsUploadSchema, settingsViewSchema, settingsSavedSchema, workspaceSettingsViewSchema, workspaceSettingsSavedSchema;
914
1020
  var init_contracts = __esmMin((() => {
1021
+ init_host_readings();
915
1022
  bindSchema = type("\"local\" | \"lan\" | /^\\d{1,3}(?:\\.\\d{1,3}){3}$/");
916
1023
  workspaceIdSchema = type("/^[a-z0-9][a-z0-9_-]*$/");
917
1024
  workspaceSchema = type({
@@ -982,6 +1089,14 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
982
1089
  runOnce: "boolean = true"
983
1090
  }).onUndeclaredKey("reject");
984
1091
  bootstrapOrNullSchema = bootstrapSchema.or(type("null"));
1092
+ bootstrapPatchSchema = type({
1093
+ command: "string >= 1?",
1094
+ args: "string[]?",
1095
+ env: "Record<string, string>?",
1096
+ timeoutMs: "number >= 1000?",
1097
+ runOnce: "boolean?"
1098
+ }).onUndeclaredKey("reject");
1099
+ bootstrapPatchOrNullSchema = bootstrapPatchSchema.or(type("null"));
985
1100
  backupHookSchema = type({
986
1101
  command: "string >= 1",
987
1102
  args: type("string[]").default(() => []),
@@ -998,6 +1113,14 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
998
1113
  waitMs: "number >= 0 = 2000"
999
1114
  }).onUndeclaredKey("reject");
1000
1115
  backupHookOrNullSchema = backupHookSchema.or(type("null"));
1116
+ backupHookPatchSchema = type({
1117
+ command: "string >= 1?",
1118
+ args: "string[]?",
1119
+ env: "Record<string, string>?",
1120
+ timeoutMs: "number >= 1000?",
1121
+ waitMs: "number >= 0?"
1122
+ }).onUndeclaredKey("reject");
1123
+ backupHookPatchOrNullSchema = backupHookPatchSchema.or(type("null"));
1001
1124
  labelOrNullSchema = type("string | null");
1002
1125
  logBufferLinesSchema = type("50 <= number.integer <= 100000");
1003
1126
  serverSchema = type({
@@ -1124,12 +1247,20 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1124
1247
  intervalMs: "number >= 5000 = 15000",
1125
1248
  /** Filesystems reported and alerted on; templates and `~` are expanded. */
1126
1249
  diskPaths: type("string[]").default(() => ["."]),
1127
- /** 0 disables an individual alert. */
1128
- diskUsedPercent: "number >= 0 = 90",
1129
- memoryUsedPercent: "number >= 0 = 90",
1130
- swapUsedPercent: "number >= 0 = 50",
1131
- loadPerCpu: "number >= 0 = 2",
1132
- tempCelsius: "number >= 0 = 85",
1250
+ /**
1251
+ * 0 disables an individual alert. Each default is written from `HOST_ALERT_DEFAULTS`, so the
1252
+ * number a fresh config gets and the number a surface bands against when a frame carries no
1253
+ * threshold are one value — the same one-home rule `loadPerCpu` follows below.
1254
+ */
1255
+ diskUsedPercent: `number >= 0 = ${HOST_ALERT_DEFAULTS.diskUsedPercent}`,
1256
+ memoryUsedPercent: `number >= 0 = ${HOST_ALERT_DEFAULTS.memoryUsedPercent}`,
1257
+ swapUsedPercent: `number >= 0 = ${HOST_ALERT_DEFAULTS.swapUsedPercent}`,
1258
+ /**
1259
+ * The per-cpu load the panel notifies on. One home: the frame's `loadAlertPerCpu` is this value,
1260
+ * and `loadBand` reads it, so a surface cannot band the load against a number nobody configured.
1261
+ */
1262
+ loadPerCpu: type("number >= 0").default(2),
1263
+ tempCelsius: `number >= 0 = ${HOST_ALERT_DEFAULTS.tempCelsius}`,
1133
1264
  /**
1134
1265
  * How to read the CPU temperature when the kernel exposes no sensor.
1135
1266
  *
@@ -1227,7 +1358,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1227
1358
  providers: ddnsProviderInfoSchema.array(),
1228
1359
  /** Account ids whose credentials are stored. */
1229
1360
  credentials: type("string[]")
1230
- });
1361
+ }).onDeepUndeclaredKey("ignore");
1231
1362
  ddnsCredentialsSchema = type({
1232
1363
  provider: "string >= 1",
1233
1364
  credentials: type("Record<string, string>")
@@ -1441,9 +1572,9 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1441
1572
  cwd: "string?",
1442
1573
  env: "Record<string, string>?",
1443
1574
  dataEnvs: "Record<string, string>?",
1444
- bootstrap: bootstrapOrNullSchema.optional(),
1445
- dump: backupHookOrNullSchema.optional(),
1446
- load: backupHookOrNullSchema.optional(),
1575
+ bootstrap: bootstrapPatchOrNullSchema.optional(),
1576
+ dump: backupHookPatchOrNullSchema.optional(),
1577
+ load: backupHookPatchOrNullSchema.optional(),
1447
1578
  port: portSchema.optional(),
1448
1579
  bind: bindSchema.optional(),
1449
1580
  onPortConflict: onPortConflictSchema.optional(),
@@ -1655,7 +1786,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1655
1786
  */
1656
1787
  "retryInMinutes?": "number"
1657
1788
  })
1658
- });
1789
+ }).onDeepUndeclaredKey("ignore");
1659
1790
  proxyRunStateSchema = type.enumerated("off", "stopped", "starting", "running", "error", "unsupported");
1660
1791
  proxyStatusSchema = type({
1661
1792
  state: proxyRunStateSchema,
@@ -1702,7 +1833,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1702
1833
  "certificates": proxyCertificateViewSchema.array(),
1703
1834
  /** Every DNS account a route may name. Optional: an older panel omits it. */
1704
1835
  "dnsAccounts?": proxyDnsAccountViewSchema.array()
1705
- });
1836
+ }).onDeepUndeclaredKey("ignore");
1706
1837
  proxyRoutePatchSchema = type({
1707
1838
  id: "string",
1708
1839
  host: "string",
@@ -1860,7 +1991,38 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1860
1991
  "disks": hostDiskSchema.array(),
1861
1992
  /** Human readable threshold breaches, for the banner and notifications. */
1862
1993
  "alerts": type("string[]"),
1863
- "sampledAt": "number | null"
1994
+ "sampledAt": "number | null",
1995
+ /**
1996
+ * The per-cpu load this panel notifies on — `host.loadPerCpu`, the number the alert fires at.
1997
+ *
1998
+ * Optional: a panel that predates this field alerts on the default, which is what the UI's band
1999
+ * assumes when the field is absent. It travels here because the frame is the only thing a host
2000
+ * surface reads, and a surface that cannot see the threshold hardcoded `2`/`1.4` — so raising
2001
+ * the threshold in Settings left the tile painting a healthy box `danger` while the alert the
2002
+ * threshold governs stayed silent. `0` disables the alert, so nothing can breach it.
2003
+ */
2004
+ "loadAlertPerCpu?": "number",
2005
+ /**
2006
+ * The percentage alert thresholds — `host.diskUsedPercent`, `host.memoryUsedPercent`,
2007
+ * `host.swapUsedPercent` and `host.tempCelsius` — the numbers the panel notifies at.
2008
+ *
2009
+ * Optional for the same reason as `loadAlertPerCpu`, and carried for the same reason: a surface
2010
+ * that cannot see the threshold has to invent one, and the invented ones disagreed with the
2011
+ * panel's verdict. The swap bar called 50% `warn` while the alert fired there; raising
2012
+ * `host.tempCelsius` to 95 left a 90 °C box painted `danger` for a notification that never
2013
+ * arrives; and a disk threshold lowered to 80 notified at 82% while every disk bar called it
2014
+ * `warn`. `0` disables that alert, so nothing can breach it.
2015
+ */
2016
+ "memoryUsedPercentAlert?": "number",
2017
+ "swapUsedPercentAlert?": "number",
2018
+ "tempCelsiusAlert?": "number",
2019
+ /**
2020
+ * `host.diskUsedPercent`, the threshold a filesystem is banded against.
2021
+ *
2022
+ * It travels once for the frame rather than per disk: the threshold is one config value that
2023
+ * applies to every configured path, which is why `hostReadings` copies it onto each disk's `band`.
2024
+ */
2025
+ "diskUsedPercentAlert?": "number"
1864
2026
  });
1865
2027
  wslTemperatureSchema = type({
1866
2028
  /** This process runs under WSL. */
@@ -1880,7 +2042,14 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1880
2042
  /** The last probe's reading, so the page can say "this works" without running it again. */
1881
2043
  "lastReadingCelsius?": "number | null",
1882
2044
  /** Why the last probe failed, if it did — a missing library and no sensor read differently. */
1883
- "lastError?": "string | null"
2045
+ "lastError?": "string | null",
2046
+ /**
2047
+ * The library is missing and installing it needs consent.
2048
+ *
2049
+ * The panel will not download a third-party binary on a click that did not mention one, so the
2050
+ * first press answers `needsDownload` and the page asks. Absent on an older panel.
2051
+ */
2052
+ "needsDownload?": "boolean"
1884
2053
  });
1885
2054
  backupFileSchema = type({
1886
2055
  name: "string",
@@ -1954,9 +2123,24 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
1954
2123
  }),
1955
2124
  /** Extra paths from the global config, in addition to each server's own. */
1956
2125
  "includePaths": type("string[]"),
2126
+ /**
2127
+ * The selection model, carried here only by a panel older than this release.
2128
+ *
2129
+ * Reading it costs a `readFileSync` of the global and every workspace's `.secrets.json` plus a
2130
+ * `statSync` per archive, and the state frame is rebuilt ~13×/s — so it moved to
2131
+ * `GET /api/backups` (`backupSelectionSchema`), which a dialog fetches when it opens. Optional on
2132
+ * purpose: a newer UI reads a panel that still sends it, and a UI must never reject a payload for
2133
+ * a field it does not use. Absent means "ask the endpoint".
2134
+ */
2135
+ "entries?": backupEntrySchema.array(),
2136
+ "files?": backupFileSchema.array()
2137
+ });
2138
+ backupSelectionSchema = type({
2139
+ /** The archive directory, so a dialog can print the path without a second read. */
2140
+ dir: "string",
1957
2141
  /** Every selectable entry, global first, then each workspace. */
1958
- "entries": backupEntrySchema.array(),
1959
- "files": backupFileSchema.array()
2142
+ entries: backupEntrySchema.array(),
2143
+ files: backupFileSchema.array()
1960
2144
  });
1961
2145
  restoreItemSchema = type({
1962
2146
  /** A backup entry or leaf id (`workspace:<id>:servers`, `data:<path>`, ...). */
@@ -2110,7 +2294,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
2110
2294
  /** Last health probe latency (TCP connect or HTTP request). */
2111
2295
  "responseMs": "number | null",
2112
2296
  "resources": processResourcesSchema.or(type("null"))
2113
- });
2297
+ }).onDeepUndeclaredKey("ignore");
2114
2298
  healthResponseSchema = type({
2115
2299
  "status": "\"ok\" | \"degraded\"",
2116
2300
  "uptimeMs": "number",
@@ -2199,7 +2383,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
2199
2383
  */
2200
2384
  "orphans?": serverOrphanSchema.array(),
2201
2385
  "servers": serverViewSchema.array()
2202
- });
2386
+ }).onDeepUndeclaredKey("ignore");
2203
2387
  appStateSchema = type({
2204
2388
  "control": controlViewSchema,
2205
2389
  "host": hostViewSchema,
@@ -2214,7 +2398,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
2214
2398
  "dataRoot": "string",
2215
2399
  /** The release this panel is running. Optional: an older panel does not send one. */
2216
2400
  "version?": "string"
2217
- });
2401
+ }).onDeepUndeclaredKey("ignore");
2218
2402
  sseMessageSchema = type({
2219
2403
  "type": "\"hello\" | \"state\" | \"log\" | \"server\"",
2220
2404
  "ts": "number",
@@ -2223,7 +2407,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
2223
2407
  "state": appStateSchema.optional(),
2224
2408
  "server": serverViewSchema.optional(),
2225
2409
  "lines": logLineSchema.array().optional()
2226
- });
2410
+ }).onDeepUndeclaredKey("ignore");
2227
2411
  logQuerySchema = type({ limit: "string?" });
2228
2412
  actionResultSchema = type({
2229
2413
  "ok": "boolean",
@@ -2260,14 +2444,15 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
2260
2444
  file: backupFileSchema,
2261
2445
  files: backupFileSchema.array()
2262
2446
  });
2447
+ bufferedLogsResponseSchema = type({ lines: logLineSchema.array() });
2263
2448
  logLinesResponseSchema = type({
2264
2449
  serverId: "string",
2265
2450
  enabled: "boolean",
2266
2451
  sizeBytes: "number",
2267
2452
  /** The rotated files this entry has, newest first. */
2268
2453
  files: "string[]",
2269
- /** The whole search window, or null when the request carried no `search`. */
2270
- searched: logLineSchema.array().or(type("null")),
2454
+ /** How many lines the search looked at, or null when the request carried no `search`. */
2455
+ searched: "number | null",
2271
2456
  lines: logLineSchema.array()
2272
2457
  });
2273
2458
  freePortResultSchema = type({
@@ -2345,7 +2530,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
2345
2530
  host: hostSchema,
2346
2531
  backups: backupsViewSchema,
2347
2532
  ui: uiStatusSchema
2348
- });
2533
+ }).onDeepUndeclaredKey("ignore");
2349
2534
  settingsSavedSchema = settingsViewSchema.and(type({
2350
2535
  /** The listener is moving; reconnect at `targetUrl` when it stops being null. */
2351
2536
  rebinding: "boolean",
@@ -2360,7 +2545,7 @@ maxRssBytes: "number.integer >= 0 = 0" }).onUndeclaredKey("reject");
2360
2545
  defaults: defaultsSchema,
2361
2546
  logs: logsSchema,
2362
2547
  notifications: notificationViewSchema
2363
- });
2548
+ }).onDeepUndeclaredKey("ignore");
2364
2549
  workspaceSettingsSavedSchema = workspaceSettingsViewSchema;
2365
2550
  }));
2366
2551
  //#endregion
@@ -2445,17 +2630,18 @@ var init_atomic = __esmMin((() => {}));
2445
2630
  /**
2446
2631
  * Decodes a hand-editable state file the way the editors that write them save it.
2447
2632
  *
2448
- * Every file the panel invites a person to hand-edit is JSON, and `JSON.parse` refuses a
2449
- * **byte-order mark**: PowerShell's `Set-Content -Encoding UTF8` (5.1) and `Out-File`/`>`
2450
- * (UTF-16LE) both prepend one, and Notepad writes one for a "UTF-8 with BOM" save. The
2451
- * refusal is a parse error naming an invisible character — `Unexpected token '\uFEFF'` — so the
2452
- * person is told their JSON is broken when it is not, and is invited to
2453
- * fix a file the editor will re-encode identically on the next save.
2633
+ * A file the panel invites a person to hand-edit arrives the way their editor saved it, and the
2634
+ * editors that write one on Windows prepend a **byte-order mark**: PowerShell's
2635
+ * `Set-Content -Encoding UTF8` (5.1) and `Out-File`/`>` (UTF-16LE) both do, and Notepad writes one
2636
+ * for a "UTF-8 with BOM" save. For JSON the refusal is a parse error naming an invisible character
2637
+ * — `Unexpected token '\uFEFF'` — so the person is told their JSON is broken when it is not. For a
2638
+ * `KEY=value` file it is quieter: every key carries a NUL and is dropped, so the process starts
2639
+ * without the secrets the file exists to hold.
2454
2640
  *
2455
2641
  * Stripping the mark is not a silent coercion: a BOM is not content, and a file whose real
2456
2642
  * content is unchanged parses to the same object with or without it. UTF-16 is decoded rather
2457
- * than refused because that is what `>` produces on Windows, and it is recognisable from its
2458
- * own prefix — a wrong guess would still fail loudly on `JSON.parse`.
2643
+ * than refused because that is what `>` produces on Windows, and it is recognisable from its own
2644
+ * prefix — a file in neither encoding still fails loudly in the reader above.
2459
2645
  *
2460
2646
  * Read as a `Buffer`, never with `'utf8'`: a `'utf8'` read of UTF-16LE text has already lost
2461
2647
  * the information this needs to tell them apart.
@@ -3658,212 +3844,6 @@ function parseOrThrow(schema, input, label) {
3658
3844
  }
3659
3845
  var init_validate = __esmMin((() => {}));
3660
3846
  //#endregion
3661
- //#region src/helpers/paths.ts
3662
- var paths_exports = /* @__PURE__ */ __exportAll({
3663
- DEFAULT_WORKSPACE_ID: () => DEFAULT_WORKSPACE_ID,
3664
- daemonLogPath: () => daemonLogPath,
3665
- dataRoot: () => dataRoot,
3666
- globalSecretsPath: () => globalSecretsPath,
3667
- globalSettingsPath: () => globalSettingsPath,
3668
- hasLegacyLayout: () => hasLegacyLayout,
3669
- hhDir: () => hhDir,
3670
- legacy: () => legacy,
3671
- projectDir: () => projectDir,
3672
- proxyAdminPath: () => proxyAdminPath,
3673
- proxyBinDir: () => proxyBinDir,
3674
- proxyChallengeAuthPath: () => proxyChallengeAuthPath,
3675
- proxyConfigPath: () => proxyConfigPath,
3676
- proxyDir: () => proxyDir,
3677
- proxyEngineDir: () => proxyEngineDir,
3678
- proxyPreviousConfigPath: () => proxyPreviousConfigPath,
3679
- proxyStateDir: () => proxyStateDir,
3680
- proxyTlsDir: () => proxyTlsDir,
3681
- resolveDataRoot: () => resolveDataRoot,
3682
- resolveProjectDir: () => resolveProjectDir,
3683
- resolveUserPath: () => resolveUserPath,
3684
- runtimePath: () => runtimePath,
3685
- tlsDir: () => tlsDir,
3686
- uiDir: () => uiDir,
3687
- workspaceDdnsStatePath: () => workspaceDdnsStatePath,
3688
- workspaceDir: () => workspaceDir,
3689
- workspaceHistoryPath: () => workspaceHistoryPath,
3690
- workspaceLogsDir: () => workspaceLogsDir,
3691
- workspaceSecretsPath: () => workspaceSecretsPath,
3692
- workspaceServersPath: () => workspaceServersPath,
3693
- workspaceSettingsPath: () => workspaceSettingsPath,
3694
- workspaceStateDir: () => workspaceStateDir,
3695
- workspacesPath: () => workspacesPath
3696
- });
3697
- /**
3698
- * Where home-hosted keeps everything it owns. `HHOSTED_HOME` overrides it —
3699
- * which is how a project repo keeps its own state directory while the package
3700
- * itself ships no configuration at all.
3701
- *
3702
- * Everything below `dataRoot/.hh`: the global panel state at its top level, and
3703
- * one directory per workspace. A workspace owns its settings, servers, secrets,
3704
- * logs and nanny state; only what is genuinely panel-wide (listener, auth,
3705
- * host vitals, backups, TLS, UI, run.json) stays global.
3706
- */
3707
- function resolveDataRoot() {
3708
- const override = process.env.HHOSTED_HOME;
3709
- if (override !== void 0 && override.length > 0) return path.resolve(override);
3710
- return path.join(os.homedir(), ".home-hosted");
3711
- }
3712
- /**
3713
- * The directory home-hosted was started from. Relative entry paths (`cwd`,
3714
- * declared data directories) resolve against it, so the project's own launcher
3715
- * decides the base instead of wherever the package happens to be installed.
3716
- * `HHOSTED_PROJECT` pins it explicitly.
3717
- */
3718
- function resolveProjectDir() {
3719
- const override = process.env.HHOSTED_PROJECT;
3720
- if (override !== void 0 && override.length > 0) return path.resolve(override);
3721
- return process.cwd();
3722
- }
3723
- function workspaceDir(id) {
3724
- return path.join(hhDir, id);
3725
- }
3726
- /** Workspace-scoped settings: server defaults, logs, notifications, DDNS. */
3727
- function workspaceSettingsPath(id) {
3728
- return path.join(workspaceDir(id), "settings.json");
3729
- }
3730
- /** The servers a workspace supervises. */
3731
- function workspaceServersPath(id) {
3732
- return path.join(workspaceDir(id), "servers.config.json");
3733
- }
3734
- /** Workspace secrets: Telegram bot token and DDNS credentials. Mode 0600. */
3735
- function workspaceSecretsPath(id) {
3736
- return path.join(workspaceDir(id), ".secrets.json");
3737
- }
3738
- /** Rotated per-server JSONL logs. */
3739
- function workspaceLogsDir(id) {
3740
- return path.join(workspaceDir(id), ".logs");
3741
- }
3742
- /** Persisted restart/crash history for one workspace. */
3743
- function workspaceHistoryPath(id) {
3744
- return path.join(workspaceLogsDir(id), "history.json");
3745
- }
3746
- /** Per-entry nanny state and spawn specs — how a persistent server survives a restart. */
3747
- function workspaceStateDir(id) {
3748
- return path.join(workspaceDir(id), ".state");
3749
- }
3750
- /** The last public address each DDNS target was confirmed to serve. */
3751
- function workspaceDdnsStatePath(id) {
3752
- return path.join(workspaceStateDir(id), "ddns.json");
3753
- }
3754
- /**
3755
- * True when a pre-workspace instance left state at the old paths **and** never
3756
- * crossed into `.hh`: `workspaces.json` means the layout is current, so a stray
3757
- * root-level copy beside it is not an old instance.
3758
- */
3759
- function hasLegacyLayout() {
3760
- if (fs.existsSync(workspacesPath)) return false;
3761
- return fs.existsSync(legacy.configPath) || fs.existsSync(legacy.secretsPath);
3762
- }
3763
- /** Expands `~` and resolves relative paths against `base`, for config-declared paths. */
3764
- function resolveUserPath(target, base = projectDir) {
3765
- let value = target;
3766
- if (value === "~") value = os.homedir();
3767
- else if (value.startsWith("~/") || value.startsWith("~\\")) value = path.join(os.homedir(), value.slice(2));
3768
- return path.isAbsolute(value) ? value : path.resolve(base, value);
3769
- }
3770
- var dataRoot, projectDir, hhDir, DEFAULT_WORKSPACE_ID, globalSettingsPath, globalSecretsPath, workspacesPath, tlsDir, daemonLogPath, runtimePath, uiDir, proxyDir, proxyBinDir, proxyEngineDir, proxyConfigPath, proxyPreviousConfigPath, proxyStateDir, proxyAdminPath, proxyTlsDir, proxyChallengeAuthPath, legacy;
3771
- var init_paths = __esmMin((() => {
3772
- dataRoot = resolveDataRoot();
3773
- projectDir = resolveProjectDir();
3774
- hhDir = path.join(dataRoot, ".hh");
3775
- DEFAULT_WORKSPACE_ID = "default";
3776
- globalSettingsPath = path.join(hhDir, "settings.json");
3777
- globalSecretsPath = path.join(hhDir, ".control-secrets.json");
3778
- workspacesPath = path.join(hhDir, "workspaces.json");
3779
- tlsDir = path.join(hhDir, ".tls");
3780
- daemonLogPath = path.join(hhDir, ".logs", "home-hosted.log");
3781
- runtimePath = path.join(hhDir, "run.json");
3782
- uiDir = path.join(hhDir, ".ui");
3783
- proxyDir = path.join(hhDir, ".proxy");
3784
- proxyBinDir = path.join(proxyDir, "bin");
3785
- proxyEngineDir = path.join(proxyDir, "engine");
3786
- proxyConfigPath = path.join(proxyEngineDir, "current.json");
3787
- proxyPreviousConfigPath = path.join(proxyEngineDir, "previous.json");
3788
- proxyStateDir = path.join(proxyDir, "state");
3789
- proxyAdminPath = path.join(proxyStateDir, "admin.json");
3790
- proxyTlsDir = path.join(proxyDir, "tls");
3791
- proxyChallengeAuthPath = path.join(proxyStateDir, "challenge.json");
3792
- legacy = {
3793
- configPath: path.join(dataRoot, "servers.config.json"),
3794
- secretsPath: path.join(dataRoot, ".control-secrets.json")
3795
- };
3796
- }));
3797
- //#endregion
3798
- //#region src/services/state.ts
3799
- /**
3800
- * The panel's own settings are derived here — configured values from the store,
3801
- * live values from the listener, security state from the auth service and the
3802
- * certificate pair from disk — so the UI never has to reason about the
3803
- * differences.
3804
- */
3805
- function buildControlView(settings, auth, control, tls) {
3806
- const config = settings.control;
3807
- const exposure = checkExposure(config, auth.passwordSet, auth.usingDefaultPassword);
3808
- return {
3809
- label: config.label,
3810
- port: config.port,
3811
- host: config.host,
3812
- bindHost: control.bindHost,
3813
- url: control.url,
3814
- protocol: control.protocol,
3815
- openBrowser: config.openBrowser,
3816
- restartRequired: control.port !== config.port || control.host !== config.host,
3817
- auth: {
3818
- enabled: config.auth.enabled,
3819
- passwordSet: auth.passwordSet,
3820
- passwordUpdatedAt: auth.passwordUpdatedAt,
3821
- apiTokenSet: auth.apiTokenSet,
3822
- usingDefaultPassword: auth.usingDefaultPassword,
3823
- exposed: exposure.exposed,
3824
- blockedReason: exposure.blockedReason,
3825
- sessionTtlMs: config.auth.sessionTtlMs,
3826
- cookieSecure: config.auth.cookieSecure,
3827
- trustProxy: config.auth.trustProxy,
3828
- maxLoginAttempts: config.auth.maxLoginAttempts,
3829
- lockoutMs: config.auth.lockoutMs
3830
- },
3831
- tls: tls.status(config.tls.enabled)
3832
- };
3833
- }
3834
- function buildBackupsView(backups) {
3835
- return backups.view();
3836
- }
3837
- /** One workspace's subtree of the state frame. */
3838
- function buildWorkspaceView(source) {
3839
- const servers = source.supervisor.views();
3840
- return {
3841
- id: source.id,
3842
- label: source.label,
3843
- configPath: source.store.path,
3844
- settingsPath: source.store.settingsPath,
3845
- configError: source.store.configError,
3846
- configWarnings: source.store.configWarnings,
3847
- logsDir: source.logsDir,
3848
- defaults: source.store.defaults,
3849
- logs: source.store.logs,
3850
- notifications: {
3851
- defaults: source.notifications.defaults(),
3852
- destinations: source.notifications.destinations()
3853
- },
3854
- ddns: source.ddns.view,
3855
- serverCount: servers.length,
3856
- runningCount: servers.filter((server) => server.status === "running").length,
3857
- crashedCount: servers.filter((server) => server.status === "crashed").length,
3858
- orphans: source.supervisor.orphans?.() ?? [],
3859
- servers
3860
- };
3861
- }
3862
- var init_state$1 = __esmMin((() => {
3863
- init_paths();
3864
- init_exposure();
3865
- }));
3866
- //#endregion
3867
3847
  //#region src/shared/backup-scope.ts
3868
3848
  /**
3869
3849
  * What a configured automatic scope asks a `create` for.
@@ -3948,9 +3928,9 @@ function createBackupsRoute(deps) {
3948
3928
  summary: "Archives on disk, and the paths a backup would capture",
3949
3929
  responses: { 200: {
3950
3930
  description: "Backups",
3951
- content: jsonBody(backupsViewSchema)
3931
+ content: jsonBody(backupSelectionSchema)
3952
3932
  } }
3953
- }), (c) => c.json(buildBackupsView(deps.backups))).post("/backups", describeRoute({
3933
+ }), (c) => c.json(deps.backups.selection())).post("/backups", describeRoute({
3954
3934
  tags: ["backups"],
3955
3935
  summary: "Create a backup (optionally password-protected)",
3956
3936
  responses: {
@@ -4147,7 +4127,6 @@ var init_backups$1 = __esmMin((() => {
4147
4127
  init_validate();
4148
4128
  init_validator();
4149
4129
  init_auth();
4150
- init_state$1();
4151
4130
  init_backup_scope();
4152
4131
  init_contracts();
4153
4132
  MAX_UPLOAD_BYTES = 268435456;
@@ -4313,6 +4292,143 @@ var init_schema = __esmMin((() => {
4313
4292
  ];
4314
4293
  }));
4315
4294
  //#endregion
4295
+ //#region src/helpers/paths.ts
4296
+ var paths_exports = /* @__PURE__ */ __exportAll({
4297
+ DEFAULT_WORKSPACE_ID: () => DEFAULT_WORKSPACE_ID,
4298
+ daemonLogPath: () => daemonLogPath,
4299
+ dataRoot: () => dataRoot,
4300
+ globalSecretsPath: () => globalSecretsPath,
4301
+ globalSettingsPath: () => globalSettingsPath,
4302
+ hasLegacyLayout: () => hasLegacyLayout,
4303
+ hhDir: () => hhDir,
4304
+ legacy: () => legacy,
4305
+ projectDir: () => projectDir,
4306
+ proxyAdminPath: () => proxyAdminPath,
4307
+ proxyBinDir: () => proxyBinDir,
4308
+ proxyChallengeAuthPath: () => proxyChallengeAuthPath,
4309
+ proxyConfigPath: () => proxyConfigPath,
4310
+ proxyDir: () => proxyDir,
4311
+ proxyEngineDir: () => proxyEngineDir,
4312
+ proxyPreviousConfigPath: () => proxyPreviousConfigPath,
4313
+ proxyStateDir: () => proxyStateDir,
4314
+ proxyTlsDir: () => proxyTlsDir,
4315
+ resolveDataRoot: () => resolveDataRoot,
4316
+ resolveProjectDir: () => resolveProjectDir,
4317
+ resolveUserPath: () => resolveUserPath,
4318
+ runtimePath: () => runtimePath,
4319
+ tlsDir: () => tlsDir,
4320
+ uiDir: () => uiDir,
4321
+ workspaceDdnsStatePath: () => workspaceDdnsStatePath,
4322
+ workspaceDir: () => workspaceDir,
4323
+ workspaceHistoryPath: () => workspaceHistoryPath,
4324
+ workspaceLogsDir: () => workspaceLogsDir,
4325
+ workspaceSecretsPath: () => workspaceSecretsPath,
4326
+ workspaceServersPath: () => workspaceServersPath,
4327
+ workspaceSettingsPath: () => workspaceSettingsPath,
4328
+ workspaceStateDir: () => workspaceStateDir,
4329
+ workspacesPath: () => workspacesPath
4330
+ });
4331
+ /**
4332
+ * Where home-hosted keeps everything it owns. `HHOSTED_HOME` overrides it —
4333
+ * which is how a project repo keeps its own state directory while the package
4334
+ * itself ships no configuration at all.
4335
+ *
4336
+ * Everything below `dataRoot/.hh`: the global panel state at its top level, and
4337
+ * one directory per workspace. A workspace owns its settings, servers, secrets,
4338
+ * logs and nanny state; only what is genuinely panel-wide (listener, auth,
4339
+ * host vitals, backups, TLS, UI, run.json) stays global.
4340
+ */
4341
+ function resolveDataRoot() {
4342
+ const override = process.env.HHOSTED_HOME;
4343
+ if (override !== void 0 && override.length > 0) return path.resolve(override);
4344
+ return path.join(os.homedir(), ".home-hosted");
4345
+ }
4346
+ /**
4347
+ * The directory home-hosted was started from. Relative entry paths (`cwd`,
4348
+ * declared data directories) resolve against it, so the project's own launcher
4349
+ * decides the base instead of wherever the package happens to be installed.
4350
+ * `HHOSTED_PROJECT` pins it explicitly.
4351
+ */
4352
+ function resolveProjectDir() {
4353
+ const override = process.env.HHOSTED_PROJECT;
4354
+ if (override !== void 0 && override.length > 0) return path.resolve(override);
4355
+ return process.cwd();
4356
+ }
4357
+ function workspaceDir(id) {
4358
+ return path.join(hhDir, id);
4359
+ }
4360
+ /** Workspace-scoped settings: server defaults, logs, notifications, DDNS. */
4361
+ function workspaceSettingsPath(id) {
4362
+ return path.join(workspaceDir(id), "settings.json");
4363
+ }
4364
+ /** The servers a workspace supervises. */
4365
+ function workspaceServersPath(id) {
4366
+ return path.join(workspaceDir(id), "servers.config.json");
4367
+ }
4368
+ /** Workspace secrets: Telegram bot token and DDNS credentials. Mode 0600. */
4369
+ function workspaceSecretsPath(id) {
4370
+ return path.join(workspaceDir(id), ".secrets.json");
4371
+ }
4372
+ /** Rotated per-server JSONL logs. */
4373
+ function workspaceLogsDir(id) {
4374
+ return path.join(workspaceDir(id), ".logs");
4375
+ }
4376
+ /** Persisted restart/crash history for one workspace. */
4377
+ function workspaceHistoryPath(id) {
4378
+ return path.join(workspaceLogsDir(id), "history.json");
4379
+ }
4380
+ /** Per-entry nanny state and spawn specs — how a persistent server survives a restart. */
4381
+ function workspaceStateDir(id) {
4382
+ return path.join(workspaceDir(id), ".state");
4383
+ }
4384
+ /** The last public address each DDNS target was confirmed to serve. */
4385
+ function workspaceDdnsStatePath(id) {
4386
+ return path.join(workspaceStateDir(id), "ddns.json");
4387
+ }
4388
+ /**
4389
+ * True when a pre-workspace instance left state at the old paths **and** never
4390
+ * crossed into `.hh`: `workspaces.json` means the layout is current, so a stray
4391
+ * root-level copy beside it is not an old instance.
4392
+ */
4393
+ function hasLegacyLayout() {
4394
+ if (fs.existsSync(workspacesPath)) return false;
4395
+ return fs.existsSync(legacy.configPath) || fs.existsSync(legacy.secretsPath);
4396
+ }
4397
+ /** Expands `~` and resolves relative paths against `base`, for config-declared paths. */
4398
+ function resolveUserPath(target, base = projectDir) {
4399
+ let value = target;
4400
+ if (value === "~") value = os.homedir();
4401
+ else if (value.startsWith("~/") || value.startsWith("~\\")) value = path.join(os.homedir(), value.slice(2));
4402
+ return path.isAbsolute(value) ? value : path.resolve(base, value);
4403
+ }
4404
+ var dataRoot, projectDir, hhDir, DEFAULT_WORKSPACE_ID, globalSettingsPath, globalSecretsPath, workspacesPath, tlsDir, daemonLogPath, runtimePath, uiDir, proxyDir, proxyBinDir, proxyEngineDir, proxyConfigPath, proxyPreviousConfigPath, proxyStateDir, proxyAdminPath, proxyTlsDir, proxyChallengeAuthPath, legacy;
4405
+ var init_paths = __esmMin((() => {
4406
+ dataRoot = resolveDataRoot();
4407
+ projectDir = resolveProjectDir();
4408
+ hhDir = path.join(dataRoot, ".hh");
4409
+ DEFAULT_WORKSPACE_ID = "default";
4410
+ globalSettingsPath = path.join(hhDir, "settings.json");
4411
+ globalSecretsPath = path.join(hhDir, ".control-secrets.json");
4412
+ workspacesPath = path.join(hhDir, "workspaces.json");
4413
+ tlsDir = path.join(hhDir, ".tls");
4414
+ daemonLogPath = path.join(hhDir, ".logs", "home-hosted.log");
4415
+ runtimePath = path.join(hhDir, "run.json");
4416
+ uiDir = path.join(hhDir, ".ui");
4417
+ proxyDir = path.join(hhDir, ".proxy");
4418
+ proxyBinDir = path.join(proxyDir, "bin");
4419
+ proxyEngineDir = path.join(proxyDir, "engine");
4420
+ proxyConfigPath = path.join(proxyEngineDir, "current.json");
4421
+ proxyPreviousConfigPath = path.join(proxyEngineDir, "previous.json");
4422
+ proxyStateDir = path.join(proxyDir, "state");
4423
+ proxyAdminPath = path.join(proxyStateDir, "admin.json");
4424
+ proxyTlsDir = path.join(proxyDir, "tls");
4425
+ proxyChallengeAuthPath = path.join(proxyStateDir, "challenge.json");
4426
+ legacy = {
4427
+ configPath: path.join(dataRoot, "servers.config.json"),
4428
+ secretsPath: path.join(dataRoot, ".control-secrets.json")
4429
+ };
4430
+ }));
4431
+ //#endregion
4316
4432
  //#region src/config/workspaces.ts
4317
4433
  /** `My Project AB!` -> `my-project-ab`, and never an empty id. */
4318
4434
  function slugifyWorkspaceId(label, taken = []) {
@@ -4588,13 +4704,13 @@ function createControlRoute(deps) {
4588
4704
  responses: {
4589
4705
  200: {
4590
4706
  description: "The archives",
4591
- content: jsonBody(backupsViewSchema)
4707
+ content: jsonBody(backupSelectionSchema)
4592
4708
  },
4593
4709
  403: { description: "Bad token, or not a local caller" }
4594
4710
  }
4595
4711
  }), (c) => {
4596
4712
  assertLocalCall(c, "list backups");
4597
- return c.json(buildBackupsView(deps.backups));
4713
+ return c.json(deps.backups.selection());
4598
4714
  }).post("/backups", describeRoute({
4599
4715
  tags: ["panel"],
4600
4716
  summary: "Create a backup archive (local token required)",
@@ -4612,7 +4728,8 @@ function createControlRoute(deps) {
4612
4728
  const include = c.req.query("include")?.split(",").filter((part) => part.length > 0);
4613
4729
  const exclude = c.req.query("exclude")?.split(",").filter((part) => part.length > 0);
4614
4730
  if (c.req.query("confirm") !== "true") {
4615
- const view = buildBackupsView(deps.backups);
4731
+ const view = deps.backups.selection();
4732
+ const includePaths = deps.backups.view().includePaths;
4616
4733
  const selects = selectionOf({
4617
4734
  include,
4618
4735
  exclude
@@ -4625,7 +4742,7 @@ function createControlRoute(deps) {
4625
4742
  return c.json({
4626
4743
  apply: false,
4627
4744
  entries,
4628
- includePaths: view.includePaths
4745
+ includePaths
4629
4746
  });
4630
4747
  }
4631
4748
  const result = await deps.backups.create({
@@ -4705,7 +4822,6 @@ var init_control = __esmMin((() => {
4705
4822
  init_validator();
4706
4823
  init_workspace();
4707
4824
  init_loopback();
4708
- init_state$1();
4709
4825
  init_backup_scope();
4710
4826
  init_contracts();
4711
4827
  }));
@@ -6906,11 +7022,18 @@ function parseEnvFile(text) {
6906
7022
  }
6907
7023
  return env;
6908
7024
  }
6909
- /** Missing files are not an error: an env file is an optional override layer. */
7025
+ /**
7026
+ * Missing files are not an error: an env file is an optional override layer.
7027
+ *
7028
+ * Read through `readStateFile`: an entry's `envFile` is written by a person, not by this panel, so a
7029
+ * Windows editor's byte-order mark or UTF-16 save is the normal state of it. A `'utf8'` read made
7030
+ * every key carry a NUL — dropped by `resolveSpawn` as "an environment key containing a null byte" —
7031
+ * so the process started without the secret the file exists to keep out of the config.
7032
+ */
6910
7033
  function loadEnvFile(file) {
6911
7034
  try {
6912
7035
  return {
6913
- env: parseEnvFile(fs.readFileSync(file, "utf8")),
7036
+ env: parseEnvFile(readStateFile(file)),
6914
7037
  path: file,
6915
7038
  error: null
6916
7039
  };
@@ -6943,6 +7066,7 @@ function resolveEnvFilePath(file, cwd) {
6943
7066
  }
6944
7067
  var VARIABLE;
6945
7068
  var init_env_file = __esmMin((() => {
7069
+ init_config_text();
6946
7070
  init_error_message();
6947
7071
  VARIABLE = /\$\{([A-Z_]\w*)\}/gi;
6948
7072
  }));
@@ -7993,7 +8117,7 @@ function createMetricsRoute(deps) {
7993
8117
  responses: { 200: { description: "text/plain; version=0.0.4" } }
7994
8118
  }), (c) => {
7995
8119
  const servers = deps.panel.serverViews();
7996
- const host = deps.panel.getState().host;
8120
+ const host = hostReadings(deps.panel.getState().host);
7997
8121
  const lines = [];
7998
8122
  const metric = (name, help, samples) => {
7999
8123
  if (samples.length === 0) return;
@@ -8008,18 +8132,17 @@ function createMetricsRoute(deps) {
8008
8132
  metric("hh_server_response_ms", "Last health probe latency in milliseconds", servers.filter((server) => server.responseMs !== null).map((server) => `hh_server_response_ms{${labels(server)}} ${server.responseMs}`));
8009
8133
  metric("hh_server_rss_bytes", "RSS of the server process tree, or the summed containers of a compose entry", servers.filter((server) => server.resources?.rssBytes != null).map((server) => `hh_server_rss_bytes{${labels(server)}} ${server.resources.rssBytes}`));
8010
8134
  metric("hh_server_cpu_percent", "CPU percent of the server process tree, or the summed containers of a compose entry", servers.filter((server) => server.resources?.cpuPercent != null).map((server) => `hh_server_cpu_percent{${labels(server)}} ${server.resources.cpuPercent}`));
8011
- if (host.sampledAt !== null) {
8012
- metric("hh_host_disk_used_percent", "Disk usage percent per configured path", host.disks.map((disk) => `hh_host_disk_used_percent{mount="${labelValue(disk.path)}"} ${disk.usedPercent.toFixed(2)}`));
8013
- metric("hh_host_cpu_used_percent", "Share of this machine's CPU capacity in use, 0-100", host.cpuUsedPercent == null ? [] : [`hh_host_cpu_used_percent ${host.cpuUsedPercent.toFixed(2)}`]);
8014
- metric("hh_host_memory_used_percent", "Memory usage percent", [`hh_host_memory_used_percent ${host.memoryUsedPercent.toFixed(2)}`]);
8015
- metric("hh_host_swap_used_percent", "Swap usage percent", [`hh_host_swap_used_percent ${host.swapUsedPercent.toFixed(2)}`]);
8016
- metric("hh_host_load1_per_cpu", "1 minute load average per cpu", [`hh_host_load1_per_cpu ${((host.loadAvg[0] ?? 0) / Math.max(1, host.cpus)).toFixed(3)}`]);
8017
- }
8135
+ metric("hh_host_disk_used_percent", "Disk usage percent per configured path", host.disks.map((disk) => `hh_host_disk_used_percent{mount="${labelValue(disk.path)}"} ${disk.usedPercent.toFixed(2)}`));
8136
+ metric("hh_host_cpu_used_percent", "Share of this machine's CPU capacity in use, 0-100", host.cpuUsedPercent === null ? [] : [`hh_host_cpu_used_percent ${host.cpuUsedPercent.toFixed(2)}`]);
8137
+ metric("hh_host_memory_used_percent", "Memory usage percent", host.memoryUsedPercent === null ? [] : [`hh_host_memory_used_percent ${host.memoryUsedPercent.toFixed(2)}`]);
8138
+ metric("hh_host_swap_used_percent", "Swap usage percent", host.swapUsedPercent === null ? [] : [`hh_host_swap_used_percent ${host.swapUsedPercent.toFixed(2)}`]);
8139
+ metric("hh_host_load1_per_cpu", "1 minute load average per cpu", host.loadPerCpu === null ? [] : [`hh_host_load1_per_cpu ${host.loadPerCpu.toFixed(3)}`]);
8018
8140
  return c.text(`${lines.join("\n")}\n`, 200, { "Content-Type": "text/plain; version=0.0.4; charset=utf-8" });
8019
8141
  });
8020
8142
  }
8021
8143
  var init_metrics = __esmMin((() => {
8022
8144
  init_factory();
8145
+ init_host_readings();
8023
8146
  }));
8024
8147
  //#endregion
8025
8148
  //#region src/providers/telegram.ts
@@ -8716,8 +8839,9 @@ function matchesSpawn(info, spawn) {
8716
8839
  async function processArgv(pid) {
8717
8840
  if (process.platform === "win32") return null;
8718
8841
  if (process.platform === "linux") try {
8719
- const argv = (await fs.promises.readFile(`/proc/${pid}/cmdline`)).toString("utf8").split("\0").filter((part) => part.length > 0);
8720
- return argv.length > 0 ? argv : null;
8842
+ const words = (await fs.promises.readFile(`/proc/${pid}/cmdline`)).toString("utf8").split("\0");
8843
+ if (words.at(-1) === "") words.pop();
8844
+ return words.length > 0 ? words : null;
8721
8845
  } catch {
8722
8846
  return null;
8723
8847
  }
@@ -9324,6 +9448,7 @@ var init_process = __esmMin((() => {
9324
9448
  var nanny_exports$2 = /* @__PURE__ */ __exportAll({
9325
9449
  HEARTBEAT_STALE_MS: () => HEARTBEAT_STALE_MS,
9326
9450
  NANNY_HEARTBEAT_MS: () => NANNY_HEARTBEAT_MS,
9451
+ NANNY_TRAPPED_SIGNALS: () => NANNY_TRAPPED_SIGNALS,
9327
9452
  SPEC_SUFFIX: () => SPEC_SUFFIX,
9328
9453
  clearNannySpec: () => clearNannySpec,
9329
9454
  clearNannyState: () => clearNannyState,
@@ -9504,18 +9629,23 @@ function signalName(number) {
9504
9629
  }
9505
9630
  /**
9506
9631
  * Is the nanny this state describes still ours? A live pid proves nothing on its
9507
- * own — pids are reused. A fresh heartbeat means a process is still rewriting the
9508
- * file; the environment marker (Linux, macOS) or the argv we spawned it with answers
9509
- * everywhere else, Windows included.
9632
+ * own — pids are reused, and the heartbeat is written *into the file*, not by the
9633
+ * process the file names, so a recycled pid with a recent write reads as running.
9634
+ * `startedAt` settles that first (`processLiveness`), exactly as `run.json` uses it:
9635
+ * the nanny stamps its record during its own boot, so its process is always born
9636
+ * before the stamp. The environment marker (Linux, macOS) or the argv we spawned it
9637
+ * with answers the rest, Windows included.
9510
9638
  */
9511
- async function nannyIsAlive(state, id) {
9512
- if (state.nannyPid <= 0 || !isProcessAlive(state.nannyPid)) return false;
9639
+ async function nannyIsAlive(state, id, options = {}) {
9640
+ if (state.nannyPid <= 0) return false;
9641
+ const liveness = await processLiveness(state.nannyPid, state.startedAt, options);
9642
+ if (liveness === "gone" || liveness === "recycled") return false;
9513
9643
  if (Date.now() - state.heartbeatAt <= 3e4) return true;
9514
9644
  if (await processCarriesServerId(state.nannyPid, id)) return true;
9515
9645
  const words = await processArgv(state.nannyPid);
9516
9646
  return words !== null && words.includes("__nanny") && words.some((word) => word.endsWith(`${id}.spec.json`));
9517
9647
  }
9518
- var SPEC_MODE, SPEC_SUFFIX, NANNY_HEARTBEAT_MS, HEARTBEAT_STALE_MS;
9648
+ var SPEC_MODE, SPEC_SUFFIX, NANNY_TRAPPED_SIGNALS, NANNY_HEARTBEAT_MS, HEARTBEAT_STALE_MS;
9519
9649
  var init_nanny$2 = __esmMin((() => {
9520
9650
  init_atomic();
9521
9651
  init_runtime();
@@ -9526,6 +9656,7 @@ var init_nanny$2 = __esmMin((() => {
9526
9656
  init_contracts();
9527
9657
  SPEC_MODE = 384;
9528
9658
  SPEC_SUFFIX = ".spec.json";
9659
+ NANNY_TRAPPED_SIGNALS = /* @__PURE__ */ new Set(["SIGTERM", "SIGINT"]);
9529
9660
  NANNY_HEARTBEAT_MS = 5e3;
9530
9661
  HEARTBEAT_STALE_MS = 3e4;
9531
9662
  }));
@@ -12235,7 +12366,7 @@ function createServersRoute(deps) {
12235
12366
  responses: {
12236
12367
  200: {
12237
12368
  description: "Lines",
12238
- content: jsonBody(logLinesResponseSchema)
12369
+ content: jsonBody(bufferedLogsResponseSchema)
12239
12370
  },
12240
12371
  404: ERROR_RESPONSES[404]
12241
12372
  }
@@ -12448,6 +12579,72 @@ var init_$_routes$1 = __esmMin((() => {
12448
12579
  bufferedLogsQuery = logQuerySchema.merge(workspaceQuerySchema);
12449
12580
  }));
12450
12581
  //#endregion
12582
+ //#region src/services/state.ts
12583
+ /**
12584
+ * The panel's own settings are derived here — configured values from the store,
12585
+ * live values from the listener, security state from the auth service and the
12586
+ * certificate pair from disk — so the UI never has to reason about the
12587
+ * differences.
12588
+ */
12589
+ function buildControlView(settings, auth, control, tls) {
12590
+ const config = settings.control;
12591
+ const exposure = checkExposure(config, auth.passwordSet, auth.usingDefaultPassword);
12592
+ return {
12593
+ label: config.label,
12594
+ port: config.port,
12595
+ host: config.host,
12596
+ bindHost: control.bindHost,
12597
+ url: control.url,
12598
+ protocol: control.protocol,
12599
+ openBrowser: config.openBrowser,
12600
+ restartRequired: control.port !== config.port || control.host !== config.host,
12601
+ auth: {
12602
+ enabled: config.auth.enabled,
12603
+ passwordSet: auth.passwordSet,
12604
+ passwordUpdatedAt: auth.passwordUpdatedAt,
12605
+ apiTokenSet: auth.apiTokenSet,
12606
+ usingDefaultPassword: auth.usingDefaultPassword,
12607
+ exposed: exposure.exposed,
12608
+ blockedReason: exposure.blockedReason,
12609
+ sessionTtlMs: config.auth.sessionTtlMs,
12610
+ cookieSecure: config.auth.cookieSecure,
12611
+ trustProxy: config.auth.trustProxy,
12612
+ maxLoginAttempts: config.auth.maxLoginAttempts,
12613
+ lockoutMs: config.auth.lockoutMs
12614
+ },
12615
+ tls: tls.status(config.tls.enabled)
12616
+ };
12617
+ }
12618
+ /** One workspace's subtree of the state frame. */
12619
+ function buildWorkspaceView(source) {
12620
+ const servers = source.supervisor.views();
12621
+ return {
12622
+ id: source.id,
12623
+ label: source.label,
12624
+ configPath: source.store.path,
12625
+ settingsPath: source.store.settingsPath,
12626
+ configError: source.store.configError,
12627
+ configWarnings: source.store.configWarnings,
12628
+ logsDir: source.logsDir,
12629
+ defaults: source.store.defaults,
12630
+ logs: source.store.logs,
12631
+ notifications: {
12632
+ defaults: source.notifications.defaults(),
12633
+ destinations: source.notifications.destinations()
12634
+ },
12635
+ ddns: source.ddns.view,
12636
+ serverCount: servers.length,
12637
+ runningCount: servers.filter((server) => server.status === "running").length,
12638
+ crashedCount: servers.filter((server) => server.status === "crashed").length,
12639
+ orphans: source.supervisor.orphans?.() ?? [],
12640
+ servers
12641
+ };
12642
+ }
12643
+ var init_state$1 = __esmMin((() => {
12644
+ init_paths();
12645
+ init_exposure();
12646
+ }));
12647
+ //#endregion
12451
12648
  //#region src/api/settings.ts
12452
12649
  /** The archive's name is only a label, so it never reaches the filesystem. */
12453
12650
  function sanitizeName(name) {
@@ -12520,7 +12717,7 @@ function createSettingsRoute(deps) {
12520
12717
  });
12521
12718
  const scope = patch.backups?.schedule?.scope;
12522
12719
  if (scope !== void 0 && scope !== null) {
12523
- const unknown = unknownBackupIds(scope.ids, deps.backups.view().entries);
12720
+ const unknown = unknownBackupIds(scope.ids, deps.backups.selection().entries);
12524
12721
  if (unknown.length > 0) throw new DetailedError(`the automatic backup scope names ${unknown.map((id) => `"${id}"`).join(", ")}, which this panel cannot capture`, {
12525
12722
  statusCode: 400,
12526
12723
  code: "INVALID_SETTINGS"
@@ -12986,12 +13183,14 @@ var init_$_routes = __esmMin((() => {
12986
13183
  var wsl_temperature_exports = /* @__PURE__ */ __exportAll({
12987
13184
  LHM_RELEASE: () => LHM_RELEASE,
12988
13185
  LHM_SUBDIR: () => LHM_SUBDIR,
13186
+ forgetWslPaths: () => forgetWslPaths,
12989
13187
  installLibreHardwareMonitor: () => installLibreHardwareMonitor,
12990
13188
  isWsl: () => isWsl,
12991
13189
  lhmDirectory: () => lhmDirectory,
12992
13190
  lhmDirectoryWindows: () => lhmDirectoryWindows,
12993
13191
  lhmInstalled: () => lhmInstalled,
12994
13192
  probeWslTemperature: () => probeWslTemperature,
13193
+ removeWslTemperatureScript: () => removeWslTemperatureScript,
12995
13194
  tempCommandFor: () => tempCommandFor,
12996
13195
  tempCommandForWindows: () => tempCommandForWindows,
12997
13196
  toGuestPath: () => toGuestPath,
@@ -13001,10 +13200,20 @@ var wsl_temperature_exports = /* @__PURE__ */ __exportAll({
13001
13200
  wslScriptPathWindows: () => wslScriptPathWindows,
13002
13201
  wslTemperatureStatus: () => wslTemperatureStatus
13003
13202
  });
13004
- /** The install directory in Windows terms, read from the environment (the system drive may not be `C:`). */
13005
- function lhmDirectoryWindows() {
13203
+ /**
13204
+ * `$env:ProgramData` from the Windows side, read **once**.
13205
+ *
13206
+ * `powershell.exe` across the 9p mount measured ~360 ms here, and this is a **synchronous** spawn: it
13207
+ * stops the whole event loop, so the tick, the SSE hub and every in-flight request wait behind it.
13208
+ * Every bridge-state read did it twice — once for the install directory, once for the library — which
13209
+ * made `GET /api/host/temperature` block the panel for ~720 ms, on a route the settings page calls
13210
+ * whenever it opens. Same rule as `lanAddress()`: a host read on a request path is cached, never
13211
+ * paid per call.
13212
+ */
13213
+ function windowsProgramData() {
13214
+ if (windowsBase !== null) return windowsBase;
13006
13215
  try {
13007
- const base = execFileSync("powershell.exe", [
13216
+ const base = cp.execFileSync("powershell.exe", [
13008
13217
  "-NoProfile",
13009
13218
  "-NonInteractive",
13010
13219
  "-Command",
@@ -13014,10 +13223,18 @@ function lhmDirectoryWindows() {
13014
13223
  windowsHide: true,
13015
13224
  encoding: "utf8"
13016
13225
  }).trim();
13017
- return base.length === 0 ? null : path.win32.join(base, LHM_SUBDIR);
13018
- } catch {
13019
- return null;
13020
- }
13226
+ if (base.length > 0) windowsBase = base;
13227
+ } catch {}
13228
+ return windowsBase;
13229
+ }
13230
+ /** The install directory in Windows terms, read from the environment (the system drive may not be `C:`). */
13231
+ function lhmDirectoryWindows() {
13232
+ const base = windowsProgramData();
13233
+ return base === null ? null : path.win32.join(base, LHM_SUBDIR);
13234
+ }
13235
+ /** Forgets the cached Windows path. A test that simulates the Windows side calls this first. */
13236
+ function forgetWslPaths() {
13237
+ windowsBase = null;
13021
13238
  }
13022
13239
  /** A Windows path as a path this process can read: `C:\x` -> `/mnt/c/x`. */
13023
13240
  function toGuestPath(windowsPath) {
@@ -13107,18 +13324,12 @@ function wslTemperatureStatus(scriptPath, tempCommand) {
13107
13324
  const wsl = isWsl();
13108
13325
  const scriptWritten = scriptPath !== null && fs.existsSync(scriptPath);
13109
13326
  const configured = tempCommand.trim().length > 0;
13110
- let libraryPresent = false;
13111
- try {
13112
- libraryPresent = fs.existsSync(path.join("/mnt", "c", "Tools", "LibreHardwareMonitor", "LibreHardwareMonitorLib.dll"));
13113
- } catch {
13114
- libraryPresent = false;
13115
- }
13116
13327
  return {
13117
13328
  wsl,
13118
13329
  supported: wsl,
13119
13330
  configured,
13120
13331
  scriptWritten,
13121
- libraryPresent,
13332
+ libraryPresent: lhmInstalled(),
13122
13333
  scriptPath: wsl ? scriptPath : null,
13123
13334
  tempCommand: configured ? tempCommand : null
13124
13335
  };
@@ -13128,6 +13339,20 @@ function writeWslTemperatureScript(scriptPath) {
13128
13339
  fs.mkdirSync(path.dirname(scriptPath), { recursive: true });
13129
13340
  fs.writeFileSync(scriptPath, scriptBody(), { mode: 384 });
13130
13341
  }
13342
+ /**
13343
+ * Delete the helper script, best-effort: a file someone already removed is the outcome they wanted.
13344
+ *
13345
+ * The one home for it, because `--clear` promises it in the CLI help and in `docs/SERVERS.md` — and
13346
+ * the CLI cleared `host.tempCommand` without ever removing the file, so the helper outlived the
13347
+ * setting that pointed at it. A command nothing names any more is left for the next person to
13348
+ * wonder about, and the route that *did* delete it was the only caller.
13349
+ */
13350
+ function removeWslTemperatureScript(scriptPath) {
13351
+ if (scriptPath === null) return;
13352
+ try {
13353
+ fs.rmSync(scriptPath, { force: true });
13354
+ } catch {}
13355
+ }
13131
13356
  /** Whether the DLL the helper loads is installed where the helper expects it. */
13132
13357
  function lhmInstalled() {
13133
13358
  const dir = lhmDirectory();
@@ -13225,7 +13450,7 @@ async function probeWslTemperature(tempCommand, timeoutMs) {
13225
13450
  const match = /-?\d+(?:\.\d+)?/.exec(stdout);
13226
13451
  if (match === null) return {
13227
13452
  celsius: null,
13228
- error: stderr.trim().length > 0 ? stderr.trim() : "the script printed no number — is LibreHardwareMonitor installed at C:\\Tools\\LibreHardwareMonitor?"
13453
+ error: stderr.trim().length > 0 ? stderr.trim() : "the script printed no number — is LibreHardwareMonitor installed?"
13229
13454
  };
13230
13455
  const celsius = Number.parseFloat(match[0]);
13231
13456
  if (!Number.isFinite(celsius) || celsius <= 0 || celsius >= 150) return {
@@ -13245,12 +13470,13 @@ async function probeWslTemperature(tempCommand, timeoutMs) {
13245
13470
  };
13246
13471
  }
13247
13472
  }
13248
- var execFileAsync$2, SCRIPT_NAME, LHM_SUBDIR, LHM_RELEASE;
13473
+ var execFileAsync$2, SCRIPT_NAME, LHM_SUBDIR, windowsBase, LHM_RELEASE;
13249
13474
  var init_wsl_temperature$1 = __esmMin((() => {
13250
13475
  init_logger();
13251
- execFileAsync$2 = promisify(execFile);
13476
+ execFileAsync$2 = promisify(cp.execFile);
13252
13477
  SCRIPT_NAME = "cpu-temp.ps1";
13253
13478
  LHM_SUBDIR = "home-hosted\\LibreHardwareMonitor";
13479
+ windowsBase = null;
13254
13480
  LHM_RELEASE = {
13255
13481
  version: "0.9.6",
13256
13482
  asset: "LibreHardwareMonitor.zip",
@@ -13325,6 +13551,17 @@ function createWslTemperatureRoute(deps) {
13325
13551
  code: "SCRIPT_WRITE_FAILED"
13326
13552
  });
13327
13553
  }
13554
+ if (!lhmInstalled()) {
13555
+ if (c.req.query("download") !== "true") return c.json({
13556
+ ...status(deps),
13557
+ needsDownload: true
13558
+ });
13559
+ const install = await installLibreHardwareMonitor();
13560
+ if (install.error !== null) throw new DetailedError(`LibreHardwareMonitor could not be installed: ${install.error}`, {
13561
+ statusCode: 400,
13562
+ code: "LIBRARY_INSTALL_FAILED"
13563
+ });
13564
+ }
13328
13565
  const command = tempCommandFor(target);
13329
13566
  const probe = await probeWslTemperature(command, 5e3);
13330
13567
  if (probe.celsius === null) return c.json({
@@ -13352,11 +13589,8 @@ function createWslTemperatureRoute(deps) {
13352
13589
  400: ERROR_RESPONSES[400]
13353
13590
  }
13354
13591
  }), async (c) => {
13355
- const target = scriptPath();
13356
13592
  deps.panel.settings.updateHost({ tempCommand: "" });
13357
- try {
13358
- if (target !== null) fs.rmSync(target, { force: true });
13359
- } catch {}
13593
+ removeWslTemperatureScript(scriptPath());
13360
13594
  return c.json(status(deps));
13361
13595
  });
13362
13596
  }
@@ -13543,78 +13777,108 @@ var init_openapi_reference = __esmMin((() => {
13543
13777
  */
13544
13778
  /** The version the package was built with, so the spec never drifts from it. */
13545
13779
  function setupOpenAPI(app) {
13546
- return appFactory.createApp().get(`${PREFIX}/spec.json`, openAPIRouteHandler(app, { documentation: {
13547
- info: {
13548
- title: "home-hosted",
13549
- version: appVersion(),
13550
- description: "Control plane for the processes you host at home: servers, logs, vitals, backups and settings."
13551
- },
13552
- tags: [
13553
- {
13554
- name: "panel",
13555
- description: "Snapshot, health and the local shutdown channel"
13556
- },
13557
- {
13558
- name: "servers",
13559
- description: "The processes being supervised"
13560
- },
13561
- {
13562
- name: "logs",
13563
- description: "Live and persisted logs"
13564
- },
13565
- {
13566
- name: "workspaces",
13567
- description: "The ownership boundary: one scope per setup"
13568
- },
13569
- {
13570
- name: "backups",
13571
- description: "Archives of config, secrets, TLS and data paths"
13572
- },
13573
- {
13574
- name: "auth",
13575
- description: "Sessions and the panel password"
13576
- },
13577
- {
13578
- name: "notifications",
13579
- description: "Telegram delivery and webhook destinations"
13580
- },
13581
- {
13582
- name: "ddns",
13583
- description: "Dynamic DNS accounts and hostnames"
13584
- },
13585
- {
13586
- name: "proxy",
13587
- description: "The reverse proxy: engine, routes and certificates"
13588
- },
13589
- {
13590
- name: "tls",
13591
- description: "The panel certificate"
13592
- }
13593
- ],
13780
+ return appFactory.createApp().get(`${PREFIX}/spec.json`, openAPIRouteHandler(app, {
13594
13781
  /**
13595
- * The auth scheme, so a generated client can be told how to send a credential.
13782
+ * The `400` every validated route gets, written as this server's own envelope.
13596
13783
  *
13597
- * Every `/api` route takes `Authorization: Bearer hh_…`, and the spec said nothing
13598
- * about it: openapi-typescript, openapi-generator and Scalar's "try it" all produced
13599
- * clients with no auth hook, and the README tells an agent this document *is* the API
13600
- * it may call. Two lines here are the difference between generating a client and
13601
- * hand-writing one.
13784
+ * hono-openapi injects its own default on any operation that has a validator and does not
13785
+ * name a `400`: `{ success: false, error: [], data }`. This API has never sent that shape —
13786
+ * `src/helpers/error.ts` maps every failure through one `DetailedError` envelope,
13787
+ * `{ message, code, detail }`, which is what AGENTS.md promises and what a client parses.
13788
+ * Measured on 29 operations: `GET /api/servers`, `POST /api/servers/{id}/start`, every
13789
+ * `/_hh` lifecycle route, `GET /api/logs/{id}`. The document described a body no successful
13790
+ * client would ever see, and every generated client was typed against it.
13791
+ *
13792
+ * Spelled as a resolved JSON schema rather than `ERROR_RESPONSES[400]`: this option takes
13793
+ * an OpenAPI response object, not a Standard Schema, and `apiErrorSchema` is what that
13794
+ * envelope is defined by (`test/api/panel.test.ts` pins the two together).
13602
13795
  */
13603
- components: { securitySchemes: { bearerAuth: {
13604
- type: "http",
13605
- scheme: "bearer",
13606
- description: "An API token from `home-hosted set-token --generate`. A cookie session works too, but is not part of this scheme."
13607
- } } },
13608
- security: [{ bearerAuth: [] }],
13609
- servers: [{
13610
- url: "/",
13611
- description: "This panel"
13612
- }]
13613
- } })).get(`${PREFIX}/ui`, (c) => c.html(openApiReferencePage(`${PREFIX}/spec.json`)));
13796
+ defaultValidationErrorResponse: {
13797
+ description: ERROR_RESPONSES[400].description,
13798
+ content: { "application/json": { schema: {
13799
+ type: "object",
13800
+ properties: {
13801
+ message: { type: "string" },
13802
+ code: { type: "string" },
13803
+ detail: {}
13804
+ },
13805
+ required: ["message", "code"]
13806
+ } } }
13807
+ },
13808
+ documentation: {
13809
+ info: {
13810
+ title: "home-hosted",
13811
+ version: appVersion(),
13812
+ description: "Control plane for the processes you host at home: servers, logs, vitals, backups and settings."
13813
+ },
13814
+ tags: [
13815
+ {
13816
+ name: "panel",
13817
+ description: "Snapshot, health and the local shutdown channel"
13818
+ },
13819
+ {
13820
+ name: "servers",
13821
+ description: "The processes being supervised"
13822
+ },
13823
+ {
13824
+ name: "logs",
13825
+ description: "Live and persisted logs"
13826
+ },
13827
+ {
13828
+ name: "workspaces",
13829
+ description: "The ownership boundary: one scope per setup"
13830
+ },
13831
+ {
13832
+ name: "backups",
13833
+ description: "Archives of config, secrets, TLS and data paths"
13834
+ },
13835
+ {
13836
+ name: "auth",
13837
+ description: "Sessions and the panel password"
13838
+ },
13839
+ {
13840
+ name: "notifications",
13841
+ description: "Telegram delivery and webhook destinations"
13842
+ },
13843
+ {
13844
+ name: "ddns",
13845
+ description: "Dynamic DNS accounts and hostnames"
13846
+ },
13847
+ {
13848
+ name: "proxy",
13849
+ description: "The reverse proxy: engine, routes and certificates"
13850
+ },
13851
+ {
13852
+ name: "tls",
13853
+ description: "The panel certificate"
13854
+ }
13855
+ ],
13856
+ /**
13857
+ * The auth scheme, so a generated client can be told how to send a credential.
13858
+ *
13859
+ * Every `/api` route takes `Authorization: Bearer hh_…`, and the spec said nothing
13860
+ * about it: openapi-typescript, openapi-generator and Scalar's "try it" all produced
13861
+ * clients with no auth hook, and the README tells an agent this document *is* the API
13862
+ * it may call. Two lines here are the difference between generating a client and
13863
+ * hand-writing one.
13864
+ */
13865
+ components: { securitySchemes: { bearerAuth: {
13866
+ type: "http",
13867
+ scheme: "bearer",
13868
+ description: "An API token from `home-hosted set-token --generate`. A cookie session works too, but is not part of this scheme."
13869
+ } } },
13870
+ security: [{ bearerAuth: [] }],
13871
+ servers: [{
13872
+ url: "/",
13873
+ description: "This panel"
13874
+ }]
13875
+ }
13876
+ })).get(`${PREFIX}/ui`, (c) => c.html(openApiReferencePage(`${PREFIX}/spec.json`)));
13614
13877
  }
13615
13878
  var PREFIX;
13616
13879
  var init_openapi = __esmMin((() => {
13617
13880
  init_factory();
13881
+ init_openapi$1();
13618
13882
  init_version();
13619
13883
  init_openapi_reference();
13620
13884
  PREFIX = "/openapi";
@@ -15094,7 +15358,7 @@ function dependenciesOf(server, servers) {
15094
15358
  if (seen.has(dependency)) continue;
15095
15359
  seen.add(dependency);
15096
15360
  const target = byId.get(dependency);
15097
- if (!target) continue;
15361
+ if (!target || target.id === server.id) continue;
15098
15362
  walk(target);
15099
15363
  found.push(target);
15100
15364
  }
@@ -17838,7 +18102,13 @@ var init_backups = __esmMin((() => {
17838
18102
  get directory() {
17839
18103
  return this.resolveDir();
17840
18104
  }
17841
- /** The whole two-level selection model the backup dialog reads. */
18105
+ /**
18106
+ * The policy and the status: what the settings page shows, and what the state frame carries.
18107
+ *
18108
+ * Deliberately **not** the selection model. `entries()` reads every workspace's `.secrets.json` and
18109
+ * `list()` stats every archive on disk, so including them here made the frame's cost scale with
18110
+ * workspaces × archives on a path rebuilt ~13×/s. A dialog asks `selection()` instead.
18111
+ */
17842
18112
  view() {
17843
18113
  const config = this.options.getConfig();
17844
18114
  const sources = this.options.getSources();
@@ -17849,8 +18119,18 @@ var init_backups = __esmMin((() => {
17849
18119
  schedule: { ...config.schedule },
17850
18120
  lastAutomaticAt: this.lastAutomatic(),
17851
18121
  ...this.scheduleError === null ? {} : { scheduleError: { ...this.scheduleError } },
17852
- includePaths: [...sources.includePaths],
17853
- entries: this.entries(sources),
18122
+ includePaths: [...sources.includePaths]
18123
+ };
18124
+ }
18125
+ /**
18126
+ * The selection model: every entry a capture could include, and every archive already on disk.
18127
+ *
18128
+ * Served by `GET /api/backups` and fetched when a dialog opens, never on a per-frame path.
18129
+ */
18130
+ selection() {
18131
+ return {
18132
+ dir: this.directory,
18133
+ entries: this.entries(this.options.getSources()),
17854
18134
  files: this.list()
17855
18135
  };
17856
18136
  }
@@ -19422,7 +19702,12 @@ async function sampleHost(config, resolvePath) {
19422
19702
  tempCelsius,
19423
19703
  disks,
19424
19704
  alerts,
19425
- sampledAt: Date.now()
19705
+ sampledAt: Date.now(),
19706
+ loadAlertPerCpu: config.loadPerCpu,
19707
+ memoryUsedPercentAlert: config.memoryUsedPercent,
19708
+ swapUsedPercentAlert: config.swapUsedPercent,
19709
+ tempCelsiusAlert: config.tempCelsius,
19710
+ diskUsedPercentAlert: config.diskUsedPercent
19426
19711
  };
19427
19712
  }
19428
19713
  function emptyHostView(config) {
@@ -19441,7 +19726,12 @@ function emptyHostView(config) {
19441
19726
  tempCelsius: null,
19442
19727
  disks: [],
19443
19728
  alerts: [],
19444
- sampledAt: null
19729
+ sampledAt: null,
19730
+ loadAlertPerCpu: config.loadPerCpu,
19731
+ memoryUsedPercentAlert: config.memoryUsedPercent,
19732
+ swapUsedPercentAlert: config.swapUsedPercent,
19733
+ tempCelsiusAlert: config.tempCelsius,
19734
+ diskUsedPercentAlert: config.diskUsedPercent
19445
19735
  };
19446
19736
  }
19447
19737
  var execFileAsync, SWAP_CACHE_MS, swapCache, previousCpuTimes, CPU_SENSOR, ACPI_SENSOR;
@@ -20604,10 +20894,9 @@ function stateSignature(state) {
20604
20894
  state.control.auth.exposed,
20605
20895
  state.control.restartRequired,
20606
20896
  state.control.tls.enabled,
20607
- state.host.sampledAt,
20608
- state.host.alerts.join(","),
20609
- state.backups.files.length,
20610
- state.backups.entries.length,
20897
+ JSON.stringify(state.host),
20898
+ state.backups.lastAutomaticAt,
20899
+ state.backups.scheduleError?.at ?? 0,
20611
20900
  `${state.ui.custom}:${state.ui.meta?.name ?? ""}:${state.ui.meta?.version ?? ""}`,
20612
20901
  state.proxy === void 0 ? "" : [
20613
20902
  state.proxy.config.enabled,
@@ -21235,7 +21524,7 @@ function resolveRoot(staging) {
21235
21524
  }
21236
21525
  function readManifest(root) {
21237
21526
  try {
21238
- const parsed = manifestSchema(JSON.parse(fs.readFileSync(path.join(root, META), "utf8")));
21527
+ const parsed = manifestSchema(JSON.parse(readStateFile(path.join(root, META))));
21239
21528
  return parsed instanceof type.errors ? null : parsed;
21240
21529
  } catch {
21241
21530
  return null;
@@ -21252,6 +21541,7 @@ function countFiles(root) {
21252
21541
  var META, MAX_ENTRIES, MAX_BYTES, MAX_NAME, manifestSchema, UiService, installLocks;
21253
21542
  var init_ui = __esmMin((() => {
21254
21543
  init_atomic();
21544
+ init_config_text();
21255
21545
  init_archive();
21256
21546
  init_contracts();
21257
21547
  init_error_message();
@@ -21294,7 +21584,7 @@ var init_ui = __esmMin((() => {
21294
21584
  }
21295
21585
  readMeta() {
21296
21586
  try {
21297
- const parsed = uiMetaSchema(JSON.parse(fs.readFileSync(path.join(this.directory, META), "utf8")));
21587
+ const parsed = uiMetaSchema(JSON.parse(readStateFile(path.join(this.directory, META))));
21298
21588
  return parsed instanceof type.errors ? null : parsed;
21299
21589
  } catch {
21300
21590
  return null;
@@ -22115,7 +22405,7 @@ function printEffectiveConfig(settings, registry) {
22115
22405
  const dir = path.join(hhDir, workspace.id);
22116
22406
  const read = (name) => {
22117
22407
  try {
22118
- return JSON.parse(fs.readFileSync(path.join(dir, name), "utf8"));
22408
+ return JSON.parse(readStateFile(path.join(dir, name)));
22119
22409
  } catch {
22120
22410
  return null;
22121
22411
  }
@@ -22139,6 +22429,7 @@ var init_src = __esmMin((() => {
22139
22429
  init_secrets();
22140
22430
  init_settings$1();
22141
22431
  init_workspaces();
22432
+ init_config_text();
22142
22433
  init_daemon();
22143
22434
  init_logger();
22144
22435
  init_open();
@@ -22406,7 +22697,7 @@ async function stopPersistentEntries(handles, options = {}) {
22406
22697
  });
22407
22698
  continue;
22408
22699
  }
22409
- if (!stop.killGroup && nanny === "force-killed" && state.childPid !== null && state.childPid > 0) await terminate(state.childPid, {
22700
+ if (state.childPid !== null && state.childPid > 0 && !stop.killGroup && (!NANNY_TRAPPED_SIGNALS.has(stop.signal) || nanny === "force-killed")) await terminate(state.childPid, {
22410
22701
  signal: "SIGKILL",
22411
22702
  killGroup: false,
22412
22703
  graceMs: 0
@@ -22490,7 +22781,12 @@ async function runDown(options = {}) {
22490
22781
  }
22491
22782
  process.stdout.write(`${dim("it did not stop in time — forcing")}\n`);
22492
22783
  forceStop(runtime.pid);
22493
- await waitForExit(runtime.pid, 5e3);
22784
+ if (!await waitForExit(runtime.pid, 5e3)) {
22785
+ process.stdout.write(`${paint("31", "error")} could not stop pid ${runtime.pid} — it is still running, and its record was kept\n`);
22786
+ process.stdout.write(`${dim(`stop it yourself with \`kill -9 ${runtime.pid}\` (Windows: \`taskkill /PID ${runtime.pid} /T /F\`), then run \`down\` again`)}\n`);
22787
+ process.exitCode = 1;
22788
+ return finish();
22789
+ }
22494
22790
  clearRuntime();
22495
22791
  reportStopped(true);
22496
22792
  return finish();
@@ -22796,13 +23092,19 @@ var init_server = __esmMin((() => {
22796
23092
  //#region src/cli/restart.ts
22797
23093
  var restart_exports = /* @__PURE__ */ __exportAll({ restartCommand: () => restartCommand });
22798
23094
  /**
22799
- * `restart` restarts the panel (`down`, then `up`) — or, given a server id, just that entry.
23095
+ * Whether argv names one of these flags, in either the `--flag value` or `--flag=value` form.
22800
23096
  *
22801
- * The id is optional on purpose. `restart` already meant the panel, and it still does when
22802
- * called the way it always was; adding a positional would have been a hard error before this
22803
- * ("Unexpected argument 'web'"), so nothing existing changes meaning. The per-server case is
22804
- * what the UI's Restart button has always done and the shell could not.
23097
+ * Read from `rawArgs` rather than the parsed args: citty fills a default in for the boolean flags
23098
+ * (`autostart` defaults to true), so the parsed object cannot tell "the caller said `--no-autostart`"
23099
+ * from "the caller said nothing".
22805
23100
  */
23101
+ function mentions(rawArgs, spellings) {
23102
+ return rawArgs.some((token) => {
23103
+ if (!token.startsWith("-")) return false;
23104
+ const name = token.includes("=") ? token.slice(0, token.indexOf("=")) : token;
23105
+ return spellings.includes(name);
23106
+ });
23107
+ }
22806
23108
  function restartCommand(entry) {
22807
23109
  return defineCommand({
22808
23110
  meta: { name: "restart" },
@@ -22823,10 +23125,12 @@ function restartCommand(entry) {
22823
23125
  description: "the workspace to act in (default: the panel's default workspace)"
22824
23126
  }
22825
23127
  },
22826
- run: async ({ args }) => {
23128
+ run: async ({ args, rawArgs }) => {
22827
23129
  const id = typeof args.id === "string" ? args.id.trim() : "";
22828
23130
  if (id.length > 0) {
22829
23131
  if (args.withPersistent === true) fail("restart <id> restarts one server — drop --with-persistent, or use it on a bare `restart`");
23132
+ const panelFlag = PANEL_ONLY_FLAGS.find((flag) => mentions(rawArgs, flag.spellings));
23133
+ if (panelFlag !== void 0) fail(`restart <id> restarts one server and takes no panel option — drop ${panelFlag.name}, or use it on a bare \`restart\``);
22830
23134
  await runServerAction("restart", id, typeof args.workspace === "string" ? args.workspace.trim() : void 0);
22831
23135
  return;
22832
23136
  }
@@ -22855,11 +23159,38 @@ async function startPersistentBack(stopped) {
22855
23159
  if (body.ok !== true) process.stderr.write(`${paint("31", "error")} ${workspaceId}/${serverId} did not come back: ${body.error ?? `the panel answered ${answer?.status}`}\n`);
22856
23160
  }
22857
23161
  }
23162
+ var PANEL_ONLY_FLAGS;
22858
23163
  var init_restart = __esmMin((() => {
22859
23164
  init_down();
22860
23165
  init_io();
22861
23166
  init_server();
22862
23167
  init_up();
23168
+ PANEL_ONLY_FLAGS = [
23169
+ {
23170
+ name: "--port",
23171
+ spellings: ["--port", "-p"]
23172
+ },
23173
+ {
23174
+ name: "--host",
23175
+ spellings: ["--host"]
23176
+ },
23177
+ {
23178
+ name: "--no-autostart",
23179
+ spellings: ["--no-autostart", "--autostart"]
23180
+ },
23181
+ {
23182
+ name: "--open",
23183
+ spellings: ["--open"]
23184
+ },
23185
+ {
23186
+ name: "--foreground",
23187
+ spellings: ["--foreground"]
23188
+ },
23189
+ {
23190
+ name: "--print-config",
23191
+ spellings: ["--print-config"]
23192
+ }
23193
+ ];
22863
23194
  }));
22864
23195
  //#endregion
22865
23196
  //#region src/cli/status.ts
@@ -23004,9 +23335,8 @@ async function runLogs(input) {
23004
23335
  const lines = parseLines(input.lines);
23005
23336
  if (input.follow === true) {
23006
23337
  const { followLog } = await Promise.resolve().then(() => (init_daemon_log(), daemon_log_exports));
23007
- const count = lines === 0 ? DEFAULT_LINES : lines;
23008
23338
  if (input.json !== true) {
23009
- await followLog(daemonLogPath, count, (chunk) => process.stdout.write(chunk));
23339
+ await followLog(daemonLogPath, lines, (chunk) => process.stdout.write(chunk));
23010
23340
  return;
23011
23341
  }
23012
23342
  const emit = (line) => {
@@ -23016,7 +23346,7 @@ async function runLogs(input) {
23016
23346
  })}\n`);
23017
23347
  };
23018
23348
  let pending = "";
23019
- await followLog(daemonLogPath, count, (chunk) => {
23349
+ await followLog(daemonLogPath, lines, (chunk) => {
23020
23350
  pending += chunk;
23021
23351
  const parts = pending.split("\n");
23022
23352
  pending = parts.pop() ?? "";
@@ -23212,6 +23542,7 @@ var init_set_token = __esmMin((() => {
23212
23542
  //#endregion
23213
23543
  //#region src/cli/setup-temp.ts
23214
23544
  var setup_temp_exports = /* @__PURE__ */ __exportAll({
23545
+ flagProblem: () => flagProblem,
23215
23546
  runSetupTemp: () => runSetupTemp,
23216
23547
  setupTempArgs: () => setupTempArgs,
23217
23548
  setupTempCommand: () => setupTempCommand,
@@ -23223,18 +23554,49 @@ function sourceFromFlags(flags) {
23223
23554
  if (flags.wsl === true) return "wsl";
23224
23555
  return null;
23225
23556
  }
23557
+ /**
23558
+ * The refusal for a flag set that cannot mean what it says, or `null`.
23559
+ *
23560
+ * `download` is a **modifier of `--wsl`**, not a command of its own: only the WSL2 branch fetches
23561
+ * anything, and the no-flag branch ends before a source is chosen. Left unreachable it was silently
23562
+ * dropped — `setup-temp --download` exited 0 having done nothing, which a script reads as
23563
+ * "installed" — so the flag is refused instead, naming the one it belongs to.
23564
+ *
23565
+ * `--clear` is the opposite request, so pairing it with either is refused rather than letting one
23566
+ * quietly win.
23567
+ */
23568
+ function flagProblem(flags) {
23569
+ const download = flags.download === void 0 ? null : flags.download === true ? "--download" : "--no-download";
23570
+ if (flags.clear === true) {
23571
+ if (download !== null) return `\`--clear\` and \`${download}\` ask for opposite things — clear the source, or set one up, not both`;
23572
+ if (flags.wsl === true) return "`--clear` and `--wsl` ask for opposite things — clear the source, or set one up, not both";
23573
+ return null;
23574
+ }
23575
+ if (download !== null && flags.wsl !== true) return `\`${download}\` only means something with \`--wsl\` — pass \`setup-temp --wsl ${download}\`, or drop it to read the state`;
23576
+ return null;
23577
+ }
23226
23578
  async function runSetupTemp(flags) {
23579
+ const problem = flagProblem(flags);
23580
+ if (problem !== null) fail(problem);
23227
23581
  const store = new GlobalSettingsStore(globalSettingsPath);
23228
23582
  store.load();
23229
23583
  const host = store.host;
23230
23584
  const configured = host.tempCommand.trim().length > 0;
23231
23585
  if (flags.clear === true) {
23232
- if (!configured) {
23586
+ const helper = wslScriptPath();
23587
+ const hadHelper = helper !== null && fs.existsSync(helper);
23588
+ if (configured) store.updateHost({ tempCommand: "" });
23589
+ removeWslTemperatureScript(helper);
23590
+ if (!configured && !hadHelper) {
23233
23591
  process.stdout.write("no temperature command is set — nothing to clear\n");
23234
23592
  return;
23235
23593
  }
23236
- store.updateHost({ tempCommand: "" });
23594
+ if (!configured) {
23595
+ process.stdout.write(`no temperature command is set — removed the leftover helper at ${dim(helper)}\n`);
23596
+ return;
23597
+ }
23237
23598
  process.stdout.write(`${green("temperature command cleared")} — the tile uses the built-in probe again\n`);
23599
+ if (hadHelper) process.stdout.write(` ${dim(`helper ${helper} deleted`)}\n`);
23238
23600
  return;
23239
23601
  }
23240
23602
  const source = sourceFromFlags(flags);
@@ -23261,11 +23623,7 @@ async function runSetupTemp(flags) {
23261
23623
  const command = tempCommandFor(scriptPath);
23262
23624
  process.stdout.write(` helper ${dim(`${scriptPath} (${windowsScriptPath(scriptPath)} on Windows)`)}\n`);
23263
23625
  const probe = await probeWslTemperature(command, 5e3);
23264
- if (probe.celsius === null) {
23265
- process.stdout.write(`${fail("not set up")} — the helper did not answer: ${probe.error ?? "unknown reason"}\n`);
23266
- process.stdout.write(`${dim(`the script is at ${scriptPath}; the config was left unchanged`)}\n`);
23267
- return;
23268
- }
23626
+ if (probe.celsius === null) fail(`not set up — the helper did not answer: ${probe.error ?? "unknown reason"}\n the script is at ${scriptPath}; the config was left unchanged`);
23269
23627
  store.updateHost({
23270
23628
  tempCommand: command,
23271
23629
  tempCommandTimeoutMs: 5e3
@@ -23293,10 +23651,7 @@ async function offerLibreHardwareMonitor(flags) {
23293
23651
  }
23294
23652
  }
23295
23653
  const result = await installLibreHardwareMonitor({ onProgress: (message) => process.stdout.write(` ${dim(message)}\n`) });
23296
- if (result.error !== null) {
23297
- process.stdout.write(`${fail("the download did not install")} — ${result.error}\n`);
23298
- return;
23299
- }
23654
+ if (result.error !== null) fail(`the download did not install — ${result.error}`);
23300
23655
  process.stdout.write(` library ${green("installed")} in ${result.dir}\n`);
23301
23656
  }
23302
23657
  var setupTempArgs, setupTempCommand;
@@ -23971,9 +24326,17 @@ async function uiUpdate(argv, io) {
23971
24326
  if (repo === null) throw new Error(`invalid --repo "${values.repo}" — expected an "owner/name" slug, e.g. ${DEFAULT_REPO}`);
23972
24327
  installed.repo = repoSlug(repo);
23973
24328
  }
24329
+ if (values.asset !== void 0) {
24330
+ const named = values.asset.trim();
24331
+ if (named.length === 0) throw new Error("--asset is empty — name the release asset to install, or drop the flag");
24332
+ installed.asset = named;
24333
+ }
23974
24334
  const order = values.old === true ? "older" : "newer";
23975
24335
  const repo = installed.repo === null ? null : parseRepoSlug(installed.repo);
23976
- if (values.tag !== void 0 && repo === null) throw new Error(["--tag needs a repository to fetch from, and this UI does not declare one", ` pass it: home-hosted ui-update --repo ${DEFAULT_REPO} --tag ${values.tag}`].join("\n"));
24336
+ if ((values.tag !== void 0 || values.asset !== void 0) && repo === null) {
24337
+ const flag = values.tag !== void 0 ? "--tag" : "--asset";
24338
+ throw new Error([`${flag} needs a repository to fetch from, and this UI does not declare one`, ` pass it: home-hosted ui-update --repo ${DEFAULT_REPO} ${flag} ${values[values.tag !== void 0 ? "tag" : "asset"]}`].join("\n"));
24339
+ }
23977
24340
  if (values.check === true && repo !== null) {
23978
24341
  if (isOwnRepo(repo)) {
23979
24342
  printCheck(io, installed, values.tag ?? `v${context.version}`);
@@ -23985,7 +24348,7 @@ async function uiUpdate(argv, io) {
23985
24348
  return;
23986
24349
  }
23987
24350
  if (values.tag !== void 0 && repo !== null) {
23988
- await installTag(repo, values.asset ?? installed.asset ?? null, values.tag, context);
24351
+ await installTag(repo, installed.asset, values.tag, context);
23989
24352
  return;
23990
24353
  }
23991
24354
  let releases = [];
@@ -24003,7 +24366,7 @@ async function uiUpdate(argv, io) {
24003
24366
  return;
24004
24367
  }
24005
24368
  io.write(`${io.style.bold(`${plan.identity.name} ${plan.identity.version ?? ""}`.trim())} is on ${plan.identity.tag ?? "an unknown tag"}; this panel is ${plan.target} — updating\n`);
24006
- await installTag(repo, plan.identity.asset ?? values.asset ?? null, plan.target, context);
24369
+ await installTag(repo, installed.asset, plan.target, context);
24007
24370
  return;
24008
24371
  }
24009
24372
  if (plan.kind !== "choice") return;
@@ -24150,6 +24513,7 @@ var init_ui_revert = __esmMin((() => {
24150
24513
  init_ui();
24151
24514
  uiRevertCommand = defineCommand({
24152
24515
  meta: { name: "ui-revert" },
24516
+ args: {},
24153
24517
  run: async () => {
24154
24518
  await runUiRevert();
24155
24519
  }
@@ -24485,7 +24849,7 @@ async function availableRowsFromDisk(action, suffix) {
24485
24849
  try {
24486
24850
  const { service } = await offlineBackup();
24487
24851
  await service.warm();
24488
- if (action === "create") return service.view().entries;
24852
+ if (action === "create") return service.selection().entries;
24489
24853
  const query = new URLSearchParams(suffix.startsWith("?") ? suffix.slice(1) : suffix);
24490
24854
  const from = query.get("from");
24491
24855
  const name = query.get("name");
@@ -24560,7 +24924,7 @@ async function runBackupList(json) {
24560
24924
  }
24561
24925
  const { service } = await offlineBackup();
24562
24926
  await service.warm();
24563
- printList(service.view(), json);
24927
+ printList(service.selection(), json);
24564
24928
  }
24565
24929
  function printList(view, json) {
24566
24930
  const files = view?.files ?? [];
@@ -24607,7 +24971,7 @@ async function runBackupCreate(options) {
24607
24971
  }
24608
24972
  const { service } = await offlineBackup();
24609
24973
  await service.warm();
24610
- return service.view().entries;
24974
+ return service.selection().entries;
24611
24975
  })();
24612
24976
  assertKnown(options.exclude, entries, "--exclude", "create");
24613
24977
  assertKnown(scope.kind === "include" ? scope.ids : void 0, entries, "--include", "create");
@@ -24694,14 +25058,18 @@ function planRefusal(plan) {
24694
25058
  return null;
24695
25059
  }
24696
25060
  /**
24697
- * The plan's refusals and per-item skips, as lines a person can act on.
25061
+ * A restore's per-item skips, as lines a person can act on.
24698
25062
  *
24699
25063
  * `skipped` is the same list the UI draws, and it is the only thing that says a piece of an
24700
25064
  * otherwise successful restore was left behind — an unreadable `servers.config.json`, a data path
24701
- * whose declaration changed. Printing only the applied count reported such a restore as complete.
25065
+ * whose declaration changed, a dump staged for an entry with no `load` hook. Printing only the
25066
+ * applied count reported such a restore as complete.
25067
+ *
25068
+ * Read from the outcome of the run that is being reported: the plan and the apply answer different
25069
+ * lists, because a skip such as a missing load hook is only known once the files have landed.
24702
25070
  */
24703
- function restoreNotes(plan) {
24704
- return plan?.skipped ?? [];
25071
+ function restoreNotes(outcome) {
25072
+ return outcome?.skipped ?? [];
24705
25073
  }
24706
25074
  async function runBackupRestore(options) {
24707
25075
  const scope = options.scope;
@@ -24831,7 +25199,7 @@ async function runBackupRestore(options) {
24831
25199
  }
24832
25200
  const applied = (outcome.items ?? []).filter((item) => item.selected !== false);
24833
25201
  const hooks = (outcome.hooks ?? []).filter((hook) => hook.action === "load");
24834
- const notes = restoreNotes(plan);
25202
+ const notes = restoreNotes(outcome);
24835
25203
  if (options.json) {
24836
25204
  process.stdout.write(`${JSON.stringify({
24837
25205
  action: "restore",
@@ -25019,8 +25387,7 @@ async function runNanny(spec, statePath) {
25019
25387
  if (spawned === null) pending = signal;
25020
25388
  else stopChild(spawned, signal);
25021
25389
  };
25022
- process.on("SIGTERM", () => onSignal("SIGTERM"));
25023
- process.on("SIGINT", () => onSignal("SIGINT"));
25390
+ for (const signal of NANNY_TRAPPED_SIGNALS) process.on(signal, () => onSignal(signal));
25024
25391
  const child = spawnManaged({
25025
25392
  command: spec.command,
25026
25393
  args: spec.args,
@@ -25251,8 +25618,8 @@ var SETUP_TEMP_SECTION = {
25251
25618
  heading: "Options for setup-temp",
25252
25619
  lines: [
25253
25620
  ["--wsl", "read the temperature through the Windows host (WSL2)"],
25254
- ["--download", "fetch LibreHardwareMonitor without asking (for a script)"],
25255
- ["--no-download", "never fetch it; report what is missing"],
25621
+ ["--download", "with --wsl: fetch LibreHardwareMonitor without asking (for a script)"],
25622
+ ["--no-download", "with --wsl: never fetch it; report what is missing"],
25256
25623
  ["--clear", "stop using the command and delete the helper"]
25257
25624
  ]
25258
25625
  };