viewable-one 0.12.2 → 0.12.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +2 -2
  3. package/SPAWN.md +107 -53
  4. package/glytch.mjs +41 -10
  5. package/lib/acp.mjs +110 -148
  6. package/lib/admission.mjs +25 -5
  7. package/lib/agents.mjs +59 -16
  8. package/lib/answerTag.mjs +47 -0
  9. package/lib/atomic.mjs +1 -16
  10. package/lib/auth.mjs +25 -9
  11. package/lib/boardside.mjs +28 -12
  12. package/lib/child.mjs +89 -116
  13. package/lib/claudeModels.mjs +168 -0
  14. package/lib/codex-rpc.mjs +2 -2
  15. package/lib/codex.mjs +43 -63
  16. package/lib/codexApps.mjs +5 -3
  17. package/lib/codexToolInputs.mjs +98 -22
  18. package/lib/codingChecks.mjs +8 -4
  19. package/lib/conversationRules.mjs +46 -6
  20. package/lib/detect.mjs +14 -23
  21. package/lib/devserver.mjs +6 -6
  22. package/lib/doctor.mjs +4 -2
  23. package/lib/folderReads.mjs +96 -0
  24. package/lib/followUps.mjs +170 -0
  25. package/lib/hosted.mjs +13 -4
  26. package/lib/init-connect.mjs +29 -10
  27. package/lib/lateResume.mjs +135 -0
  28. package/lib/logindaemon.mjs +113 -33
  29. package/lib/mcpjson.mjs +35 -2
  30. package/lib/multiwatch.mjs +25 -38
  31. package/lib/pagePictures.mjs +14 -11
  32. package/lib/paths.mjs +0 -1
  33. package/lib/permissionAsk.mjs +341 -58
  34. package/lib/procs.mjs +73 -2
  35. package/lib/refusal.mjs +0 -2
  36. package/lib/restartPass.mjs +39 -11
  37. package/lib/rowsAnswers.mjs +18 -34
  38. package/lib/rowsEvents.mjs +20 -2
  39. package/lib/runner-health.mjs +26 -2
  40. package/lib/runner.mjs +106 -1363
  41. package/lib/runnerAdmission.mjs +6 -12
  42. package/lib/runnerApi.mjs +20 -11
  43. package/lib/runnerBeat.mjs +384 -0
  44. package/lib/runnerCompletion.mjs +5 -2
  45. package/lib/runnerExecute.mjs +227 -0
  46. package/lib/runnerGates.mjs +338 -0
  47. package/lib/runnerLaunch.mjs +351 -0
  48. package/lib/runnerLease.mjs +31 -9
  49. package/lib/runnerOps.mjs +217 -0
  50. package/lib/runnerPace.mjs +10 -6
  51. package/lib/runnerRecovery.mjs +457 -0
  52. package/lib/runnerRegister.mjs +28 -7
  53. package/lib/runnerSettlement.mjs +29 -9
  54. package/lib/spawn.mjs +0 -5
  55. package/lib/sync.mjs +26 -14
  56. package/lib/viewableFolder.mjs +8 -2
  57. package/lib/worktree.mjs +66 -13
  58. package/lib/writePolicy.mjs +90 -10
  59. package/package.json +1 -1
@@ -1,30 +1,25 @@
1
1
  /** Admission requires durable completion delivery and a free slot. */
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { acquireAdmission } from "./admission.mjs";
4
+ import { runningRoom } from "./runnerRecovery.mjs";
4
5
  import { flushCompletions } from "./runnerSettlement.mjs";
5
6
  import * as runnerApiModule from "./runnerApi.mjs";
6
7
 
7
8
  const retryHint = (out) => (Number.isFinite(out.retryAfterMs) ? { retryAfterMs: out.retryAfterMs } : {});
8
9
 
9
- export async function claimOne(root, project, settings) {
10
+ export async function claimOne(root, project, settings, { activeRunIds = [], log } = {}) {
10
11
  const runnerApi = settings.runnerApi ?? runnerApiModule;
11
12
  const rowsOpts = { env: settings.env, fetchImpl: settings.fetchImpl };
12
13
  const admission = await acquireAdmission(root);
13
- if (!admission.ok) return { claimed: false, detail: admission.detail };
14
+ if (!admission.ok) return { claimed: false, transient: true, detail: admission.detail };
14
15
  try {
15
16
  // `transient` (ticket e8): the claim loop backs off on these. A saved
16
17
  // completion that will not sync is almost always the server failing, and
17
18
  // claiming is blocked until it lands either way.
18
19
  if (!(await flushCompletions(project, settings))) return { claimed: false, transient: true, detail: "Saved completions are waiting to sync." };
19
- // With no limit on how many run at once (the default) the count can never
20
- // refuse, so it is not asked for: one call fewer per pass (#616).
21
- if (Number.isFinite(settings.maxConcurrent)) {
22
- const listed = await runnerApi.runs({ projectIds: [project.id], status: "running" }, rowsOpts);
23
- if (!listed.ok) return { claimed: false, transient: listed.transient === true, ...retryHint(listed), detail: `Cannot verify running sessions: ${listed.error}` };
24
- const running = (listed.runs ?? []).length;
25
- if (running >= settings.maxConcurrent) return { claimed: false, detail: `${running} session(s) already running, and up to ${settings.maxConcurrent} run at once` };
26
- }
27
- const claimed = await runnerApi.claim({ projectIds: [project.id], runnerInstanceId: settings.runnerInstanceId ??= randomUUID() }, rowsOpts);
20
+ const room = await runningRoom(project, settings, runnerApi, { activeRunIds, log });
21
+ if (!room.ok) return { claimed: false, ...room };
22
+ const claimed = await runnerApi.claim({ projectIds: [project.id], runnerInstanceId: settings.runnerInstanceId ??= randomUUID(), fencing: true }, rowsOpts);
28
23
  if (!claimed.ok) return { claimed: false, transient: claimed.transient === true, ...retryHint(claimed), detail: claimed.error };
29
24
  if (!claimed.run) return { claimed: false, idle: true, detail: "nothing pending" };
30
25
  return { claimed: true, run: claimed.run };
@@ -32,4 +27,3 @@ export async function claimOne(root, project, settings) {
32
27
  await admission.release();
33
28
  }
34
29
  }
35
-
package/lib/runnerApi.mjs CHANGED
@@ -155,7 +155,9 @@ async function call(op, body = {}, options = {}) {
155
155
  return { ok: false, error: `board-runner answered with unreadable JSON: ${text.slice(0, 400)}` };
156
156
  }
157
157
  if (payload.ok === false) {
158
- return { ok: false, error: errorDetail(payload.error) ?? "board-runner refused the request." };
158
+ // `refused`: the function answered no. `retry` marks the refusals that
159
+ // only hold while other work runs; the rest stay refused.
160
+ return { ok: false, refused: true, ...(payload.retry === true ? { retry: true } : {}), error: errorDetail(payload.error) ?? "board-runner refused the request." };
159
161
  }
160
162
  if (payload.ok !== true) return { ok: false, error: "board-runner returned an incomplete response." };
161
163
  return payload;
@@ -179,8 +181,8 @@ export function register({ runnerId, host, platform, presence, projects }, optio
179
181
  * rows), stop signals for every running run on them, and op signals
180
182
  * (untaken `run_ops` rows) - replacing `.runner.json`'s beat, `<id>.stop`,
181
183
  * and the merge/delete/relaunch/preview signal files all at once. */
182
- export function heartbeat({ projectIds, presence, runnerInstanceId, activeRunIds } = {}, options = {}) {
183
- return call("heartbeat", { projectIds, ...(presence !== undefined ? { presence } : {}), ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}), ...(activeRunIds !== undefined ? { activeRunIds } : {}) }, options);
184
+ export function heartbeat({ projectIds, presence, runnerInstanceId, activeRunIds, leaseGenerations } = {}, options = {}) {
185
+ return call("heartbeat", { projectIds, ...(presence !== undefined ? { presence } : {}), ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}), ...(activeRunIds !== undefined ? { activeRunIds } : {}), ...(leaseGenerations !== undefined ? { leaseGenerations } : {}) }, options);
184
186
  }
185
187
 
186
188
  /** `claim {projectIds}` -> `{run}` or `{run:null}`. The oldest approved,
@@ -188,8 +190,8 @@ export function heartbeat({ projectIds, presence, runnerInstanceId, activeRunIds
188
190
  * `listRequests`/`claimRequest`'s exclusive-create-on-disk race. `run.request`
189
191
  * is the SpawnRequest a file used to carry; `run.project_id` names which
190
192
  * registered project (and therefore which root) it belongs to. */
191
- export function claim({ projectIds, runnerInstanceId }, options = {}) {
192
- return call("claim", { projectIds, ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}) }, options);
193
+ export function claim({ projectIds, runnerInstanceId, fencing }, options = {}) {
194
+ return call("claim", { projectIds, ...(runnerInstanceId !== undefined ? { runnerInstanceId } : {}), ...(fencing === true ? { fencing } : {}) }, options);
193
195
  }
194
196
 
195
197
  /** `update {runId, patch}` -> ok, or `{ok:false, error:"result already
@@ -198,8 +200,8 @@ export function claim({ projectIds, runnerInstanceId }, options = {}) {
198
200
  * is the one call that replaces `<id>.session.json`, `<id>.server`, and
199
201
  * `<id>.result.txt` all at once, plus the `startSession`/`endSession` ops
200
202
  * files: the run row IS the start/end stamp now. */
201
- export function update({ runId, patch }, options = {}) {
202
- return call("update", { runId, patch }, options);
203
+ export function update({ runId, patch, generation }, options = {}) {
204
+ return call("update", { runId, patch, ...(generation ? { generation } : {}) }, options);
203
205
  }
204
206
 
205
207
  /** `events {runId, events:[{seq, kind, text}]}` -> insert, duplicates on
@@ -228,8 +230,8 @@ export function opResult({ opId, result }, options = {}) {
228
230
  /** `runs {projectIds, status?}` -> a list, for maintenance: the sweep's
229
231
  * equivalent of scanning `inbox/spawn/` for finished ids, and late
230
232
  * promotion's equivalent of finding a session's own row to resume. */
231
- export function runs({ projectIds, status } = {}, options = {}) {
232
- return call("runs", { projectIds, ...(status !== undefined ? { status } : {}) }, options);
233
+ export function runs({ projectIds, status, lateMessages } = {}, options = {}) {
234
+ return call("runs", { projectIds, ...(status !== undefined ? { status } : {}), ...(lateMessages ? { lateMessages: true } : {}) }, options);
233
235
  }
234
236
 
235
237
  /** `resume {runId, message, images?}` -> inserts an APPROVED child run row
@@ -254,8 +256,8 @@ export function runs({ projectIds, status } = {}, options = {}) {
254
256
  * function does not destructure is simply absent from `body` there, never
255
257
  * a hard failure; the day that worker's change lands, this call needs no
256
258
  * edit to start actually delivering pictures. */
257
- export function resume({ runId, message, images, unlessStopped }, options = {}) {
258
- return call("resume", { runId, message, ...(images?.length > 0 ? { images } : {}), ...(unlessStopped ? { unlessStopped: true } : {}) }, options);
259
+ export function resume({ runId, message, images, unlessStopped, promotionId }, options = {}) {
260
+ return call("resume", { runId, message, ...(images?.length > 0 ? { images } : {}), ...(unlessStopped ? { unlessStopped: true } : {}), ...(promotionId ? { promotionId } : {}) }, options);
259
261
  }
260
262
 
261
263
  /** `presence {paths?}` -> `{projects:[{id, path, host, runner_id,
@@ -310,3 +312,10 @@ export function realtime(options = {}) {
310
312
  /** Names-only discovery, requested by the person in Settings (#1132). */
311
313
  export function computerAppsTake(body, options = {}) { return call("computerAppsTake", body, options); }
312
314
  export function computerAppsResult(body, options = {}) { return call("computerAppsResult", body, options); }
315
+
316
+ /** The Folder panel's file list or one file, asked from the app (#3703). */
317
+ export function folderReadTake(body, options = {}) { return call("folderReadTake", body, options); }
318
+ export function folderReadResult(body, options = {}) { return call("folderReadResult", body, options); }
319
+
320
+ /** Recover a locally proven dead owner without waiting for lease expiry. */
321
+ export function recover(body, options = {}) { return call("recover", body, options); }
@@ -0,0 +1,384 @@
1
+ // The heartbeat half of `watch()` (runner.mjs), moved out of it (#4668):
2
+ // one beat (register, heartbeat, ops, the restart pass, the server sweep),
3
+ // the pace that schedules the next one, and what the realtime channel's
4
+ // events ask of it. `w` is the watcher's state the beat shares with
5
+ // `watch()`'s claim loop: `project`, `forgotten`, `finished`, `claimHint`,
6
+ // `hintSeq`, and `wake`/`kickClaim` for the loop's two waits.
7
+
8
+ import * as runnerApiModule from "./runnerApi.mjs";
9
+ import { callRunnerTool } from "./hosted.mjs";
10
+ import { DEFAULTS } from "./child.mjs";
11
+ import { presenceBody, refreshProjectPaths, registerAndFindProject } from "./runnerRegister.mjs";
12
+ import { liveRuns, restartPass, RECOVERY_RECHECK_MS, RESTART_RECHECK_MS } from "./restartPass.mjs";
13
+ import { orphanRecoveries } from "./runnerRecovery.mjs";
14
+ import { flushCompletions } from "./runnerSettlement.mjs";
15
+ import { SERVER_SWEEP_INTERVAL_MS, sweepDetachedServers } from "./serverSweep.mjs";
16
+ import { createSharedPreviewService } from "./sharedPreview.mjs";
17
+ import { createMemberPreviewTunnel } from "./memberPreview.mjs";
18
+ import { beatPace } from "./runnerPace.mjs";
19
+ import { resumeLateMessages } from "./lateResume.mjs";
20
+ import { serviceForgetOps, serviceRowOps } from "./runnerOps.mjs";
21
+
22
+ /** How soon the beat looks again for late messages: while one waits, and
23
+ * while none does (a pushed reply brings it forward either way). */
24
+ export const LATE_MESSAGES_BUSY_MS = 60_000;
25
+ export const LATE_MESSAGES_IDLE_MS = 5 * 60_000;
26
+
27
+ /** When the next look for late messages is due, after one listed `waiting`
28
+ * runs (resumeLateMessages's count). */
29
+ export const nextLateLookAt = (waiting, settings = {}, now = Date.now()) =>
30
+ now + (waiting > 0 ? LATE_MESSAGES_BUSY_MS : settings.lateMessagesIdleMs ?? LATE_MESSAGES_IDLE_MS);
31
+
32
+ /** Whether a pushed reply may be a late message: it names a session this
33
+ * process is not running. A live run reads its own replies (rowsAnswers.mjs)
34
+ * and its key is its run id, so every watcher stays still for those. */
35
+ export const replyMayBeLate = (payload, live = liveRuns) =>
36
+ typeof payload?.session_key === "string" && payload.session_key !== "" && !live.has(payload.session_key);
37
+
38
+ /** A wait anyone can end: `wait()` hands out the pending promise (made on
39
+ * first ask), `fire()` resolves it and starts a fresh one next time. */
40
+ export function makeLatch() {
41
+ let pending = null;
42
+ return {
43
+ wait: () => (pending ??= (() => {
44
+ let resolve;
45
+ const promise = new Promise((r) => { resolve = r; });
46
+ return { promise, resolve };
47
+ })()).promise,
48
+ fire: () => {
49
+ pending?.resolve();
50
+ pending = null;
51
+ },
52
+ };
53
+ }
54
+
55
+ /** The shared preview service a watcher owns, with its one in-flight tick
56
+ * and its one close. */
57
+ export function makeWatchPreview(settings, log, startPreviewTransport) {
58
+ // Both CLI entry points and multiwatch arrive here. Always service preview
59
+ // rows through the member gateway; tests can replace the public transport,
60
+ // but the membership and target-ownership checks stay on this path. Missing
61
+ // access configuration becomes an error on the op, without exposing a port.
62
+ const previewService = createSharedPreviewService({
63
+ runnerApi: settings.runnerApi ?? runnerApiModule,
64
+ hostedCallTool: settings.hostedCallTool ?? callRunnerTool,
65
+ env: settings.env,
66
+ fetchImpl: settings.fetchImpl,
67
+ startTunnel: (origin, context) => createMemberPreviewTunnel(origin, context, {
68
+ env: settings.env, startTransport: startPreviewTransport,
69
+ }),
70
+ });
71
+ let previewClosing;
72
+ const closePreview = () => previewClosing ??= previewService.close().catch((error) => {
73
+ log(`preview shutdown failed: ${error instanceof Error ? error.message : String(error)}`);
74
+ });
75
+ let previewTick;
76
+ const tickPreview = () => {
77
+ if (previewTick || previewClosing) return;
78
+ // Download/connect can take minutes. The preview owns that wait; runner
79
+ // presence, Stop/forget delivery and first-run admission must keep moving.
80
+ previewTick = previewService.tick()
81
+ .catch((error) => log(`preview tick failed: ${error instanceof Error ? error.message : String(error)}`))
82
+ .finally(() => { previewTick = null; });
83
+ };
84
+ return { service: previewService, close: closePreview, tick: tickPreview, closing: () => Boolean(previewClosing) };
85
+ }
86
+
87
+ /** The beat, its schedule, and the handlers for pushed events and asked-for
88
+ * beats. `watch()` starts it with `beat()` then `scheduleBeat()`. */
89
+ export function makeBeatLoop(w) {
90
+ const { root, settings, log, stopped, heartbeats, realtime, beatBase, preview } = w;
91
+ // THE DETACHED DEV SERVERS this folder's finished runs left behind, checked
92
+ // once a day off the beat (lib/serverSweep.mjs). Rows, not files: the
93
+ // record lives on the run row since brief 30.
94
+ let serverSweptAt = 0;
95
+ const sweepServers = async () => {
96
+ if (Date.now() - serverSweptAt < (settings.serverSweepMs ?? SERVER_SWEEP_INTERVAL_MS)) return;
97
+ serverSweptAt = Date.now();
98
+ try {
99
+ await sweepDetachedServers(w.project, settings, { log });
100
+ } catch (error) {
101
+ log(`dev server sweep failed: ${error instanceof Error ? error.message : String(error)}`);
102
+ }
103
+ };
104
+ // Recheck periodically too: the same watcher may lose touch and recover
105
+ // more than once without restarting its own process (#1252).
106
+ let restartDueAt = 0;
107
+ let recoveryDueAt = 0;
108
+ let lateMessagesDueAt = 0;
109
+ // A dead owner's record on this computer (#4948). Disk only; while there is
110
+ // none, the pass and the beat keep the pace they had (#616).
111
+ const orphaned = () => Boolean(w.project) && orphanRecoveries(w.project, settings, liveRuns) > 0;
112
+
113
+ // Ownership misses (including a deleted id) use this exact refusal. After
114
+ // glytch login changes accounts, retry registration on the next beat without
115
+ // letting either shared cache hand back the old account's project id.
116
+ const clearRefusedProject = (answer) => {
117
+ if (!w.project || answer.ok !== false || answer.transient === true || answer.error !== "not yours") return;
118
+ heartbeats.leave(w.project.id);
119
+ realtime?.setFolder(w.project.id, false);
120
+ w.project = null;
121
+ w.claimHint = false;
122
+ settings.registrar.invalidate?.();
123
+ };
124
+
125
+ // The Retry-After of the last beat that failed, for the beat's own pace.
126
+ let beatRetryAfterMs;
127
+ const runBeat = async () => {
128
+ beatRetryAfterMs = undefined;
129
+ if (w.forgotten) return;
130
+ const registered = w.project !== null;
131
+ // A known folder must hear Remove before register can clear forgotten_at
132
+ // through its link RPC. Only startup needs register to obtain the id.
133
+ if (!registered) {
134
+ const reg = await registerAndFindProject(root, settings);
135
+ if (!reg.ok) {
136
+ log(`could not register with the board: ${reg.error}`);
137
+ beatRetryAfterMs = reg.retryAfterMs;
138
+ return reg.transient ? "failed" : "steady";
139
+ }
140
+ if (!reg.myProjectId) {
141
+ log(`this folder is not among the projects the board acknowledged; nothing will be claimed`);
142
+ return "steady";
143
+ }
144
+ w.project = { id: reg.myProjectId, path: root };
145
+ realtime?.setFolder(w.project.id, true);
146
+ }
147
+ const flushed = await flushCompletions(w.project, settings, log);
148
+ const runnerApi = settings.runnerApi ?? runnerApiModule;
149
+ const seen = w.hintSeq;
150
+ await refreshProjectPaths(root, settings);
151
+ const beat = await heartbeats.beat(w.project.id, (projectIds) => runnerApi.heartbeat({ projectIds, presence: presenceBody(settings) }, { env: settings.env, fetchImpl: settings.fetchImpl }));
152
+ if (!beat.ok) {
153
+ clearRefusedProject(beat);
154
+ log(`heartbeat failed: ${beat.error}`);
155
+ beatRetryAfterMs = beat.retryAfterMs;
156
+ return beat.transient ? "failed" : "steady";
157
+ }
158
+ // The shared answer holds every folder's ops; keep this folder's. An op
159
+ // naming no project is only taken from an answer for this folder alone.
160
+ const alone = (beat.coveredProjectIds ?? [w.project.id]).every((id) => id === w.project.id);
161
+ const ops = (beat.ops ?? []).filter((op) => (op.project_id ? op.project_id === w.project.id : alone));
162
+ if (Array.isArray(beat.pending)) {
163
+ w.claimHint = beat.pending.includes(w.project.id) || w.hintSeq !== seen;
164
+ if (w.claimHint) w.hintSeq += 1, w.wake();
165
+ } else {
166
+ w.claimHint = null;
167
+ w.hintSeq += 1;
168
+ w.wake();
169
+ }
170
+ try { await settings.onHealthy?.(root); }
171
+ catch (error) { log(`Could not write local connection check: ${error.message}`); }
172
+ // Stops are run ids: another folder's in this set is never acted on.
173
+ for (const runId of beat.stops ?? []) stopped.add(runId);
174
+ let opsFailed = false;
175
+ if (ops.length > 0) {
176
+ // FIRST, and it returns early: there is no point merging a worktree or
177
+ // standing a preview up for a folder that is leaving this machine.
178
+ try {
179
+ if (await serviceForgetOps(root, w.project, ops, settings, log)) {
180
+ w.forgotten = true;
181
+ heartbeats.leave(w.project.id);
182
+ realtime?.setFolder(w.project.id, false);
183
+ w.wake();
184
+ await preview.close();
185
+ return "work";
186
+ }
187
+ } catch (error) {
188
+ opsFailed = true;
189
+ log(`forget failed: ${error instanceof Error ? error.message : String(error)}`);
190
+ }
191
+ }
192
+ // Retry retained Look answers even though claimed requests are absent
193
+ // from later heartbeat operations. Forget above always takes priority.
194
+ try { opsFailed = !(await serviceRowOps(root, w.project, ops, settings, log)).ok || opsFailed; }
195
+ catch (error) {
196
+ opsFailed = true;
197
+ log(`ops sweep failed: ${error instanceof Error ? error.message : String(error)}`);
198
+ }
199
+ if (ops.length > 0) {
200
+ try { await preview.service.onOps(ops, w.project.id); }
201
+ catch (error) {
202
+ opsFailed = true;
203
+ log(`preview claim failed: ${error instanceof Error ? error.message : String(error)}`);
204
+ }
205
+ }
206
+ // The shared register names ALL folders. If another folder is leaving,
207
+ // let its watcher consume the same forget before refreshing that list.
208
+ // A failed heartbeat or forget never reaches a register that could erase it.
209
+ if (registered && !opsFailed && !(beat.ops ?? []).some((op) => op.kind === "forget")) {
210
+ const reg = await refreshRegistration(root, settings, runnerApi);
211
+ if (!reg.ok) {
212
+ clearRefusedProject(reg);
213
+ log(`could not register with the board: ${reg.error}`);
214
+ beatRetryAfterMs = reg.retryAfterMs;
215
+ return reg.transient ? "failed" : "steady";
216
+ }
217
+ if (!reg.myProjectId) {
218
+ log(`this folder is not among the projects the board acknowledged; nothing will be claimed`);
219
+ return "steady";
220
+ }
221
+ }
222
+ // THE RESTART PASS (brief 52, ruling 7): sessions the last process left
223
+ // running pick up where they were. Only once receipts that were saved but
224
+ // not yet delivered have gone out, or a run that really finished would be
225
+ // continued over its own ending.
226
+ if (flushed && (Date.now() >= restartDueAt || (Date.now() >= recoveryDueAt && orphaned()))) {
227
+ restartDueAt = Date.now() + (settings.restartRecheckMs ?? RESTART_RECHECK_MS);
228
+ recoveryDueAt = Date.now() + (settings.recoveryRecheckMs ?? RECOVERY_RECHECK_MS);
229
+ try { await restartPass(w.project, settings, { log, startRun: w.startRecovered }); }
230
+ catch (error) { log(`restart pass failed: ${error instanceof Error ? error.message : String(error)}`); }
231
+ }
232
+ // LATE MESSAGES (#5101, #5106): every minute while some finished run has
233
+ // one waiting, every five while none does. A reply pushed for a run this
234
+ // process is not running brings the next look forward (onPush below).
235
+ if (flushed && Date.now() >= lateMessagesDueAt) {
236
+ lateMessagesDueAt = Date.now() + LATE_MESSAGES_BUSY_MS;
237
+ try { lateMessagesDueAt = nextLateLookAt(await resumeLateMessages(w.project, settings, log), settings); }
238
+ catch (error) { opsFailed = true; log(`late answers: ${error.message}`); }
239
+ }
240
+ await sweepServers();
241
+ preview.tick();
242
+ // Use the existing failure backoff while an answer is waiting, rather
243
+ // than the five-minute idle cadence used with realtime connected.
244
+ return opsFailed ? "failed" : "work";
245
+ };
246
+ let beatInFlight;
247
+ // THE PACE OF BOTH LOOPS (ticket e8, lib/runnerPace.mjs). The beat keeps
248
+ // its 10 s while the board answers and backs off to 60 s on 5xx or network
249
+ // failures; the claim loop does the same under errors. While the queue
250
+ // stays empty it makes no call at all when the beat carries `pending`, and
251
+ // slows to 30 s against an older function that does not (#616).
252
+ const beatPacer = beatPace(settings, DEFAULTS.beatMs);
253
+ let beatDelay = beatPacer.work();
254
+ // A failed beat backs off from 10 s whatever the cadence; any other waits
255
+ // the cadence of the moment: 5 minutes while joined, 10 s while not.
256
+ const beat = () => {
257
+ if (w.forgotten || w.finished) return Promise.resolve();
258
+ // Serialize the row sweeps, independently of the long-lived preview work.
259
+ return beatInFlight ??= runBeat()
260
+ .then((outcome) => {
261
+ if (outcome === "failed") beatDelay = beatPacer.failed(beatRetryAfterMs);
262
+ else {
263
+ beatPacer.work();
264
+ beatDelay = beatBase();
265
+ }
266
+ }, (error) => {
267
+ beatPacer.steady();
268
+ beatDelay = beatBase();
269
+ throw error;
270
+ })
271
+ .finally(() => { beatInFlight = null; });
272
+ };
273
+ const beatFailed = (error) => log(`heartbeat failed: ${error instanceof Error ? error.message : String(error)}`);
274
+ // A chain of timeouts rather than an interval, so the wait after each beat
275
+ // can depend on how that beat went. One timer at most: every schedule
276
+ // replaces the last.
277
+ let beating;
278
+ let beatAgain = false;
279
+ const scheduleBeat = () => {
280
+ clearTimeout(beating);
281
+ if (w.forgotten || w.finished) return;
282
+ const delay = beatAgain ? 0 : orphaned() ? Math.min(beatDelay, settings.recoveryRecheckMs ?? RECOVERY_RECHECK_MS) : beatDelay;
283
+ beatAgain = false;
284
+ beating = setTimeout(() => {
285
+ void beat().catch(beatFailed).finally(scheduleBeat);
286
+ }, delay);
287
+ beating.unref?.();
288
+ };
289
+ // A beat now, for an event: after the one in flight if there is one.
290
+ const beatNow = () => {
291
+ if (w.forgotten || w.finished) return;
292
+ if (beatInFlight) {
293
+ beatAgain = true;
294
+ return;
295
+ }
296
+ clearTimeout(beating);
297
+ void beat().catch(beatFailed).finally(scheduleBeat);
298
+ };
299
+
300
+ // WHAT THE CHANNEL SAYS (#813). Each event becomes the call this loop
301
+ // already makes; none of them claims or stops by itself.
302
+ // - joined: one heartbeat now, the catch-up for whatever was sent while
303
+ // the socket was down, then every 5 minutes
304
+ // - left: back to every 10 s, from now
305
+ // - pending (this folder): claim now, through claimOne (#364)
306
+ // - stop: the run id joins `stopped`, which the session checks every 2 s
307
+ // - op (this folder): a heartbeat now, which hands the op over
308
+ // `at` is the same for every folder, so the hub still sends one heartbeat
309
+ // for all of them.
310
+ const onPush = (event) => {
311
+ if (w.forgotten || w.finished) return;
312
+ const payload = event.payload ?? {};
313
+ const mine = () => w.project !== null && (payload.project_id ?? w.project.id) === w.project.id;
314
+ if (event.type === "joined") {
315
+ lateMessagesDueAt = 0;
316
+ heartbeats.invalidate(event.at);
317
+ beatNow();
318
+ } else if (event.type === "left") {
319
+ heartbeats.invalidate(event.at);
320
+ beatDelay = beatBase();
321
+ if (!beatInFlight) scheduleBeat();
322
+ } else if (event.type === "pending" && mine()) {
323
+ w.claimHint = true;
324
+ w.hintSeq += 1;
325
+ w.wake();
326
+ w.kickClaim();
327
+ } else if (event.type === "stop" && typeof payload.run_id === "string") {
328
+ if (w.project === null || mine()) stopped.add(payload.run_id);
329
+ } else if (event.type === "op" && mine()) {
330
+ heartbeats.invalidate(event.at);
331
+ beatNow();
332
+ } else if (event.type === "reply" && w.project !== null && replyMayBeLate(payload)) {
333
+ // A reply names only its session (the runner_reply_push broadcast), so
334
+ // only one for a run not live here brings the next look forward (#5106).
335
+ lateMessagesDueAt = 0;
336
+ beatNow();
337
+ }
338
+ };
339
+ // `glytch init` asking for a fresh beat (multiwatch's beatRequests).
340
+ const onBeatAsk = (at) => {
341
+ if (w.forgotten || w.finished) return;
342
+ heartbeats.invalidate(at);
343
+ beatNow();
344
+ };
345
+ return { beat, scheduleBeat, beatNow, onPush, onBeatAsk, stop: () => clearTimeout(beating), inFlight: () => beatInFlight };
346
+ }
347
+
348
+ /** Register again after a beat's ops, through a registrar that first checks
349
+ * no folder removal is pending (a register would erase it). */
350
+ async function refreshRegistration(root, settings, runnerApi) {
351
+ const refreshSettings = {
352
+ ...settings,
353
+ registrar: {
354
+ register: (key, send) => settings.registrar.register(key, async () => {
355
+ // Row ops may have awaited a slow merge after the beat snapshot.
356
+ // Bypass the heartbeat cache, only when register is actually due.
357
+ // The remaining read/write gap is closed server-side by
358
+ // https://github.com/glytch-ai/glytch/issues/1065.
359
+ const rowsOpts = { env: settings.env, fetchImpl: settings.fetchImpl };
360
+ // The registrar key is the exact path list captured by send().
361
+ // Presence includes forgotten rows; scope to this register's host.
362
+ const listed = await runnerApi.presence({ paths: JSON.parse(key) }, rowsOpts);
363
+ if (!listed.ok) return listed;
364
+ const projectIds = (listed.projects ?? [])
365
+ .filter((p) => p.host === (settings.host ?? "local"))
366
+ .map((p) => p.id);
367
+ // New paths have no id yet and cannot have a pending forget.
368
+ // This bare heartbeat only bumps last_seen_at: it neither replaces
369
+ // presence nor claims, acknowledges or marks ops delivered.
370
+ const latest = projectIds.length > 0
371
+ ? await runnerApi.heartbeat({ projectIds }, rowsOpts)
372
+ : { ok: true, ops: [] };
373
+ if (!latest.ok) return latest;
374
+ if ((latest.ops ?? []).some((op) => op.kind === "forget")) {
375
+ return { ok: false, error: "Registration deferred: a folder removal is pending." };
376
+ }
377
+ return send();
378
+ }),
379
+ },
380
+ };
381
+ const reg = await registerAndFindProject(root, refreshSettings);
382
+ Object.assign(settings, { noGit: refreshSettings.noGit, projectPaths: refreshSettings.projectPaths });
383
+ return reg;
384
+ }
@@ -197,8 +197,9 @@ export async function completeRequest(context, services = defaultServices) {
197
197
  if (!mayHaveChangedFiles(outcome.log, { dropped: outcome.dropped })) return false;
198
198
  try { return !(await inGit(made.cwd)); } catch { return false; }
199
199
  };
200
+ let resultLanded = false;
200
201
  try {
201
- await reportOutcomeOnBoard(session, outcome, from, {
202
+ const receipt = await reportOutcomeOnBoard(session, outcome, from, {
202
203
  callTool: hostedCallTool,
203
204
  env: hostedEnv,
204
205
  request,
@@ -207,6 +208,7 @@ export async function completeRequest(context, services = defaultServices) {
207
208
  inPlace: await changedNonGitFolder(),
208
209
  preview: Number.isFinite(Number(server?.port)) ? `http://localhost:${Number(server.port)}` : undefined,
209
210
  });
211
+ resultLanded = receipt?.landed === true;
210
212
  } catch (error) {
211
213
  log(`[${id}] could not comment the outcome onto the board: ${error instanceof Error ? error.message : String(error)}`);
212
214
  }
@@ -245,7 +247,7 @@ export async function completeRequest(context, services = defaultServices) {
245
247
  // final sidecar and may retain their early workspace receipt instead.
246
248
  // The pictures ride on the closing reply only: two of them on every run
247
249
  // row would weigh down each list of runs (#2194).
248
- sidecar: { ...(sidecar ?? {}), ...(outcome.result ? { result: withoutPictures(outcome.result) } : {}), ...(status === "error" ? agentErrorOf(outcome) : {}) },
250
+ sidecar: { ...(sidecar ?? {}), resultLanded, ...(outcome.result ? { result: withoutPictures(outcome.result) } : {}), ...(status === "error" ? agentErrorOf(outcome) : {}) },
249
251
  ...(server ? { server } : {}),
250
252
  };
251
253
 
@@ -260,6 +262,7 @@ export async function completeRequest(context, services = defaultServices) {
260
262
  root, id,
261
263
  {
262
264
  poller: rowsPoll, callTool: hostedCallTool, sessionKey: session.key, env: hostedEnv,
265
+ deferMessages: true, // The heartbeat asks after the terminal receipt is saved (#5103).
263
266
  promote: async (_root, targetId, reply, _log, promotionId) => {
264
267
  // IMAGES, item 6: `reply.images` is the late row's own images
265
268
  // (rowsAnswers.mjs's `promoteLateRows`), carried into `resume`