viewable-one 0.12.3 → 0.12.4
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/CHANGELOG.md +32 -0
- package/glytch.mjs +8 -2
- package/lib/multiwatch.mjs +55 -7
- package/lib/restartPass.mjs +18 -5
- package/lib/runnerAdmission.mjs +27 -0
- package/lib/runnerApi.mjs +8 -1
- package/lib/runnerBeat.mjs +15 -1
- package/lib/runnerOps.mjs +10 -1
- package/lib/runnerRegister.mjs +2 -2
- package/lib/selfUninstall.mjs +239 -0
- package/lib/update.mjs +184 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -13,6 +13,37 @@ package.
|
|
|
13
13
|
|
|
14
14
|
## [Unreleased]
|
|
15
15
|
|
|
16
|
+
## [0.12.4] - 2026-11-09
|
|
17
|
+
|
|
18
|
+
### Added
|
|
19
|
+
|
|
20
|
+
- The computer app updates itself from the board's More menu (#4949). The
|
|
21
|
+
board's Update request reaches it on its heartbeat; it waits for running
|
|
22
|
+
runs, then installs. While an update waits or installs, no run starts,
|
|
23
|
+
including a recovered run in the restart pass (`runGate` in
|
|
24
|
+
`runnerAdmission.mjs`, used by `claimOne` and `restartPass`); the record
|
|
25
|
+
stays so a later pass or the restarted app carries it on.
|
|
26
|
+
- A take that failed with no answer may have won on the server, which
|
|
27
|
+
deletes the request. If the request is then gone, the update fails where
|
|
28
|
+
the user sees it ("Nothing was installed") instead of idling; Try again
|
|
29
|
+
files a new request. A failed read of update requests is reported in the
|
|
30
|
+
heartbeat (`updatesUnread`) and the computer keeps the request it holds
|
|
31
|
+
instead of reading the missing op as Cancel update.
|
|
32
|
+
- Remove uninstalls the computer app (#4951, #4978). It uninstalls only when
|
|
33
|
+
every key the computer holds reads removed for good, and never deletes the
|
|
34
|
+
Viewable folder. Removal evidence lives in `computer_removed_keys`, which
|
|
35
|
+
the OAuth cleanup does not delete, so a computer away past the 30-day
|
|
36
|
+
cleanup still hears it. A folder added again after an uninstall is not
|
|
37
|
+
uninstalled again.
|
|
38
|
+
- The uninstall request arrives within seconds: a database trigger sends an
|
|
39
|
+
`op` hint on the owner's live runner topics, and the bridge beats at once.
|
|
40
|
+
- On Linux and WSL the uninstall starts in its own `systemd-run --user
|
|
41
|
+
--collect` unit; on Windows it starts through WMI so Task Scheduler's end
|
|
42
|
+
of the job does not kill it. Both fall back to a plain detached child. The
|
|
43
|
+
launched script carries a curated environment with no tokens or keys.
|
|
44
|
+
- An online computer that does not take uninstall requests (older apps) keeps
|
|
45
|
+
the copy-a-prompt way, with the board-only Remove.
|
|
46
|
+
|
|
16
47
|
## [0.12.3] - 2026-11-09
|
|
17
48
|
|
|
18
49
|
### Fixed
|
|
@@ -60,6 +91,7 @@ package.
|
|
|
60
91
|
`--model`, because Claude Code refuses the OpenRouter id. Other ids pass
|
|
61
92
|
through unchanged (#3869). The fix reaches people with the next bridge
|
|
62
93
|
release.
|
|
94
|
+
|
|
63
95
|
## [0.12.2] - 2026-10-30
|
|
64
96
|
|
|
65
97
|
### Changed
|
package/glytch.mjs
CHANGED
|
@@ -50,7 +50,7 @@ import { readRegistry, registryPath, removeFolder, touchRegistry } from "./lib/r
|
|
|
50
50
|
import { settingsFromEnv, newRunnerId, registerAndFindProject } from "./lib/runner.mjs";
|
|
51
51
|
import { syncFolder, syncRegistry } from "./lib/sync.mjs";
|
|
52
52
|
import { SETUP_HEALTH_SLOW_MS, SETUP_HEALTH_WAIT_MS, hasFreshBeat, waitForRunnerHealth, writeRunnerHealth } from "./lib/runner-health.mjs";
|
|
53
|
-
import { initServiceScript, packageVersion, runUpdate } from "./lib/update.mjs";
|
|
53
|
+
import { initServiceScript, packageVersion, runUpdate, UPDATE_RESTART_EXIT_CODE } from "./lib/update.mjs";
|
|
54
54
|
import { initOptions, chooseAgents, readAgentSelection, saveAgentSelection } from "./lib/agent-selection.mjs";
|
|
55
55
|
import { projectMcpServerKey } from "./lib/project-mcp.mjs";
|
|
56
56
|
import { AGENT_CONNECT_HINT, agentLoginStep, personalBoardToken, signInStep } from "./lib/init-connect.mjs";
|
|
@@ -475,7 +475,13 @@ async function runner(args) {
|
|
|
475
475
|
log("stopping. Any session already running keeps going; it is a separate process.");
|
|
476
476
|
controller.abort();
|
|
477
477
|
});
|
|
478
|
-
await watchRegistered({ settings, signal: controller.signal, log });
|
|
478
|
+
const watched = await watchRegistered({ settings, signal: controller.signal, log });
|
|
479
|
+
// The board's Update installed a new version (#4949): exit nonzero so
|
|
480
|
+
// launchd, systemd and Task Scheduler each start the new code.
|
|
481
|
+
if (watched?.restart) {
|
|
482
|
+
log(`restarting on the new version`);
|
|
483
|
+
return UPDATE_RESTART_EXIT_CODE;
|
|
484
|
+
}
|
|
479
485
|
return null;
|
|
480
486
|
}
|
|
481
487
|
|
package/lib/multiwatch.mjs
CHANGED
|
@@ -50,7 +50,10 @@ import { makeHeartbeatHub, makeRegistrar, REGISTER_REFRESH_MS } from "./runnerPa
|
|
|
50
50
|
import { beatBaseMs, makeRunnerRealtime } from "./runnerRealtime.mjs";
|
|
51
51
|
import { sweepAll } from "./sweep.mjs";
|
|
52
52
|
import { syncFolder } from "./sync.mjs";
|
|
53
|
-
import { makeUpdateChecker, packageVersion } from "./update.mjs";
|
|
53
|
+
import { makeSelfUpdate, makeUpdateChecker, packageVersion } from "./update.mjs";
|
|
54
|
+
import { liveRuns } from "./restartPass.mjs";
|
|
55
|
+
import { activeRecoveryRunIds } from "./runnerRecovery.mjs";
|
|
56
|
+
import * as runnerApiModule from "./runnerApi.mjs";
|
|
54
57
|
|
|
55
58
|
export const SWEEP_INTERVAL_MS = 86_400_000;
|
|
56
59
|
/** How often the registry is re-read when the stat poll below tells us
|
|
@@ -74,11 +77,13 @@ const isDir = async (path) => {
|
|
|
74
77
|
/** Watch every registered folder until `signal` aborts.
|
|
75
78
|
*
|
|
76
79
|
* Returns {watched, missing} after signal-driven shutdown and after every
|
|
77
|
-
* folder's watch has ended. An empty registry still waits for new folders.
|
|
80
|
+
* folder's watch has ended. An empty registry still waits for new folders.
|
|
81
|
+
* `restart: true` means the board's Update installed a new version and the
|
|
82
|
+
* caller should exit so the service manager starts it (#4949). */
|
|
78
83
|
export async function watchRegistered({
|
|
79
84
|
env = process.env,
|
|
80
85
|
settings,
|
|
81
|
-
signal,
|
|
86
|
+
signal: outerSignal,
|
|
82
87
|
log = () => {},
|
|
83
88
|
folders,
|
|
84
89
|
sweep = sweepAll,
|
|
@@ -105,7 +110,14 @@ export async function watchRegistered({
|
|
|
105
110
|
// THE PUSH CHANNEL (#813), one per process. Injected for the tests, which
|
|
106
111
|
// pass a fake, or `() => null` for none (every 10 s, as before).
|
|
107
112
|
makeRealtime = makeRunnerRealtime,
|
|
113
|
+
// THE BOARD'S UPDATE BUTTON (#4949). Injected for the tests.
|
|
114
|
+
makeSelfUpdater = makeSelfUpdate,
|
|
108
115
|
} = {}) {
|
|
116
|
+
// An installed update stops every watcher the same way Ctrl-C does: each
|
|
117
|
+
// drains the runs it started (there are none by then) before it ends.
|
|
118
|
+
const restartStop = new AbortController();
|
|
119
|
+
const signal = outerSignal ? AbortSignal.any([outerSignal, restartStop.signal]) : restartStop.signal;
|
|
120
|
+
let restarting = false;
|
|
109
121
|
// An injected list is the whole list: a caller that says which folders to
|
|
110
122
|
// watch is not asking the registry anything, so the live re-read below
|
|
111
123
|
// stands down for it. Nothing in the package passes this; the tests do.
|
|
@@ -186,7 +198,43 @@ export async function watchRegistered({
|
|
|
186
198
|
// starting a detached dev server - the browser may be on another box
|
|
187
199
|
// entirely (lib/platform.mjs says why it is not `navigator`).
|
|
188
200
|
const health = makeRunnerHealth({ env, version: updater.state?.().version ?? packageVersion() });
|
|
189
|
-
|
|
201
|
+
// Every folder a beat has named, so the update can see each folder's
|
|
202
|
+
// recovered runs whose owner is gone but whose child processes are not.
|
|
203
|
+
const projects = new Map();
|
|
204
|
+
const activeRuns = async () => {
|
|
205
|
+
let count = liveRuns.size;
|
|
206
|
+
for (const project of projects.values()) {
|
|
207
|
+
for (const id of await activeRecoveryRunIds(project, settings ?? {}, { log })) if (!liveRuns.has(id)) count += 1;
|
|
208
|
+
}
|
|
209
|
+
return count;
|
|
210
|
+
};
|
|
211
|
+
const updateApi = settings?.runnerApi ?? runnerApiModule;
|
|
212
|
+
let askBeat = () => {};
|
|
213
|
+
const selfUpdater = makeSelfUpdater({
|
|
214
|
+
version: updater.state?.().version ?? packageVersion(),
|
|
215
|
+
activeRuns,
|
|
216
|
+
take: async (op) => {
|
|
217
|
+
const taken = await updateApi.updateTake({ projectId: op.project_id, requestId: op.id }, { env: settings?.env, fetchImpl: settings?.fetchImpl });
|
|
218
|
+
if (!taken?.ok) throw new Error(taken?.error ?? "Could not take the update request.");
|
|
219
|
+
return taken.taken === true;
|
|
220
|
+
},
|
|
221
|
+
onChange: () => askBeat(),
|
|
222
|
+
restart: async () => {
|
|
223
|
+
restarting = true;
|
|
224
|
+
restartStop.abort();
|
|
225
|
+
},
|
|
226
|
+
log,
|
|
227
|
+
});
|
|
228
|
+
const selfUpdate = {
|
|
229
|
+
request: (op) => selfUpdater.request(op),
|
|
230
|
+
seen: (project, ops) => {
|
|
231
|
+
if (project?.id) projects.set(project.id, project);
|
|
232
|
+
selfUpdater.seen(project, ops);
|
|
233
|
+
},
|
|
234
|
+
holdsRuns: () => selfUpdater.holdsRuns(),
|
|
235
|
+
claimStarted: () => selfUpdater.claimStarted(),
|
|
236
|
+
};
|
|
237
|
+
const markExtra = () => ({ ...platform, ...updater.mark(), ...probe.mark(), ...health.mark(), ...selfUpdater.mark() });
|
|
190
238
|
|
|
191
239
|
// ONE REGISTER AND ONE HEARTBEAT FOR THE WHOLE PROCESS (ticket e8,
|
|
192
240
|
// 2026-10-03; #616, 2026-10-16). Every folder's beat registers the whole
|
|
@@ -220,7 +268,7 @@ export async function watchRegistered({
|
|
|
220
268
|
// sharing one heartbeat (one `at` for all of them).
|
|
221
269
|
const beatAsks = new Set();
|
|
222
270
|
const beatRequests = { subscribe: (fn) => { beatAsks.add(fn); return () => beatAsks.delete(fn); } };
|
|
223
|
-
|
|
271
|
+
askBeat = () => {
|
|
224
272
|
const at = Date.now();
|
|
225
273
|
for (const fn of [...beatAsks]) fn(at);
|
|
226
274
|
};
|
|
@@ -265,7 +313,7 @@ export async function watchRegistered({
|
|
|
265
313
|
const entry = { controller, done: false, leaving: false };
|
|
266
314
|
let started;
|
|
267
315
|
try {
|
|
268
|
-
started = watchOne(folder, { ...settings, runnerId, realtime, onHealthy: (path) => health.beat(path), markExtra, registrar, heartbeats, beatRequests, refreshAgents: () => probe.once() }, {
|
|
316
|
+
started = watchOne(folder, { ...settings, runnerId, realtime, onHealthy: (path) => health.beat(path), markExtra, registrar, heartbeats, beatRequests, refreshAgents: () => probe.once(), selfUpdate }, {
|
|
269
317
|
signal: controller.signal,
|
|
270
318
|
log: (line) => log(`[${folder}] ${line}`),
|
|
271
319
|
});
|
|
@@ -411,5 +459,5 @@ export async function watchRegistered({
|
|
|
411
459
|
clearInterval(polling);
|
|
412
460
|
if (statWatching) unwatchFile(regPath, onRegistryStat);
|
|
413
461
|
}
|
|
414
|
-
return { watched, missing };
|
|
462
|
+
return { watched, missing, ...(restarting ? { restart: true } : {}) };
|
|
415
463
|
}
|
package/lib/restartPass.mjs
CHANGED
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
// local dead-owner evidence and transfer the original row through recovery.
|
|
11
11
|
|
|
12
12
|
import { hasRecoveryRecord, recoverLocalRun } from "./runnerRecovery.mjs";
|
|
13
|
+
import { runGate } from "./runnerAdmission.mjs";
|
|
13
14
|
import { randomUUID } from "node:crypto";
|
|
14
15
|
import { stat } from "node:fs/promises";
|
|
15
16
|
import * as runnerApiModule from "./runnerApi.mjs";
|
|
@@ -91,12 +92,24 @@ export async function restartPass(project, settings, { log = () => {}, now = Dat
|
|
|
91
92
|
return done;
|
|
92
93
|
}
|
|
93
94
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
95
|
+
// A recovered run is a run start like a claim: it waits while an update
|
|
96
|
+
// waits or installs (#4949 review). Its record stays, so a later pass, or
|
|
97
|
+
// the restarted computer app, carries it on; the loop below never ends a
|
|
98
|
+
// fenced row that still has its record.
|
|
99
|
+
const recoverable = startRun ? rows.filter(row => row.lease_generation && !liveRuns.has(row.id)) : [];
|
|
100
|
+
const endStart = recoverable.length ? runGate(settings.selfUpdate) : null;
|
|
101
|
+
if (recoverable.length && !endStart) {
|
|
102
|
+
log("restart pass: an update is waiting; recovered sessions start after it");
|
|
103
|
+
done.skipped.push(...recoverable.map((row) => row.id));
|
|
99
104
|
}
|
|
105
|
+
if (endStart) try {
|
|
106
|
+
for (const row of recoverable) {
|
|
107
|
+
try {
|
|
108
|
+
const recovered = await recoverLocalRun(project, row, settings, api, opts, log);
|
|
109
|
+
if (recovered) { startRun(recovered); done.resumed.push(row.id); }
|
|
110
|
+
} catch (error) { log(`[${row.id}] local recovery failed: ${error.message}`); }
|
|
111
|
+
}
|
|
112
|
+
} finally { setImmediate(endStart); }
|
|
100
113
|
// A fenced row whose record is still here belongs to a live owner or to a
|
|
101
114
|
// recovery that will try again; only a row nobody here can carry on ends.
|
|
102
115
|
const ours = (row) => !row.lease_generation || (!done.resumed.includes(row.id) && !hasRecoveryRecord(project, row.id, settings));
|
package/lib/runnerAdmission.mjs
CHANGED
|
@@ -7,8 +7,35 @@ import * as runnerApiModule from "./runnerApi.mjs";
|
|
|
7
7
|
|
|
8
8
|
const retryHint = (out) => (Number.isFinite(out.retryAfterMs) ? { retryAfterMs: out.retryAfterMs } : {});
|
|
9
9
|
|
|
10
|
+
/** The update gate every run start passes, a claim or a recovered run (#4949).
|
|
11
|
+
* null while an update waits or installs, so no run starts under it; else
|
|
12
|
+
* the call that says this start has settled. Until then the update counts
|
|
13
|
+
* it, so a request that comes while the start is on its way never installs
|
|
14
|
+
* under it. Call the returned function with setImmediate, after the run is
|
|
15
|
+
* in `liveRuns`. */
|
|
16
|
+
export function runGate(update) {
|
|
17
|
+
if (!update) return () => {};
|
|
18
|
+
if (update.claimStarted) return update.claimStarted();
|
|
19
|
+
return update.holdsRuns() ? null : () => {};
|
|
20
|
+
}
|
|
21
|
+
|
|
10
22
|
export async function claimOne(root, project, settings, { activeRunIds = [], log } = {}) {
|
|
11
23
|
const runnerApi = settings.runnerApi ?? runnerApiModule;
|
|
24
|
+
// An update waits for the runs going to end, so no new one starts (#4949).
|
|
25
|
+
const endClaim = runGate(settings.selfUpdate);
|
|
26
|
+
if (!endClaim) return { claimed: false, idle: true, detail: "An update is waiting for runs to finish." };
|
|
27
|
+
try {
|
|
28
|
+
return await claimAdmitted(root, project, settings, runnerApi, { activeRunIds, log });
|
|
29
|
+
} finally {
|
|
30
|
+
// Both callers start the run (runRequest adds it to `liveRuns` before its
|
|
31
|
+
// first await) in the continuation right after this settles. Microtasks
|
|
32
|
+
// run before setImmediate, so the update counts the run before it stops
|
|
33
|
+
// counting the claim.
|
|
34
|
+
setImmediate(endClaim);
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function claimAdmitted(root, project, settings, runnerApi, { activeRunIds, log }) {
|
|
12
39
|
const rowsOpts = { env: settings.env, fetchImpl: settings.fetchImpl };
|
|
13
40
|
const admission = await acquireAdmission(root);
|
|
14
41
|
if (!admission.ok) return { claimed: false, transient: true, detail: admission.detail };
|
package/lib/runnerApi.mjs
CHANGED
|
@@ -122,7 +122,7 @@ async function call(op, body = {}, options = {}) {
|
|
|
122
122
|
// below. A 401 and every refusal leave it unset.
|
|
123
123
|
return { ok: false, transient: true, error: `Could not reach ${url}: ${error instanceof Error ? error.message : String(error)}${cause ? ` (${cause})` : ""}` };
|
|
124
124
|
}
|
|
125
|
-
if (result.authError) return { ok: false, error: result.authError };
|
|
125
|
+
if (result.authError) return { ok: false, unauthorized: true, error: result.authError };
|
|
126
126
|
|
|
127
127
|
const { response, text, payload } = result;
|
|
128
128
|
if (!response.ok) {
|
|
@@ -144,6 +144,9 @@ async function call(op, body = {}, options = {}) {
|
|
|
144
144
|
return {
|
|
145
145
|
ok: false,
|
|
146
146
|
...(transient ? { transient: true } : {}),
|
|
147
|
+
// A refused key. Only a cue to ask the board whether Remove took it
|
|
148
|
+
// away (lib/selfUninstall.mjs); never proof on its own (#4978).
|
|
149
|
+
...(response.status === 401 ? { unauthorized: true } : {}),
|
|
147
150
|
...(wait !== undefined ? { retryAfterMs: wait } : {}),
|
|
148
151
|
error:
|
|
149
152
|
response.status === 401
|
|
@@ -317,5 +320,9 @@ export function computerAppsResult(body, options = {}) { return call("computerAp
|
|
|
317
320
|
export function folderReadTake(body, options = {}) { return call("folderReadTake", body, options); }
|
|
318
321
|
export function folderReadResult(body, options = {}) { return call("folderReadResult", body, options); }
|
|
319
322
|
|
|
323
|
+
/** Take the board's Update request once no run is going (#4949). Taking
|
|
324
|
+
* deletes it, so Cancel update and the take cannot both win. */
|
|
325
|
+
export function updateTake(body, options = {}) { return call("updateTake", body, options); }
|
|
326
|
+
|
|
320
327
|
/** Recover a locally proven dead owner without waiting for lease expiry. */
|
|
321
328
|
export function recover(body, options = {}) { return call("recover", body, options); }
|
package/lib/runnerBeat.mjs
CHANGED
|
@@ -18,6 +18,7 @@ import { createMemberPreviewTunnel } from "./memberPreview.mjs";
|
|
|
18
18
|
import { beatPace } from "./runnerPace.mjs";
|
|
19
19
|
import { resumeLateMessages } from "./lateResume.mjs";
|
|
20
20
|
import { serviceForgetOps, serviceRowOps } from "./runnerOps.mjs";
|
|
21
|
+
import { serviceUninstallOps, uninstallIfRemoved } from "./selfUninstall.mjs";
|
|
21
22
|
|
|
22
23
|
/** How soon the beat looks again for late messages: while one waits, and
|
|
23
24
|
* while none does (a pushed reply brings it forward either way). */
|
|
@@ -122,6 +123,14 @@ export function makeBeatLoop(w) {
|
|
|
122
123
|
settings.registrar.invalidate?.();
|
|
123
124
|
};
|
|
124
125
|
|
|
126
|
+
// A refused key is only a cue: the board decides whether Remove took it
|
|
127
|
+
// away while this computer was off (#4978, lib/selfUninstall.mjs).
|
|
128
|
+
const askIfRemoved = async (answer) => {
|
|
129
|
+
if (answer.unauthorized !== true) return;
|
|
130
|
+
try { await (settings.uninstallIfRemoved ?? uninstallIfRemoved)(settings, log); }
|
|
131
|
+
catch (error) { log(`uninstall check failed: ${error instanceof Error ? error.message : String(error)}`); }
|
|
132
|
+
};
|
|
133
|
+
|
|
125
134
|
// The Retry-After of the last beat that failed, for the beat's own pace.
|
|
126
135
|
let beatRetryAfterMs;
|
|
127
136
|
const runBeat = async () => {
|
|
@@ -134,6 +143,7 @@ export function makeBeatLoop(w) {
|
|
|
134
143
|
const reg = await registerAndFindProject(root, settings);
|
|
135
144
|
if (!reg.ok) {
|
|
136
145
|
log(`could not register with the board: ${reg.error}`);
|
|
146
|
+
await askIfRemoved(reg);
|
|
137
147
|
beatRetryAfterMs = reg.retryAfterMs;
|
|
138
148
|
return reg.transient ? "failed" : "steady";
|
|
139
149
|
}
|
|
@@ -152,6 +162,7 @@ export function makeBeatLoop(w) {
|
|
|
152
162
|
if (!beat.ok) {
|
|
153
163
|
clearRefusedProject(beat);
|
|
154
164
|
log(`heartbeat failed: ${beat.error}`);
|
|
165
|
+
await askIfRemoved(beat);
|
|
155
166
|
beatRetryAfterMs = beat.retryAfterMs;
|
|
156
167
|
return beat.transient ? "failed" : "steady";
|
|
157
168
|
}
|
|
@@ -172,6 +183,9 @@ export function makeBeatLoop(w) {
|
|
|
172
183
|
// Stops are run ids: another folder's in this set is never acted on.
|
|
173
184
|
for (const runId of beat.stops ?? []) stopped.add(runId);
|
|
174
185
|
let opsFailed = false;
|
|
186
|
+
// Remove on this online computer (#4951): it uninstalls itself, which
|
|
187
|
+
// stops this daemon in a moment, so nothing else on this beat starts.
|
|
188
|
+
if (serviceUninstallOps(ops, settings, log)) return "steady";
|
|
175
189
|
if (ops.length > 0) {
|
|
176
190
|
// FIRST, and it returns early: there is no point merging a worktree or
|
|
177
191
|
// standing a preview up for a folder that is leaving this machine.
|
|
@@ -191,7 +205,7 @@ export function makeBeatLoop(w) {
|
|
|
191
205
|
}
|
|
192
206
|
// Retry retained Look answers even though claimed requests are absent
|
|
193
207
|
// from later heartbeat operations. Forget above always takes priority.
|
|
194
|
-
try { opsFailed = !(await serviceRowOps(root, w.project, ops, settings, log)).ok || opsFailed; }
|
|
208
|
+
try { opsFailed = !(await serviceRowOps(root, w.project, ops, settings, log, { updatesUnread: beat.updatesUnread === true })).ok || opsFailed; }
|
|
195
209
|
catch (error) {
|
|
196
210
|
opsFailed = true;
|
|
197
211
|
log(`ops sweep failed: ${error instanceof Error ? error.message : String(error)}`);
|
package/lib/runnerOps.mjs
CHANGED
|
@@ -132,7 +132,7 @@ async function writeOpResult(runnerApi, opId, result, rowsOpts, log, { attempts
|
|
|
132
132
|
return last;
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
-
export async function serviceRowOps(root, project, ops, settings, log = () => {}) {
|
|
135
|
+
export async function serviceRowOps(root, project, ops, settings, log = () => {}, { updatesUnread = false } = {}) {
|
|
136
136
|
const runnerApi = settings.runnerApi ?? runnerApiModule;
|
|
137
137
|
const rowsOpts = { env: settings.env, fetchImpl: settings.fetchImpl };
|
|
138
138
|
// OVERRIDABLE SO A TEST DOES NOT PAY FOR A REAL BACKOFF: every other
|
|
@@ -141,7 +141,16 @@ export async function serviceRowOps(root, project, ops, settings, log = () => {}
|
|
|
141
141
|
// being the one delay a test cannot shorten.
|
|
142
142
|
const retryOpts = { attempts: settings.opResultAttempts ?? 3, delayMs: settings.opResultRetryMs ?? 500 };
|
|
143
143
|
let ok = await flushComputerApps(root, project, runnerApi, rowsOpts);
|
|
144
|
+
// THE BOARD'S UPDATE BUTTON (#4949). The update is the whole computer's,
|
|
145
|
+
// so it goes to the one self-updater the daemon holds; this folder's ops
|
|
146
|
+
// missing its request is Cancel update, unless the board could not read
|
|
147
|
+
// the requests this time: then nothing is known and the wait goes on.
|
|
148
|
+
if (!updatesUnread) settings.selfUpdate?.seen(project, ops ?? []);
|
|
144
149
|
for (const op of ops ?? []) {
|
|
150
|
+
if (op.kind === "update") {
|
|
151
|
+
settings.selfUpdate?.request(op);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
145
154
|
if (op.kind === "computer-apps") {
|
|
146
155
|
ok = await serviceComputerApps(root, project, op, runnerApi, rowsOpts, settings.lookForComputerApps) && ok;
|
|
147
156
|
continue;
|
package/lib/runnerRegister.mjs
CHANGED
|
@@ -41,7 +41,7 @@ export const presenceBody = (settings) => {
|
|
|
41
41
|
try { return statSync(path).isDirectory(); }
|
|
42
42
|
catch (error) { return error.code !== "ENOENT" && error.code !== "ENOTDIR"; }
|
|
43
43
|
});
|
|
44
|
-
return { ...rest, ...(availableFolders ? { availableFolders } : {}), planApproval: true, computerAppsLook: true, folderReads: true, ...(settings.noGit?.length ? { noGit: settings.noGit } : {}) };
|
|
44
|
+
return { ...rest, ...(availableFolders ? { availableFolders } : {}), planApproval: true, computerAppsLook: true, folderReads: true, uninstallRequests: true, ...(settings.noGit?.length ? { noGit: settings.noGit } : {}) };
|
|
45
45
|
};
|
|
46
46
|
|
|
47
47
|
/** Re-read the machine's folder list into `settings.projectPaths` before a
|
|
@@ -111,7 +111,7 @@ async function registerProject(root, settings, { readd = false, onlyRoot = false
|
|
|
111
111
|
// folder the same `registrar`, so the folders that beat inside one window
|
|
112
112
|
// share one call for the same folder list instead of each sending it.
|
|
113
113
|
const out = settings.registrar ? await settings.registrar.register(JSON.stringify(list), send) : await send();
|
|
114
|
-
if (!out.ok) return { ok: false, error: out.error, ...(readd ? { readdRequired: Boolean(readdForgottenAt) } : {}), ...(out.transient ? { transient: true } : {}), ...(Number.isFinite(out.retryAfterMs) ? { retryAfterMs: out.retryAfterMs } : {}) };
|
|
114
|
+
if (!out.ok) return { ok: false, error: out.error, ...(readd ? { readdRequired: Boolean(readdForgottenAt) } : {}), ...(out.transient ? { transient: true } : {}), ...(out.unauthorized ? { unauthorized: true } : {}), ...(Number.isFinite(out.retryAfterMs) ? { retryAfterMs: out.retryAfterMs } : {}) };
|
|
115
115
|
const mine = (out.projects ?? []).find((p) => p.path === root);
|
|
116
116
|
return { ok: true, projects: out.projects ?? [], myProjectId: mine?.id, runnerId };
|
|
117
117
|
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
// THE COMPUTER UNINSTALLS ITSELF (#4951, rulings #2885, #4977, #4978).
|
|
2
|
+
//
|
|
3
|
+
// Two ways in, and both end in the same `viewable uninstall --yes`:
|
|
4
|
+
//
|
|
5
|
+
// 1. Remove on an online computer. The app marks the computer's rows
|
|
6
|
+
// (`runner_computer_uninstall_request`) and board-runner hands this daemon
|
|
7
|
+
// an `uninstall` op on its next heartbeat. The board asked, over this
|
|
8
|
+
// computer's own signed-in channel, so it runs.
|
|
9
|
+
//
|
|
10
|
+
// 2. A computer removed while it was off ("Remove it from the board only")
|
|
11
|
+
// comes back and finds its board key refused. A refusal alone proves
|
|
12
|
+
// nothing: an expired token, a refresh that failed for a moment, a key
|
|
13
|
+
// revoked in Access tokens or a banned account all look the same from
|
|
14
|
+
// here. So it asks the board one question, `POST /oauth/removed`, about
|
|
15
|
+
// each key it holds, and runs only when every one of them gets a plain
|
|
16
|
+
// 200 `{removed: true}`. The board says yes only for a key that Remove
|
|
17
|
+
// took away (#4978). Anything else (a network failure, a 5xx, a 404 from
|
|
18
|
+
// an older board, odd JSON, `removed: false`) for any key leaves the
|
|
19
|
+
// computer exactly as it is.
|
|
20
|
+
//
|
|
21
|
+
// Every key, not the first yes: a sign-in with a personal key keeps the
|
|
22
|
+
// older OAuth pair beside it (auth.mjs login). If that older pair was
|
|
23
|
+
// taken away by an earlier Remove and the new personal key is later
|
|
24
|
+
// refused for another reason, the pair's yes alone would uninstall a
|
|
25
|
+
// computer nobody removed. Asking only about the refused key is not
|
|
26
|
+
// enough either: once the personal key is marked dead the daemon falls
|
|
27
|
+
// back to the old pair and sends its access token, and a refused refresh
|
|
28
|
+
// sends no key at all.
|
|
29
|
+
//
|
|
30
|
+
// `viewable uninstall` stops the background app, revokes the key and deletes
|
|
31
|
+
// ~/.glytch. It never touches the Viewable folder or its files: the folder
|
|
32
|
+
// steps only take out the config entries `viewable init` wrote.
|
|
33
|
+
//
|
|
34
|
+
// The uninstall runs outside this daemon, because stopping the background app
|
|
35
|
+
// is the second thing it does and that kills this daemon. A detached process
|
|
36
|
+
// group is enough on a Mac (launchctl unload ends the one process). It is not
|
|
37
|
+
// on Linux and WSL: systemd stops every process left in the service's cgroup,
|
|
38
|
+
// a detached child included, so the uninstall starts in its own transient
|
|
39
|
+
// unit (`systemd-run --user --collect`). Nor on Windows: Task Scheduler ends
|
|
40
|
+
// a task's whole job (`schtasks /end`), and Node never asks to break away from
|
|
41
|
+
// a job, so it starts through WMI (Win32_Process.Create), whose processes
|
|
42
|
+
// belong to no task. Either launcher falls back to the plain detached child
|
|
43
|
+
// when it is missing or refuses: on a machine where the daemon is not under
|
|
44
|
+
// systemd or Task Scheduler, that child survives anyway.
|
|
45
|
+
|
|
46
|
+
import { spawn } from "node:child_process";
|
|
47
|
+
import { createHash } from "node:crypto";
|
|
48
|
+
import { writeFileSync } from "node:fs";
|
|
49
|
+
import { tmpdir } from "node:os";
|
|
50
|
+
import { dirname, join, sep } from "node:path";
|
|
51
|
+
import { fileURLToPath } from "node:url";
|
|
52
|
+
|
|
53
|
+
import { appUrlFrom, readAuthFile } from "./auth.mjs";
|
|
54
|
+
|
|
55
|
+
const CLI_PATH = join(dirname(fileURLToPath(import.meta.url)), "..", "glytch.mjs");
|
|
56
|
+
/** How often a refused computer may ask the board whether it was removed. */
|
|
57
|
+
export const REMOVED_CHECK_EVERY_MS = 5 * 60_000;
|
|
58
|
+
const REMOVED_CHECK_TIMEOUT_MS = 15_000;
|
|
59
|
+
|
|
60
|
+
let started = false;
|
|
61
|
+
let lastCheckAt = -Infinity;
|
|
62
|
+
|
|
63
|
+
/** Test seam: forget this process's one-shot state. */
|
|
64
|
+
export function resetSelfUninstall() {
|
|
65
|
+
started = false;
|
|
66
|
+
lastCheckAt = -Infinity;
|
|
67
|
+
launch = Promise.resolve(null);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The board keys this computer holds: the stored pair or personal key, and
|
|
71
|
+
* the script key from the environment. */
|
|
72
|
+
export function heldCredentials(stored, env = process.env) {
|
|
73
|
+
const fromEnv = (env.VIEWABLE_BOARD_TOKEN ?? env.GLYTCH_BOARD_TOKEN)?.trim();
|
|
74
|
+
const tokens = [stored?.refreshToken, stored?.accessToken, stored?.oauthAccessToken, fromEnv];
|
|
75
|
+
return [...new Set(tokens.filter((token) => typeof token === "string" && token !== ""))];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const fingerprint = (tokens) => createHash("sha256").update(tokens.join("\n")).digest("hex");
|
|
79
|
+
|
|
80
|
+
/** Does the board say Remove took this computer's keys away? Only a plain
|
|
81
|
+
* `200 {removed: true}` for every key it holds counts. */
|
|
82
|
+
export async function credentialRemoved({ env = process.env, fetchImpl = fetch, stored } = {}) {
|
|
83
|
+
const auth = stored === undefined ? await readAuthFile(env) : stored;
|
|
84
|
+
const tokens = heldCredentials(auth, env);
|
|
85
|
+
if (tokens.length === 0) return { removed: false, reason: "no key on this computer" };
|
|
86
|
+
const appUrl = auth?.appUrl || appUrlFrom(undefined, env);
|
|
87
|
+
for (const token of tokens) {
|
|
88
|
+
let response;
|
|
89
|
+
try {
|
|
90
|
+
response = await fetchImpl(`${appUrl}/oauth/removed`, {
|
|
91
|
+
method: "POST",
|
|
92
|
+
headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" },
|
|
93
|
+
body: new URLSearchParams({ token }),
|
|
94
|
+
signal: AbortSignal.timeout(REMOVED_CHECK_TIMEOUT_MS),
|
|
95
|
+
});
|
|
96
|
+
} catch {
|
|
97
|
+
return { removed: false, reason: "the board could not be reached" };
|
|
98
|
+
}
|
|
99
|
+
if (response?.status !== 200) {
|
|
100
|
+
if (response?.status === 404) return { removed: false, reason: "this board cannot say yet" };
|
|
101
|
+
return { removed: false, reason: `the board answered ${response?.status ?? "nothing"}` };
|
|
102
|
+
}
|
|
103
|
+
let body;
|
|
104
|
+
try { body = JSON.parse(await response.text()); } catch { return { removed: false, reason: "the board's answer was unreadable" }; }
|
|
105
|
+
if (body === null || typeof body !== "object" || body.removed !== true) return { removed: false, reason: "a key was not removed" };
|
|
106
|
+
}
|
|
107
|
+
return { removed: true, tokens };
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Where the global npm package lives when this copy came from one. */
|
|
111
|
+
function globalPackageDir(cliPath) {
|
|
112
|
+
const marker = `${sep}node_modules${sep}viewable-one${sep}`;
|
|
113
|
+
return cliPath.includes(marker) ? cliPath.slice(0, cliPath.indexOf(marker) + marker.length - 1) : null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** What the uninstall needs from this daemon's environment. A launcher
|
|
117
|
+
* outside this process (a systemd unit, WMI) starts it with the user's
|
|
118
|
+
* default environment instead, so the script carries these itself. Keys and
|
|
119
|
+
* tokens stay out: the uninstall reads the stored sign-in from the home. */
|
|
120
|
+
export function carriedEnv(env = process.env) {
|
|
121
|
+
const keep = /^(HOME|PATH|USERPROFILE|APPDATA|LOCALAPPDATA|TMPDIR|TEMP|TMP|XDG_[A-Z_]+|(VIEWABLE|GLYTCH)_[A-Z0-9_]+)$/;
|
|
122
|
+
const secret = /TOKEN|SECRET|KEY|PASSWORD/i;
|
|
123
|
+
return Object.fromEntries(Object.entries(env).filter(([name, value]) => typeof value === "string" && keep.test(name) && !secret.test(name)));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The detached command: `viewable uninstall --yes`, then, only when it
|
|
127
|
+
* finished and this copy is the global npm package, `npm uninstall -g`. */
|
|
128
|
+
export function selfUninstallCommand({ execPath = process.execPath, cliPath = CLI_PATH, env = process.env } = {}) {
|
|
129
|
+
const npm = globalPackageDir(cliPath) ? join(dirname(execPath), process.platform === "win32" ? "npm.cmd" : "npm") : null;
|
|
130
|
+
const script = [
|
|
131
|
+
'const { spawnSync } = require("node:child_process");',
|
|
132
|
+
`const env = { ...process.env, ...${JSON.stringify(carriedEnv(env))} };`,
|
|
133
|
+
`const done = spawnSync(process.execPath, [${JSON.stringify(cliPath)}, "uninstall", "--yes"], { stdio: "ignore", env });`,
|
|
134
|
+
npm ? `if (done.status === 0) spawnSync(${JSON.stringify(npm)}, ["uninstall", "-g", "viewable-one"], { stdio: "ignore", env, shell: process.platform === "win32" });` : "",
|
|
135
|
+
].join("\n");
|
|
136
|
+
return { command: execPath, args: ["-e", script], script };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** The launcher that starts `command` outside this daemon's service, or null
|
|
140
|
+
* where a detached child already outlives it (macOS). */
|
|
141
|
+
export function outsideServiceLauncher(command, { platform = process.platform, dir = tmpdir(), writeFile = writeFileSync } = {}) {
|
|
142
|
+
if (platform === "linux") {
|
|
143
|
+
return { command: "systemd-run", args: ["--user", "--collect", "--quiet", "--", command.command, ...command.args] };
|
|
144
|
+
}
|
|
145
|
+
if (platform === "win32") {
|
|
146
|
+
// WMI takes one command line; a script file keeps it free of quoting.
|
|
147
|
+
const file = join(dir, `viewable-uninstall-${process.pid}.cjs`);
|
|
148
|
+
writeFile(file, command.script ?? "");
|
|
149
|
+
const quoted = (value) => `"${value}"`;
|
|
150
|
+
const line = `${quoted(command.command)} ${quoted(file)}`.replaceAll("'", "''");
|
|
151
|
+
return {
|
|
152
|
+
command: "powershell.exe",
|
|
153
|
+
args: ["-NoProfile", "-NonInteractive", "-Command",
|
|
154
|
+
`$r = Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{ CommandLine = '${line}'; CurrentDirectory = '${dir.replaceAll("'", "''")}' }; exit $r.ReturnValue`],
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const LAUNCH_TIMEOUT_MS = 20_000;
|
|
161
|
+
|
|
162
|
+
/** Run a launcher and wait for it to say it started the uninstall. */
|
|
163
|
+
function launched(launcher, { env, spawnFn, timeoutMs = LAUNCH_TIMEOUT_MS }) {
|
|
164
|
+
return new Promise((resolve) => {
|
|
165
|
+
let child;
|
|
166
|
+
try {
|
|
167
|
+
child = spawnFn(launcher.command, launcher.args, { env, cwd: tmpdir(), stdio: "ignore", windowsHide: true });
|
|
168
|
+
} catch { resolve(false); return; }
|
|
169
|
+
if (!child?.once) { resolve(false); return; }
|
|
170
|
+
const timer = setTimeout(() => { child.kill?.(); resolve(false); }, timeoutMs);
|
|
171
|
+
timer.unref?.();
|
|
172
|
+
child.once("error", () => { clearTimeout(timer); resolve(false); });
|
|
173
|
+
child.once("exit", (code) => { clearTimeout(timer); resolve(code === 0); });
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** The plain detached child. Throws when it cannot start. */
|
|
178
|
+
function spawnDetached(command, { env, spawnFn }) {
|
|
179
|
+
const child = spawnFn(command.command, command.args, { env, cwd: tmpdir(), detached: true, stdio: "ignore", windowsHide: true });
|
|
180
|
+
child?.unref?.();
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Start the uninstall once per process. Returns whether this call started
|
|
184
|
+
* it; on Linux, WSL and Windows the launch finishes in the background
|
|
185
|
+
* (`selfUninstallLaunch()` resolves to how it started). */
|
|
186
|
+
let launch = Promise.resolve(null);
|
|
187
|
+
export const selfUninstallLaunch = () => launch;
|
|
188
|
+
|
|
189
|
+
export function startSelfUninstall({ env = process.env, spawnFn = spawn, log = () => {}, why, platform = process.platform, command = selfUninstallCommand({ env }), launcher } = {}) {
|
|
190
|
+
if (started) return false;
|
|
191
|
+
started = true;
|
|
192
|
+
log(`uninstall: ${why} - uninstalling Viewable from this computer. Your Viewable folder and its files stay.`);
|
|
193
|
+
const failed = (error) => {
|
|
194
|
+
started = false;
|
|
195
|
+
log(`uninstall: could not start: ${error instanceof Error ? error.message : String(error)}`);
|
|
196
|
+
};
|
|
197
|
+
let outside = null;
|
|
198
|
+
try { outside = launcher === undefined ? outsideServiceLauncher(command, { platform }) : launcher; }
|
|
199
|
+
catch (error) { log(`uninstall: ${error instanceof Error ? error.message : String(error)}; starting it here`); }
|
|
200
|
+
if (outside === null) {
|
|
201
|
+
try { spawnDetached(command, { env, spawnFn }); launch = Promise.resolve("detached"); return true; }
|
|
202
|
+
catch (error) { failed(error); launch = Promise.resolve(null); return false; }
|
|
203
|
+
}
|
|
204
|
+
launch = launched(outside, { env, spawnFn }).then((ok) => {
|
|
205
|
+
if (ok) return outside.command;
|
|
206
|
+
log(`uninstall: ${outside.command} did not start it; starting it here`);
|
|
207
|
+
try { spawnDetached(command, { env, spawnFn }); return "detached"; }
|
|
208
|
+
catch (error) { failed(error); return null; }
|
|
209
|
+
});
|
|
210
|
+
return true;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** An `uninstall` op on this beat: the board's Remove on an online computer. */
|
|
214
|
+
export function serviceUninstallOps(ops, settings = {}, log = () => {}) {
|
|
215
|
+
if (!(ops ?? []).some((op) => op?.kind === "uninstall")) return false;
|
|
216
|
+
if (started) return true;
|
|
217
|
+
return startSelfUninstall({ env: settings.env ?? process.env, spawnFn: settings.spawnFn, platform: settings.platform, log, why: "the board asked (Remove in Settings)" });
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** After the board refused this computer's key: ask whether Remove took its
|
|
221
|
+
* keys away, at most once every few minutes, and uninstall only on a yes
|
|
222
|
+
* for every key that is still on file. */
|
|
223
|
+
export async function uninstallIfRemoved(settings = {}, log = () => {}, { now = Date.now } = {}) {
|
|
224
|
+
if (started) return { started: false, reason: "already uninstalling" };
|
|
225
|
+
const at = now();
|
|
226
|
+
if (at - lastCheckAt < REMOVED_CHECK_EVERY_MS) return { started: false, reason: "asked a moment ago" };
|
|
227
|
+
lastCheckAt = at;
|
|
228
|
+
const env = settings.env ?? process.env;
|
|
229
|
+
const fetchImpl = settings.fetchImpl ?? fetch;
|
|
230
|
+
const stored = await readAuthFile(env);
|
|
231
|
+
const answer = await credentialRemoved({ env, fetchImpl, stored });
|
|
232
|
+
if (!answer.removed) return { started: false, reason: answer.reason };
|
|
233
|
+
// A new sign-in while the question was out wins: never uninstall a computer
|
|
234
|
+
// that has just been connected again.
|
|
235
|
+
const current = heldCredentials(await readAuthFile(env), env);
|
|
236
|
+
if (current.length === 0 || fingerprint(current) !== fingerprint(answer.tokens)) return { started: false, reason: "the key changed while asking" };
|
|
237
|
+
const ok = startSelfUninstall({ env, spawnFn: settings.spawnFn, platform: settings.platform, log, why: "this computer was removed from the board while it was away" });
|
|
238
|
+
return { started: ok, reason: ok ? "removed" : "could not start" };
|
|
239
|
+
}
|
package/lib/update.mjs
CHANGED
|
@@ -300,3 +300,187 @@ export async function runUpdate({
|
|
|
300
300
|
log(`Viewable ${latest} is installed. Your computer restarted and has a fresh connection.`);
|
|
301
301
|
return { ok: true, version: latest };
|
|
302
302
|
}
|
|
303
|
+
|
|
304
|
+
// ---------------------------------------------------------------------------
|
|
305
|
+
// THE BOARD'S UPDATE BUTTON (#4949). The person presses Update in More; the
|
|
306
|
+
// app files a `runner_update_requests` row; the heartbeat hands this process
|
|
307
|
+
// an `update` op. From then on new runs wait (claims are held), and nothing
|
|
308
|
+
// happens to a run already going. Once no run and no run's child process is
|
|
309
|
+
// left, the request is TAKEN (an atomic delete on the server, so Cancel update
|
|
310
|
+
// and the take cannot both win), the new version installs in place, and this
|
|
311
|
+
// process exits with UPDATE_RESTART_EXIT_CODE. The service the computer
|
|
312
|
+
// already has starts it again on the new code: launchd KeepAlive and systemd
|
|
313
|
+
// Restart=always on any exit, Windows' RestartOnFailure on a nonzero one.
|
|
314
|
+
// Restarting the service from in here would kill the process doing the
|
|
315
|
+
// restart halfway (see multiwatch's `daemon: true`), so this never does.
|
|
316
|
+
//
|
|
317
|
+
// The daily check above stays a notice: nothing installs unless a person
|
|
318
|
+
// pressed Update for this computer.
|
|
319
|
+
|
|
320
|
+
/** Nonzero on purpose: Task Scheduler restarts only a failed task. */
|
|
321
|
+
export const UPDATE_RESTART_EXIT_CODE = 75;
|
|
322
|
+
const UPDATE_POLL_MS = 2_000;
|
|
323
|
+
|
|
324
|
+
const readPackageVersion = async (path) => JSON.parse(readFileSync(path, "utf8")).version;
|
|
325
|
+
|
|
326
|
+
/** Install the latest in place, for the running service to pick up when it
|
|
327
|
+
* restarts. Refuses BEFORE installing when npm's global copy is not the one
|
|
328
|
+
* this process runs (npx, Volta, a second prefix): installing elsewhere would
|
|
329
|
+
* change nothing, and the copy prompt still covers that computer. */
|
|
330
|
+
export async function installUpdate({
|
|
331
|
+
env = process.env, platform = process.platform, exec = execNpm, version = packageVersion(),
|
|
332
|
+
scriptPath = fileURLToPath(new URL("../glytch.mjs", import.meta.url)),
|
|
333
|
+
resolvePath = realpath, readVersion = readPackageVersion, log = () => {},
|
|
334
|
+
} = {}) {
|
|
335
|
+
const failure = (error) => ({ ok: false, error });
|
|
336
|
+
if (noDaemonInstall(env)) return failure("Updates are turned off on this computer.");
|
|
337
|
+
const npm = (args, options) => exec(args, { env, platform, ...options });
|
|
338
|
+
const latest = await latestFromNpm({ exec: npm });
|
|
339
|
+
if (!latest) return failure("Could not reach npm to find the new version.");
|
|
340
|
+
if (compareVersions(latest, version) <= 0) return { ok: true, version, restart: false };
|
|
341
|
+
const root = await npm(["root", "-g"]);
|
|
342
|
+
if (!root?.ok || !root.stdout.trim()) return failure("Could not find where npm installs Viewable.");
|
|
343
|
+
const path = platform === "win32" ? win32 : { join };
|
|
344
|
+
const installedScript = path.join(root.stdout.trim(), PACKAGE_NAME, "glytch.mjs");
|
|
345
|
+
const same = await Promise.all([resolvePath(installedScript), resolvePath(scriptPath)])
|
|
346
|
+
.then(([a, b]) => a === b, () => false);
|
|
347
|
+
if (!same) return failure("This computer runs Viewable from another folder, so it cannot update itself.");
|
|
348
|
+
log(`update: installing Viewable ${latest}…`);
|
|
349
|
+
const installed = await npm(["install", "-g", `${PACKAGE_NAME}@${latest}`, "--force"], { timeoutMs: 180_000 });
|
|
350
|
+
if (!installed?.ok) return failure("Installation failed. Nothing was restarted.");
|
|
351
|
+
const found = await readVersion(path.join(root.stdout.trim(), PACKAGE_NAME, "package.json")).catch(() => null);
|
|
352
|
+
if (found !== latest) return failure(`Installed, but the version reads ${found ?? "nothing"}, not ${latest}. Nothing was restarted.`);
|
|
353
|
+
return { ok: true, version: latest, restart: true };
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/** One per computer app process: every folder's beat shares it.
|
|
357
|
+
*
|
|
358
|
+
* `activeRuns()` counts this process's runs AND recovery records whose child
|
|
359
|
+
* processes are still alive (runnerRecovery's own journal, not a second run
|
|
360
|
+
* tracker), so the restart comes only after the last child ends. */
|
|
361
|
+
export function makeSelfUpdate({
|
|
362
|
+
version = packageVersion(), activeRuns = async () => 0, take = async () => false,
|
|
363
|
+
install = (options) => installUpdate({ version, ...options }), restart = async () => {},
|
|
364
|
+
onChange = () => {}, log = () => {}, pollMs = UPDATE_POLL_MS,
|
|
365
|
+
after = setTimeout, cancel = clearTimeout,
|
|
366
|
+
} = {}) {
|
|
367
|
+
/** idle | waiting {request, runs, taken} | updating {to} | failed {error} */
|
|
368
|
+
let state = { name: "idle" };
|
|
369
|
+
let timer = null;
|
|
370
|
+
let checking = null;
|
|
371
|
+
// Claims that passed the gate before the update was asked for. Their run
|
|
372
|
+
// may not be counted by `activeRuns()` yet, so nothing installs until each
|
|
373
|
+
// one has settled and its run, if any, is counted (#4949 review).
|
|
374
|
+
let claims = 0;
|
|
375
|
+
// A take whose answer has not come back. The server deleted the request
|
|
376
|
+
// when it took it, so a heartbeat in between no longer lists it; the take's
|
|
377
|
+
// answer decides, not that heartbeat (#4949 review).
|
|
378
|
+
let taking = false;
|
|
379
|
+
// A take that failed with no answer may have won on the server, which
|
|
380
|
+
// deleted the request. If the request is then gone, nobody can tell a
|
|
381
|
+
// lost win from Cancel update, so it fails where the user can see it
|
|
382
|
+
// rather than vanishing; Try again files a new one (#4949 review).
|
|
383
|
+
let takeUnknown = false;
|
|
384
|
+
const lostTake = () => {
|
|
385
|
+
takeUnknown = false;
|
|
386
|
+
log("update: the board stopped answering while the update was taken; nothing was installed");
|
|
387
|
+
set({ name: "failed", error: "The board stopped answering while the update started. Nothing was installed." });
|
|
388
|
+
};
|
|
389
|
+
const holds = () => state.name === "waiting" || state.name === "updating";
|
|
390
|
+
const set = (next) => {
|
|
391
|
+
const before = JSON.stringify(view());
|
|
392
|
+
state = next;
|
|
393
|
+
if (JSON.stringify(view()) !== before) onChange();
|
|
394
|
+
};
|
|
395
|
+
const view = () => {
|
|
396
|
+
if (state.name === "waiting") return { state: "waiting", runs: state.runs ?? 0 };
|
|
397
|
+
if (state.name === "updating") return { state: "updating", ...(state.to ? { to: state.to } : {}) };
|
|
398
|
+
if (state.name === "failed") return { state: "failed", error: state.error };
|
|
399
|
+
return undefined;
|
|
400
|
+
};
|
|
401
|
+
const schedule = () => {
|
|
402
|
+
if (timer || state.name !== "waiting") return;
|
|
403
|
+
timer = after(() => { timer = null; void check(); }, pollMs);
|
|
404
|
+
timer?.unref?.();
|
|
405
|
+
};
|
|
406
|
+
const runOnce = async () => {
|
|
407
|
+
if (state.name !== "waiting") return;
|
|
408
|
+
let runs;
|
|
409
|
+
try { runs = await activeRuns(); }
|
|
410
|
+
catch (error) { log(`update: cannot tell whether runs are going (${error.message}); waiting`); return; }
|
|
411
|
+
if (state.name !== "waiting") return;
|
|
412
|
+
if (runs + claims > 0) { set({ ...state, runs: runs + claims }); return; }
|
|
413
|
+
if (!state.taken) {
|
|
414
|
+
let taken = false;
|
|
415
|
+
taking = true;
|
|
416
|
+
try { taken = await take(state.request); }
|
|
417
|
+
catch (error) { takeUnknown = true; log(`update: could not take the request (${error.message}); trying again`); return; }
|
|
418
|
+
finally { taking = false; }
|
|
419
|
+
if (state.name !== "waiting") return;
|
|
420
|
+
if (!taken && takeUnknown) { lostTake(); return; }
|
|
421
|
+
if (!taken) { log("update: the request was cancelled or already taken"); set({ name: "idle" }); return; }
|
|
422
|
+
takeUnknown = false;
|
|
423
|
+
state = { ...state, taken: true };
|
|
424
|
+
}
|
|
425
|
+
// A claim in flight when the request came may have started a run, or may
|
|
426
|
+
// still be on its way. Read both again right before installing.
|
|
427
|
+
const late = (await activeRuns().catch(() => 1)) + claims;
|
|
428
|
+
if (state.name !== "waiting") return;
|
|
429
|
+
if (late > 0) { set({ ...state, runs: late }); return; }
|
|
430
|
+
set({ name: "updating" });
|
|
431
|
+
let result;
|
|
432
|
+
try { result = await install({ log }); }
|
|
433
|
+
catch (error) { result = { ok: false, error: `Installation failed: ${error.message}` }; }
|
|
434
|
+
if (!result?.ok) {
|
|
435
|
+
log(`update: ${result?.error ?? "failed"}; the old version keeps running`);
|
|
436
|
+
set({ name: "failed", error: result?.error ?? "The update failed." });
|
|
437
|
+
return;
|
|
438
|
+
}
|
|
439
|
+
if (!result.restart) { log(`update: already on ${result.version ?? version}`); set({ name: "idle" }); return; }
|
|
440
|
+
set({ name: "updating", to: result.version });
|
|
441
|
+
log(`update: Viewable ${result.version} installed; restarting on it`);
|
|
442
|
+
await restart();
|
|
443
|
+
};
|
|
444
|
+
const check = () => {
|
|
445
|
+
checking ??= runOnce().finally(() => { checking = null; schedule(); });
|
|
446
|
+
return checking;
|
|
447
|
+
};
|
|
448
|
+
return {
|
|
449
|
+
/** An `update` op off a heartbeat. A second press while waiting is the
|
|
450
|
+
* same request; a press after a failure is Try again. */
|
|
451
|
+
request(op) {
|
|
452
|
+
if (!op?.id) return;
|
|
453
|
+
if (state.name === "waiting" && state.request.id === op.id) return;
|
|
454
|
+
if (state.name === "updating" || (state.name === "waiting" && (state.taken || taking))) return;
|
|
455
|
+
log(`update: asked for from the board`);
|
|
456
|
+
takeUnknown = false;
|
|
457
|
+
set({ name: "waiting", request: op, runs: state.name === "waiting" ? state.runs : 0, taken: false });
|
|
458
|
+
void check();
|
|
459
|
+
},
|
|
460
|
+
/** This folder's heartbeat ops. Its untaken request missing from them is
|
|
461
|
+
* Cancel update. Another folder's beat says nothing about it. */
|
|
462
|
+
seen(project, ops) {
|
|
463
|
+
const projectId = typeof project === "string" ? project : project?.id;
|
|
464
|
+
if (state.name !== "waiting" || state.taken || taking || state.request.project_id !== projectId) return;
|
|
465
|
+
if ((ops ?? []).some((op) => op.kind === "update" && op.id === state.request.id)) return;
|
|
466
|
+
if (timer) { cancel(timer); timer = null; }
|
|
467
|
+
if (takeUnknown) { lostTake(); return; }
|
|
468
|
+
log("update: cancelled from the board");
|
|
469
|
+
set({ name: "idle" });
|
|
470
|
+
},
|
|
471
|
+
/** New runs wait while an update is asked for or installing. */
|
|
472
|
+
holdsRuns: holds,
|
|
473
|
+
/** The claim gate and its count in one step: null while runs are held,
|
|
474
|
+
* else the call that says this claim has settled and its run, if any,
|
|
475
|
+
* is counted by `activeRuns()`. */
|
|
476
|
+
claimStarted() {
|
|
477
|
+
if (holds()) return null;
|
|
478
|
+
claims += 1;
|
|
479
|
+
let ended = false;
|
|
480
|
+
return () => { if (!ended) { ended = true; claims -= 1; } };
|
|
481
|
+
},
|
|
482
|
+
/** Beside `version` in the presence the app reads. */
|
|
483
|
+
mark: () => ({ updateRequests: true, ...(view() ? { update: view() } : {}) }),
|
|
484
|
+
check,
|
|
485
|
+
};
|
|
486
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "viewable-one",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.4",
|
|
4
4
|
"description": "Run coding agents from the Viewable board. Connects your machine to app.viewable.one, launches a session in its own worktree when you press Run, and streams what it does back to the canvas.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"mcp",
|